code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * Module dependencies. */ var api = require('lib/db-api'); var config = require('lib/config'); var express = require('express'); var jwt = require('lib/jwt'); var passport = require('passport'); var log = require('debug')('democracyos:auth:facebook:routes'); var User = require('lib/models').User; var fbSignedParser = require('fb-signed-parser'); /** * Expose auth app */ var app = module.exports = express(); /* * Facebook Auth routes */ app.get('/auth/facebook', passport.authenticate('facebook', { scope: config.auth.facebook.permissions }) ); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), function(req, res) { // After successful authentication // redirect to homepage. log('Log in user %s', req.user.id); var token = jwt.encodeToken(api.user.expose.confidential(req.user), config.jwtSecret); return res.cookie('token', token.token, { expires: new Date(token.expires), httpOnly: true }).redirect('/'); } ); app.post('/auth/facebook/deauthorize', function(req, res) { log('Parsing call to "/auth/facebook/deauthorize".'); res.send(200); var signedRequest = req.params.signed_request; if (!signedRequest) return log('"signed_request" param not found.'); var data = fbSignedParser.parse(signedRequest, config.auth.facebook.clientSecret); if (!data || !data.user || !data.user.id) { return log('Invalid "signed_request" data: ', data); } setTimeout(function(){ deauthorizeUser(data.user.id) }, 0); }); function deauthorizeUser(userFacebookId) { log('Deauthorizing user with facebook id "%s".', userFacebookId); var profile = { id: userFacebookId, provider: 'facebook' }; User.findByProvider(profile, function (err, user) { if (err) { return log('Error looking for user with facebook id "%s".', userFacebookId); } if (!user) { return log('User with facebook id "%s" not found.', userFacebookId); } user.set('profiles.facebook.deauthorized', true); return user.save(function(err){ if (err) return log(err); log('Facebook login for user "%s" deauthorized.', user.id); }); }); }
fonorobert/evoks
lib/auth-facebook/routes.js
JavaScript
mit
2,185
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Face.Contract; namespace Novanet { public static class FaceServiceClientExtensions { public static async Task CreatePersonGroupIfNotExising(this FaceServiceClient client, string personGroupId, string name) { var personGroups = await client.ListPersonGroupsAsync(); if (!personGroups.Any(pg => pg.PersonGroupId.Equals(personGroupId, StringComparison.InvariantCultureIgnoreCase))) { await client.CreatePersonGroupAsync(personGroupId, name); } } public static async Task<Guid> CreateUserAsPersonIfNotExising(this FaceServiceClient client, string personGroupId, User user) { // Use person UserData property to store external UserId for matching var persons = await client.GetPersonsAsync(personGroupId); if (persons.Any(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase))) { return persons.First(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase)).PersonId; } var person = await client.CreatePersonAsync(personGroupId, user.Name, user.Id.ToString()); return person.PersonId; } public static async Task WaitForPersonGroupStatusNotRunning(this FaceServiceClient client, string personGroupId, TraceWriter log) { // WOW, this is ugly, should probably put back on queue? try { var status = await client.GetPersonGroupTrainingStatusAsync(personGroupId); while (status.Status == Status.Running) { log.Info("Waiting for training..."); await Task.Delay(5000); } } catch (FaceAPIException notTrainedException) { // Throws if never tained before, and I don't care. } } } }
novanet/ndc2017
src/EmoApi/AzureFunctionsCCC/IdentificationTrainingFunction/FaceServiceClientExtensions.cs
C#
mit
2,140
# Latte-lang 规范 # 目录 1. [起步](#p1) 1. [基础语法](#p1-1) 2. [文件结构](#p1-2) 2. [基础](#p2) 1. [字面量](#p2-1) 2. [基本类型](#p2-2) 3. [控制流](#p2-3) 3. [类和对象](#p3) 1. [类与继承](#p3-1) 2. [接口](#p3-2) 3. [字段和方法](#p3-3) 4. [修饰符](#p3-4) 5. [Data Class](#p3-5) 6. [实例化](#p3-6) 7. [Object Class](#p3-7) 8. [隐式转换](#p3-8) 4. [函数类和Lambda](#p4) 1. [函数类](#p4-1) 2. [高阶函数和Lambda](#p4-2) 5. [其他](#p5) 1. [Json 集合](#p5-1) 2. [范围](#p5-2) 3. [类型检查与转换](#p5-3) 4. [运算符绑定](#p5-4) 5. [异常](#p5-5) 6. [注解](#p5-6) 7. [过程(Procedure)](#p5-7) 8. [参数可用性检查](#p5-8) 9. [解构](#p5-9) 10. [模式匹配](#p5-10) 6. [Java 交互](#p6) 1. [在Latte中调用Java代码](#p6-1) 2. [在Java中调用Latte代码](#p6-2) <h1 id="p1">1. 起步</h1> `Latte-lang`是一种JVM语言,基于JDK 1.6。它支持Java的所有语义,能够与Java完美互通,并提供比Java更多的函数式特性。 <h2 id="p1-1">1.1 基础语法</h2> Latte-lang(后文简称Latte)借鉴了主流语言的语法特征。如果您熟悉`Java`,或者了解过`Kotlin`,`Scala`,`Python`,`JavaScript`,`Swift`中的一到两种,那么阅读`Latte-lang`代码是很轻松的。 > 对Latte影响最大的语言应该是Kotlin和Scala <h3 id="p1-1-1">1.1.1 注释</h3> 单行注释使用`//`开头。例如 ```java // i am a comment ``` 多行注释以`/*`开头,以`*/`结尾。例如 ```java /* comment */ /* multiple line comment */ a/* comment */=1 /* the comment splits an expression */ ``` <h3 id="p1-1-2">1.1.2 包与导入</h3> ```kotlin package lt::spec import java::util::_ ``` 或者使用`.`分割 ```kotlin package lt.spec import java.util._ ``` 代码段由`package`开始。一个latte文件只能包含一个`package`。它定义了其中定义的类、接口所在的“包”。包是一个java概念,可以理解为一个名字空间。 声明了这个文件中定义的所有类和接口都在`lt::spec`包下。子包的名称通过`::`,或者`.`分隔。 文件也可以不声明包,那么包名将被视为空字符串`""` 在导入包时使用`import`关键字,有三种导入方式: ```kotlin import java::awt::_ /* 导入所有java::awt包中的所有类 */ import java::util::List /* 导入类java::util::List */ import java::util::Collections._ /* 导入Collections类的所有静态字段和方法 */ ``` >使用`.`无法在语法上区分包与字段访问,所以在latte中建议使用`::`分割包名。但是考虑到其他JVM语言均使用`.`,所以也提供了`.`以符合使用习惯。 <h3 id="p1-1-3">1.1.3 类</h3> 定义类User ```kotlin class User(id: int, name: String) ``` 定义MyList类,并继承了LinkedList类 ```kotlin class MyList(ls:List):LinkedList(ls) ``` 定义抽象类MyList,并实现了List接口 ```kotlin abstract class MyList:List ``` 详见[3.1 类与继承](#p3-1) 定义`data class` ```kotlin data class User(id: int, name: String) ``` 定义data class后,编译器会自动生成所有字段的getter/setter,类的toString/hashCode/equals方法,并继承和实现Serializable、Cloneable接口。 详见[3.5 Data Class](#p3-5) 定义`object class` ```kotlin object Singleton ``` 可以直接使用类名获取该对象。 详见[3.7 object class](#p3-7) <h3 id="p1-1-4">1.1.4 接口</h3> 定义接口Consumer ```kotlin interface Supplier def supply ``` 详见[3.2 接口](#p3-2) <h3 id="p1-1-5">1.1.5 函数类</h3> 定义函数类sum ```kotlin fun sum(a, b) return a+b ``` 详见[4.1 函数类](#p4-1) <h3 id="p1-1-6">1.1.6 变量</h3> 只读变量 ```kotlin val a:int = 1 val b = 1 ``` 可变变量 ```kotlin var x = 5 x += 1 ``` 可变变量的`var`可以省略 ```python y = 6 ``` <h3 id="p1-1-7">1.1.7 字符串模板</h3> ```kotlin main(args : []String) println("First argument: ${args[0]}") ``` <h3 id="p1-1-8">1.1.8 使用条件表达式</h3> ```python if a > b return a else return b ``` 或者 ```kotlin result = (if a > b {a} else {b}) ``` >一个方法需要返回值,那么只要末尾一个值为表达式,Latte就会自动生成方法的return语句 详见[2.3.1 If 语句](#p2-3-1) <h3 id="p1-1-9">1.1.9 for循环</h3> ```swift for item in list println(item) ``` 或者 ```swift for i in 0 until list.size println(list[i]) ``` 详见[2.3.2 For 语句](#p2-3-2) <h3 id="p-1-1-10">1.1.10 while循环</h3> ```swift i = 0 while i < list.size println(list[i++]) ``` 详见[2.3.3 While 语句](#p2-3-3) <h3 id="p-1-1-11">1.1.11 范围</h3> 检查x是否在范围中 ```kotlin if x in 1 to y-1 print("OK") ``` 从1到5进行循环 ```swift for x in 1 to 5 print(x) ``` 详见[5.2 范围](#p5-2) <h3 id="p1-1-12">1.1.12 Lambda</h3> ```kotlin list.stream. filter{it.startsWith("A")}. map{it.toUpperCase()}. forEach{print(it)} f = a -> 1 + a f(2) /* 结果为 3 */ ``` 详见[4.2 高阶函数和Lambda](#p4-2) <h3 id="p1-1-13">1.1.13 Json语法</h3> ```js list = [1, 2, 3] map = [ "a": 1 "b": 2 ] ``` 详见[5.1 Json 集合](#p5-1) <h3 id="p1-1-14">1.1.14 返回对象的"或"</h3> 拥有JavaScript的`||`的功能。 ```js a = a || 1 ``` <h3 id="p1-1-15">1.1.15 指定生成器</h3> ``` #js def method(a) return a+1 ``` 将会被转换成如下JavaScript代码 ```js function method(a) { return a + 1; } ``` <h3 id="p1-1-16">1.1.16 模式匹配</h3> ```scala val (x,y) = Bean(1,2) ``` 详见[5.9 解构](#p5-9) ```scala o match case Bean(a,b) => ... case People(name, age) if age > 20 => ... case _ => ... ``` 详见[5.10 解构](#p5-10) <h2 id="p1-2">1.2 文件结构</h2> Latte源文件以`.lt`或者`.lts`为扩展名。不过实际上后缀名并不重要,手动构造编译器时附加特定参数即可。 <h3 id="p1-2-1">1.2.1 定义层次结构</h3> 编译器首先会检查文件的第一行。第一行可以标注该文件 使用缩进定义层次结构,还是 使用大括号定义层次结构。 例如: ```java /// :scanner-brace ``` 表示使用大括号定义层次结构。 ```java /// :scanner-indent ``` 表示使用缩进定义层次结构。 **默认为缩进**。提供这个选项是为了满足不同人的编码喜好。这两者的选择在词法上完全一样。 >注意:Latte并不限定缩进数量。比上一行“更大的缩进”均代表一个新层次。 <h3 id="p1-2-2">1.2.2 层次结构</h3> 使用*大括号*定义层次结构时,有如下几个符号会开启一个新层: ``` ( [ { ``` 当其对应的符号出现时,这个开启的层将关闭: ``` ) ] } ``` 使用*缩进*定义层次结构时,还有两个符号会开启一个新层: `->`、`=>` 由于层将在缩进“变得更小”时关闭。所以,如下代码不加上括号也可以正确的工作: ```java f = x->x+1 f() ``` >注:使用大括号定义层次结构时,`->`不会开启新层,若要书写多行语句请使用{...}。此时规则和java完全一致。 这里有一个示例,帮助理解“层”的概念: ┌───────────────────────┐ │ ┌─┐ │ │classA(│a│):B │ │ └─┘ │ │ ┌─────────────────┐│ │ │ ┌────────┐││ │ │method(│arg0 │││ │ │ ┌──┘ │││ │ │ │arg1 │││ │ │ │arg2, arg3 │││ │ │ └───────────┘││ │ │):Unit ││ │ │ ┌────┐ ││ │ │ │pass│ ││ │ │ └────┘ ││ │ └─────────────────┘│ └───────────────────────┘ 该源码将被解析成如下结构: -[class]-[A]-[(]-[│]-[)]-[:]-[B]-[│] └[a]- ┌──────┘ ┌──────────────────────────┘ └────[method]-[(]-[│]-[)]-[│]- ┌──────────────────┘ └───────[pass]- │ └──[arg0]-[EndNode]-[arg1]-[EndNode]-[arg2]-[StrongEndNode]-[arg3] **注意:** 本文除非注明,否则均使用“缩进”进行描述。在注明为“大括号”时,会在示例代码开头标注`/// :scanner-brace`。 <h3 id="p1-2-4">1.2.4 层次控制字符</h3> Latte支持直接使用`{`和`}`定义层次结构。不过要注意,如果写为`{}`则表示空Map(映射) 例如: ```kotlin if a > b {1} else {2} /* 相当于 */ if a > b 1 else 2 ``` ```js var map = {} /* 这是一个map */ ``` ```js /* 可以正常编译,定义了一个方法,其中定义一个局部变量,赋值一个map */ def method { map = [ "a": 1 "b": 2 ] } ``` <h1 id="p2">2. 基础</h1> <h2 id="p2-1">2.1 字面量</h2> Latte中有6种字面量: 1. number 2. string 3. bool 4. array 5. map <h3 id="p2-1-1">2.1.1 number</h3> 数字可以分为整数和浮点数 例如: 1 1.2 `1`是一个整数,`1.2`是一个浮点数。 整数字面量可以赋值给任意数字类型,而浮点数字面量只能赋值给`float`和`double`。详见 [2.2 基本类型](#p2-2)。 <h3 id="p2-1-2">2.1.2 string</h3> 字符串可以以`'`或`"`开头,并以同样的字符结尾。 例如: 'a string' "a string" 使用`\`作为转义字符 例如: ``` 'escape \'' "escape \"" ``` 字符串字面量分为两种,若字符串长度为1,则它可以赋值给`char`类型或`java.lang.String`类型。否则只能赋值给`java.lang.String`类型。 <h3 id="p2-1-3">2.1.3 bool</h3> 布尔型有下述4种书写形式: true false yes no `true`和`yes`表示逻辑真,`false`和`no`表示逻辑假。 布尔值字面量只能赋值给`bool`类型。 <h3 id="p2-1-4">2.1.4 array</h3> 数组以`[`开头,并以`]`结尾,其中包含的元素可以用`,`分隔,也可以通过换行分隔。 例如: ```js [1,2,3] [ object1 object2 object3 ] [ object1, object2, object3 ] ``` <h3 id="p2-1-5">2.1.5 map</h3> 映射(字典)像swift一样,以`[`开头,以`]`结尾。 键值对通过类型符号`:`分隔,不同的entry通过`,`或者换行进行分隔。 例如: ```swift ['a':1, 'b':2, 'c':3] [ 'a':1 'b':2 'c':3 ] [ 'a':1, 'b':2, 'c':3 ] ``` <h2 id="p2-2">2.2 基本类型</h2> Latte保留了Java的8种基本类型。由于Latte是动态类型语言,并且可以在编译期和运行时自动装包和拆包,所以基本类型与包装类型可以认为没有差异。 八种基本类型: ``` int long float double short byte char bool ``` 其中`int/long/float/double/short/byte`为数字类型。 注意,与Java不同的是,Latte使用`bool`而非`boolean`。 <h3 id="p2-2-1">2.2.1 基本类型转换</h3> 在转换时,所有基本类型都可以互相转换(除了bool,它可以被任何类型转换到,但不能转换为其他类型,详见[5.8 参数可用性检查](#p5-8))而不会出现任何错误。但是,在高精度向低精度转换时可能会丢失信息。例如: ```scala i:int = 3.14 /* i == 3 丢失了小数部分 */ b:bool = 10 /* b == true 除了数字不是0外,信息都丢失了 (只有0在转换为bool时才会是false) */ ``` <h3 id="p2-2-2">2.2.2 基本类型运算</h3> Latte支持所有Java的运算符,并在其基础上有所扩展 对于数字的基本运算,其结果均为“精度较高的值”的类型,且最低为`int`型。例如: ```c# r1 = (1 as long) + (2 as int) /* r1 是 long */ r2 = (1 as byte) + (2 as short) /* r2 是 int */ ``` 由于Latte可以任意转换基本类型,所以这么写也可以正常编译并运行: ```java a:short = 1 a+=1 /* a == 2 */ a++ /* a == 3 */ ``` >由于Latte支持基本类型的互相转换,你可以直接把`int`的结果赋值给`short`。 Latte支持所有Java运算符,当然也包括位运算。和`java`一样,位运算必须作用于整数上。Latte支持所有整数类型的位运算:`int/long/short/byte`。 此外,Latte还支持乘方运算: ```groovy a ^^ b ``` 结果均为`double`型。 > 本质来说,Latte不存在“运算符”。所有运算符都是方法调用。基本类型的运算是由其包装类型隐式转换后调用方法完成的。 <h2 id="p2-3">2.3 控制流</h2> <h3 id="p2-3-1">2.3.1 If 语句</h3> 和Java一样,if是一个语句而非像Kotlin,Scala那样作为表达式。 但是,Latte支持`Procedure`,并且可以自动添加返回语句,所以使用起来和作为表达式区别并不大。 ```ruby if a > b return 1 else return 2 val result = (if a>b {1} else {2}) ``` <h3 id="p2-3-2">2.3.2 For 语句</h3> for语句格式如下: ```kotlin for item in iter ... ``` 其中`iter`可以是数组、Iterable对象、Iterator对象、Enumerable对象、Map对象。 当`iter`为前4种时,for语句将把其包含的对象依次赋值给`item`并执行循环体。当`iter`为Map对象时,`item`是一个Entry对象,它来自`Map#entrySet()`。 你也可以使用`to`或者`until`,并在循环体内使用下标来访问元素: ```kotlin for i in 0 until arr.length val elem = arr[i] ... ``` <h3 id="p2-3-3">2.3.3 While 语句</h3> while语句格式如下: ```python while boolExp ... do ... while boolExp ``` 它的含义和Java完全一致。 <h3 id="p2-3-4">2.3.4 break, continue, return</h3> 在循环中可以使用 `break` 和 `continue` 来控制循环。break将直接跳出循环,continue会跳到循环末尾,然后立即开始下一次循环。它的含义与Java完全一致。 `return`可以用在lambda、方法(包括“内部方法”)、Procedure、脚本、函数类中: ```kotlin /* lambda */ foo = ()->return 1 /* 方法 */ def bar() return 2 /* Procedure */ ( return 3 ) /* 函数类 */ fun Fun1 return 4 ``` 脚本中的return语句表示将这个值返回到外部,在`require`这个脚本时将返回这个值。 如果`return`是这个函数/方法最后的一条语句,或者该函数任意一条逻辑分支的最末尾,那么`return`都可以被省略: ```kotlin fun add(a, b) a+b val result = add(1, 2) /* result is 3 */ ``` 转换方式很简单,首先取出这个函数/方法的最后一条语句,如果是表达式,而且这个函数/方法要求返回值,则直接将其包装在`AST.Return`中。 如果最后一条语句是`if`,那么对其每一个逻辑分支进行该算法。 <h1 id="p3">3. 类和对象</h1> <h2 id="p3-1">3.1 类与继承</h2> <h3 id="p3-1-1">3.1.1 类</h3> 类通过`class`关键字进行定义 当类内部不需要填充任何内容时,可以非常简单的书写为: ```kotlin class Empty ``` 当需要提供构造函数参数时,写为: ```kotlin class User(id, name) ``` 当然,你也可以为参数指定类型: ```scala class User(id:int, name:String) ``` 如果不指定类型则类型视为`java.lang.Object` Latte不支持在类内部再定义构造函数,不过,你可以指定参数默认值来创建多个构造函数: ```scala class Rational(a:int, b:int=1) ``` 此时你可以使用`Rational(1)`或者`Rational(1, 2)`来实例化这个类。 -- 构造函数内容直接书写在class内: ```kotlin class Customer(name: String) logger = Logger.getLogger('') logger.info("Customer initialized with value ${name}") ``` 直接定义在类中的变量,以及构造函数参数,将直接视为字段(Field)。也就是说,上述例子中定义的name和logger都是字段。详见 [3.3 字段和方法](#p3-3) 。 -- 使用`private`修饰符来确保类不会被实例化: ```kotlin private class DontCreateMe ``` 在Latte中,所有类都是`public`的,所以,在`class`前的任何“访问关键字”均为该类构造函数的访问关键字。 <h3 id="p3-1-2">3.1.2 继承</h3> 和Java一样:Latte是单继承,并且所有的类都默认继承自`java.lang.Object`。你可以使用类型符号`:`来指定继承的类。继承的规则和Java完全一致。 ```kotlin class Base(p:int) class Derived(p:int) : Base(p) ``` 父类的构造函数参数直接在父类类型后面的括号中指定。 如果使用了父类的无参构造函数,那么可以省略括号: ```kotlin class Example : Object ``` 如果想指定一个类不可被继承,那么需要在它前面加上`val`修饰符: ```kotlin val class NoInher ``` <h3 id="p3-1-3">3.1.3 抽象类</h3> 使用`abstract`关键字定义抽象类: ```kotlin abstract class MyAbsClass abstract f() ``` 抽象类规则与Java完全一致。抽象类可以拥有未实现的方法。 继承一个抽象类: ```kotlin class MyImpl : MyAbsClass @Override def f=1 ``` <h3 id="p3-1-4">3.1.4 静态成员</h3> 使用`static`定义静态成员。static可以“看作”一个修饰符,也可以“看作”一个结构块的起始。例如: ```js class TestStatic static public val STATIC_FIELD = 'i am a static field' static func()=1 ``` <h2 id="p3-2">3.2 接口</h2> Latte接口遵循Java的接口定义。使用`interface`关键字: ```kotlin interface MyInterface foo()=... ``` 定义了`abstract`方法`foo()`。 让一个类实现接口,也使用类型符号`:`。 ```kotlin class Child : MyInterface foo()=456 child = Child child.foo /* result is 456 */ child.bar /* result is 123 */ ``` 接口可以拥有字段,但是和Java规则一样,字段必须是`static public val`(默认也是)。 ```kotlin interface MyInterface FLAG = 1 ``` 接口也可以拥有`static`方法(和Java一样) ```js interface TestStaticMethod static method()=111 TestStaticMethod.method() /* result is 111 */ ``` <h2 id="p3-3">3.3 字段和方法</h2> <h3 id="p3-3-1">3.3.1 定义字段</h3> 你可以在类或接口中定义字段: ```kotlin class Address(name) public street public city public state public zip interface MyInterface FLAG = 1 ``` 在类中定义的字段默认被`private`修饰,可选的访问修饰符还有`public`, `protected`, `internal`。 字段可以为`static`,只要写在static块中即可(接口默认就是static的,不需要修改)。也可以为不可变的,使用`val`修饰即可。由于构造函数参数也是字段,所以这些修饰符可以直接写在构造函数参数中。例如: ```kotlin class User(protected val id, public val name) ``` 使用字段很简单,直接使用`.`符号访问即可,和Java一致。 ```kotlin val user = User(1, 'latte') user.name /* result is 'latte' */ val address = Address('home') address.city = 'hz' ``` Latte提供所谓的`property`支持:使用`getter`和`setter`来定义`property`。详情见 [3.3.3 Accessor](#p3-3-3) <h3 id="p3-3-2">3.3.2 方法</h3> Latte支持多种定义方法的语法,先看一个最完整的方法定义: ```scala def foo(x:int, y:int):int return x + y ``` 如果方法没有参数,那么可以省略里面的内容,甚至省略括号: ```scala /* 无参数 */ def foo:int return 1 ``` 返回类型可以不指定,默认为`java.lang.Object` ```scala def foo return 1 ``` 如果方法体只有一行并返回一个值,可以把在方法定义后直接接`=value` ```scala def foo = 1 ``` 如果方法体不存在(即空方法),可以只写一个方法名称(如果有参数再把参数加上) ```scala def foo ``` 上述定义的缩写方式可以混合使用。 此外,如果在定义方法的时候(使用了括号)并且(附带一个修饰符/注解,或者定义了返回值,或者使用了`=`语法),那么可以省略`def` ``` bar():int foobar()='hello' fizz():int=1 ``` -- 如果明确方法不返回值,那么可以附加`Unit`类型。Latte中只能写作`Unit`,代表了Java中的`void`。 但是,在Latte中所有方法都会返回一个值,对于Unit类型的方法,虽然会被编译为void类型,但是依然会返回`Unit`,它是`lt.lang.Unit`类型。 和构造函数参数一样,方法参数也可以设定默认值: ```scala foo(a, b=1)=a+b foo(1) /* result is 2 */ ``` **注意**,`def`实际上是一个“修饰符”(虽然它什么都不做),并不属于“关键字”。设置`def`是为了和“省略参数的lambda”进行语法上的区分。 例如: ```js foo(x) ... ``` 实际上会被转化为[4.2.2 Lambda](#p4-2-2)中描述的形式: ```js foo(x)(it->...) ``` 所以使用类似于这种方式(`VALID_NAME ( [PARAM [, PARAM, ...]] ) { ... }`)定义的方法,如果没有注解,也没有其他修饰符,会造成歧义,所以不可省略`def`。 方法返回类型为`Unit`时,你依然可以书写`return value`,这个value会被求值,但是不会被返回。 方法非`Unit`时,你也可以直接书写`return`,这时默认返回一个`Unit`。当然,如果返回类型不匹配,编译期依然会报错。 #### 内部方法 Latte支持“内部方法”。所谓内部方法是指在方法内部再定义一个方法。 ``` def outer def inner ``` 内部方法可以访问外部的所有变量,并且可以修改它们。 >实际上,Lambda、Procedure都基于“内部方法”特性。所以它们也可以修改捕获到的所有变量。 <h3 id="p3-3-3">3.3.3 Accessor</h3> accessor分为两种,一种是取值:getter,一种是赋值:setter。 对于getter有两种定义方式: 1. 定义为`get{Name}()` 2. 定义为`{name}()` 对于setter只有一种定义方式:定义为`set{Name}(name)` ```scala class User(id, name) def getId=id setId(id) this.id = id def name=name /* 放心,这么写是正确的 */ setName(name) this.name = name ``` 如此定义就可以像直接访问field一样来调用这几个方法了。 ```kotlin user = User(1, 'latte') println("user_id is ${user.id} and user_name is ${user.name}") user.id = 2 user.name = 'jvm' ``` 不过要注意的是:如果字段暴露给访问者,那么还是优先直接取字段或者对字段赋值。 此外,还有一对特殊的accessor: * `set(String, ?)` 方法签名要求方法名为"set",第一个参数接受一个String,第二个参数接受一个值,类型没有限制。(只不过使用时只能赋值为该类型的子类型)。 * `get(String)` 方法签名要求方法名为"get",第一个参数接受一个String。 定义有上述accessor的类的实例,在取`o.field`时,将转换为`o.get('field')`。在设置`o1.field = o2`时,将转换为`o1.set('field', o2)`。 <h2 id="p3-4">3.4 修饰符</h2> <h3 id="p3-4-1">3.4.1 访问修饰符</h3> Latte有4种访问修饰符: * public 公有,所有实例均可访问 * protected 受保护,包名相同的类型,或者子类可访问 * internal 包内可访问,包名相同的类型可以访问 * private 私有,只有本类型可访问 访问修饰符可以用来修饰: * 类 * 接口 * 字段 * 方法 * 构造函数的参数 其中,类访问修饰符并不是规定给类用的。Latte中,类的访问修饰符永远为`public`,这个修饰符是作为构造函数而存在的。 | 位置 | public | protected | internal | private | |-------|--------|-----------|----------|--------| | 类 | √ | √ | √ | √ | | 接口 | √ | | | | | 字段 | √ | √ | √ | √ | | 方法 | √ | √ | √ | √ | | 构造函数参数 | √ | √ | √ | √ | <h3 id="p3-4-2">3.4.2 其他修饰符</h3> Latte支持所有Java的修饰符,但是名称可能有改动: * var 表示可变变量(可省略,默认即为可变) * val 表示不可变变量,或者不可被重载的方法,或者不可被继承的类 * abstract 抽象类/方法 * native 本地方法 * synchronized 同步方法 * transient 不持久化的字段 * volatile 原子性的字段 * strictfp 方法内的符点计算完全遵循标准 * data 类是一个data class:详见 [3.5 data class](#p3-5) >`val` 其实就是Java的 `final` <h2 id="p3-5">3.5 Data Class</h2> 编译器会为data class的每一个字段生成一个getter和setter。并生成无参构造函数,`toString()`, `hashCode()`, `equals(Object)`方法。此外,还会实现Serializable和Cloneable接口。 ```kotlin data class User(val name: String, val age: int) user = User('cass', 22) user.toString() /* result is User(name='cass', age=22) */ ``` 你也可以定义自己的getter/setter/toString/hashCode/equals,编译器将跳过对应方法的生成。 <h2 id="p3-6">3.6 实例化</h2> Latte不需要`new`关键字就可以实例化一个类。对于无参数的实例化,甚至不需要附加括号: ```kotlin class Empty empty = Empty class User(id, name) user = User(1, 'latte') ``` 当然,Latte也允许你加上`new`: ```scala empty = new Empty user = new User(1, "latte") ``` 不过,Latte中的`new`的“优先级”非常低,java中的`new X().doSth()`的写法在Latte中必须写为`(new X).doSth`这样的写法。 > Latte中建议不要写new 此外,Latte提供另外一种特殊的实例化方式 调用无参构造函数,并依次赋值: ```python class open(file, mode) public encoding f = open('/User/a', "r", encoding='utf-8') ``` 这是一个语法糖,相当于如下Latte代码: ```kotlin f = open('/User/a', "r") f.encoding = 'utf-8' ``` 即:首先使用不带`=`的参数进行类型的实例化,然后把剩余“参数”看作对accessor的赋值操作。 这个语法糖不光适用于Latte定义的data class,还可以支持任意具有无参构造函数,并有可访问的field或者[accessor](#p3-3-3)的对象。例如标准Java Bean就可以使用这个语法。 ```java class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` <h2 id="p3-7">3.7 Object Class</h2> ```scala object DataProviderManager def registerDataProvider(provider: DataProvider) ... val allDataProviders: Collection = ... ``` 本质上,`object class`定义了一个类,但是这个类不能拥有构造函数的参数,构造函数为private,并拥有一个`static public val`的字段来存放单例。 object class可以继承父类、实现接口,其规则与普通的class完全相同 ```scala object DefaultListener : MouseAdapter() def mouseClicked(e: MouseEvent):Unit ... def mouseEntered(e: MouseEvent):Unit ... ``` 你可以直接使用类名来获取这个单例对象: ``` val o = DataProviderManager ``` <h2 id="p3-8">3.8 隐式转换</h2> 隐式转换可以帮助你为对象扩展方法,从而更灵活的进行编程。 使用隐式转换分为四步 ### 1. 定义一个类用来表示隐式转换后的类型 这一步是可选的,您可以直接隐式转换到已有的类型。这里为了说明方便,单独定义一个: ```scala class RichInteger(i:Integer) minutes() = i + " minute" + ( if i != 1 { "s" } else { "" } ) ``` ### 2. 定义一个隐式对象: 隐式对象是一个普通的`object class`,不过需要用`implicit`修饰它。 在其中定义一些"隐式方法",用来进行隐式类型转换。 “隐式方法”就是普通的方法,不过需要用`implicit`修饰它。 隐式方法有一些要求:参数只能有一个,其类型为隐式转换的源类型(或源类型的父类型);返回类型为目标类型。 例如:我们想要将`Integer`转换为`RichInteger` ```scala implicit object TestImplicitCast implicit def cast(i:Integer):RichInteger = RichInteger(i) ``` ### 3. 启用隐式类 ```scala import implicit TestImplicitCast ``` 使用`import implicit`引入隐式类。这里注意,隐式类必须使用类名引入,而且,即使隐式类与使用者定义在同一个包下,也必须显式引入。这样错用几率会比较小。 ### 4. 使用 ``` val x = 30 minutes ``` 此时,`x`的值即为`"30 minutes"`。运行时会寻找可用的隐式转换,并判断转换后是否能够调用指定方法:发现`Integer => RichInteger`可用,且RichInteger可以调用`minutes()`方法;那么最终执行时的代码相当于`val x = TestImplicitCast.cast(30).minutes()` <h1 id="p4">4. 函数类和Lambda</h1> <h2 id="p4-1">4.1 函数类</h2> <h3 id="p4-1-1">4.1.1 函数式接口 和 函数式抽象类</h3> Java8中规定了:只有一个未实现方法的接口为“函数式接口”。例如: ```java interface Consumer { void consume(Object o); } ``` 只有一个`consume`方法没有被实现,所以它是函数式接口。 类似的,Latte中除了支持Java的函数式接口外,还支持定义“函数式抽象类”。 如果一个类有无参的`public`构造函数,且只有一个未被实现的方法,那么这个类是一个函数式抽象类。例如: ```kotlin abstract class F abstract apply()=... ``` <h3 id="p4-1-2">4.1.2 定义函数类</h3> 要使用函数式接口/抽象类,必须有特定的实现。Latte提供一种简便的方式来书写其实现类: ```kotlin fun Impl(x, y) return x + y ``` 使用`fun`关键字定义“函数类”,参数即为函数式类型未实现方法的参数,内部语句即为实现的方法的语句。 函数类默认可以不附加类型,它在编译期将被视为`FunctionX`,其中X为参数个数。在运行时,`FunctionX`可以转化为任何参数个数相同的类型。 如果确定其实现的类型,可以使用类型符号`:`定义: ```kotlin fun MyTask : Runnable println('hello world') ``` <h3 id="p4-1-3">4.1.3 使用函数类</h3> 函数类会被编译为Java的类(`class`),所以,Latte中,它既有函数的特征,又有类的特征: * 函数类可以被import(就像类一样) * 可以直接调用这个类,例如:`Impl(1, 2)`。这条语句将实例化`Impl`并执行它实现的方法(这个用法就像lambda一样) * 可以将它作为值赋值给变量(实际上是调用了无参数构造函数,就像类一样) 总之,对于函数类,你完全可以把它当做一个变量来考虑。 ```kotlin Thread(MyTask).start() ``` 同时由于它是正常的类,所以也具有父类型的所有字段/方法: ```kotlin task = MyTask task.run() ``` <h3 id="p4-1-4">4.1.4 函数式对象</h3> 在Latte中,对于所有的函数式对象,都可以使用“像调用方法那样的语法”。 ```js task() ``` 一个对象是“函数式对象”,有三种情形: 1. 它的类(`.getClass`)的直接父类为函数式抽象类 2. 它的类(`.getClass`)只实现了一个接口,且这个接口是函数式接口 3. 这个对象具有`apply(...)`方法 所以,在Latte中,函数式对象就是函数。 <h2 id="p4-2">4.2 高阶函数和Lambda</h2> <h3 id="p4-2-1">4.2.1 高阶函数</h3> 如果一个函数可以接受另一个函数作为参数,或者返回一个函数,那么这个函数就是高阶函数。 [4.1.3 使用函数类](#p4.1.3) 中提到过“函数式对象”就是“函数”,所以,任何能够接收(并处理)函数式对象,或者返回函数式对象的函数/方法,就是高阶函数。 如下代码是Java使用stream api的做法: ```java List<String> strList = ...; strList.stream(). map(s->Integer.parseInt(s)). filter(n->n>10). collect(Collectors.toList()) ``` 可以看到,map,filter都接受一个函数作为参数,所以它们也可以看作高阶函数。 在Latte中,上述代码可以用Latte的`lambda`语法来表达: ```kotlin /// :scanner-brace strList = ... strList.stream. map { Integer.parseInt(it) }. filter { it > 10 }. collect(Collectors.toList()) ``` <h3 id="p4-2-2">4.2.2 Lambda</h3> Latte支持和Java完全一样的Lambda语法: ```java strList.stream(). map(s->Integer.parseInt(s)). filter(n->n>10). collect(Collectors.toList()) ``` 从外观上看不出任何差别?没错,语法上完全一致(特别是使用大括号区分层次的时候)。 使用缩进的情况下,多行lambda可以这么写: ```coffee strList.stream.map( s-> s = s.subString(1) Integer.parseInt(s) ) ``` >注:可以不写return,因为Latte会帮你把需要的return补上。这个特性适用于任何“编译为JVM方法”的语法。 如果lambda只有一个参数(例如上述代码),那么名称和`->`可以被省略。其中,名称会被标记为`it`。 ```js strList.stream.map it = it.subString(1) Integer.parseInt(it) ``` 这个特性可以让代码更简洁,同时也可以构造更灵活的内部DSL ```python latteIsWrittenInJava if it is great star the repo ``` >做一丁点处理后,这是可以正常编译的代码!(不需要hack编译器) 可以写成一行 ```coffee latteIsWrittenInJava { if it is great { star the repo }} ``` 此外Lambda的变量捕捉机制和Java不同。Latte可以在Lambda中的任何地方修改被捕获的变量。 ```coffee var count = 0 (1 to 10).forEach { count+=it } println(count) ``` <h1 id="p5">5. 其他</h1> <h2 id="p5-1">5.1 Json 集合</h2> Latte支持Json格式的字面量。 Json数组: ```js var list = [1, 2, 3, 4] ``` 使用Json的数组语法,可以创建一个`java.util.LinkedList`实例,也可以创建一个数组。这取决于你将它赋值给什么类型的变量,或者使用`as`符号把它转换为什么类型。 int数组: ```c# [1, 2, 3, 4] as []int ``` Object数组: ```c# [1, 2, 3, 4] as []Object ``` 在Latte中,你可以将一个`java.util.List`类型的对象转换为其它种类的Object。该特性将尝试使用无参构造函数构造目标类型对象,然后对每一个List中的元素,调用add方法。 ```kotlin class JsonArray list = [] def add(o)=list.add(o) res = [1,2,3] as JsonArray /* same as: res = JsonArray() for item in [1,2,3] res.add(item) */ ``` -- Json对象: ```swift var map = [ 'one': 1, 'two': 2, 'three', 3 ] ``` 其中`,`是不必须的。“换行”和`,`都可以用来来分割list的元素,以及map的entry 在Latte中,你还可以把一个"所有键都是string"的map转换为指定类型的对象。 ```kotlin data class Bean(hello, foo) res = [ "hello" : "world" "foo" : "bar ] as Bean /* res will be Bean(hello=world, foo=bar) */ ``` 该转换将首先用无参构造函数构造指定类型,然后对map中每一个键,进行Latte的赋值操作。 不光可以显式的转换,还可以作为方法参数隐式转换过去。 <h2 id="p5-2">5.2 范围</h2> 在Latte中可以使用`to`或者`until`运算符来定义一个“范围”(range)。这两个运算符只接受整数作为参数。它的结果是一个`java.util.List`实例。 使用`to`可以定义一个包含头和尾的范围,使用`until`可以定义一个只包含头,不包含尾的范围: ```scala oneToTen = 1 to 10 /* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */ oneToNine = 1 until 10 /* [1, 2, 3, 4, 5, 6, 7, 8, 9] */ ``` range也支持尾比头更小: ```scala tenToOne = 10 to 1 /* [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] */ tenToTwo = 10 to 1 /* [10, 9, 8, 7, 6, 5, 4, 3, 2] */ ``` >范围的实现基于“隐式类型转换”,Latte默认定义的RichInt提供了`to`和`until`方法。 <h2 id="p5-3">5.3 类型检查与转换</h2> <h3 id="p5-3-1">5.3.1 类型检查</h3> Latte为静态类型和动态类型混合的语言。总体来说,类型检查比较宽松,并且不一定在编译期检查。 Latte不要求显式转换,在赋值、方法return时,值会自动的尝试转换为需要的类型。 ```kotlin class Base class Sub:Base var x:Base = Sub var y:Sub = x ``` 其中在赋值给`y`时,自动增加了一个类型转换。 <h3 id="p5-3-2">5.3.2 类型转换</h3> 在调用方法时,自动转换并不会做,因为并不确定变量的类型,也不确定方法参数需要哪种类型。 如果编译期没有找到方法,则会在运行时再获取参数对象的类型并进行方法的寻找。如果一定要在编译期确定调用何种方法,可以手动转换类型。 ```kotlin class Data i:int def setI(i:int) { this.i=i } fun call(x) var data:Data = Data data.setI(x as int) ``` 上述例子中,x类型不确定,但是可以显式地转化为int。 <h2 id="p5-4">5.4 运算符绑定</h2> Latte支持运算符“绑定”。Latte的运算符绑定策略非常简单。每个运算符都看作方法调用。`a+b`看作`a.add(b)`,`a*b`看作`a.multiply(b)`,`!a`看作`a.not()` 这些运算符绑定依照`BigInteger`和`BigDecimal`的命名,所以你可以直接使用运算符来计算大数。 ```kotlin a = BigInteger(3) b = BigInteger(4) c = a + b ``` 若需要绑定运算符,只需要写出签名相符的方法即可,例如定义一个`Rational`类来表示分数: ```kotlin class Rational(a, b) add(that: Rational)=Rational(this.a * that.b + that.a * this.b, this.a * that.b) toString():String="${a}/${b}" a = Rational(1, 4) /* 1/4 */ b = Rational(3, 7) /* 3/7 */ c = a + b /* 19/28 */ ``` 有一些运算符是“复合”的,即:它们可以由多个操作构成。例如`++a`,就可以由`(a = a + 1 , return a)`构成。这类运算符不提供绑定,如果有需要,请绑定它们的展开式用到的运算符。 下表描述了所有提供绑定的运算符,以及一些展开式规则: | 运算符 | 方法签名 | |----------|-------------------------| | a:::b | a.concat(b) | | a * b | a.multiply(b) | | a / b | a.divide(b) | | a % b | a.remainder(b) | | a + b | a.add(b) | | a - b | a.subtract(b) | | a << b | a.shiftLeft(b) | | a >> b | a.shiftRight(b) | | a >>> b | a.unsignedShiftRight(b) | | a > b | a.gt(b) | | a < b | a.lt(b) | | a >= b | a.ge(b) | | a <= b | a.le(b) | | a == b | a.eq(b) | | a != b | !a.ne(b) | | a in b | b.contains(a) | | a & b | a.`and`(b) | | a ^ b | a.xor(b) | | a | b | a.`or`(b) | | !a | a.logicNot() | | ~a | a.not() | | -a | a.negate() | | a\[0\] | a.get(0) | | a\[0, 1\] | a.get(0, 1) | > `+a` 这种用法在Latte中不对`+`做任何处理,当做`a` > 上面的`a[0, 1]`用法,如果a是一个二维数组,则相当于java的`a[0][1]` > Latte对所有对象均可隐式转换到`RichObject`,在其中提供了`==`和`!=`的绑定,其中会调用对象的`equals`方法 Latte的运算符优先级和Java完全一致,而Latte特有的运算符优先级如下: * `in` 和 `==` 优先级相同 * `:::` 优先级最高 由于`==`被绑定到equals方法,所以检查引用相同使用`===`,引用不同使用`!==`。 此外,Latte还提供两个运算符`is`和`not`,它除了可以检查引用、equals,在右侧对象是一个Class实例时还可以检查左侧对象是否为右侧对象的实例。 > 虽然`==`绑定到equals方法,但是如果写为`null==x`,编译器能够知道左侧一定为null,这时会检查null值而不是调用equals > `!=`同理。 | 运算符 | 展开式 | |--------|----------------------------------| | a?=b | a = a ? b | | a++ | tmp = a , a = a + 1 , return tmp | | ++a | a = a + 1 , return a | | a-- | tmp = a , a = a - 1 , return tmp | | --a | a = a - 1 , return a | > 其中`?=`的`?`代表任何二元运算符 --- Latte中,和普通的方法调用不同,运算符前不需要附加`.`,也不需要对参数包裹括号。但是因为Latte的运算符和方法调用是一回事,所以为了一致性,普通方法调用也可以将方法名看作运算符来书写: ```scala list isEmpty // list.isEmpty() map put "Feb", 2 // map.put("Feb", 2) .println o // println(o) ``` 使用逗号分隔多个参数。使用`.`表示直接调用方法(而不是在某个对象或者某个类上调用)。 <h2 id="p5-5">5.5 异常</h2> Latte和Java总体上是类似的,但是仍有多处不同: * Latte没有`checked exception` * Latte可以`throw`任何类型的对象,比如`throw 'error-message'` * Latte可以`catch`任何类型的对象 * 由于上一条,Latte不提供`catch(Type e)`这种写法,需使用if-elseif-else来处理 ```kotlin fun isGreaterThanZero(x) if x <= 0 { throw '${x} is littler than 0' } var a = -1 try isGreaterThanZero(a) catch e e.toCharArray /* succeed. `e` is a String */ finally a = 1 ``` <h2 id="p5-6">5.6 注解</h2> Latte使用`annotation`关键字定义注解 ```kotlin annotation Anno a:int = 1 b:long ``` Latte中的注解默认为运行时可见的(而Java中默认不可见)。 可以使用`java::lang::annotation::Retention`注解重新规定可见性。 同时默认为可以标注在所有地方(和Java一样)。 可以使用`java::lang::annotation::Target`注解重新规定标注位置。 > 因为annotation是一个关键字,所以导入包时需要用 点号 包围 `annotation`这个单词。 --- Latte的注解使用方式和Java一致 ```kotlin class PrintSelf @Override toString():String='PrintSelf' ``` 不过有一点要注意,Latte的注解不能和其所标注的对象在同一行,除非加一个逗号,比如: ```scala @Anno1,@Anno2,method()=... ``` 和Java一样,注解的value参数可以省略`value`这个键本身。 ```java @Value1('value') @Value2(value='value') ``` <h2 id="p5-7">5.7 过程(Procedure)</h2> Latte支持把一组语句当做一个值,这个特性称作“过程”。 过程由小括号开始,小括号结束。 用这个特性可以省略不必要的中间变量声明。 ```kotlin class Rational(a, b) toString():String = a + ( if b == 1 return "" else return "/" + b ) ``` 过程最终也是编译为“方法”的,可以省略最后的`return`,所以可以写为: ```kotlin ;; :scanner-brace class Rational(a, b) toString():String = a + ( if b==1 {""} else {"/" + b} ) ``` <h2 id="p5-8">5.8 参数可用性检查</h2> Latte支持**参数**上的null值或“空”值检查,分别使用`nonnull`和`nonempty`修饰符。 由于Latte的`Unit`方法也返回一个值(`Unit`),所以在`nonnull`中不光会检查null值,还会检查Unit。 如果出现null则会立即抛出`java.lang.NullPointerException`异常 如果出现Unit则会立即抛出`java.lang.IllegalArgumentException`异常 ```scala def add(nonnull a, nonnull b)= a + b add(null, 1) /* 抛出NullPointerException */ add(Unit, 2) /* 抛出IllegalArgumentException */ ``` 对于`nonempty`,检查的范围更广。首先Latte会将这个值转换为`bool`类型(Latte中任何类型都可以转为bool) 如果结果为`false`则会抛出异常`java.lang.IllegalArgumentException` ```scala def listNotEmpty(nonempty list) listNotEmpty([]) /* 抛出 IllegalArgumentException */ ``` 在转换为`bool`时,Latte会尝试 1. 如果是null,则返回false 2. 如果是Unit,则返回false 3. 如果是Boolean类型,则返回其对应的`bool`值 4. 如果是数字类型,则:如果转换为`double`的结果是0,那么返回false,否则返回true 5. 如果是Character类型,则:如果转换为`int`的结果是0,那么返回false,否则返回true 6. 如果这个对象带有`def isEmpty:bool`或者`def isEmpty:Boolean`方法,那么调用之,并返回相应结果 7. 返回true <h2 id="p5-9">5.9 解构</h2> <h3 id="p5-9-1">5.9.1 解构用法</h3> 解构指的是将一个对象分解为其组成部分的多个对象。 例如有如下定义和实例化: ```kotlin data class Bean(a,b) val bean = Bean(1,2) ``` 可以知道,bean是由`1`和`2`组成的,它应当被分解为(1,2)。 Latte提供这样简化的分解: ```scala val (x,y) = bean ``` 定义了x和y,并分别赋值为1、2。 <h3 id="p5-9-2">5.9.2 解构实现方式</h3> 使用解构,首先需要定义一个static方法`unapply`: ```java class X { static { unapply(o)=... } } ``` 这个方法需要接受一个参数,表示被解构的对象,并返回`null`或一个`java::util::List`实例。 如果返回`null`则说明解构失败,如果返回`List`实例,则表示会被分解为存在于列表中的对象。 如果解构失败,则解构表达式返回`false`,否则返回`true`。 可以指定使用“带有unapply方法的类”来执行解构: ```scala Bean(x,y) <- bean ``` 如果没有指定,则尝试使用右侧对象的类中的unapply方法进行解构。 ```scala (x,y) <- bean /* 相当于 Bean(x,y) <- bean */ ``` 如果没有指定类型,则可以将`<-`替换为`=`。 解构可以放在`if`中使用: ```scala if List(a,b,c) <- o println("result is ${a},${b},${c}") else println("destruct failed!") ``` <h2 id="p5-10">5.10 模式匹配</h2> 和`scala`一样,`Latte`不提供`java`的`switch`语句,但是提供更强大的模式匹配。 ```scala def doMatch(o) = o match case 1 => ... /* 根据值匹配 */ case b:Apple => ... /* 检查类型并定义一个新的变量 */ case _:Banana => ... /* 根据类型匹配 */ case Bean(x,y) => ... /* 根据解构匹配 */ case Bean(1, Bean(x, _:Integer)) => ... /* 多重模式 */ case Bean(x,y) if x > 0 => ... /* 解构后再做判断 */ case _ => ... /* 匹配所有(默认行为) */ ``` 模式匹配会从上到下依次尝试匹配。如果匹配成功则进入该分支执行语句,最终返回一个值(也可能返回`Unit`)。如果匹配失败,则会抛出`lt::lang::MatchError`。 任何匹配模式都可以添加if语句,仅当if判断成立时才会进入执行。 <h1 id="p6">6. Java交互</h1> 在设计时就考虑了Latte和Java的互操作。所以它们基本是无缝衔接的。 <h2 id="p6-1">6.1 在Latte中调用Java代码</h2> 实际上这里不会出现任何问题。Latte源代码最终是编译到Java字节码的,所以Latte调用Java就像Latte调用自己一样。 而设计时也考虑到了互通性,几乎所有Latte特性都可以通过编写Java源代码来模拟。 这里给出一些Latte与Java相同语义的表达: ### 1. 规定变量和它的类型 在Field操作时会有交互。 java: ```java Integer integer; List list; final int anInt; Object obj; ``` latte: ```scala integer : Integer list : List val anInt : int obj ``` Latte可以使用`var`表示可变变量,不过也可以不写,默认即为可变变量。Object类型不需要写,同样也是默认值。 ### 2. 定义方法、参数类型和返回类型 在调用方法时会有交互。 java: ```java void method1() {} Object method2() { return null; } int method3(int x) { return x; } ``` latte: ```kotlin method1():Unit=... method2()=null method3(x:int):int = x ``` ### 3. 获取java类,判断类型 java: ```java Class c = Object.class; if (s instanceof String) {} ``` latte: ```typescript c = type Object if s is type String ``` <h2 id="p6-2">6.2 在Java中调用Latte代码</h2> 如果是已编译的Latte二进制文件,那么加载到class-path中,直接在Java中调用即可。Latte在设计时非常小心的不暴露任何“不一致状态”给Java,所以除了反射访问private外,尽管放心的调用吧。 <h3 id="p6-2-1">6.2.1 在Java中编译Latte</h3> 如果是Latte源文件,则需要使用Latte-compiler编译。 ```java import lt.repl.Compiler; Compiler compiler = new Compiler(); ClassLoader cl = compiler.compile(new HashMap<String, Reader>(){{ put('source-name.lt', new InputStreamReader(...)); }}); Class<?> cls = cl.loadClass('...'); ``` <h3 id="p6-2-2">6.2.2 在Java中执行eval</h3> Latte支持`eval`,在latte代码中`eval('...')`即可。在Java中,你也可以直接调用 ```java lt.lang.Utils.eval("[\"id\":1,\"lang\":\"java\"]"); ``` 或者使用`Evaluator`获取完整的eval支持: ```java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); Evaluator evaluator = new Evaluator(new ClassPathLoader(Thread.currentThread().getContextClassLoader())); evaluator.setScannerType(Evaluator.SCANNER_TYPE_BRACE); evaluator.put("list", list); // 把list对象放进Evaluator上下文中 Evaluator.Entry entry = evaluator.eval("" + "import java::util::stream::Collectors._\n" + "list.stream.filter{it > 0}.collect(toList())"); List newList = (List) entry.result; // newList is [3, 4, 5] ``` <h3 id="p6-2-3">6.2.3 在Java中执行Latte脚本</h3> Latte支持脚本,脚本以源代码形式呈现。所以你可以构造一个`ScriptCompiler`来执行并取得脚本结果。 ```java ScriptCompiler.Script script = scriptCompiler.compile("script", "return 1"); script.run().getResult(); // 或者 run(new String[]{...}) 来指定启动参数 ``` ScriptCompiler有多个`compile`的重载,各种情况都可以方便的调用。
wkgcass/LessTyping
mannual-zh.md
Markdown
mit
49,942
<?xml version="1.0" ?><!DOCTYPE TS><TS language="th_TH" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Linkcoin</source> <translation>เกี่ยวกับ บิตคอย์น</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Linkcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;บิตคอย์น&lt;b&gt;รุ่น</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Linkcoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>สมุดรายชื่อ</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>ดับเบิลคลิก เพื่อแก้ไขที่อยู่ หรือชื่อ</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>สร้างที่อยู่ใหม่</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Linkcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Linkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Linkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>ลบ</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Linkcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>ส่งออกรายชื่อทั้งหมด</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>ส่งออกผิดพลาด</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>ใส่รหัสผ่าน</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>รหัสผา่นใหม่</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>กระเป๋าสตางค์ที่เข้ารหัส</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>เปิดกระเป๋าสตางค์</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>ถอดรหัสกระเป๋าสตางค์</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>เปลี่ยนรหัสผ่าน</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>กรอกรหัสผ่านเก่าและรหัสผ่านใหม่สำหรับกระเป๋าสตางค์</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation> </message> <message> <location line="-56"/> <source>Linkcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your linkcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about Linkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Linkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Linkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Linkcoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Linkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Linkcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Linkcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Linkcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Linkcoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Linkcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Linkcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Linkcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Linkcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Linkcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Linkcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Linkcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Linkcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Linkcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Linkcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Linkcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Linkcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start linkcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Linkcoin-Qt help message to get a list with possible Linkcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Linkcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Linkcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Linkcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Linkcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Linkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Linkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Linkcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Linkcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation>วันนี้</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>ส่งออกผิดพลาด</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Linkcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or linkcoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: linkcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: linkcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=linkcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Linkcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Linkcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Linkcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Linkcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Linkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Linkcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Linkcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
Linkproject/winpro
src/qt/locale/bitcoin_th_TH.ts
TypeScript
mit
97,840
#region Using directives using System; using System.Data; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Data; #endregion namespace Nettiers.AdventureWorks.Data.Bases { ///<summary> /// This class is the base class for any <see cref="SalesOrderHeaderSalesReasonProviderBase"/> implementation. /// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures. ///</summary> public abstract partial class SalesOrderHeaderSalesReasonProviderBase : SalesOrderHeaderSalesReasonProviderBaseCore { } // end class } // end namespace
netTiers/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data/Bases/SalesOrderHeaderSalesReasonProviderBase.cs
C#
mit
735
# Be sure to restart your server when you modify this file. Hypermedia::Application.config.session_store :cookie_store, key: '_hypermedia_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Hypermedia::Application.config.session_store :active_record_store
oestrich/hypermedia_rails
config/initializers/session_store.rb
Ruby
mit
422
#ifndef ANONCOIN_MINER_H #define ANONCOIN_MINER_H #include <stdint.h> typedef long long int64; typedef unsigned long long uint64; class CBlock; class CBlockHeader; class CBlockIndex; struct CBlockTemplate; class CReserveKey; class CScript; #ifdef ENABLE_WALLET class CWallet; void AnoncoinMiner(CWallet *pwallet); #endif /** Run the miner threads */ void GenerateAnoncoins(bool fGenerate, CWallet* pwallet); /** Generate a new block, without valid proof-of-work */ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn); CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey); /** Modify the extranonce in a block */ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); /** Do mining precalculation */ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1); /** Check mined block */ bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey); /** Base sha256 mining transform */ void SHA256Transform(void* pstate, void* pinput, const void* pinit); #endif
coinkeeper/2015-06-22_18-30_anoncoin
src/miner.h
C
mit
1,063
<TS language="hi_IN" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation> </message> <message> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <source>FairCoin</source> <translation>बीटकोइन</translation> </message> <message> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> <message> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>संस्करण</translation> </message> <message> <source>Usage:</source> <translation>खपत :</translation> </message> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>भूल</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>विकल्प</translation> </message> <message> <source>W&amp;allet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>फार्म</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>N/A</source> <translation>लागू नही </translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <source>&amp;Information</source> <translation>जानकारी</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>राशि :</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Pay To:</source> <translation>प्राप्तकर्ता:</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Transaction ID</source> <translation>ID</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>true</source> <translation>सही</translation> </message> <message> <source>false</source> <translation>ग़लत</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Type</source> <translation>टाइप</translation> </message> <message> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <source>Mined</source> <translation>माइंड</translation> </message> <message> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>सभी</translation> </message> <message> <source>Today</source> <translation>आज</translation> </message> <message> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <source>This month</source> <translation>इस महीने</translation> </message> <message> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <source>This year</source> <translation>इस साल</translation> </message> <message> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <source>Mined</source> <translation>माइंड</translation> </message> <message> <source>Other</source> <translation>अन्य</translation> </message> <message> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Type</source> <translation>टाइप</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> </context> <context> <name>WalletView</name> <message> <source>Backup Wallet</source> <translation>बैकप वॉलेट</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>वॉलेट डेटा (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>बैकप असफल</translation> </message> <message> <source>Backup Successful</source> <translation>बैकप सफल</translation> </message> </context> <context> <name>FairCoin-core</name> <message> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <source>Specify data directory</source> <translation>डेटा डायरेक्टरी बताएं </translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation> </message> <message> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> </context> </TS>
faircoin/faircoin2
src/qt/locale/bitcoin_hi_IN.ts
TypeScript
mit
30,726
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SecurityRulesOperations operations. /// </summary> internal partial class SecurityRulesOperations : IServiceOperations<NetworkManagementClient>, ISecurityRulesOperations { /// <summary> /// Initializes a new instance of the SecurityRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SecurityRulesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified network security rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='securityRuleName'> /// The name of the security rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get the specified network security rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='securityRuleName'> /// The name of the security rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (securityRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("securityRuleName", securityRuleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SecurityRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a security rule in the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='securityRuleName'> /// The name of the security rule. /// </param> /// <param name='securityRuleParameters'> /// Parameters supplied to the create or update network security rule /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<SecurityRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all security rules in a network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SecurityRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified network security rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='securityRuleName'> /// The name of the security rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (securityRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("securityRuleName", securityRuleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a security rule in the specified network security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='securityRuleName'> /// The name of the security rule. /// </param> /// <param name='securityRuleParameters'> /// Parameters supplied to the create or update network security rule /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName"); } if (securityRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName"); } if (securityRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters"); } if (securityRuleParameters != null) { securityRuleParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName); tracingParameters.Add("securityRuleName", securityRuleName); tracingParameters.Add("securityRuleParameters", securityRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName)); _url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(securityRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(securityRuleParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SecurityRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all security rules in a network security group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SecurityRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
ayeletshpigelman/azure-sdk-for-net
sdk/network/Microsoft.Azure.Management.Network/src/Generated/SecurityRulesOperations.cs
C#
mit
51,940
// © 2000 NEOSYS Software Ltd. All Rights Reserved.//**Start Encode** function form_postinit() { //enable/disable password changing button neosyssetexpression('button_password', 'disabled', '!gusers_authorisation_update&&gkey!=gusername') //force retrieval of own record if (gro.dictitem('USER_ID').defaultvalue) window.setTimeout('focuson("USER_NAME")', 100) gwhatsnew = neosysgetcookie(glogincode, 'NEOSYS2', 'wn').toLowerCase() if (gwhatsnew) { if (window.location.href.toString().slice(0, 5) == 'file:') gwhatsnew = 'file:///' + gwhatsnew else gwhatsnew = '..' + gwhatsnew.slice(gwhatsnew.indexOf('\\data\\')) neosyssetcookie(glogincode, 'NEOSYS2', '', 'wn') neosyssetcookie(glogincode, 'NEOSYS2', gwhatsnew, 'wn2') window.setTimeout('windowopen(gwhatsnew)', 1000) //windowopen(gwhatsnew) } $$('button_password').onclick = user_setpassword return true } //just to avoid confirmation function form_prewrite() { return true } //in authorisation.js and users.htm var gtasks_newpassword function form_postwrite() { //if change own password then login with the new one //otherwise cannot continue/unlock document so the lock hangs if (gtasks_newpassword) db.login(gusername, gtasks_newpassword) gtasks_newpassword = false //to avoid need full login to get new font/colors neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_BODY_COLOR'), 'fc') neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT'), 'ff') neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT_SIZE'), 'fs') return true } function users_postdisplay() { var signatureimageelement = document.getElementById('signature_image') if (signatureimageelement) { signatureimageelement.src = '' signatureimageelement.height = 0 signatureimageelement.width = 0 signatureimageelement.src = '../images/'+gdataset+'SHARP/UPLOAD/USERS/' + gkey.neosysconvert(' ', '') + '_signature.jpg' } //show only first five lines form_filter('refilter', 'LOGIN_DATE', '', 4) var reminderdays = 6 var passwordexpires = gds.getx('PASSWORD_EXPIRY_DATE') $passwordexpiryelement = $$('passwordexpiryelement') $passwordexpiryelement.innerHTML = '' if (passwordexpires) { var expirydays = (neosysint(passwordexpires) - neosysdate()) if (expirydays <= reminderdays) $passwordexpiryelement.innerHTML = '<font color=red>&nbsp;&nbsp;&nbsp;Password expires in ' + expirydays + ' days.</font>' } return true } function form_postread() { window.setTimeout('users_postdisplay()', 10) return true } function users_upload_signature() { //return openwindow('EXECUTE\r\MEDIA\r\OPENMATERIAL',scheduleno+'.'+materialletter) /* params=new Object() params.scheduleno=scheduleno params.materialletter=materialletter neosysshowmodaldialog('../NEOSYS/upload.htm',params) */ //images are not stored per dataset at the moment so that they can be //nor are they stored per file or per key so that they can be easily saved into a shared folder instead of going by web upload params = {} params.database = gdataset params.filename = 'USERS' params.key = gkey.neosysconvert(' ', '') + '_signature' params.versionno = ''//newarchiveno params.updateallowed = true params.deleteallowed = true //params.allowimages = true //we only allow one image type merely so that the signature file name //is always know and doesnt need saving in the user file //and no possibility of uploading two image files with different extensions params.allowablefileextensions = 'jpg' var targetfilename = neosysshowmodaldialog('../NEOSYS/upload.htm', params) window.setTimeout('users_postdisplay()', 1) if (!targetfilename) return false return true } function user_signature_onload(el) { el.removeAttribute("width") el.removeAttribute("height") }
tectronics/exodusdb
www/neosys/scripts/users.js
JavaScript
mit
4,156
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin // Author: Maxim Kuzmin using Autofac; using Autofac.Core; using Makc2017.Core.App; using System.Collections.Generic; using System.Linq; namespace Makc2017.Modules.Dummy.Caching { /// <summary> /// Модули. Модуль "Dummy". Кэширование. Плагин. /// </summary> public class ModuleDummyCachingPlugin : ModuleDummyPlugin { #region Properties /// <summary> /// Конфигурация кэширования. /// </summary> private ModuleDummyCachingConfig CachingConfig { get; set; } #endregion Properties #region Public methods /// <summary> /// Инициализировать. /// </summary> /// <param name="pluginEnvironment">Окружение плагинов.</param> public sealed override void Init(CoreAppPluginEnvironment pluginEnvironment) { base.Init(pluginEnvironment); CachingConfig.Init(ConfigurationProvider); } /// <summary> /// Распознать зависимости. /// </summary> /// <param name="componentContext">Контекст компонентов.</param> public sealed override void Resolve(IComponentContext componentContext) { base.Resolve(componentContext); CachingConfig = componentContext.Resolve<ModuleDummyCachingConfig>(); } #endregion Public methods #region Protected methods /// <summary> /// Создать распознаватель зависимостей. /// </summary> /// <returns>Распознаватель зависимостей.</returns> protected sealed override IModule CreateResolver() { return new ModuleDummyCachingResolver(); } /// <summary> /// Создать пути к файлам конфигурации. /// </summary> /// <returns>Пути к файлам конфигурации.</returns> protected sealed override IEnumerable<string> CreateConfigFilePaths() { return base.CreateConfigFilePaths().Concat(new[] { @"Makc2017.Modules.Dummy.Caching\config.json" }); } #endregion Protected methods } }
maxim-kuzmin/Makc2017
src/Makc2017.Modules.Dummy.Caching/ModuleDummyCachingPlugin.cs
C#
mit
2,426
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export { AnimationDriver, ɵAnimation, ɵAnimationStyleNormalizer, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsStyleNormalizer, ɵAnimationDriver, ɵNoopAnimationDriver, ɵAnimationEngine, ɵCssKeyframesDriver, ɵCssKeyframesPlayer, ɵcontainsElement, ɵinvokeQuery, ɵmatchesElement, ɵvalidateStyleProperty, ɵWebAnimationsDriver, ɵsupportsWebAnimations, ɵWebAnimationsPlayer, ɵallowPreviousPlayerStylesMerge } from './src/browser'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFhQSx1WkFBYyxlQUFlLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8qKlxuICogQG1vZHVsZVxuICogQGRlc2NyaXB0aW9uXG4gKiBFbnRyeSBwb2ludCBmb3IgYWxsIHB1YmxpYyBBUElzIG9mIHRoaXMgcGFja2FnZS5cbiAqL1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvYnJvd3Nlcic7XG4iXX0=
friendsofagape/mt2414ui
node_modules/@angular/animations/esm2015/browser/public_api.js
JavaScript
mit
1,618
package queue; /** * Queue server metadata manager. * * @author Thanh Nguyen <[email protected]> * @since 0.1.0 */ public interface IQsMetadataManager { }
kangkot/queue-server
app/queue/IQsMetadataManager.java
Java
mit
166
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Routing\Generator; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Exception\InvalidParameterException; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; use Psr\Log\LoggerInterface; /** * UrlGenerator can generate a URL or a path for any route in the RouteCollection * based on the passed parameters. * * @author Fabien Potencier <[email protected]> * @author Tobias Schultze <http://tobion.de> */ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface { protected $routes; protected $context; /** * @var bool|null */ protected $strictRequirements = true; protected $logger; /** * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL. * * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g. * "?" and "#" (would be interpreted wrongly as query and fragment identifier), * "'" and """ (are used as delimiters in HTML). */ protected $decodedChars = array( // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning // some webservers don't allow the slash in encoded form in the path for security reasons anyway // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss '%2F' => '/', // the following chars are general delimiters in the URI specification but have only special meaning in the authority component // so they can safely be used in the path in unencoded form '%40' => '@', '%3A' => ':', // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability '%3B' => ';', '%2C' => ',', '%3D' => '=', '%2B' => '+', '%21' => '!', '%2A' => '*', '%7C' => '|', ); public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null) { $this->routes = $routes; $this->context = $context; $this->logger = $logger; } /** * {@inheritdoc} */ public function setContext(RequestContext $context) { $this->context = $context; } /** * {@inheritdoc} */ public function getContext() { return $this->context; } /** * {@inheritdoc} */ public function setStrictRequirements($enabled) { $this->strictRequirements = null === $enabled ? null : (bool) $enabled; } /** * {@inheritdoc} */ public function isStrictRequirements() { return $this->strictRequirements; } /** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { if (null === $route = $this->routes->get($name)) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name)); } // the Route has a cache of its own and is not recompiled as long as it does not get modified $compiledRoute = $route->compile(); return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes()); } /** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()) { if (is_bool($referenceType) || is_string($referenceType)) { @trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED); if (true === $referenceType) { $referenceType = self::ABSOLUTE_URL; } elseif (false === $referenceType) { $referenceType = self::ABSOLUTE_PATH; } elseif ('relative' === $referenceType) { $referenceType = self::RELATIVE_PATH; } elseif ('network' === $referenceType) { $referenceType = self::NETWORK_PATH; } } $variables = array_flip($variables); $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters); // all params must be given if ($diff = array_diff_key($variables, $mergedParams)) { throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name)); } $url = ''; $optional = true; foreach ($tokens as $token) { if ('variable' === $token[0]) { if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) { // check requirement if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $url = $token[1].$mergedParams[$token[3]].$url; $optional = false; } } else { // static text $url = $token[1].$url; $optional = false; } } if ('' === $url) { $url = '/'; } // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request) $url = strtr(rawurlencode($url), $this->decodedChars); // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3 // so we need to encode them as they are not used for this purpose here // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/')); if ('/..' === substr($url, -3)) { $url = substr($url, 0, -2).'%2E%2E'; } elseif ('/.' === substr($url, -2)) { $url = substr($url, 0, -1).'%2E'; } $schemeAuthority = ''; if ($host = $this->context->getHost()) { $scheme = $this->context->getScheme(); if ($requiredSchemes) { if (!in_array($scheme, $requiredSchemes, true)) { $referenceType = self::ABSOLUTE_URL; $scheme = current($requiredSchemes); } } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) { // We do this for BC; to be removed if _scheme is not supported anymore $referenceType = self::ABSOLUTE_URL; $scheme = $req; } if ($hostTokens) { $routeHost = ''; foreach ($hostTokens as $token) { if ('variable' === $token[0]) { if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) { $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]); if ($this->strictRequirements) { throw new InvalidParameterException($message); } if ($this->logger) { $this->logger->error($message); } return; } $routeHost = $token[1].$mergedParams[$token[3]].$routeHost; } else { $routeHost = $token[1].$routeHost; } } if ($routeHost !== $host) { $host = $routeHost; if (self::ABSOLUTE_URL !== $referenceType) { $referenceType = self::NETWORK_PATH; } } } if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) { $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { $port = ':'.$this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { $port = ':'.$this->context->getHttpsPort(); } $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://"; $schemeAuthority .= $host.$port; } } if (self::RELATIVE_PATH === $referenceType) { $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority.$this->context->getBaseUrl().$url; } // add a query string if needed $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) { return $a == $b ? 0 : 1; }); if ($extra && $query = http_build_query($extra, '', '&')) { // "/" and "?" can be left decoded for better user experience, see // http://tools.ietf.org/html/rfc3986#section-3.4 $url .= '?'.strtr($query, array('%2F' => '/')); } return $url; } /** * Returns the target path as relative reference from the base path. * * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash. * Both paths must be absolute and not contain relative parts. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. * Furthermore, they can be used to reduce the link size in documents. * * Example target paths, given a base path of "/a/b/c/d": * - "/a/b/c/d" -> "" * - "/a/b/c/" -> "./" * - "/a/b/" -> "../" * - "/a/b/c/other" -> "other" * - "/a/x/y" -> "../../x/y" * * @param string $basePath The base path * @param string $targetPath The target path * * @return string The relative target path */ public static function getRelativePath($basePath, $targetPath) { if ($basePath === $targetPath) { return ''; } $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath); array_pop($sourceDirs); $targetFile = array_pop($targetDirs); foreach ($sourceDirs as $i => $dir) { if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) { unset($sourceDirs[$i], $targetDirs[$i]); } else { break; } } $targetDirs[] = $targetFile; $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs); // A reference to the same base directory or an empty subdirectory must be prefixed with "./". // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used // as the first segment of a relative-path reference, as it would be mistaken for a scheme name // (see http://tools.ietf.org/html/rfc3986#section-4.2). return '' === $path || '/' === $path[0] || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; } }
BaderLab/openPIP
vendor/symfony/symfony/src/Symfony/Component/Routing/Generator/UrlGenerator.php
PHP
mit
13,796
'use strict'; const path = require('path'), mongoose = require('mongoose'), Promise = require('bluebird'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), _ = require('lodash'); mongoose.Promise = Promise; const User = mongoose.model('User'); const Project = mongoose.model('Project'); /** * Patch Update User Fields */ exports.patchUser = (req, res) => { _.extend(req.model, req.body) .save() .then(updatedUser => { res.jsonp(updatedUser); }) .catch(err => { console.error('ERROR on patch update for user `err`:\n', err); res.status(400).send({ message: errorHandler.getErrorMessage(err) }); }); }; /** * Return list of projects by contributor - query param `publishedOnly`, if true, returns only published projects * * @param req * @param req.query.publishedOnly * @param res */ exports.getContributorProjects = (req, res) => { const projectIdsArray = []; const projectsArray = []; req.model.associatedProjects.map(assocProjId => { projectIdsArray.push(assocProjId); }); Project.find({ '_id': { $in: projectIdsArray } }) .then(projects => { if (req.query.publishedOnly===true) { projects.map(project => { if(project.status[0]==='published') { projectsArray.push(project); } }); projects = projectsArray; } res.jsonp(projects); }) .catch(err => { console.error('error:\n', err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); }); };
mapping-slc/mapping-slc
modules/users/server/controllers/admin.v2.server.controller.js
JavaScript
mit
1,576
using System.Linq; using System.Threading.Tasks; using JSONAPI.Documents; using Newtonsoft.Json; namespace JSONAPI.Json { /// <summary> /// Default implementation of ISingleResourceDocumentFormatter /// </summary> public class SingleResourceDocumentFormatter : ISingleResourceDocumentFormatter { private readonly IResourceObjectFormatter _resourceObjectFormatter; private readonly IMetadataFormatter _metadataFormatter; private const string PrimaryDataKeyName = "data"; private const string RelatedDataKeyName = "included"; private const string MetaKeyName = "meta"; /// <summary> /// Creates a SingleResourceDocumentFormatter /// </summary> /// <param name="resourceObjectFormatter"></param> /// <param name="metadataFormatter"></param> public SingleResourceDocumentFormatter(IResourceObjectFormatter resourceObjectFormatter, IMetadataFormatter metadataFormatter) { _resourceObjectFormatter = resourceObjectFormatter; _metadataFormatter = metadataFormatter; } public Task Serialize(ISingleResourceDocument document, JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName(PrimaryDataKeyName); _resourceObjectFormatter.Serialize(document.PrimaryData, writer); if (document.RelatedData != null && document.RelatedData.Any()) { writer.WritePropertyName(RelatedDataKeyName); writer.WriteStartArray(); foreach (var resourceObject in document.RelatedData) { _resourceObjectFormatter.Serialize(resourceObject, writer); } writer.WriteEndArray(); } if (document.Metadata != null) { writer.WritePropertyName(MetaKeyName); _metadataFormatter.Serialize(document.Metadata, writer); } writer.WriteEndObject(); return Task.FromResult(0); } public async Task<ISingleResourceDocument> Deserialize(JsonReader reader, string currentPath) { if (reader.TokenType != JsonToken.StartObject) throw new DeserializationException("Invalid document root", "Document root is not an object!", currentPath); IResourceObject primaryData = null; IMetadata metadata = null; while (reader.Read()) { if (reader.TokenType != JsonToken.PropertyName) break; // Has to be a property name var propertyName = (string)reader.Value; reader.Read(); switch (propertyName) { case RelatedDataKeyName: // TODO: If we want to capture related resources, this would be the place to do it reader.Skip(); break; case PrimaryDataKeyName: primaryData = await DeserializePrimaryData(reader, currentPath + "/" + PrimaryDataKeyName); break; case MetaKeyName: metadata = await _metadataFormatter.Deserialize(reader, currentPath + "/" + MetaKeyName); break; default: reader.Skip(); break; } } return new SingleResourceDocument(primaryData, new IResourceObject[] { }, metadata); } private async Task<IResourceObject> DeserializePrimaryData(JsonReader reader, string currentPath) { if (reader.TokenType == JsonToken.Null) return null; var primaryData = await _resourceObjectFormatter.Deserialize(reader, currentPath); return primaryData; } } }
danshapir/JSONAPI.NET
JSONAPI/Json/SingleResourceDocumentFormatter.cs
C#
mit
3,963
/*jshint unused:false*/ var chai = require('chai'), expect = chai.expect; var request = require('supertest'); module.exports = function() { 'use strict'; this.Then(/^The JSON is returned by issuing a "GET" at the specified uri:$/, function(json, callback) { request(this.serverLocation) .get('/hello') .expect('Content-Type', /json/) .expect(200) .end(function(error, res) { if(error) { expect(false).to.equal(true, error); } else { expect(res.body).to.deep.equal(JSON.parse(json)); } callback(); }); }); };
bustardcelly/caddis
features/step_definitions/add-get.steps.js
JavaScript
mit
615
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; using System.Windows.Forms.Design; namespace DotSpatial.Symbology.Forms { /// <summary> /// FontFamilyNameEditor. /// </summary> public class FontFamilyNameEditor : UITypeEditor { #region Fields private IWindowsFormsEditorService _dialogProvider; #endregion #region Properties /// <summary> /// Gets a value indicating whether the drop down is resizeable. /// </summary> public override bool IsDropDownResizable => true; #endregion #region Methods /// <summary> /// Edits a value based on some user input which is collected from a character control. /// </summary> /// <param name="context">The type descriptor context.</param> /// <param name="provider">The service provider.</param> /// <param name="value">Not used.</param> /// <returns>The selected font family name.</returns> public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { _dialogProvider = provider?.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; ListBox cmb = new ListBox(); FontFamily[] fams = FontFamily.Families; cmb.SuspendLayout(); foreach (FontFamily fam in fams) { cmb.Items.Add(fam.Name); } cmb.SelectedValueChanged += CmbSelectedValueChanged; cmb.ResumeLayout(); _dialogProvider?.DropDownControl(cmb); string test = (string)cmb.SelectedItem; return test; } /// <summary> /// Gets the UITypeEditorEditStyle, which in this case is drop down. /// </summary> /// <param name="context">The type descriptor context.</param> /// <returns>The UITypeEditorEditStyle.</returns> public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } private void CmbSelectedValueChanged(object sender, EventArgs e) { _dialogProvider.CloseDropDown(); } #endregion } }
DotSpatial/DotSpatial
Source/DotSpatial.Symbology.Forms/FontFamilyNameEditor.cs
C#
mit
2,604
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>deprecation.rb</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" /> <script src="../../../../../../../../../../../../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../../../../../../../../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../../../../../../../../../../../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../../../../../../../../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.1.6</span><br /> <h1> deprecation.rb </h1> <ul class="files"> <li> ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.6/lib/active_support/core_ext/module/deprecation.rb </li> <li>Last modified: 2014-10-25 21:53:16 +1100</li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Namespace --> <div class="sectiontitle">Namespace</div> <ul> <li> <span class="type">MODULE</span> <a href="../../../../../../../../../../../../../../../../classes/ActiveSupport.html">ActiveSupport</a> </li> <li> <span class="type">CLASS</span> <a href="../../../../../../../../../../../../../../../../classes/Module.html">Module</a> </li> </ul> <!-- Methods --> </div> </div> </body> </html>
SeanYamaguchi/circle
doc/api/files/__/__/_rbenv/versions/2_1_0/lib/ruby/gems/2_1_0/gems/activesupport-4_1_6/lib/active_support/core_ext/module/deprecation_rb.html
HTML
mit
2,389
/* global sinon, setup, teardown */ /** * __init.test.js is run before every test case. */ window.debug = true; var AScene = require('aframe').AScene; beforeEach(function () { this.sinon = sinon.sandbox.create(); // Stub to not create a WebGL context since Travis CI runs headless. this.sinon.stub(AScene.prototype, 'attachedCallback'); }); afterEach(function () { // Clean up any attached elements. ['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) { var els = document.querySelectorAll(tagName); for (var i = 0; i < els.length; i++) { els[i].parentNode.removeChild(els[i]); } }); AScene.scene = null; this.sinon.restore(); });
donmccurdy/aframe-gamepad-controls
tests/__init.test.js
JavaScript
mit
664
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// /// Auto-generated by Stone, do not modify. /// #import <Foundation/Foundation.h> #import "DBSerializableProtocol.h" @class DBPAPERImportFormat; @class DBPAPERPaperDocCreateArgs; NS_ASSUME_NONNULL_BEGIN #pragma mark - API Object /// /// The `PaperDocCreateArgs` struct. /// /// This class implements the `DBSerializable` protocol (serialize and /// deserialize instance methods), which is required for all Obj-C SDK API route /// objects. /// @interface DBPAPERPaperDocCreateArgs : NSObject <DBSerializable, NSCopying> #pragma mark - Instance fields /// The Paper folder ID where the Paper document should be created. The API user /// has to have write access to this folder or error is thrown. @property (nonatomic, readonly, copy, nullable) NSString *parentFolderId; /// The format of provided data. @property (nonatomic, readonly) DBPAPERImportFormat *importFormat; #pragma mark - Constructors /// /// Full constructor for the struct (exposes all instance variables). /// /// @param importFormat The format of provided data. /// @param parentFolderId The Paper folder ID where the Paper document should be /// created. The API user has to have write access to this folder or error is /// thrown. /// /// @return An initialized instance. /// - (instancetype)initWithImportFormat:(DBPAPERImportFormat *)importFormat parentFolderId:(nullable NSString *)parentFolderId; /// /// Convenience constructor (exposes only non-nullable instance variables with /// no default value). /// /// @param importFormat The format of provided data. /// /// @return An initialized instance. /// - (instancetype)initWithImportFormat:(DBPAPERImportFormat *)importFormat; - (instancetype)init NS_UNAVAILABLE; @end #pragma mark - Serializer Object /// /// The serialization class for the `PaperDocCreateArgs` struct. /// @interface DBPAPERPaperDocCreateArgsSerializer : NSObject /// /// Serializes `DBPAPERPaperDocCreateArgs` instances. /// /// @param instance An instance of the `DBPAPERPaperDocCreateArgs` API object. /// /// @return A json-compatible dictionary representation of the /// `DBPAPERPaperDocCreateArgs` API object. /// + (nullable NSDictionary *)serialize:(DBPAPERPaperDocCreateArgs *)instance; /// /// Deserializes `DBPAPERPaperDocCreateArgs` instances. /// /// @param dict A json-compatible dictionary representation of the /// `DBPAPERPaperDocCreateArgs` API object. /// /// @return An instantiation of the `DBPAPERPaperDocCreateArgs` object. /// + (DBPAPERPaperDocCreateArgs *)deserialize:(NSDictionary *)dict; @end NS_ASSUME_NONNULL_END
wtanuw/WTLibrary-iOS
Example/Pods/ObjectiveDropboxOfficial/Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/Paper/Headers/DBPAPERPaperDocCreateArgs.h
C
mit
2,644
#container{ width: 750px; margin: 0 auto; text-align: left; } #header { position: relative; top:2px; } #menu{ float: left; width: 150px; } #anchorMenu{ position: fixed; top: auto; width: 8em; left: auto; margin: -2.5em 0 0 0; z-index: 5; overflow: hidden; padding-top: 20px; } #mainArea{ padding-top: 5px; float: left; width: 570px } #footer{ clear: both; text-align: center; font-size: 80%; padding-left: 33.3% } body{ text-align: center; font-family: arial; background: #FFF; padding: 0; } a:link, a:visited { display: block; color:rgb(41,136,126); text-decoration:none; background-color: #EBEBE6; width: 130px; text-align: left; padding: 3px; } a:hover, a:active { color: white; background-color:#7A991A; } a:hover.anchor, a:active.anchor { color: white; background-color:brown; } a.w3c{ width: 83px; } h2, h4{ margin: 8px; } ul li{ font-size: 15px; } table{ border:0px solid black; text-align: left; } td.padded{ border:0px solid black; padding: 0px 0px 38px 0px; width:25% } h3.headings{ text-align: left; } h4.subHead{ text-align:left; } p{ text-align:left; font-size: 15px; } p.profile{ text-align:left; font-weight: bold; font-size: 15px; } .center{ text-align: center; } .padded{ padding-left: 110px; }
mbonez006/me
initial-me/cs15020/mycss.css
CSS
mit
1,306
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Frames &mdash; Leap Motion C++ SDK v3.1 documentation</title> <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1471552333.css" type="text/css" /> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '3.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../cpp/_static/bootstrap-3.0.0/js/documentation-bundle.1471552333.js"></script> <link rel="top" title="Leap Motion C++ SDK v3.1 documentation" href="../index.html" /> <link rel="up" title="Using the Tracking API" href="Leap_Guides2.html" /> <link rel="next" title="Hands" href="Leap_Hand.html" /> <link rel="prev" title="Tracking Model" href="Leap_Tracking.html" /> <script type="text/javascript" src="/assets/standalone-header.js?r9"></script> <link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" /> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-31536531-1']); _gaq.push(['_setDomainName', 'leapmotion.com']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script> function getQueryValue(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); } var relPath = "../../"; var requestedAPI = getQueryValue("proglang"); if(requestedAPI == "current") requestedAPI = localStorage["currentAPI"]; var pageAPI = 'cpp'; var hasAPI = {}; hasAPI.cpp = true; hasAPI.objc = true; hasAPI.java = true; hasAPI.javascript = true; hasAPI.python = true; if(requestedAPI && (requestedAPI != pageAPI)) { if(pageAPI != 'none'){ var redirectedLocation = relPath + 'cpp/devguide/Leap_Frames.html'; if( requestedAPI == 'cpp' && hasAPI.cpp){ redirectedLocation = relPath + "cpp/devguide/Leap_Frames.html"; } else if( requestedAPI == 'csharp' && hasAPI.csharp){ redirectedLocation = relPath + "csharp/devguide/Leap_Frames.html"; } else if( requestedAPI == 'unity' && hasAPI.unity){ redirectedLocation = relPath + "unity/devguide/Leap_Frames.html"; } else if( requestedAPI == 'objc' && hasAPI.objc){ redirectedLocation = relPath + "objc/devguide/Leap_Frames.html"; } else if( requestedAPI == 'java' && hasAPI.java) { redirectedLocation = relPath + "java/devguide/Leap_Frames.html"; } else if( requestedAPI == 'javascript' && hasAPI.javascript){ redirectedLocation = relPath + "javascript/devguide/Leap_Frames.html"; } else if( requestedAPI == 'python' && hasAPI.python){ redirectedLocation = relPath + "python/devguide/Leap_Frames.html"; } else if( requestedAPI == 'unreal' && hasAPI.unreal) { redirectedLocation = relPath + "unreal/devguide/Leap_Frames.html"; } else { redirectedLocation ="Leap_Guides2.html"; } //Guard against redirecting to the same page (infinitely) if(relPath + 'cpp/devguide/Leap_Frames.html' != redirectedLocation) window.location.replace(redirectedLocation); } } </script> <script> window.addEventListener('keyup', handleKeyInput); function handleKeyInput(e) { var code; if (!e) var e = window.event; if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code); if( character == "J" & e.altKey){ window.location.assign("Leap_Tracking.html"); } else if( character == "K" & e.altKey){ window.location.assign("Leap_Hand.html"); } } </script> </head> <body role="document"> <div class="developer-portal-styles"> <header class="navbar navbar-static-top developer-navbar header beta-header"> <nav class="container pr"> <a class="logo-link pull-left" href="/"> <img alt="Leap Motion Developers" class="media-object pull-left white-background" src="../_static/logo.png" /> </a> <span class="inline-block hidden-phone developer-logo-text"> <div class="text"> <a href="/"> <span class="more-than-1199">Developer Portal</span> </a> </div> </span> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Everything within here will be hidden at 940px or less, accessible via a button. --> <div class="nav-collapse"> <ul class="nav header-navigation developer-links"> <li class="external-link"><a href="https://developer.leapmotion.com/features">What's new</a> </li> <li class="external-link"><a href="https://developer.leapmotion.com/downloads/skeletal-beta" class="">Getting Started</a></li> <li><a class="active" href="#" class="">Documentation</a></li> <li class="external-link"> <a href="https://developer.leapmotion.com/gallery" class="">Examples</a> </li> <li class="external-link"> <a href="https://www.leapmotion.com/blog/category/labs/" class="" target="_blank">Blog <i class='fa fa-external-link'></i></a> </li> <li class="external-link"> <a href="https://community.leapmotion.com/category/beta" class="" target="_blank">Community <i class='fa fa-external-link'></i></a> </li> </ul> </div> </nav> </header> </div> <section class="main-wrap"> <div data-swiftype-index="true"> <div class="second_navigation"> <div class="container"> <div class="row"> <div class="col-md-8"> <ul> <li> <a href="../../javascript/devguide/Leap_Frames.html?proglang=javascript" onclick="localStorage['currentAPI'] = 'javascript'">JavaScript</a> </li> <li> <a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'unity'">Unity</a> </li> <li> <a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'csharp'">C#</a> </li> <li> C++ </li> <li> <a href="../../java/devguide/Leap_Frames.html?proglang=java" onclick="localStorage['currentAPI'] = 'java'">Java</a> </li> <li> <a href="../../python/devguide/Leap_Frames.html?proglang=python" onclick="localStorage['currentAPI'] = 'python'">Python</a> </li> <li> <a href="../../objc/devguide/Leap_Frames.html?proglang=objc" onclick="localStorage['currentAPI'] = 'objc'">Objective-C</a> </li> <li> <a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'unreal'">Unreal</a> </li> </ul> </div> <div class="col-md-4 search"> <script> function storeThisPage(){ sessionStorage["pageBeforeSearch"] = window.location; return true; } function doneWithSearch(){ var storedPage = sessionStorage["pageBeforeSearch"]; if(storedPage){ window.location = storedPage; } else { window.location = "index.html"; //fallback } return false; } </script> <div style="margin-top:-4px"> <ul style="display:inline; white-space:nowrap"><li> <form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()"> <div class="form-group"> <input type="search" results="5" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form></li> </ul> </div> </div> </div> </div> </div> <script> //Remove dev portal header and footer when viewing from file system if(window.location.protocol == 'file:'){ var navNode = document.querySelector(".developer-links"); navNode.parentNode.removeChild(navNode); } </script> <div id="wrap" data-spy="scroll" data-target="#sidebar"> <div class="container"> <div class="row"> <div class="col-md-9 pull-right"> <!-- <span id="breadcrumbs"> <a href="../index.html">Home</a>&raquo; <a href="Leap_Guides2.html" accesskey="U">Using the Tracking API</a>&raquo; Frames </span> --> <div class="section" id="frames"> <h1>Frames<a class="headerlink" href="#frames" title="Permalink to this headline">¶</a></h1> <p>The Leap Motion API presents motion tracking data to your application as a series of snapshots called <em>frames</em>. Each frame of tracking data contains the measured positions and other information about each entity detected in that snapshot. This article discusses the details of getting <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> objects from the Leap Motion controller.</p> <div class="section" id="overview"> <h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2> <p>Each <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> object contains an instantaneous snapshot of the scene recorded by the Leap Motion controller. Hands, fingers, and tools are the basic physical entities tracked by the Leap Motion system.</p> <p>Get a <tt class="docutils literal"><span class="pre">Frame</span></tt> object containing tracking data from a connected <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object. You can get a frame whenever your application is ready to process it using the <cite>frame()</cite> method of the <tt class="docutils literal"><span class="pre">Controller</span></tt> class:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="k">if</span><span class="p">(</span> <span class="n">controller</span><span class="p">.</span><span class="n">isConnected</span><span class="p">())</span> <span class="c1">//controller is a Controller object</span> <span class="p">{</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span> <span class="c1">//The latest frame</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">previous</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">//The previous frame</span> <span class="p">}</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">frame()</span></tt> function takes a <tt class="docutils literal"><span class="pre">history</span></tt> parameter that indicates how many frames back to retrieve. The last 60 frames are maintained in the history buffer (but don&#8217;t rely on this exact value, it could change in the future).</p> <p><strong>Note:</strong> Ordinarily consecutive frames have consecutively increasing ID values. However, in some cases, frame IDs are skipped. On resource-constrained computers, the Leap Motion software can drop frames. In addition, when the software enters robust mode to compensate for bright IR lighting conditions, two sensor frames are analyzed for each <tt class="docutils literal"><span class="pre">Frame</span></tt> object produced and the IDs for consecutive Frame objects increase by two. Finally, if you are using a <a class="reference external" href="../api/Leap.Listener.html"><tt class="docutils literal"><span class="pre">Listener</span></tt></a> callback to get frames, the callback function is not invoked a second time until the first invocation returns. Thus, your application will miss frames if the callback function takes too long to process a frame. In this case, the missed frame is inserted in a history buffer.</p> </div> <div class="section" id="getting-data-from-a-frame"> <h2>Getting Data from a Frame<a class="headerlink" href="#getting-data-from-a-frame" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> class defines several functions that provide access to the data in the frame. For example, the following code illustrates how to get the basic objects tracked by the Leap Motion system:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="n">controller</span><span class="p">;</span> <span class="c1">// wait until Controller.isConnected() evaluates to true</span> <span class="c1">//...</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span> <span class="n">Leap</span><span class="o">::</span><span class="n">HandList</span> <span class="n">hands</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">hands</span><span class="p">();</span> <span class="n">Leap</span><span class="o">::</span><span class="n">PointableList</span> <span class="n">pointables</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">pointables</span><span class="p">();</span> <span class="n">Leap</span><span class="o">::</span><span class="n">FingerList</span> <span class="n">fingers</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">fingers</span><span class="p">();</span> <span class="n">Leap</span><span class="o">::</span><span class="n">ToolList</span> <span class="n">tools</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">tools</span><span class="p">();</span> </pre></div> </div> <p>The objects returned by the <tt class="docutils literal"><span class="pre">Frame</span></tt> object are all read-only. You can safely store them and use them in the future. They are thread-safe. Internally, the objects use the <a class="reference external" href="http://www.boost.org/doc/libs/1_51_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety">C++ Boost library shared pointer class</a>.</p> </div> <div class="section" id="getting-frames-by-polling"> <h2>Getting Frames by Polling<a class="headerlink" href="#getting-frames-by-polling" title="Permalink to this headline">¶</a></h2> <p>Polling the <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object for frames is the simplest and often best strategy when your application has a natural frame rate. You just call the <tt class="docutils literal"><span class="pre">Controller</span></tt> <tt class="docutils literal"><span class="pre">frame()</span></tt> function when your application is ready to process a frame of data.</p> <p>When you use polling, there is a chance that you will get the same frame twice in a row (if the application frame rate exceeds the Leap frame rate) or skip a frame (if the Leap frame rate exceeds the application frame rate). In many cases, missed or duplicated frames are not important. For example, if you are moving an object on the screen in response to hand movement, the movement should still be smooth (assuming the overall frame rate of your application is high enough). In those cases where it does matter, you can use the <tt class="docutils literal"><span class="pre">history</span></tt> parameter of the <tt class="docutils literal"><span class="pre">frame()</span></tt> function.</p> <p>To detect whether you have already processed a frame, save the ID value assigned to the last frame processed and compare it to the current frame:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="kt">int64_t</span> <span class="n">lastFrameID</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="kt">void</span> <span class="nf">processFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="p">)</span> <span class="p">{</span> <span class="k">if</span><span class="p">(</span> <span class="n">frame</span><span class="p">.</span><span class="n">id</span><span class="p">()</span> <span class="o">==</span> <span class="n">lastFrameID</span> <span class="p">)</span> <span class="k">return</span><span class="p">;</span> <span class="c1">//...</span> <span class="n">lastFrameID</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">id</span><span class="p">();</span> <span class="p">}</span> </pre></div> </div> <p>If your application has skipped frames, use the <cite>history</cite> parameter of the <cite>frame()</cite> function to access the skipped frames (as long as the <tt class="docutils literal"><span class="pre">Frame</span></tt> object is still in the history buffer):</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="kt">int64_t</span> <span class="n">lastProcessedFrameID</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="kt">void</span> <span class="nf">nextFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="n">controller</span> <span class="p">)</span> <span class="p">{</span> <span class="kt">int64_t</span> <span class="n">currentID</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">().</span><span class="n">id</span><span class="p">();</span> <span class="k">for</span><span class="p">(</span> <span class="kt">int</span> <span class="n">history</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">history</span> <span class="o">&lt;</span> <span class="n">currentID</span> <span class="o">-</span> <span class="n">lastProcessedFrameID</span><span class="p">;</span> <span class="n">history</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="n">processNextFrame</span><span class="p">(</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="n">history</span><span class="p">)</span> <span class="p">);</span> <span class="p">}</span> <span class="n">lastProcessedFrameID</span> <span class="o">=</span> <span class="n">currentID</span><span class="p">;</span> <span class="p">}</span> <span class="kt">void</span> <span class="nf">processNextFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="p">)</span> <span class="p">{</span> <span class="k">if</span><span class="p">(</span> <span class="n">frame</span><span class="p">.</span><span class="n">isValid</span><span class="p">()</span> <span class="p">)</span> <span class="p">{</span> <span class="c1">//...</span> <span class="p">}</span> <span class="p">}</span> </pre></div> </div> </div> <div class="section" id="getting-frames-with-callbacks"> <h2>Getting Frames with Callbacks<a class="headerlink" href="#getting-frames-with-callbacks" title="Permalink to this headline">¶</a></h2> <p>Alternatively, you can use a <a class="reference external" href="../api/Leap.Listener.html"><tt class="docutils literal"><span class="pre">Listener</span></tt></a> object to get frames at the Leap Motion controller&#8217;s frame rate. The <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object calls the listener&#8217;s <tt class="docutils literal"><span class="pre">onFrame()</span></tt> function when a new frame is available. In the <tt class="docutils literal"><span class="pre">onFrame</span></tt> handler, you can call the <tt class="docutils literal"><span class="pre">Controller</span></tt> <tt class="docutils literal"><span class="pre">frame()</span></tt> function to get the <tt class="docutils literal"><span class="pre">Frame</span></tt> object itself.</p> <p>Using listener callbacks is more complex because the callbacks are multi-threaded; each callback is invoked on an independent thread. You must ensure that any application data accessed by multiple threads is handled in a thread-safe manner. Even though the tracking data objects you get from the API are thread safe, other parts of your application may not be. A common problem is updating objects owned by a GUI layer that can only be modified by a specific thread. In such cases you must arrange to update the non-thread safe portions of your application from the appropriate thread rather than from the callback thread.</p> <p>The following example defines a minimal Listener subclass that handles new frames of data:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="k">class</span> <span class="nc">FrameListener</span> <span class="o">:</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Listener</span> <span class="p">{</span> <span class="kt">void</span> <span class="n">onFrame</span><span class="p">(</span><span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="o">&amp;</span><span class="n">controller</span><span class="p">)</span> <span class="p">{</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span> <span class="c1">//The latest frame</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">previous</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">//The previous frame</span> <span class="c1">//...</span> <span class="p">}</span> <span class="p">};</span> </pre></div> </div> <p>As you can see, getting the tracking data through a <tt class="docutils literal"><span class="pre">Listener</span></tt> object is otherwise the same as polling the controller.</p> <p>Note that it is possible to skip a frame even when using <tt class="docutils literal"><span class="pre">Listener</span></tt> callbacks. If your onFrame callback function takes too long to complete, then the next frame is added to the history, but the onFrame callback is skipped. Less commonly, if the Leap software itself cannot finish processing a frame in time, that frame can be abandoned and not added to the history. This problem can occur when a computer is bogged down with too many other computing tasks.</p> </div> <div class="section" id="following-entities-across-frames"> <h2>Following entities across frames<a class="headerlink" href="#following-entities-across-frames" title="Permalink to this headline">¶</a></h2> <p>If you have an ID of an entity from a different frame, you can get the object representing that entity in the current frame. Pass the ID to the <tt class="docutils literal"><span class="pre">Frame</span></tt> object function of the appropriate type:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="n">Leap</span><span class="o">::</span><span class="n">Hand</span> <span class="n">hand</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">hand</span><span class="p">(</span><span class="n">handID</span><span class="p">);</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Pointable</span> <span class="n">pointable</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">pointable</span><span class="p">(</span><span class="n">pointableID</span><span class="p">);</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">finger</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">finger</span><span class="p">(</span><span class="n">fingerID</span><span class="p">);</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Tool</span> <span class="n">tool</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">tool</span><span class="p">(</span><span class="n">toolID</span><span class="p">);</span> </pre></div> </div> <p>If an object with the same ID cannot be found &#8211; perhaps a hand moved out of the field of view &#8211; then a special, invalid object is returned instead. Invalid objects are instances of the appropriate class, but all their members return 0 values, zero vectors, or other invalid objects. This technique makes it more convenient to chain method calls together. For example, the following code snippet averages finger tip positions over several frames:</p> <div class="highlight-cpp"><div class="highlight"><pre><span class="c1">//Average a finger position for the last 10 frames</span> <span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Vector</span> <span class="n">average</span> <span class="o">=</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Vector</span><span class="p">();</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">fingerToAverage</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">fingers</span><span class="p">()[</span><span class="mi">0</span><span class="p">];</span> <span class="k">for</span><span class="p">(</span> <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span> <span class="p">)</span> <span class="p">{</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">fingerFromFrame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="n">i</span><span class="p">).</span><span class="n">finger</span><span class="p">(</span><span class="n">fingerToAverage</span><span class="p">.</span><span class="n">id</span><span class="p">());</span> <span class="k">if</span><span class="p">(</span> <span class="n">fingerFromFrame</span><span class="p">.</span><span class="n">isValid</span><span class="p">()</span> <span class="p">)</span> <span class="p">{</span> <span class="n">average</span> <span class="o">+=</span> <span class="n">fingerFromFrame</span><span class="p">.</span><span class="n">tipPosition</span><span class="p">();</span> <span class="n">count</span><span class="o">++</span><span class="p">;</span> <span class="p">}</span> <span class="p">}</span> <span class="n">average</span> <span class="o">/=</span> <span class="n">count</span><span class="p">;</span> </pre></div> </div> <p>Without invalid objects, this code would have to check each <tt class="docutils literal"><span class="pre">Frame</span></tt> object before checking the returned Finger objects. Invalid objects reduce the amount of null checking you have to do when accessing Leap Motion tracking data.</p> </div> <div class="section" id="serialization"> <h2>Serialization<a class="headerlink" href="#serialization" title="Permalink to this headline">¶</a></h2> <p>The <tt class="docutils literal"><span class="pre">Frame</span></tt> class provides <a class="reference external" href="../api/Leap.Frame.html#cppclass_leap_1_1_frame_1aa163dee25d1f498f7b52279c3eb2c38e">serialize()</a> and <a class="reference external" href="../api/Leap.Frame.html#cppclass_leap_1_1_frame_1adff8cf1970aee948138c9cd4406025e2">deserialize()</a> functions that allow you to store the data from a frame and later reconstruct it as a valid <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> object. See <a class="reference internal" href="Leap_Serialization.html"><em>Serializing Tracking Data</em></a></p> </div> </div> <!-- get_disqus_sso --> </div> <div id="sidebar" class="col-md-3"> <div class="well-sidebar" data-offset-top="188"> <ul> <li><a href="../index.html" title="Home">C++ Docs (v3.1)</a></li> </ul><ul class="current"> <li class="toctree-l1"><a class="reference internal" href="Leap_Overview.html">API Overview</a></li> <li class="toctree-l1"><a class="reference internal" href="../practices/Leap_Practices.html">Guidelines</a></li> <li class="toctree-l1"><a class="reference internal" href="Leap_Guides.html">Application Development</a></li> <li class="toctree-l1 current"><a class="reference internal" href="Leap_Guides2.html">Using the Tracking API</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="Leap_Controllers.html">Connecting to the Controller</a></li> <li class="toctree-l2"><a class="reference internal" href="Leap_Tracking.html">Tracking Model</a></li> <li class="toctree-l2 current"><a class="current reference internal" href="">Frames</a><ul> <li class="toctree-l3"><a class="reference internal" href="#overview">Overview</a></li> <li class="toctree-l3"><a class="reference internal" href="#getting-data-from-a-frame">Getting Data from a Frame</a></li> <li class="toctree-l3"><a class="reference internal" href="#getting-frames-by-polling">Getting Frames by Polling</a></li> <li class="toctree-l3"><a class="reference internal" href="#getting-frames-with-callbacks">Getting Frames with Callbacks</a></li> <li class="toctree-l3"><a class="reference internal" href="#following-entities-across-frames">Following entities across frames</a></li> <li class="toctree-l3"><a class="reference internal" href="#serialization">Serialization</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="Leap_Hand.html">Hands</a></li> <li class="toctree-l2"><a class="reference internal" href="Leap_Pointables.html">Fingers</a></li> <li class="toctree-l2"><a class="reference internal" href="Leap_Coordinate_Mapping.html">Coordinate Systems</a></li> <li class="toctree-l2"><a class="reference internal" href="Leap_Images.html">Camera Images</a></li> <li class="toctree-l2"><a class="reference internal" href="Leap_Serialization.html">Serializing Tracking Data</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../api/Leap_Classes.html">API Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="../supplements/Leap_Supplements.html">Appendices</a></li> </ul> </div> </div> </div> </div> </div> <!-- <div class="ribbon"> <p>C++</p> </div> <footer> <div id="footer" class="container"> <div class="container"> <div class="copyright"> <span>Copyright &copy; 2012 - 2016, Leap Motion, Inc.</span> </div> </div> </div> </footer> </body> </html>
MTASZTAKI/ApertusVR
plugins/track/hand/leapMotion/3rdParty/leapMotion/docs/cpp/devguide/Leap_Frames.html
HTML
mit
33,410
{% raw %}{% extends "wagtailadmin/home.html" %} {% load wagtailcore_tags wagtailsettings_tags %} {% get_settings %} {% block branding_welcome %} Welcome {% if settings.pages.SiteBranding.site_name %}to {{ settings.pages.SiteBranding.site_name }}{% endif %} {% endblock %}{% endraw %}
ilendl2/wagtail-cookiecutter-foundation
{{cookiecutter.project_slug}}/pages/templates/wagtailadmin/home.html
HTML
mit
288
public enum CoffeePrice { Small = 50, Normal = 100, Double =200 }
zrusev/SoftUni_2016
06. C# OOP Advanced - July 2017/04. Enums And Attributes/04. Enums And Attributes - Lab/Lab Enumerations and Attributes/02. Coffee Machine/CoffeePrice.cs
C#
mit
80
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66-internal) on Tue Dec 08 09:28:01 GMT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct (Apache Jena ARQ)</title> <meta name="date" content="2015-12-08"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct (Apache Jena ARQ)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/jena/sparql/expr/aggregate/AggAvgDistinct.html" title="class in org.apache.jena.sparql.expr.aggregate">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/jena/sparql/expr/aggregate/class-use/AggAvgDistinct.html" target="_top">Frames</a></li> <li><a href="AggAvgDistinct.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct" class="title">Uses of Class<br>org.apache.jena.sparql.expr.aggregate.AggAvgDistinct</h2> </div> <div class="classUseContainer">No usage of org.apache.jena.sparql.expr.aggregate.AggAvgDistinct</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/jena/sparql/expr/aggregate/AggAvgDistinct.html" title="class in org.apache.jena.sparql.expr.aggregate">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/jena/sparql/expr/aggregate/class-use/AggAvgDistinct.html" target="_top">Frames</a></li> <li><a href="AggAvgDistinct.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
manonsys/MVC
libs/Jena/javadoc-arq/org/apache/jena/sparql/expr/aggregate/class-use/AggAvgDistinct.html
HTML
mit
4,828
"use strict"; var mathUtils = require("./math-utils"); exports.shuffle = function(array) { var len = array.length; for ( var i=0; i<len; i++ ) { var rand = mathUtils.randomInt(0,len-1); var temp = array[i]; array[i] = array[rand]; array[rand] = temp; } };
jedrichards/portfolio
api/utils/array-utils.js
JavaScript
mit
303
# -*- coding: utf-8 -*- # # Cloud Robotics FX 会話理解API用メッセージ # # @author: Osamu Noguchi <[email protected]> # @version: 0.0.1 import cloudrobotics.message as message APP_ID = 'SbrApiServices' PROCESSING_ID = 'RbAppConversationApi' # 会話メッセージ # class ConversationMessage(message.CRFXMessage): def __init__(self, visitor, visitor_id, talkByMe, type): super(ConversationMessage, self).__init__() self.header['RoutingType'] = message.ROUTING_TYPE_CALL self.header['AppProcessingId'] = PROCESSING_ID self.header['MessageId'] = type self.body = { 'visitor': visitor, 'visitor_id': visitor_id, 'talkByMe': talkByMe }
seijim/cloud-robotics-fx-v2
CloudRoboticsApi/ClientCode_Pepper/HeadWaters/PepperCode2/lib/cloudrobotics/conversation/message.py
Python
mit
746
Rails.application.routes.draw do namespace :admin do namespace :reports do get 'deliveries' => 'deliveries#index' end get 'users' => 'users#index' get 'users/:id' => 'users#show' end root to: 'pages#index' end
mmontossi/crumbs
test/dummy/config/routes.rb
Ruby
mit
241
/* eslint quote-props: ["error", "consistent"] */ // Japanese Hirajoshi scale // 1-4-2-1-4 // Gb G B Db D Gb export default { 'a': { instrument: 'piano', note: 'a4' }, 'b': { instrument: 'piano', note: 'eb3' }, 'c': { instrument: 'piano', note: 'd6' }, 'd': { instrument: 'piano', note: 'eb4' }, 'e': { instrument: 'piano', note: 'd4' }, 'f': { instrument: 'piano', note: 'bb5' }, 'g': { instrument: 'piano', note: 'd7' }, 'h': { instrument: 'piano', note: 'g3' }, 'i': { instrument: 'piano', note: 'g5' }, 'j': { instrument: 'piano', note: 'bb6' }, 'k': { instrument: 'piano', note: 'eb6' }, 'l': { instrument: 'piano', note: 'bb4' }, 'm': { instrument: 'piano', note: 'a6' }, 'n': { instrument: 'piano', note: 'a5' }, 'o': { instrument: 'piano', note: 'd5' }, 'p': { instrument: 'piano', note: 'a2' }, 'q': { instrument: 'piano', note: 'bb2' }, 'r': { instrument: 'piano', note: 'a3' }, 's': { instrument: 'piano', note: 'd3' }, 't': { instrument: 'piano', note: 'g4' }, 'u': { instrument: 'piano', note: 'g6' }, 'v': { instrument: 'piano', note: 'bb3' }, 'w': { instrument: 'piano', note: 'eb5' }, 'x': { instrument: 'piano', note: 'eb2' }, 'y': { instrument: 'piano', note: 'g2' }, 'z': { instrument: 'piano', note: 'eb7' }, 'A': { instrument: 'celesta', note: 'a4' }, 'B': { instrument: 'celesta', note: 'eb3' }, 'C': { instrument: 'celesta', note: 'd6' }, 'D': { instrument: 'celesta', note: 'eb4' }, 'E': { instrument: 'celesta', note: 'd4' }, 'F': { instrument: 'celesta', note: 'bb4' }, 'G': { instrument: 'celesta', note: 'd2' }, 'H': { instrument: 'celesta', note: 'g3' }, 'I': { instrument: 'celesta', note: 'g5' }, 'J': { instrument: 'celesta', note: 'bb6' }, 'K': { instrument: 'celesta', note: 'eb6' }, 'L': { instrument: 'celesta', note: 'bb5' }, 'M': { instrument: 'celesta', note: 'a6' }, 'N': { instrument: 'celesta', note: 'a5' }, 'O': { instrument: 'celesta', note: 'd5' }, 'P': { instrument: 'celesta', note: 'a7' }, 'Q': { instrument: 'celesta', note: 'bb7' }, 'R': { instrument: 'celesta', note: 'a3' }, 'S': { instrument: 'celesta', note: 'd3' }, 'T': { instrument: 'celesta', note: 'g4' }, 'U': { instrument: 'celesta', note: 'g6' }, 'V': { instrument: 'celesta', note: 'bb3' }, 'W': { instrument: 'celesta', note: 'eb5' }, 'X': { instrument: 'celesta', note: 'eb7' }, 'Y': { instrument: 'celesta', note: 'g7' }, 'Z': { instrument: 'celesta', note: 'eb2' }, '$': { instrument: 'swell', note: 'eb3' }, ',': { instrument: 'swell', note: 'eb3' }, '/': { instrument: 'swell', note: 'bb3' }, '\\': { instrument: 'swell', note: 'eb3' }, ':': { instrument: 'swell', note: 'g3' }, ';': { instrument: 'swell', note: 'bb3' }, '-': { instrument: 'swell', note: 'bb3' }, '+': { instrument: 'swell', note: 'g3' }, '|': { instrument: 'swell', note: 'bb3' }, '{': { instrument: 'swell', note: 'bb3' }, '}': { instrument: 'swell', note: 'eb3' }, '[': { instrument: 'swell', note: 'g3' }, ']': { instrument: 'swell', note: 'bb3' }, '%': { instrument: 'swell', note: 'bb3' }, '&': { instrument: 'swell', note: 'eb3' }, '*': { instrument: 'swell', note: 'eb3' }, '^': { instrument: 'swell', note: 'bb3' }, '#': { instrument: 'swell', note: 'g3' }, '!': { instrument: 'swell', note: 'g3' }, '@': { instrument: 'swell', note: 'eb3' }, '(': { instrument: 'swell', note: 'g3' }, ')': { instrument: 'swell', note: 'eb3' }, '=': { instrument: 'swell', note: 'eb3' }, '~': { instrument: 'swell', note: 'g3' }, '`': { instrument: 'swell', note: 'eb3' }, '_': { instrument: 'swell', note: 'g3' }, '"': { instrument: 'swell', note: 'eb3' }, "'": { instrument: 'swell', note: 'bb3' }, '<': { instrument: 'swell', note: 'g3' }, '>': { instrument: 'swell', note: 'g3' }, '.': { instrument: 'swell', note: 'g3' }, '?': { instrument: 'swell', note: 'bb3' }, '0': { instrument: 'fluteorgan', note: 'd3' }, '1': { instrument: 'fluteorgan', note: 'eb3' }, '2': { instrument: 'fluteorgan', note: 'g3' }, '3': { instrument: 'fluteorgan', note: 'a3' }, '4': { instrument: 'fluteorgan', note: 'bb3' }, '5': { instrument: 'fluteorgan', note: 'd2' }, '6': { instrument: 'fluteorgan', note: 'eb2' }, '7': { instrument: 'fluteorgan', note: 'g2' }, '8': { instrument: 'fluteorgan', note: 'a2' }, '9': { instrument: 'fluteorgan', note: 'bb2' }, 's1': { instrument: 'swell', note: 'eb3' }, 's2': { instrument: 'swell', note: 'g3' }, 's3': { instrument: 'swell', note: 'bb3' } };
sctang/opera
src/scheme/scheme_Hirajoshi_D.js
JavaScript
mit
4,555
<html> <META HTTP-EQUIV=Content-Type Content="text/html; charset=utf8"> <!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01583/0158388122800.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:13:25 GMT --> <head><title>法編號:01583 版本:088122800</title> <link rel="stylesheet" type="text/css" href="../../version.css" > </HEAD> <body><left> <table><tr><td><FONT COLOR=blue SIZE=5>國有財產法(01583)</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <tr><td align=left valign=top> <a href=0158358011000.html target=law01583><nobr><font size=2>中華民國 58 年 1 月 10 日</font></nobr></a> </td> <td valign=top><font size=2>制定77條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 58 年 1 月 27 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158360042700.html target=law01583><nobr><font size=2>中華民國 60 年 4 月 27 日</font></nobr></a> </td> <td valign=top><font size=2>修正第60條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 60 年 5 月 5 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158364010700.html target=law01583><nobr><font size=2>中華民國 64 年 1 月 7 日</font></nobr></a> </td> <td valign=top><font size=2>修正第8, 32, 38, 42, 44, 46, 47, 50, 52, 54條<br> 刪除第15條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 64 年 1 月 17 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158369122600.html target=law01583><nobr><font size=2>中華民國 69 年 12 月 26 日</font></nobr></a> </td> <td valign=top><font size=2>修正第13, 42條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 70 年 1 月 12 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158381031900.html target=law01583><nobr><font size=2>中華民國 81 年 3 月 19 日</font></nobr></a> </td> <td valign=top><font size=2>刪除第74條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 81 年 4 月 6 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158388122800.html target=law01583><nobr><font size=2>中華民國 88 年 12 月 28 日</font></nobr></a> </td> <td valign=top><font size=2>修正第42, 43, 46, 47, 49, 52, 58條<br> 增訂第52之1, 52之2條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 89 年 1 月 12 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158391040200.html target=law01583><nobr><font size=2>中華民國 91 年 4 月 2 日</font></nobr></a> </td> <td valign=top><font size=2>修正第50, 51條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 91 年 4 月 24 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=0158392011300.html target=law01583><nobr><font size=2>中華民國 92 年 1 月 13 日</font></nobr></a> </td> <td valign=top><font size=2>修正第52之2條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 2 月 6 日公布</font></nobr></td> <tr><td align=left valign=top> <a href=01583100121400.html target=law01583><nobr><font size=2>中華民國 100 年 12 月 14 日</font></nobr></a> </td> <td valign=top><font size=2>修正第33, 39, 53條</font></td> <tr><td align=left valign=top><nobr><font size=2>中華民國 101 年 1 月 4 日公布</font></nobr></td> </table></table></table></table> <p><table><tr><td><font color=blue size=4>民國88年12月28日(非現行條文)</font></td> <td><a href=http://lis.ly.gov.tw/lghtml/lawstat/reason2/0158388122800.htm target=reason><font size=2>立法理由</font></a></td> <td><a href=http://lis.ly.gov.tw/lgcgi/lglawproc?0158388122800 target=proc><font size=2>立法紀錄</font></a></td> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一章 總則</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產之取得、保管、使用、收益及處分,依本法之規定;本法未規定者,適用其他法律。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國家依據法律規定,或基於權力行使,或由於預算支出,或由於接受捐贈所取得之財產,為國有財產。<br>   凡不屬於私有或地方所有之財產,除法律另有規定外,均應視為國有財產。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   依前條取得之國有財產,其範圍如左:<br>   一、不動產:指土地及其改良物暨天然資源。<br>   二、動產:指機械及設備、交通運輸及設備,暨其他雜項設備。<br>   三、有價證券:指國家所有之股份或股票及債券。<br>   四、權利:指地上權、地役權、典權、抵押權、礦業權、漁業權、專利權、著作權、商標權及其他財產上之權利。<br>   前項第二款財產之詳細分類,依照行政院規定辦理。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產區分為公用財產與非公用財產兩類。<br>   左列各種財產稱為公用財產。<br>   一、公務用財產:各機關、部隊、學校、辦公、作業及宿舍使用之國有財產均屬之。<br>   二、公共用財產:國家直接供公共使用之國有財產均屬之。<br>   三、事業用財產:國營事業機關使用之財產均屬之。但國營事業為公司組織者,僅指其股份而言。<br>   非公用財產,係指公用財產以外可供收益或處分之一切國有財產。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   第三條第一項所定範圍以外之左列國有財產,其保管或使用,仍依其他有關法令辦理:<br>   一、軍品及軍用器材。<br>   二、圖書、史料、古物及故宮博物。<br>   三、國營事業之生產材料。<br>   四、其他可供公用或應保存之有形或無形財產。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國家為保障邊疆各民族之土地使用,得視地方實際情況,保留國有土地及其定著物;其管理辦法由行政院定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產收益及處分,依預算程序為之;其收入應解國庫。<br>   凡屬事業用之公用財產,在使用期間或變更為非公用財產,而為收益或處分時,均依公營事業有關規定程序辦理。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有土地及國有建築改良物,除放租有收益及第四條第二項第三款所指事業用者外,免徵土地稅及建築改良物稅。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二章 機構</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部承行政院之命,綜理國有財產事務。<br>   財政部設國有財產局,承辦前項事務;其組織以法律定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   公用財產之主管機關,依預算法之規定。<br>   公用財產為二個以上機關共同使用,不屬於同一機關管理者,其主管機關由行政院指定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   公用財產以各直接使用機關為管理機關,直接管理之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產以財政部國有財產局為管理機關,承財政部之命,直接管理之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部視國有財產實際情況之需要,得委託地方政府或適當機構代為管理或經營。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產在國境外者,由外交部主管,並由各使領館直接管理;如當地無使領館時,由外交部委託適當機構代為管理。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> (刪除)<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部國有財產局設國有財產估價委員會,為國有財產估價機構;其組織由財政部定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第三章 保管</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一節 登記</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   第三條所指取得之不動產、動產、有價證券及權利,應分別依有關法令完成國有登記,或確定其權屬。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   不動產之國有登記,由管理機關囑託該管直轄市、縣(市)地政機關為之。<br>   動產、有價證券及權利有關確定權屬之程序,由管理機關辦理之。<br>   依本條規定取得之產權憑證,除第二十六條規定外,由管理機關保管之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   尚未完成登記應屬國有之土地,除公用財產依前條規定辦理外,得由財政部國有財產局或其所屬分支機構囑託該管直轄市、縣(市)地政機關辦理國有登記,必要時得分期、分區辦理。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產在國境外者,應由外交部或各使領館依所在地國家法令,辦理確定權屬之程序。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二節 產籍</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   管理機關應設國有財產資料卡及明細分類帳,就所經管之國有財產,分類、編號、製卡、登帳,並列冊層報主管機關;其異動情形,應依會計報告程序為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部應設國有財產總帳,就各管理機關所送資料整理、分類、登錄。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產因故滅失、毀損或拆卸、改裝,經有關機關核准報廢者,或依本法規定出售或贈與者,應由管理機關於三個月內列表層轉財政部註銷產籍。但涉及民事或刑事者不在此限。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   第二十一條至第二十三條所定卡、帳、表、冊之格式及財產編號,由財政部會商中央主計機關及審計機關統一訂定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第三節 維護</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   管理機關對其經管之國有財產,除依法令報廢者外,應注意保養及整修,不得毀損、棄置。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   有價證券應交由當地國庫或其代理機構負責保管。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產直接經管人員或使用人,因故意或過失,致財產遭受損害時,除涉及刑事責任部分,應由管理機關移送該管法院究辦外,並應負賠償責任。但因不可抗力而發生損害者,其責任經審計機關查核後決定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   主管機關或管理機關對於公用財產不得為任何處分或擅為收益。但其收益不違背其事業目的或原定用途者,不在此限。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第二十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產在國境外者,非依法經外交部核准,並徵得財政部同意,不得為任何處分。但為應付國際間之突發事件,得為適當之處理,於處理後即報外交部,並轉財政部及有關機關。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有不動產經他人以虛偽之方法,為權利之登記者,經主管機關或管理機關查明確實後,應依民事訴訟法之規定,提起塗銷之訴;並得於起訴後囑託該管直轄市、縣(市)地政機關,為異議登記。<br>   前項為虛偽登記之申請人及登記人員,並應移送該管法院查究其刑責。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產管理人員,對於經管之國有財產不得買受或承租,或為其他與自己有利之處分或收益行為。<br>   違反前項規定之行為無效。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第四章 使用</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一節 公用財產之用途</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   公用財產應依預定計畫及規定用途或事業目的使用;其事業用財產,仍適用營業預算程序。<br>   天然資源之開發、利用及管理,除法律另有規定外,應由管理機關善為規劃,有效運用。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   公用財產用途廢止時,應變更為非公用財產。但依法徵收之土地,適用土地法之規定。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部基於國家政策需要,得徵商主管機關同意,報經行政院核准,將公用財產變更為非公用財產。<br>   公用財產與非公用財產得互易其財產類別,經財政部與主管機關協議,報經行政院核定為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   公用財產變更為非公用財產時,由主管機關督飭該管理機關移交財政部國有財產局接管。但原屬事業用財產,得由原事業主管機關,依預算程序處理之。<br>   非公用財產經核定變更為公用財產時,由財政部國有財產局移交公用財產主管機關或管理機關接管。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   主管機關基於事實需要,得將公務用、公共用財產,在原規定使用範圍內變更用途,並得將各該種財產相互交換使用。<br>   前項變更用途或相互交換使用,須變更主管機關者,應經各該主管機關之協議,並徵得財政部之同意。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國家接受捐贈之財產,屬於第三條規定之範圍者,應由受贈機關隨時通知財政部轉報行政院,視其用途指定其主管機關。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二節 非公用財產之撥用</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,各級政府機關為公務或公共所需,得申請撥用。但有左列情形之一者,不得辦理撥用:<br>   一、位於繁盛地區,依申請撥用之目的,非有特別需要者。<br>   二、擬作為宿舍用途者。<br>   三、不合區域計畫或都市計畫土地使用分區規定者。<br>   前項撥用,應由申請撥用機關檢具使用計畫及圖說,報經其上級機關核明屬實,並徵得財政部國有財產局同意後,層報行政院核定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第三十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產經撥為公用後,遇有左列情事之一者,應由財政部查明隨時收回,交財政部國有財產局接管。但撥用土地之收回,應由財政部呈請行政院撤銷撥用後為之:<br>   一、用途廢止時。<br>   二、變更原定用途時。<br>   三、於原定用途外,擅供收益使用時。<br>   四、擅自讓由他人使用時。<br>   五、建地空置逾一年,尚未開始建築時。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第三節 非公用財產之借用</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產得供各機關、部隊、學校因臨時性或緊急性之公務用或公共用,為短期之借用;其借用期間,不得逾三個月。如屬土地,並不得供建築使用。<br>   前項借用手續,應由需用機關徵得管理機關同意為之,並通知財政部。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產經借用後,遇有左列情事之一者,應由管理機關查明隨時收回:<br>   一、借用原因消滅時。<br>   二、於原定用途外,另供收益使用時。<br>   三、擅自讓由他人使用時。<br>   非公用財產借用期間,如有增建、改良或修理情事,收回時不得請求補償。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第五章 收益</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一節 非公用財產之出租</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類不動產之出租,得以標租方式辦理。但合於左列各款規定之一者,得逕予出租:<br>   一、原有租賃期限屆滿,未逾六個月者。<br>   二、民國八十二年七月二十一日前已實際使用,並願繳清歷年使用補償金者。<br>   三、依法得讓售者。<br>   非公用財產類之不動產出租,應以書面為之;未以書面為之者,不生效力。<br>   非公用財產類之不動產依法已為不定期租賃關係者,承租人應於規定期限內訂定書面契約;未於規定期限內訂定書面契約者,管理機關得終止租賃關係。<br>   前項期限及非公用財產類不動產出租管理辦法,由財政部擬定報請行政院核定後發布之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產出租,應依左列各款規定,約定期限:<br>   一、建築改良物,五年以下。<br>   二、建築基地,二十年以下。<br>   三、其他土地,六年至十年。<br>   約定租賃期限屆滿時,得更新之。<br>   非公用財產類之不動產租金率,依有關土地法律規定;土地法律未規定者,由財政部斟酌實際情形擬訂,報請行政院核定之。但以標租方式出租或出租係供作營利使用者,其租金率得不受有關土地法律規定之限制。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產出租後,除依其他法律規定得予終止租約收回外,遇有左列情形之一者,亦得解約收回:<br>   一、基於國家政策需要,變更為公用財產時。<br>   二、承租人變更約定用途時。<br>   三、因開發、利用或重行修建,有收回必要時。<br>   承租人因前項第一、第三兩款規定,解除租約所受之損失,得請求補償。其標準由財政部核定之。<br>   非公用財產類之不動產解除租約時,除出租機關許可之增建或改良部分,得由承租人請求補償其現值外,應無償收回;其有毀損情事者,應責令承租人回復原狀。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之動產,以不出租為原則。但基於國家政策或國庫利益,在無適當用途前,有暫予出租之必要者,得經財政部專案核准為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二節 非公用財產之利用</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有耕地得提供為放租或放領之用;其放租、放領實施辦法,由內政部會商財政部擬訂,報請行政院核定之。<br>   邊際及海岸地可闢為觀光或作海水浴場等事業用者,得提供利用辦理放租;可供造林、農墾、養殖等事業用者,得辦理放租或放領。其辦法由財政部會同有關機關擬訂,報請行政院核定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類不動產,得依法改良利用。<br>   財政部國有財產局得以委託、合作或信託方式,配合區域計畫、都市計畫辦理左列事項:<br>   一、改良土地。<br>   二、興建公務或公共用房屋。<br>   三、其他非興建房屋之事業。<br>   經改良之土地,以標售為原則。但情形特殊,適於以設定地上權或其他方式處理者,得報請行政院核定之。<br>   第二項各款事業,依其計畫須由財政部國有財產局負擔資金者,應編列預算。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之動產,得提供投資之用。但以基於國家政策及國庫利益,確有必要者為限。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第六章 處分</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一節 非公用財產類不動產之處分</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第四十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,其已有租賃關係者,得讓售與直接使用人。<br>   前項得予讓售之不動產範圍,由行政院另定之。<br>   非公用財產類之不動產,其經地方政府認定應與鄰接土地合併建築使用者,得讓售與有合併使用必要之鄰地所有權人。<br>   第一項及第三項讓售,由財政部國有財產局辦理之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,為國營事業機關或地方公營事業機構,因業務上所必需者,得予讓售。<br>   前項讓售,分別由各該主管機關或省(市)政府,商請財政部核准,並徵得審計機關同意為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,為社會、文化、教育、慈善、救濟團體舉辦公共福利事業或慈善救濟事業所必需者,得予讓售。<br>   前項讓售,分別由各該主管機關或省(市)政府,商請財政部轉報行政院核定,並徵得審計機關同意為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之土地,經政府提供興建國民住宅或獎勵投資各項用地者,得予讓售。<br>   前項讓售,依國民住宅條例及其他有關規定辦理。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十二條之一</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,有左列各款情形之一者,得專案報經財政部核准讓售:<br>   一、使用他人土地之國有房屋。<br>   二、原屬國有房屋業已出售,其尚未併售之建築基地。<br>   三、共有不動產之國有持分。<br>   四、獲准整體開發範圍內之國有不動產。<br>   五、非屬公墓而其地目為「墓」並有墳墓之土地。<br>   六、其他不屬前五款情況,而其使用情形或位置情形確屬特殊者。<br>   非公用財產類之不動產,基於國家建設需要,不宜標售者,得專案報經行政院核准讓售。<br>   非公用財產類之不動產,為提高利用價值,得專案報經財政部核准與他人所有之不動產交換所有權。其交換辦法,由財政部擬訂,報請行政院核定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十二條之二</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,於民國三十五年十二月三十一日以前已供建築、居住使用至今者,其直接使用人得於本法修正施行日起三年內,檢具有關證明文件,向財政部國有財產局或所屬分支機構申請讓售。經核准者,其土地面積在五百平方公尺以內部分,得按第一次公告土地現值計價。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之空屋、空地,並無預定用途者,得予標售。<br>   前項標售,由財政部國有財產局辦理之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之不動產,使用人無租賃關係或不合第四十二條第一項第二款之規定者,應收回標售或自行利用。<br>   其有左列情形之一者,得經財政部核准辦理現狀標售:<br>   一、經財政部核准按現狀接管處理者。<br>   二、接管時已有墳墓或已作墓地使用者。<br>   三、使用情形複雜,短期間內無法騰空辦理標售,且因情形特殊,急待處理者。<br>   前項標售,由財政部國有財產局辦理之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二節 非公用財產類動產、有價證券及權利之處分</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產類之動產不堪使用者,得予標售,或拆卸後就其殘料另予改裝或標售。<br>   前項標售或拆卸、改裝,由財政部國有財產局報經財政部,按其權責核轉審計機關報廢後為之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   有價證券,得經行政院核准予以出售。<br>   前項出售,由財政部商得審計機關同意,依證券交易法之規定辦理。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   第三條第一項第四款財產上權利之處分,應分別按其財產類別,經主管機關或財政部核定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第三節 計價</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產計價方式,經國有財產估價委員會議訂,由財政部報請行政院核定之。但放領土地地價之計算,依放領土地有關法令規定辦理。<br>   有價證券之售價,由財政部核定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第五十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   非公用財產之預估售價,達於審計法令規定之稽察限額者,應經審計機關之同意。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第四節 贈與</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   在國外之國有財產,有贈與外國政府或其人民必要者,得層請行政院核准贈與之。<br>   在國內之國有財產,其贈與行為以動產為限。但現為寺廟、教堂所使用之不動產,合於國人固有信仰,有贈與該寺廟、教堂依法成立之財團法人必要者,得贈與之。<br>   前項贈與辦法。由行政院定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第七章 檢核</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第一節 財產檢查</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產之檢查,除審計機關依審計法令規定隨時稽察外,主管機關對於各管理機關或國外代管機構有關公用財產保管、使用、收益及處分情形,應為定期與不定期之檢查。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部對於各主管機關及委託代管機構管理公用財產情形,應隨時查詢。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部對於財政部國有財產局及委託經營事業機構管理或經營非公用財產情形,應隨時考查,並應注意其撥用或借用後,用途有無變更。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第二節 財產報告</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   管理機關或委託代管機構,應於每一會計年度開始前,擬具公用財產異動計畫,報由主管機關核轉財政部審查。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部國有財產局及委託經營事業機構,於每一會計年度開始前,應對非公用財產之管理或經營擬具計畫,報財政部審定。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部應於每一會計年度開始前,對於公用財產及非公用財產,就第六十四條及第六十五條所擬之計畫加具審查意見,呈報行政院;其涉及處分事項,應列入中央政府年度總預算。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   管理機關及委託代管機構,應於每一會計年度終了時,編具公用財產目錄及財產增減表,呈報主管機關彙轉財政部及中央主計機關暨審計機關。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十八條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部國有財產局及委託經營事業機構,應於每一會計年度終了時,編具非公用財產目錄及財產增減表,呈報財政部,並分轉中央主計機關及審計機關。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第六十九條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   財政部應於每一會計年度終了時,就各主管機關及財政部國有財產局等所提供之資料,編具國有財產總目錄,呈報行政院彙入中央政府年度總決算。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   第六十四條至第六十九條所指之計畫、目錄及表報格式,由財政部會商中央主計機關及審計機關定之。<br> </td> </table> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <td><font color=4000ff size=4>第八章 附則</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十一條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產經管人員違反第二十一條之規定,應登帳而未登帳,並有隱匿或侵占行為者,加重其刑至二分之一。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十二條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產被埋藏、沉沒者,其掘發、打撈辦法,由行政院定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十三條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   國有財產漏未接管,經舉報後發現,或被人隱匿經舉報後收回,或經舉報後始撈取、掘獲者,給予舉報人按財產總值一成以下之獎金。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十四條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> (刪除)<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十五條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   本法施行區域,由行政院以命令定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十六條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   本法施行細則,由行政院定之。<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>第七十七條</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>   本法自公布日施行。<br> </td> </table> </table> </table> </left> </body> <!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01583/0158388122800.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:13:25 GMT --> </html>
g0v/laweasyread-data
rawdata/utf8_lawstat/version2/01583/0158388122800.html
HTML
mit
45,532
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="WIN32_FIND_DATA"/> nested type. /// </content> public partial class Kernel32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WIN32_FIND_DATA { /// <summary> /// The file attributes of a file. /// </summary> /// <remarks> /// Although the enum we bind to here exists in the .NET Framework /// as System.IO.FileAttributes, it is not reliably present. /// Portable profiles don't include it, for example. So we have to define our own. /// </remarks> public FileAttribute dwFileAttributes; /// <summary> /// A FILETIME structure that specifies when a file or directory was created. /// If the underlying file system does not support creation time, this member is zero. /// </summary> public FILETIME ftCreationTime; /// <summary> /// A FILETIME structure. /// For a file, the structure specifies when the file was last read from, written to, or for executable files, run. /// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last access time, this member is zero. /// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight. /// </summary> public FILETIME ftLastAccessTime; /// <summary> /// A FILETIME structure. /// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used.The date and time are not updated when file attributes or security descriptors are changed. /// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last write time, this member is zero. /// </summary> public FILETIME ftLastWriteTime; /// <summary> /// The high-order DWORD value of the file size, in bytes. /// This value is zero unless the file size is greater than MAXDWORD. /// The size of the file is equal to(nFileSizeHigh* (MAXDWORD+1)) + nFileSizeLow. /// </summary> public uint nFileSizeHigh; /// <summary> /// The low-order DWORD value of the file size, in bytes. /// </summary> public uint nFileSizeLow; /// <summary> /// If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse point tag. /// Otherwise, this value is undefined and should not be used. /// For more information see Reparse Point Tags. /// </summary> public uint dwReserved0; /// <summary> /// Reserved for future use. /// </summary> public uint dwReserved1; /// <summary> /// The name of the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; /// <summary> /// An alternative name for the file. /// This name is in the classic 8.3 file name format. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } } }
vbfox/pinvoke
src/Kernel32/Kernel32+WIN32_FIND_DATA.cs
C#
mit
3,947
package arn // PersonName represents the name of a person. type PersonName struct { English Name `json:"english" editable:"true"` Japanese Name `json:"japanese" editable:"true"` } // String returns the default visualization of the name. func (name *PersonName) String() string { return name.ByUser(nil) } // ByUser returns the preferred name for the given user. func (name *PersonName) ByUser(user *User) string { if user == nil { return name.English.String() } switch user.Settings().TitleLanguage { case "japanese": if name.Japanese.String() == "" { return name.English.String() } return name.Japanese.String() default: return name.English.String() } }
animenotifier/arn
PersonName.go
GO
mit
684
package testdata import ( . "goa.design/goa/v3/dsl" ) var ConflictWithAPINameAndServiceNameDSL = func() { var _ = API("aloha", func() { Title("conflict with API name and service names") }) var _ = Service("aloha", func() {}) // same as API name var _ = Service("alohaapi", func() {}) // API name + 'api' suffix var _ = Service("alohaapi1", func() {}) // API name + 'api' suffix + sequential no. } var ConflictWithGoifiedAPINameAndServiceNamesDSL = func() { var _ = API("good-by", func() { Title("conflict with goified API name and goified service names") }) var _ = Service("good-by-", func() {}) // Goify name is same as API name var _ = Service("good-by-api", func() {}) // API name + 'api' suffix var _ = Service("good-by-api-1", func() {}) // API name + 'api' suffix + sequential no. }
goadesign/goa
codegen/service/testdata/example_svc_dsls.go
GO
mit
820
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {async, fakeAsync, tick} from '@angular/core/testing'; import {AsyncTestCompleter, beforeEach, describe, inject, it} from '@angular/core/testing/testing_internal'; import {AbstractControl, FormArray, FormControl, FormGroup, Validators} from '@angular/forms'; import {EventEmitter} from '../src/facade/async'; import {isPresent} from '../src/facade/lang'; export function main() { function asyncValidator(expected: string, timeouts = {}) { return (c: AbstractControl) => { let resolve: (result: any) => void; const promise = new Promise(res => { resolve = res; }); const t = isPresent((timeouts as any)[c.value]) ? (timeouts as any)[c.value] : 0; const res = c.value != expected ? {'async': true} : null; if (t == 0) { resolve(res); } else { setTimeout(() => { resolve(res); }, t); } return promise; }; } function asyncValidatorReturningObservable(c: FormControl) { const e = new EventEmitter(); Promise.resolve(null).then(() => { e.emit({'async': true}); }); return e; } describe('FormGroup', () => { describe('value', () => { it('should be the reduced value of the child controls', () => { const g = new FormGroup({'one': new FormControl('111'), 'two': new FormControl('222')}); expect(g.value).toEqual({'one': '111', 'two': '222'}); }); it('should be empty when there are no child controls', () => { const g = new FormGroup({}); expect(g.value).toEqual({}); }); it('should support nested groups', () => { const g = new FormGroup({ 'one': new FormControl('111'), 'nested': new FormGroup({'two': new FormControl('222')}) }); expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}}); (<FormControl>(g.get('nested.two'))).setValue('333'); expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}}); }); }); describe('getRawValue', () => { let fg: FormGroup; it('should work with nested form groups/arrays', () => { fg = new FormGroup({ 'c1': new FormControl('v1'), 'group': new FormGroup({'c2': new FormControl('v2'), 'c3': new FormControl('v3')}), 'array': new FormArray([new FormControl('v4'), new FormControl('v5')]) }); fg.get('group').get('c3').disable(); (fg.get('array') as FormArray).at(1).disable(); expect(fg.getRawValue()) .toEqual({'c1': 'v1', 'group': {'c2': 'v2', 'c3': 'v3'}, 'array': ['v4', 'v5']}); }); }); describe('adding and removing controls', () => { it('should update value and validity when control is added', () => { const g = new FormGroup({'one': new FormControl('1')}); expect(g.value).toEqual({'one': '1'}); expect(g.valid).toBe(true); g.addControl('two', new FormControl('2', Validators.minLength(10))); expect(g.value).toEqual({'one': '1', 'two': '2'}); expect(g.valid).toBe(false); }); it('should update value and validity when control is removed', () => { const g = new FormGroup( {'one': new FormControl('1'), 'two': new FormControl('2', Validators.minLength(10))}); expect(g.value).toEqual({'one': '1', 'two': '2'}); expect(g.valid).toBe(false); g.removeControl('two'); expect(g.value).toEqual({'one': '1'}); expect(g.valid).toBe(true); }); }); describe('errors', () => { it('should run the validator when the value changes', () => { const simpleValidator = (c: FormGroup) => c.controls['one'].value != 'correct' ? {'broken': true} : null; const c = new FormControl(null); const g = new FormGroup({'one': c}, simpleValidator); c.setValue('correct'); expect(g.valid).toEqual(true); expect(g.errors).toEqual(null); c.setValue('incorrect'); expect(g.valid).toEqual(false); expect(g.errors).toEqual({'broken': true}); }); }); describe('dirty', () => { let c: FormControl, g: FormGroup; beforeEach(() => { c = new FormControl('value'); g = new FormGroup({'one': c}); }); it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); }); it('should be true after changing the value of the control', () => { c.markAsDirty(); expect(g.dirty).toEqual(true); }); }); describe('touched', () => { let c: FormControl, g: FormGroup; beforeEach(() => { c = new FormControl('value'); g = new FormGroup({'one': c}); }); it('should be false after creating a control', () => { expect(g.touched).toEqual(false); }); it('should be true after control is marked as touched', () => { c.markAsTouched(); expect(g.touched).toEqual(true); }); }); describe('setValue', () => { let c: FormControl, c2: FormControl, g: FormGroup; beforeEach(() => { c = new FormControl(''); c2 = new FormControl(''); g = new FormGroup({'one': c, 'two': c2}); }); it('should set its own value', () => { g.setValue({'one': 'one', 'two': 'two'}); expect(g.value).toEqual({'one': 'one', 'two': 'two'}); }); it('should set child values', () => { g.setValue({'one': 'one', 'two': 'two'}); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); }); it('should set child control values if disabled', () => { c2.disable(); g.setValue({'one': 'one', 'two': 'two'}); expect(c2.value).toEqual('two'); expect(g.value).toEqual({'one': 'one'}); expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'}); }); it('should set group value if group is disabled', () => { g.disable(); g.setValue({'one': 'one', 'two': 'two'}); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); expect(g.value).toEqual({'one': 'one', 'two': 'two'}); }); it('should set parent values', () => { const form = new FormGroup({'parent': g}); g.setValue({'one': 'one', 'two': 'two'}); expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}}); }); it('should not update the parent when explicitly specified', () => { const form = new FormGroup({'parent': g}); g.setValue({'one': 'one', 'two': 'two'}, {onlySelf: true}); expect(form.value).toEqual({parent: {'one': '', 'two': ''}}); }); it('should throw if fields are missing from supplied value (subset)', () => { expect(() => g.setValue({ 'one': 'one' })).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`)); }); it('should throw if a value is provided for a missing control (superset)', () => { expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'})) .toThrowError(new RegExp(`Cannot find form control with name: three`)); }); it('should throw if a value is not provided for a disabled control', () => { c2.disable(); expect(() => g.setValue({ 'one': 'one' })).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`)); }); it('should throw if no controls are set yet', () => { const empty = new FormGroup({}); expect(() => empty.setValue({ 'one': 'one' })).toThrowError(new RegExp(`no form controls registered with this group`)); }); describe('setValue() events', () => { let form: FormGroup; let logger: any[]; beforeEach(() => { form = new FormGroup({'parent': g}); logger = []; }); it('should emit one valueChange event per control', () => { form.valueChanges.subscribe(() => logger.push('form')); g.valueChanges.subscribe(() => logger.push('group')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); g.setValue({'one': 'one', 'two': 'two'}); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); it('should not fire an event when explicitly specified', fakeAsync(() => { form.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.valueChanges.subscribe((value) => { throw 'Should not happen'; }); c.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.setValue({'one': 'one', 'two': 'two'}, {emitEvent: false}); tick(); })); it('should emit one statusChange event per control', () => { form.statusChanges.subscribe(() => logger.push('form')); g.statusChanges.subscribe(() => logger.push('group')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); g.setValue({'one': 'one', 'two': 'two'}); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); }); }); describe('patchValue', () => { let c: FormControl, c2: FormControl, g: FormGroup; beforeEach(() => { c = new FormControl(''); c2 = new FormControl(''); g = new FormGroup({'one': c, 'two': c2}); }); it('should set its own value', () => { g.patchValue({'one': 'one', 'two': 'two'}); expect(g.value).toEqual({'one': 'one', 'two': 'two'}); }); it('should set child values', () => { g.patchValue({'one': 'one', 'two': 'two'}); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); }); it('should patch disabled control values', () => { c2.disable(); g.patchValue({'one': 'one', 'two': 'two'}); expect(c2.value).toEqual('two'); expect(g.value).toEqual({'one': 'one'}); expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'}); }); it('should patch disabled control groups', () => { g.disable(); g.patchValue({'one': 'one', 'two': 'two'}); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); expect(g.value).toEqual({'one': 'one', 'two': 'two'}); }); it('should set parent values', () => { const form = new FormGroup({'parent': g}); g.patchValue({'one': 'one', 'two': 'two'}); expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}}); }); it('should not update the parent when explicitly specified', () => { const form = new FormGroup({'parent': g}); g.patchValue({'one': 'one', 'two': 'two'}, {onlySelf: true}); expect(form.value).toEqual({parent: {'one': '', 'two': ''}}); }); it('should ignore fields that are missing from supplied value (subset)', () => { g.patchValue({'one': 'one'}); expect(g.value).toEqual({'one': 'one', 'two': ''}); }); it('should not ignore fields that are null', () => { g.patchValue({'one': null}); expect(g.value).toEqual({'one': null, 'two': ''}); }); it('should ignore any value provided for a missing control (superset)', () => { g.patchValue({'three': 'three'}); expect(g.value).toEqual({'one': '', 'two': ''}); }); describe('patchValue() events', () => { let form: FormGroup; let logger: any[]; beforeEach(() => { form = new FormGroup({'parent': g}); logger = []; }); it('should emit one valueChange event per control', () => { form.valueChanges.subscribe(() => logger.push('form')); g.valueChanges.subscribe(() => logger.push('group')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); g.patchValue({'one': 'one', 'two': 'two'}); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); it('should not emit valueChange events for skipped controls', () => { form.valueChanges.subscribe(() => logger.push('form')); g.valueChanges.subscribe(() => logger.push('group')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); g.patchValue({'one': 'one'}); expect(logger).toEqual(['control1', 'group', 'form']); }); it('should not fire an event when explicitly specified', fakeAsync(() => { form.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.valueChanges.subscribe((value) => { throw 'Should not happen'; }); c.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.patchValue({'one': 'one', 'two': 'two'}, {emitEvent: false}); tick(); })); it('should emit one statusChange event per control', () => { form.statusChanges.subscribe(() => logger.push('form')); g.statusChanges.subscribe(() => logger.push('group')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); g.patchValue({'one': 'one', 'two': 'two'}); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); }); }); describe('reset()', () => { let c: FormControl, c2: FormControl, g: FormGroup; beforeEach(() => { c = new FormControl('initial value'); c2 = new FormControl(''); g = new FormGroup({'one': c, 'two': c2}); }); it('should set its own value if value passed', () => { g.setValue({'one': 'new value', 'two': 'new value'}); g.reset({'one': 'initial value', 'two': ''}); expect(g.value).toEqual({'one': 'initial value', 'two': ''}); }); it('should set its own value if boxed value passed', () => { g.setValue({'one': 'new value', 'two': 'new value'}); g.reset({'one': {value: 'initial value', disabled: false}, 'two': ''}); expect(g.value).toEqual({'one': 'initial value', 'two': ''}); }); it('should clear its own value if no value passed', () => { g.setValue({'one': 'new value', 'two': 'new value'}); g.reset(); expect(g.value).toEqual({'one': null, 'two': null}); }); it('should set the value of each of its child controls if value passed', () => { g.setValue({'one': 'new value', 'two': 'new value'}); g.reset({'one': 'initial value', 'two': ''}); expect(c.value).toBe('initial value'); expect(c2.value).toBe(''); }); it('should clear the value of each of its child controls if no value passed', () => { g.setValue({'one': 'new value', 'two': 'new value'}); g.reset(); expect(c.value).toBe(null); expect(c2.value).toBe(null); }); it('should set the value of its parent if value passed', () => { const form = new FormGroup({'g': g}); g.setValue({'one': 'new value', 'two': 'new value'}); g.reset({'one': 'initial value', 'two': ''}); expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}}); }); it('should clear the value of its parent if no value passed', () => { const form = new FormGroup({'g': g}); g.setValue({'one': 'new value', 'two': 'new value'}); g.reset(); expect(form.value).toEqual({'g': {'one': null, 'two': null}}); }); it('should not update the parent when explicitly specified', () => { const form = new FormGroup({'g': g}); g.reset({'one': 'new value', 'two': 'new value'}, {onlySelf: true}); expect(form.value).toEqual({g: {'one': 'initial value', 'two': ''}}); }); it('should mark itself as pristine', () => { g.markAsDirty(); expect(g.pristine).toBe(false); g.reset(); expect(g.pristine).toBe(true); }); it('should mark all child controls as pristine', () => { c.markAsDirty(); c2.markAsDirty(); expect(c.pristine).toBe(false); expect(c2.pristine).toBe(false); g.reset(); expect(c.pristine).toBe(true); expect(c2.pristine).toBe(true); }); it('should mark the parent as pristine if all siblings pristine', () => { const c3 = new FormControl(''); const form = new FormGroup({'g': g, 'c3': c3}); g.markAsDirty(); expect(form.pristine).toBe(false); g.reset(); expect(form.pristine).toBe(true); }); it('should not mark the parent pristine if any dirty siblings', () => { const c3 = new FormControl(''); const form = new FormGroup({'g': g, 'c3': c3}); g.markAsDirty(); c3.markAsDirty(); expect(form.pristine).toBe(false); g.reset(); expect(form.pristine).toBe(false); }); it('should mark itself as untouched', () => { g.markAsTouched(); expect(g.untouched).toBe(false); g.reset(); expect(g.untouched).toBe(true); }); it('should mark all child controls as untouched', () => { c.markAsTouched(); c2.markAsTouched(); expect(c.untouched).toBe(false); expect(c2.untouched).toBe(false); g.reset(); expect(c.untouched).toBe(true); expect(c2.untouched).toBe(true); }); it('should mark the parent untouched if all siblings untouched', () => { const c3 = new FormControl(''); const form = new FormGroup({'g': g, 'c3': c3}); g.markAsTouched(); expect(form.untouched).toBe(false); g.reset(); expect(form.untouched).toBe(true); }); it('should not mark the parent untouched if any touched siblings', () => { const c3 = new FormControl(''); const form = new FormGroup({'g': g, 'c3': c3}); g.markAsTouched(); c3.markAsTouched(); expect(form.untouched).toBe(false); g.reset(); expect(form.untouched).toBe(false); }); it('should retain previous disabled state', () => { g.disable(); g.reset(); expect(g.disabled).toBe(true); }); it('should set child disabled state if boxed value passed', () => { g.disable(); g.reset({'one': {value: '', disabled: false}, 'two': ''}); expect(c.disabled).toBe(false); expect(g.disabled).toBe(false); }); describe('reset() events', () => { let form: FormGroup, c3: FormControl, logger: any[]; beforeEach(() => { c3 = new FormControl(''); form = new FormGroup({'g': g, 'c3': c3}); logger = []; }); it('should emit one valueChange event per reset control', () => { form.valueChanges.subscribe(() => logger.push('form')); g.valueChanges.subscribe(() => logger.push('group')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); c3.valueChanges.subscribe(() => logger.push('control3')); g.reset(); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); it('should not fire an event when explicitly specified', fakeAsync(() => { form.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.valueChanges.subscribe((value) => { throw 'Should not happen'; }); c.valueChanges.subscribe((value) => { throw 'Should not happen'; }); g.reset({}, {emitEvent: false}); tick(); })); it('should emit one statusChange event per reset control', () => { form.statusChanges.subscribe(() => logger.push('form')); g.statusChanges.subscribe(() => logger.push('group')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); c3.statusChanges.subscribe(() => logger.push('control3')); g.reset(); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); it('should emit one statusChange event per reset control', () => { form.statusChanges.subscribe(() => logger.push('form')); g.statusChanges.subscribe(() => logger.push('group')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); c3.statusChanges.subscribe(() => logger.push('control3')); g.reset({'one': {value: '', disabled: true}}); expect(logger).toEqual(['control1', 'control2', 'group', 'form']); }); }); }); describe('contains', () => { let group: FormGroup; beforeEach(() => { group = new FormGroup({ 'required': new FormControl('requiredValue'), 'optional': new FormControl({value: 'disabled value', disabled: true}) }); }); it('should return false when the component is disabled', () => { expect(group.contains('optional')).toEqual(false); }); it('should return false when there is no component with the given name', () => { expect(group.contains('something else')).toEqual(false); }); it('should return true when the component is enabled', () => { expect(group.contains('required')).toEqual(true); group.enable('optional'); expect(group.contains('optional')).toEqual(true); }); it('should support controls with dots in their name', () => { expect(group.contains('some.name')).toBe(false); group.addControl('some.name', new FormControl()); expect(group.contains('some.name')).toBe(true); }); }); describe('statusChanges', () => { let control: FormControl; let group: FormGroup; beforeEach(async(() => { control = new FormControl('', asyncValidatorReturningObservable); group = new FormGroup({'one': control}); })); // TODO(kara): update these tests to use fake Async it('should fire a statusChange if child has async validation change', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const loggedValues: string[] = []; group.statusChanges.subscribe({ next: (status: string) => { loggedValues.push(status); if (loggedValues.length === 2) { expect(loggedValues).toEqual(['PENDING', 'INVALID']); } async.done(); } }); control.setValue(''); })); }); describe('getError', () => { it('should return the error when it is present', () => { const c = new FormControl('', Validators.required); const g = new FormGroup({'one': c}); expect(c.getError('required')).toEqual(true); expect(g.getError('required', ['one'])).toEqual(true); }); it('should return null otherwise', () => { const c = new FormControl('not empty', Validators.required); const g = new FormGroup({'one': c}); expect(c.getError('invalid')).toEqual(null); expect(g.getError('required', ['one'])).toEqual(null); expect(g.getError('required', ['invalid'])).toEqual(null); }); }); describe('asyncValidator', () => { it('should run the async validator', fakeAsync(() => { const c = new FormControl('value'); const g = new FormGroup({'one': c}, null, asyncValidator('expected')); expect(g.pending).toEqual(true); tick(1); expect(g.errors).toEqual({'async': true}); expect(g.pending).toEqual(false); })); it('should set the parent group\'s status to pending', fakeAsync(() => { const c = new FormControl('value', null, asyncValidator('expected')); const g = new FormGroup({'one': c}); expect(g.pending).toEqual(true); tick(1); expect(g.pending).toEqual(false); })); it('should run the parent group\'s async validator when children are pending', fakeAsync(() => { const c = new FormControl('value', null, asyncValidator('expected')); const g = new FormGroup({'one': c}, null, asyncValidator('expected')); tick(1); expect(g.errors).toEqual({'async': true}); expect(g.get('one').errors).toEqual({'async': true}); })); }); describe('disable() & enable()', () => { it('should mark the group as disabled', () => { const g = new FormGroup({'one': new FormControl(null)}); expect(g.disabled).toBe(false); expect(g.valid).toBe(true); g.disable(); expect(g.disabled).toBe(true); expect(g.valid).toBe(false); g.enable(); expect(g.disabled).toBe(false); expect(g.valid).toBe(true); }); it('should set the group status as disabled', () => { const g = new FormGroup({'one': new FormControl(null)}); expect(g.status).toEqual('VALID'); g.disable(); expect(g.status).toEqual('DISABLED'); g.enable(); expect(g.status).toBe('VALID'); }); it('should mark children of the group as disabled', () => { const c1 = new FormControl(null); const c2 = new FormControl(null); const g = new FormGroup({'one': c1, 'two': c2}); expect(c1.disabled).toBe(false); expect(c2.disabled).toBe(false); g.disable(); expect(c1.disabled).toBe(true); expect(c2.disabled).toBe(true); g.enable(); expect(c1.disabled).toBe(false); expect(c2.disabled).toBe(false); }); it('should ignore disabled controls in validation', () => { const g = new FormGroup({ nested: new FormGroup({one: new FormControl(null, Validators.required)}), two: new FormControl('two') }); expect(g.valid).toBe(false); g.get('nested').disable(); expect(g.valid).toBe(true); g.get('nested').enable(); expect(g.valid).toBe(false); }); it('should ignore disabled controls when serializing value', () => { const g = new FormGroup( {nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')}); expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'}); g.get('nested').disable(); expect(g.value).toEqual({'two': 'two'}); g.get('nested').enable(); expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'}); }); it('should update its value when disabled with disabled children', () => { const g = new FormGroup( {nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})}); g.get('nested.two').disable(); expect(g.value).toEqual({nested: {one: 'one'}}); g.get('nested').disable(); expect(g.value).toEqual({nested: {one: 'one', two: 'two'}}); g.get('nested').enable(); expect(g.value).toEqual({nested: {one: 'one', two: 'two'}}); }); it('should update its value when enabled with disabled children', () => { const g = new FormGroup( {nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})}); g.get('nested.two').disable(); expect(g.value).toEqual({nested: {one: 'one'}}); g.get('nested').enable(); expect(g.value).toEqual({nested: {one: 'one', two: 'two'}}); }); it('should ignore disabled controls when determining dirtiness', () => { const g = new FormGroup( {nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')}); g.get('nested.one').markAsDirty(); expect(g.dirty).toBe(true); g.get('nested').disable(); expect(g.get('nested').dirty).toBe(true); expect(g.dirty).toEqual(false); g.get('nested').enable(); expect(g.dirty).toEqual(true); }); it('should ignore disabled controls when determining touched state', () => { const g = new FormGroup( {nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')}); g.get('nested.one').markAsTouched(); expect(g.touched).toBe(true); g.get('nested').disable(); expect(g.get('nested').touched).toBe(true); expect(g.touched).toEqual(false); g.get('nested').enable(); expect(g.touched).toEqual(true); }); it('should keep empty, disabled groups disabled when updating validity', () => { const group = new FormGroup({}); expect(group.status).toEqual('VALID'); group.disable(); expect(group.status).toEqual('DISABLED'); group.updateValueAndValidity(); expect(group.status).toEqual('DISABLED'); group.addControl('one', new FormControl({value: '', disabled: true})); expect(group.status).toEqual('DISABLED'); group.addControl('two', new FormControl()); expect(group.status).toEqual('VALID'); }); it('should re-enable empty, disabled groups', () => { const group = new FormGroup({}); group.disable(); expect(group.status).toEqual('DISABLED'); group.enable(); expect(group.status).toEqual('VALID'); }); it('should not run validators on disabled controls', () => { const validator = jasmine.createSpy('validator'); const g = new FormGroup({'one': new FormControl()}, validator); expect(validator.calls.count()).toEqual(1); g.disable(); expect(validator.calls.count()).toEqual(1); g.setValue({one: 'value'}); expect(validator.calls.count()).toEqual(1); g.enable(); expect(validator.calls.count()).toEqual(2); }); describe('disabled errors', () => { it('should clear out group errors when disabled', () => { const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true})); expect(g.errors).toEqual({'expected': true}); g.disable(); expect(g.errors).toEqual(null); g.enable(); expect(g.errors).toEqual({'expected': true}); }); it('should re-populate group errors when enabled from a child', () => { const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true})); g.disable(); expect(g.errors).toEqual(null); g.addControl('two', new FormControl()); expect(g.errors).toEqual({'expected': true}); }); it('should clear out async group errors when disabled', fakeAsync(() => { const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected')); tick(); expect(g.errors).toEqual({'async': true}); g.disable(); expect(g.errors).toEqual(null); g.enable(); tick(); expect(g.errors).toEqual({'async': true}); })); it('should re-populate async group errors when enabled from a child', fakeAsync(() => { const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected')); tick(); expect(g.errors).toEqual({'async': true}); g.disable(); expect(g.errors).toEqual(null); g.addControl('two', new FormControl()); tick(); expect(g.errors).toEqual({'async': true}); })); }); describe('disabled events', () => { let logger: string[]; let c: FormControl; let g: FormGroup; let form: FormGroup; beforeEach(() => { logger = []; c = new FormControl('', Validators.required); g = new FormGroup({one: c}); form = new FormGroup({g: g}); }); it('should emit value change events in the right order', () => { c.valueChanges.subscribe(() => logger.push('control')); g.valueChanges.subscribe(() => logger.push('group')); form.valueChanges.subscribe(() => logger.push('form')); g.disable(); expect(logger).toEqual(['control', 'group', 'form']); }); it('should emit status change events in the right order', () => { c.statusChanges.subscribe(() => logger.push('control')); g.statusChanges.subscribe(() => logger.push('group')); form.statusChanges.subscribe(() => logger.push('form')); g.disable(); expect(logger).toEqual(['control', 'group', 'form']); }); }); }); describe('updateTreeValidity()', () => { let c: FormControl, c2: FormControl, c3: FormControl; let nested: FormGroup, form: FormGroup; let logger: string[]; beforeEach(() => { c = new FormControl('one'); c2 = new FormControl('two'); c3 = new FormControl('three'); nested = new FormGroup({one: c, two: c2}); form = new FormGroup({nested: nested, three: c3}); logger = []; c.statusChanges.subscribe(() => logger.push('one')); c2.statusChanges.subscribe(() => logger.push('two')); c3.statusChanges.subscribe(() => logger.push('three')); nested.statusChanges.subscribe(() => logger.push('nested')); form.statusChanges.subscribe(() => logger.push('form')); }); it('should update tree validity', () => { form._updateTreeValidity(); expect(logger).toEqual(['one', 'two', 'nested', 'three', 'form']); }); it('should not emit events when turned off', () => { form._updateTreeValidity({emitEvent: false}); expect(logger).toEqual([]); }); }); describe('setControl()', () => { let c: FormControl; let g: FormGroup; beforeEach(() => { c = new FormControl('one'); g = new FormGroup({one: c}); }); it('should replace existing control with new control', () => { const c2 = new FormControl('new!', Validators.minLength(10)); g.setControl('one', c2); expect(g.controls['one']).toEqual(c2); expect(g.value).toEqual({one: 'new!'}); expect(g.valid).toBe(false); }); it('should add control if control did not exist before', () => { const c2 = new FormControl('new!', Validators.minLength(10)); g.setControl('two', c2); expect(g.controls['two']).toEqual(c2); expect(g.value).toEqual({one: 'one', two: 'new!'}); expect(g.valid).toBe(false); }); it('should remove control if new control is null', () => { g.setControl('one', null); expect(g.controls['one']).not.toBeDefined(); expect(g.value).toEqual({}); }); it('should only emit value change event once', () => { const logger: string[] = []; const c2 = new FormControl('new!'); g.valueChanges.subscribe(() => logger.push('change!')); g.setControl('one', c2); expect(logger).toEqual(['change!']); }); }); }); }
tolemac/angular
modules/@angular/forms/test/form_group_spec.ts
TypeScript
mit
36,063
// ========================================================================== // Project: SproutCore Metal // Copyright: ©2011 Strobe Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== require('sproutcore-metal'); function isEnumerable(obj, keyName) { var keys = []; for(var key in obj) { if (obj.hasOwnProperty(key)) keys.push(key); } return keys.indexOf(keyName)>=0; } module("SC.platform.defineProperty()"); test("defining a simple property", function() { var obj = {}; SC.platform.defineProperty(obj, 'foo', { enumerable: true, writable: true, value: 'FOO' }); equals(obj.foo, 'FOO', 'should have added property'); obj.foo = "BAR"; equals(obj.foo, 'BAR', 'writable defined property should be writable'); equals(isEnumerable(obj, 'foo'), true, 'foo should be enumerable'); }); test('defining a read only property', function() { var obj = {}; SC.platform.defineProperty(obj, 'foo', { enumerable: true, writable: false, value: 'FOO' }); equals(obj.foo, 'FOO', 'should have added property'); obj.foo = "BAR"; if (SC.platform.defineProperty.isSimulated) { equals(obj.foo, 'BAR', 'simulated defineProperty should silently work'); } else { equals(obj.foo, 'FOO', 'real defined property should not be writable'); } }); test('defining a non enumerable property', function() { var obj = {}; SC.platform.defineProperty(obj, 'foo', { enumerable: false, writable: true, value: 'FOO' }); if (SC.platform.defineProperty.isSimulated) { equals(isEnumerable(obj, 'foo'), true, 'simulated defineProperty will leave properties enumerable'); } else { equals(isEnumerable(obj, 'foo'), false, 'real defineProperty will make property not-enumerable'); } }); test('defining a getter/setter', function() { var obj = {}, getCnt = 0, setCnt = 0, v = 'FOO'; var desc = { enumerable: true, get: function() { getCnt++; return v; }, set: function(val) { setCnt++; v = val; } }; if (SC.platform.hasPropertyAccessors) { SC.platform.defineProperty(obj, 'foo', desc); equals(obj.foo, 'FOO', 'should return getter'); equals(getCnt, 1, 'should have invoked getter'); obj.foo = 'BAR'; equals(obj.foo, 'BAR', 'setter should have worked'); equals(setCnt, 1, 'should have invoked setter'); } else { raises(function() { SC.platform.defineProperty(obj, 'foo', desc); }, Error, 'should throw exception if getters/setters not supported'); } }); test('defining getter/setter along with writable', function() { var obj ={}; raises(function() { SC.platform.defineProperty(obj, 'foo', { enumerable: true, get: function() {}, set: function() {}, writable: true }); }, Error, 'defining writable and get/set should throw exception'); }); test('defining getter/setter along with value', function() { var obj ={}; raises(function() { SC.platform.defineProperty(obj, 'foo', { enumerable: true, get: function() {}, set: function() {}, value: 'FOO' }); }, Error, 'defining value and get/set should throw exception'); });
crofty/sensor_js_message_parsing
vendor/sproutcore-metal/tests/platform/defineProperty_test.js
JavaScript
mit
3,281
require 'rubygems' require 'active_support' require 'active_merchant' class GatewaySupport #:nodoc: ACTIONS = [:purchase, :authorize, :capture, :void, :credit, :recurring] include ActiveMerchant::Billing attr_reader :gateways def initialize Dir[File.expand_path(File.dirname(__FILE__) + '/../active_merchant/billing/gateways/*.rb')].each do |f| filename = File.basename(f, '.rb') gateway_name = filename + '_gateway' begin gateway_class = ('ActiveMerchant::Billing::' + gateway_name.camelize).constantize rescue NameError puts 'Could not load gateway ' + gateway_name.camelize + ' from ' + f + '.' end end @gateways = Gateway.implementations.sort_by(&:name) @gateways.delete(ActiveMerchant::Billing::BogusGateway) end def each_gateway @gateways.each{|g| yield g } end def features width = 15 print 'Name'.center(width + 20) ACTIONS.each{|f| print "#{f.to_s.capitalize.center(width)}" } puts each_gateway do |g| print "#{g.display_name.ljust(width + 20)}" ACTIONS.each do |f| print "#{(g.instance_methods.include?(f.to_s) ? "Y" : "N").center(width)}" end puts end end def to_rdoc each_gateway do |g| puts "* {#{g.display_name}}[#{g.homepage_url}] - #{g.supported_countries.join(', ')}" end end def to_textile each_gateway do |g| puts %/ * "#{g.display_name}":#{g.homepage_url} [#{g.supported_countries.join(', ')}]/ end end def to_markdown each_gateway do |g| puts %/* [#{g.display_name}](#{g.homepage_url}) - #{g.supported_countries.join(', ')}/ end end def to_s each_gateway do |g| puts "#{g.display_name} - #{g.homepage_url} [#{g.supported_countries.join(', ')}]" end end end
reinteractive/active_merchant
lib/support/gateway_support.rb
Ruby
mit
1,804
/* * Copyright (c) 2011-2015 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * http://github.com/piranhacms/piranha * */ using System; using System.Collections.Generic; namespace Piranha.Extend { /// <summary> /// Base class for easily defining a page type. /// </summary> public abstract class PageType : IPageType { /// <summary> /// Gets the name. /// </summary> public virtual string Name { get; protected set; } /// <summary> /// Gets the optional description. /// </summary> public virtual string Description { get; protected set; } /// <summary> /// Gets the html preview. /// </summary> public virtual string Preview { get; protected set; } /// <summary> /// Gets the controller/viewtemplate depending on the current /// application is using WebPages or Mvc. /// </summary> public virtual string Controller { get; protected set; } /// <summary> /// Gets if pages of the current type should be able to /// override the controller. /// </summary> public virtual bool ShowController { get; protected set; } /// <summary> /// Gets the view. This is only relevant for Mvc applications. /// </summary> public virtual string View { get; protected set; } /// <summary> /// Gets if pages of the current type should be able to /// override the controller. /// </summary> public virtual bool ShowView { get; protected set; } /// <summary> /// Gets/sets the optional permalink of a page this sould redirect to. /// </summary> public virtual string Redirect { get; protected set; } /// <summary> /// Gets/sets if the redirect can be overriden by the implementing page. /// </summary> public virtual bool ShowRedirect { get; protected set; } /// <summary> /// Gets the defíned properties. /// </summary> public virtual IList<string> Properties { get; protected set; } /// <summary> /// Gets the defined regions. /// </summary> public virtual IList<RegionType> Regions { get; protected set; } public PageType() { Properties = new List<string>(); Regions = new List<RegionType>(); Preview = "<table class=\"template\"><tr><td></td></tr></table>"; } } }
timbrown81/Piranha
Core/Piranha/Extend/PageType.cs
C#
mit
2,364
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GetNodeScriptsTest.cs" company="automotiveMastermind and contributors"> // © automotiveMastermind and contributors. Licensed under MIT. See LICENSE and CREDITS for details. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace AM.Condo.Tasks { using System.IO; using Microsoft.Build.Utilities; using Newtonsoft.Json; using Xunit; using AM.Condo.IO; [Class(nameof(GetNodeMetadata))] public class GetNodeScriptsTest { [Fact] [Priority(2)] [Purpose(PurposeType.Integration)] public void Execute_WithValidProject_Succeeds() { using (var temp = new TemporaryPath()) { // arrange var project = new { name = "test", version = "1.0.0", description = "", main = "index.js", scripts = new { test = "echo this is a test script", ci = "echo this is a ci script" }, author = "automotiveMastermind", license = "MIT" }; var expected = new[] { "test", "ci" }; var path = temp.Combine("package.json"); using (var writer = File.CreateText(path)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, project); writer.Flush(); } var items = new[] { new TaskItem(path) }; var engine = MSBuildMocks.CreateEngine(); var instance = new GetNodeMetadata { Projects = items, BuildEngine = engine }; // act var result = instance.Execute(); // assert Assert.True(result); } } } }
automotiveMastermind/condo
test/AM.Condo.Test/Tasks/GetNodeScriptsTest.cs
C#
mit
2,251
<?php /* SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig */ class __TwigTemplate_16b98d4be50387198a258942bcac860cb5e7d142e913464f9538849439128cff extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'row' => array($this, 'block_row'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 11 echo " "; // line 12 if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) { // line 13 echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-batch\"> "; // line 14 echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "batch", array(), "array")); echo " </td> "; } // line 17 echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-inline-fields\" colspan=\""; // line 18 echo twig_escape_filter($this->env, (twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "elements", array())) - ($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") + $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method"))), "html", null, true); echo "\" objectId=\""; echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true); echo "\"> "; // line 19 $this->displayBlock('row', $context, $blocks); // line 20 echo "</td> "; // line 22 if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) { // line 23 echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-_action\" objectId=\""; echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true); echo "\"> "; // line 24 echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "_action", array(), "array")); echo " </td> "; } } // line 19 public function block_row($context, array $blocks = array()) { } public function getTemplateName() { return "SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 64 => 19, 56 => 24, 51 => 23, 49 => 22, 45 => 20, 43 => 19, 37 => 18, 34 => 17, 28 => 14, 25 => 13, 23 => 12, 20 => 11,); } }
chicho2114/Proy_Frameworks
app/cache/prod/twig/16/b9/8d4be50387198a258942bcac860cb5e7d142e913464f9538849439128cff.php
PHP
mit
3,962
<?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" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: tictactoeplugin.h Example File (designer/taskmenuextension/tictactoeplugin.h)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">tictactoeplugin.h Example File</h1> <span class="small-subtitle">designer/taskmenuextension/tictactoeplugin.h</span> <!-- $$$designer/taskmenuextension/tictactoeplugin.h-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> <span class="comment">/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** &quot;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 Digia Plc and its Subsidiary(-ies) 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 ** &quot;AS IS&quot; 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.&quot; ** ** $QT_END_LICENSE$ ** ****************************************************************************/</span> <span class="preprocessor">#ifndef TICTACTOEPLUGIN_H</span> <span class="preprocessor">#define TICTACTOEPLUGIN_H</span> <span class="preprocessor">#include &lt;QDesignerCustomWidgetInterface&gt;</span> <span class="keyword">class</span> <span class="type"><a href="qicon.html">QIcon</a></span>; <span class="keyword">class</span> <span class="type"><a href="qwidget.html">QWidget</a></span>; <span class="keyword">class</span> TicTacToePlugin : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">,</span> <span class="keyword">public</span> <span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span> { Q_OBJECT Q_INTERFACES(<span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span>) <span class="keyword">public</span>: TicTacToePlugin(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>); <span class="type"><a href="qstring.html">QString</a></span> name() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> group() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> toolTip() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> whatsThis() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> includeFile() <span class="keyword">const</span>; <span class="type"><a href="qicon.html">QIcon</a></span> icon() <span class="keyword">const</span>; <span class="type">bool</span> isContainer() <span class="keyword">const</span>; <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>createWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent); <span class="type">bool</span> isInitialized() <span class="keyword">const</span>; <span class="type">void</span> initialize(<span class="type"><a href="qdesignerformeditorinterface.html">QDesignerFormEditorInterface</a></span> <span class="operator">*</span>formEditor); <span class="type"><a href="qstring.html">QString</a></span> domXml() <span class="keyword">const</span>; <span class="keyword">private</span>: <span class="type">bool</span> initialized; }; <span class="preprocessor">#endif</span></pre> </div> <!-- @@@designer/taskmenuextension/tictactoeplugin.h --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
stephaneAG/PengPod700
QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/designer-taskmenuextension-tictactoeplugin-h.html
HTML
mit
13,994
var Promise = require('ember-cli/lib/ext/promise'); module.exports = { normalizeEntityName: function() {}, afterInstall: function() { var addonContext = this; return this.addBowerPackageToProject('jquery-ui', '1.10.1') .then(function() { return addonContext.addBowerPackageToProject('jquery-mousewheel', '~3.1.4'); }) .then(function() { return addonContext.addBowerPackageToProject('taras/antiscroll', '92505e0e0d0ef9383630df509883bce558215b22'); }); } };
ming-codes/ember-cli-ember-table
blueprints/ember-cli-ember-table/index.js
JavaScript
mit
515
import time import random from random import randint # from library import Trigger, Axis # from library import PS4 from library import Joystick import RPi.GPIO as GPIO # remove!!! from emotions import angry, happy, confused # from pysabertooth import Sabertooth # from smc import SMC from library import LEDDisplay from library import factory from library import reset_all_hw # Leg Motor Speed Global global_LegMotor = 70 # # Happy Emotion # def happy(leds, servos, mc, audio): # print("4") # print("Happy") # # # Dome Motor Initialization # # mc = SMC(dome_motor_port, 115200) # # mc.init() # # # Spins Motor # # mc.init() # mc.speed(3200) # # # LED Matrix Green # # breadboard has mono # # R2 has bi-color leds # # mono:0 bi:1 # # led_type = 0 # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, led_type) # # leds[2] = LEDDisplay(0x71, led_type) # # leds[3] = LEDDisplay(0x72, led_type) # # leds[4] = LEDDisplay(0x73, led_type) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 1) # # for i in range(1, 5): # leds[i].write() # # # Servo Wave # # s0.angle = 0 # # time.sleep(0.2) # # s1.angle = 0 # # time.sleep(0.2) # # s2.angle = 0 # # time.sleep(0.2) # # s3.angle = 0 # # time.sleep(0.2) # # s4.angle = 0 # # time.sleep(0.5) # # s4.angle = 130 # # time.sleep(0.2) # # s3.angle = 130 # # time.sleep(0.2) # # s2.angle = 130 # # time.sleep(0.2) # # s1.angle = 130 # # time.sleep(0.2) # # s0.angle = 130 # # for a in [0, 130]: # for i in range(4): # servos[i].angle = a # time.sleep(0.2) # time.sleep(0.5) # # time.sleep(1.5) # mc.stop() # time.sleep(1.5) # for i in range(1, 5): # leds[i].clear() # # # # Confused Emotion # def confused(leds, servos, mc, audio): # print("5") # print("Confused") # # LED Matrix Yellow # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, 1) # # leds[2] = LEDDisplay(0x71, 1) # # leds[3] = LEDDisplay(0x72, 1) # # leds[4] = LEDDisplay(0x73, 1) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 3) # for i in range(1, 5): # leds[i].write() # time.sleep(3) # for i in range(1, 5): # leds[i].clear() # # # # Angry Emotion # def angry(leds, servos, mc, audio): # print("6") # print("Angry") # # LED Matrix Red # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, 1) # # leds[2] = LEDDisplay(0x71, 1) # # leds[3] = LEDDisplay(0x72, 1) # # leds[4] = LEDDisplay(0x73, 1) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 2) # # for i in range(1, 5): # leds[i].write() # # # Plays Imperial Theme Sound # audio.sound('imperial') # # # Servo Open and Close # # s0.angle = 0 # # s1.angle = 0 # # s2.angle = 0 # # s3.angle = 0 # # s4.angle = 0 # # time.sleep(1) # # s4.angle = 130 # # s3.angle = 130 # # s2.angle = 130 # # s1.angle = 130 # # s0.angle = 130 # # for a in [0, 130]: # for i in range(5): # servos[i].angle = a # time.sleep(1) # # time.sleep(3) # for i in range(1, 5): # leds[i].clear() ####################################### # original remote ####################################### # # Remote Mode # def remote(remoteflag, namespace): # print("Remote") # # # create objects # (leds, dome, legs, servos, Flash) = factory(['leds', 'dome', 'legs', 'servos', 'flashlight']) # # # initalize everything # dome.init() # dome.speed(0) # # legs.drive(1, 0) # legs.drive(2, 0) # # for s in servos: # s.angle = 0 # time.sleep(0.25) # # # what is this??? # GPIO.setmode(GPIO.BCM) # GPIO.setwarnings(False) # GPIO.setup(26, GPIO.OUT) # # # Joystick Initialization # js = Joystick() # # # get audio # audio = namespace.audio # # # Flash = FlashlightPWM(15) # # Flash = namespace.flashlight # # while(remoteflag.is_set()): # try: # # Button Initialization # ps4 = js.get() # btnSquare = ps4.buttons[0] # btnTriangle = ps4.buttons[1] # btnCircle = ps4.buttons[2] # btnX = ps4.buttons[3] # btnLeftStickLeftRight = ps4.leftStick.y # btnLeftStickUpDown = ps4.leftStick.x # btnRightStickLeftRight = ps4.rightStick.y # btnRightStickUpDown = ps4.rightStick.x # Left1 = ps4.shoulder[0] # Right1 = ps4.shoulder[1] # Left2 = ps4.triggers.x # Right2 = ps4.triggers.y # hat = ps4.hat # # # print("PRINT") # # # Button Controls # if hat == 1: # # Happy Emotion # print("Arrow Up Pressed") # happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio) # if hat == 8: # # Confused Emotion # print("Arrow Left Pressed") # confused(leds, servos, dome, audio) # if hat == 2: # # Angry Emotion # print("Arrow Right Pressed") # angry(leds, servos, dome, audio) # if hat == 4: # print("Arrow Down Pressed") # if btnSquare == 1: # # word = random_char(2) # audio.speak_random(2) # time.sleep(0.5) # if btnTriangle == 1: # # FlashLight ON # GPIO.output(26, GPIO.HIGH) # Flash.pwm.set_pwm(15, 0, 130) # if btnCircle == 1: # # FlashLight OFF # GPIO.output(26, GPIO.LOW) # Flash.pwm.set_pwm(15, 0, 0) # if btnX == 1: # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # if x == randint(0, 8) or y == randint(0, 8): # for i in range(1, 5): # leds[i].set(x, y, randint(0, 4)) # else: # for i in range(1, 5): # leds[i].set(x, y, 4) # for i in range(1, 5): # leds[i].write() # time.sleep(0.1) # for i in range(1, 5): # leds[i].clear() # if Left1 == 1: # # Dome Motor Forward # dome.speed(3200) # time.sleep(2) # dome.speed(0) # if Right1 == 1: # # Dome Motor Backward # dome.speed(-3200) # time.sleep(2) # dome.speed(0) # # if Left1 == 0 or Right1 == 0: # # # Dome Motor Stop # # dome.speed(0) # # if Left2 > 1: # # # Servo Open # # s0.angle = 0 # # s1.angle = 0 # # s2.angle = 0 # # s3.angle = 0 # # s4.angle = 0 # # Flash.pwm.set_pwm(15, 0, 3000) # # # # if Right2 > 1: # # # Servo Close # # s0.angle = 130 # # s1.angle = 130 # # s2.angle = 130 # # s3.angle = 130 # # s4.angle = 130 # # Flash.pwm.set_pwm(15, 0, 130) # if Left2 > 1: # for s in servos: # s.angle = 0 # time.sleep(0.25) # Flash.pwm.set_pwm(15, 0, 300) # if Right2 > 1: # for s in servos: # s.angle = 130 # time.sleep(0.25) # Flash.pwm.set_pwm(15, 0, 130) # if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3: # legs.drive(1, 0) # if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3: # legs.drive(2, 0) # if btnRightStickUpDown >= 0.3: # # Right and Left Motor Forward # legs.drive(1, btnRightStickUpDown*global_LegMotor) # legs.drive(2, btnRightStickUpDown*-global_LegMotor) # if btnRightStickUpDown <= -0.3: # # Right and Left Motor Backward # legs.drive(1, btnRightStickUpDown*global_LegMotor) # legs.drive(2, btnRightStickUpDown*-global_LegMotor) # if btnLeftStickLeftRight <= 0.3: # # Turn Left # legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) # legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) # if btnLeftStickLeftRight >= -0.3: # # Turn Right # legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) # legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) # # except KeyboardInterrupt: # print('js exiting ...') # return # return def remote_func(hw, ns): print("Remote") dome = hw['dome'] dome.speed(0) legs = hw['legs'] legs.drive(1, 0) legs.drive(2, 0) flashlight = hw['flashlight'] audio = hw['audio'] audio.speak('start') while ns.current_state == 3: print('remote ...') spd = random.randint(0, 40) legs.drive(1, spd) legs.drive(2, spd) dome.speed(spd) time.sleep(0.5) legs.drive(1, 0) legs.drive(2, 0) dome.speed(0) time.sleep(0.1) return ###### real loop here ##### # Joystick Initialization js = Joystick() while ns.current_state == 3: try: # Button Initialization ps4 = js.get() btnSquare = ps4.buttons[0] btnTriangle = ps4.buttons[1] btnCircle = ps4.buttons[2] btnX = ps4.buttons[3] btnLeftStickLeftRight = ps4.leftStick.y btnLeftStickUpDown = ps4.leftStick.x btnRightStickLeftRight = ps4.rightStick.y btnRightStickUpDown = ps4.rightStick.x Left1 = ps4.shoulder[0] Right1 = ps4.shoulder[1] Left2 = ps4.triggers.x Right2 = ps4.triggers.y hat = ps4.hat # print("PRINT") # Button Controls if hat == 1: # Happy Emotion print("Arrow Up Pressed") happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio) if hat == 8: # Confused Emotion print("Arrow Left Pressed") confused(leds, servos, dome, audio) if hat == 2: # Angry Emotion print("Arrow Right Pressed") angry(leds, servos, dome, audio) if hat == 4: print("Arrow Down Pressed") if btnSquare == 1: # word = random_char(2) audio.speak_random(2) time.sleep(0.5) if btnTriangle == 1: # FlashLight ON GPIO.output(26, GPIO.HIGH) Flash.pwm.set_pwm(15, 0, 130) if btnCircle == 1: # FlashLight OFF GPIO.output(26, GPIO.LOW) Flash.pwm.set_pwm(15, 0, 0) if btnX == 1: for x in [0, 1, 2, 3, 4, 5, 6, 7]: for y in [0, 1, 2, 3, 4, 5, 6, 7]: if x == randint(0, 8) or y == randint(0, 8): for i in range(1, 5): leds[i].set(x, y, randint(0, 4)) else: for i in range(1, 5): leds[i].set(x, y, 4) for i in range(1, 5): leds[i].write() time.sleep(0.1) for i in range(1, 5): leds[i].clear() if Left1 == 1: # Dome Motor Forward dome.speed(3200) time.sleep(2) dome.speed(0) if Right1 == 1: # Dome Motor Backward dome.speed(-3200) time.sleep(2) dome.speed(0) # if Left1 == 0 or Right1 == 0: # # Dome Motor Stop # dome.speed(0) # if Left2 > 1: # # Servo Open # s0.angle = 0 # s1.angle = 0 # s2.angle = 0 # s3.angle = 0 # s4.angle = 0 # Flash.pwm.set_pwm(15, 0, 3000) # # if Right2 > 1: # # Servo Close # s0.angle = 130 # s1.angle = 130 # s2.angle = 130 # s3.angle = 130 # s4.angle = 130 # Flash.pwm.set_pwm(15, 0, 130) if Left2 > 1: for s in servos: s.angle = 0 time.sleep(0.25) Flash.pwm.set_pwm(15, 0, 300) if Right2 > 1: for s in servos: s.angle = 130 time.sleep(0.25) Flash.pwm.set_pwm(15, 0, 130) if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3: legs.drive(1, 0) if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3: legs.drive(2, 0) if btnRightStickUpDown >= 0.3: # Right and Left Motor Forward legs.drive(1, btnRightStickUpDown*global_LegMotor) legs.drive(2, btnRightStickUpDown*-global_LegMotor) if btnRightStickUpDown <= -0.3: # Right and Left Motor Backward legs.drive(1, btnRightStickUpDown*global_LegMotor) legs.drive(2, btnRightStickUpDown*-global_LegMotor) if btnLeftStickLeftRight <= 0.3: # Turn Left legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) if btnLeftStickLeftRight >= -0.3: # Turn Right legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) except KeyboardInterrupt: print('js exiting ...') return # exiting, reset all hw reset_all_hw(hw) return
DFEC-R2D2/r2d2
pygecko/states/remote.py
Python
mit
11,721
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class Api < Domain class V2010 < Version class AccountContext < InstanceContext class ApplicationList < ListResource ## # Initialize the ApplicationList # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # {Account}[https://www.twilio.com/docs/iam/api/account] that created the # Application resource. # @return [ApplicationList] ApplicationList def initialize(version, account_sid: nil) super(version) # Path Solution @solution = {account_sid: account_sid} @uri = "/Accounts/#{@solution[:account_sid]}/Applications.json" end ## # Create the ApplicationInstance # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default # API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @param [String] friendly_name A descriptive string that you create to describe # the new application. It can be up to 64 characters long. # @return [ApplicationInstance] Created ApplicationInstance def create(api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset, friendly_name: :unset) data = Twilio::Values.of({ 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, 'FriendlyName' => friendly_name, }) payload = @version.create('POST', @uri, data: data) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Lists ApplicationInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into # memory before returning. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Array] Array of up to limit results def list(friendly_name: :unset, limit: nil, page_size: nil) self.stream(friendly_name: friendly_name, limit: limit, page_size: page_size).entries end ## # Streams ApplicationInstance records from the API as an Enumerable. # This operation lazily loads records as efficiently as possible until the limit # is reached. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit. # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Enumerable] Enumerable that will yield up to limit results def stream(friendly_name: :unset, limit: nil, page_size: nil) limits = @version.read_limits(limit, page_size) page = self.page(friendly_name: friendly_name, page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end ## # When passed a block, yields ApplicationInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit # is reached. def each limits = @version.read_limits page = self.page(page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]).each {|x| yield x} end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state # @param [Integer] page_size Number of records to return, defaults to 50 # @return [Page] Page of ApplicationInstance def page(friendly_name: :unset, page_token: :unset, page_number: :unset, page_size: :unset) params = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'PageToken' => page_token, 'Page' => page_number, 'PageSize' => page_size, }) response = @version.page('GET', @uri, params: params) ApplicationPage.new(@version, response, @solution) end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] target_url API-generated URL for the requested results page # @return [Page] Page of ApplicationInstance def get_page(target_url) response = @version.domain.request( 'GET', target_url ) ApplicationPage.new(@version, response, @solution) end ## # Provide a user friendly representation def to_s '#<Twilio.Api.V2010.ApplicationList>' end end class ApplicationPage < Page ## # Initialize the ApplicationPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [ApplicationPage] ApplicationPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of ApplicationInstance # @param [Hash] payload Payload response from the API # @return [ApplicationInstance] ApplicationInstance def get_instance(payload) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Provide a user friendly representation def to_s '<Twilio.Api.V2010.ApplicationPage>' end end class ApplicationContext < InstanceContext ## # Initialize the ApplicationContext # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # {Account}[https://www.twilio.com/docs/iam/api/account] that created the # Application resource to fetch. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationContext] ApplicationContext def initialize(version, account_sid, sid) super(version) # Path Solution @solution = {account_sid: account_sid, sid: sid, } @uri = "/Accounts/#{@solution[:account_sid]}/Applications/#{@solution[:sid]}.json" end ## # Delete the ApplicationInstance # @return [Boolean] true if delete succeeds, false otherwise def delete @version.delete('DELETE', @uri) end ## # Fetch the ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch payload = @version.fetch('GET', @uri) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback Same as message_status_callback: The URL we # should call using a POST method to send status information about SMS messages # sent by the application. Deprecated, included for backwards compatibility. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) data = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, }) payload = @version.update('POST', @uri, data: data) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Provide a user friendly representation def to_s context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end ## # Provide a detailed, user friendly representation def inspect context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end end class ApplicationInstance < InstanceResource ## # Initialize the ApplicationInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] account_sid The SID of the # {Account}[https://www.twilio.com/docs/iam/api/account] that created the # Application resource. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationInstance] ApplicationInstance def initialize(version, payload, account_sid: nil, sid: nil) super(version) # Marshaled Properties @properties = { 'account_sid' => payload['account_sid'], 'api_version' => payload['api_version'], 'date_created' => Twilio.deserialize_rfc2822(payload['date_created']), 'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']), 'friendly_name' => payload['friendly_name'], 'message_status_callback' => payload['message_status_callback'], 'sid' => payload['sid'], 'sms_fallback_method' => payload['sms_fallback_method'], 'sms_fallback_url' => payload['sms_fallback_url'], 'sms_method' => payload['sms_method'], 'sms_status_callback' => payload['sms_status_callback'], 'sms_url' => payload['sms_url'], 'status_callback' => payload['status_callback'], 'status_callback_method' => payload['status_callback_method'], 'uri' => payload['uri'], 'voice_caller_id_lookup' => payload['voice_caller_id_lookup'], 'voice_fallback_method' => payload['voice_fallback_method'], 'voice_fallback_url' => payload['voice_fallback_url'], 'voice_method' => payload['voice_method'], 'voice_url' => payload['voice_url'], } # Context @instance_context = nil @params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], } end ## # Generate an instance context for the instance, the context is capable of # performing various actions. All instance actions are proxied to the context # @return [ApplicationContext] ApplicationContext for this ApplicationInstance def context unless @instance_context @instance_context = ApplicationContext.new(@version, @params['account_sid'], @params['sid'], ) end @instance_context end ## # @return [String] The SID of the Account that created the resource def account_sid @properties['account_sid'] end ## # @return [String] The API version used to start a new TwiML session def api_version @properties['api_version'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was created def date_created @properties['date_created'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was last updated def date_updated @properties['date_updated'] end ## # @return [String] The string that you assigned to describe the resource def friendly_name @properties['friendly_name'] end ## # @return [String] The URL to send message status information to your application def message_status_callback @properties['message_status_callback'] end ## # @return [String] The unique string that identifies the resource def sid @properties['sid'] end ## # @return [String] The HTTP method used with sms_fallback_url def sms_fallback_method @properties['sms_fallback_method'] end ## # @return [String] The URL that we call when an error occurs while retrieving or executing the TwiML def sms_fallback_url @properties['sms_fallback_url'] end ## # @return [String] The HTTP method to use with sms_url def sms_method @properties['sms_method'] end ## # @return [String] The URL to send status information to your application def sms_status_callback @properties['sms_status_callback'] end ## # @return [String] The URL we call when the phone number receives an incoming SMS message def sms_url @properties['sms_url'] end ## # @return [String] The URL to send status information to your application def status_callback @properties['status_callback'] end ## # @return [String] The HTTP method we use to call status_callback def status_callback_method @properties['status_callback_method'] end ## # @return [String] The URI of the resource, relative to `https://api.twilio.com` def uri @properties['uri'] end ## # @return [Boolean] Whether to lookup the caller's name def voice_caller_id_lookup @properties['voice_caller_id_lookup'] end ## # @return [String] The HTTP method used with voice_fallback_url def voice_fallback_method @properties['voice_fallback_method'] end ## # @return [String] The URL we call when a TwiML error occurs def voice_fallback_url @properties['voice_fallback_url'] end ## # @return [String] The HTTP method used with the voice_url def voice_method @properties['voice_method'] end ## # @return [String] The URL we call when the phone number receives a call def voice_url @properties['voice_url'] end ## # Delete the ApplicationInstance # @return [Boolean] true if delete succeeds, false otherwise def delete context.delete end ## # Fetch the ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch context.fetch end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback Same as message_status_callback: The URL we # should call using a POST method to send status information about SMS messages # sent by the application. Deprecated, included for backwards compatibility. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) context.update( friendly_name: friendly_name, api_version: api_version, voice_url: voice_url, voice_method: voice_method, voice_fallback_url: voice_fallback_url, voice_fallback_method: voice_fallback_method, status_callback: status_callback, status_callback_method: status_callback_method, voice_caller_id_lookup: voice_caller_id_lookup, sms_url: sms_url, sms_method: sms_method, sms_fallback_url: sms_fallback_url, sms_fallback_method: sms_fallback_method, sms_status_callback: sms_status_callback, message_status_callback: message_status_callback, ) end ## # Provide a user friendly representation def to_s values = @params.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end ## # Provide a detailed, user friendly representation def inspect values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end end end end end end end
philnash/twilio-ruby
lib/twilio-ruby/rest/api/v2010/account/application.rb
Ruby
mit
28,693
<?php namespace Omnipay\Braintree\Message; /** * Find Customer Request * * @method CustomerResponse send() */ class FindCustomerRequest extends AbstractRequest { public function getData() { return $this->getCustomerData(); } /** * Send the request with specified data * * @param mixed $data The data to send * @return CustomerResponse */ public function sendData($data) { $response = $this->braintree->customer()->find($this->getCustomerId()); return $this->response = new CustomerResponse($this, $response); } }
Shimmi/omnipay-braintree
src/Message/FindCustomerRequest.php
PHP
mit
597
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pywim documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import pywim # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PyWIM' copyright = u"2016, Ivan Ogasawara" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = pywim.__version__ # The full version, including alpha/beta/rc tags. release = pywim.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built # documents. #keep_warnings = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. # Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. # Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages # will contain a <link> tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pywimdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'pywim.tex', u'PyWIM Documentation', u'Ivan Ogasawara', 'manual'), ] # The name of an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pywim', u'PyWIM Documentation', [u'Ivan Ogasawara'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pywim', u'PyWIM Documentation', u'Ivan Ogasawara', 'pywim', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
xmnlab/pywim
docs/conf.py
Python
mit
8,369
require_relative 'base' module Terjira module Client class StatusCategory < Base class << self def all @all_statuscategory ||= file_cache.fetch("all") do resp = api_get "statuscategory" resp.map { |category| build(category) } end end def file_cache Terjira::FileCache.new("resource/statuscategory", 60 * 60 * 48) end end end end end
keepcosmos/terjira
lib/terjira/client/status_category.rb
Ruby
mit
445
## 1.3.3 - 修复 #782 默认主题配置颜色选择透明度无法修改问题 - 修复 #774 部分情况 TOC 链接错误问题 ## 1.3.2 - 新增博客导出至 Hugo - 评论新增 [Waline](https://waline.js.org) 和 [Valine](https://valine.js.org) 的支持 - 修复 #748 代码高亮的问题 ## 1.3.1 - 修复配置 COS 之后上传图片会带上当前域名的问题 #737 - 修复代码块不显示最后一行的问题 #740 - 修复后台分享部分二级分类不显示的问题 ## 1.3.0 - 新增文章删除回收站 #734 - 新增标题自动转换成拼音URL #735 ## 1.2.8 - 修复标签管理无法打开的问题 #642 - 修复 is_public 属性值错误 ## 1.2.7 - 修复分类没有文章导致首页 500 问题 #641 - 修复主题管理主题配置显示错误问题 - 用户管理禁止删除有文章数的用户 ## 1.2.6 - 重构文章分类获取逻辑 - 文章更新后增加最新文章列表的缓存清除 - 修复接口允许自己选择自己为父分类的问题 #637 ## 1.2.5 - 修复有时候发布文章会变成编辑文章的问题 #628 ## 1.2.4 - 修复腾讯云 OSS 上传失败问题 #611 - 修复基本设置信息不显示,主题无法修改的错误 #612 - 修复投稿者可以内网登录的问题 #613 - 修复后台文章列表时间问题 #615 - 修复后台 icon 不显示问题 #618 - 修复 yarn 安装错误问题 #624 ## 1.2.3 - 登录新增自动登录选项 #571 - 修复用户管理用户最近登录时间不准确问题 #591 - 修复编辑文章插入内链格式错误问题 #599 - 修复编辑文章时间显示异常问题 #607 - 修复腾讯云 COS 支持后台选项丢失问题 #608 - 修复后台页面打开异常问题 #583 ## 1.2.2 - 重新修复后台无法访问问题 ## 1.2.1 - 紧急修复后台无法访问问题 ## 1.2.0 - 后台使用 React 16, TypeScript, Antd, Mobx 进行重构 - 新增上传到腾讯云 COS 支持 - 修复模板转义错误 #565 - 修复后台文章列表分类选择分页错误 ## 1.1.2 - 修复 Markdown 文件导入错误 #549 - 修复重复文件上传的报错问题 #555 - 修复主题自定义 404 错误页问题 #554 - 修复文章发布作者选择问题 - 修复标签页文章列表显示问题 - 修复多个安全漏洞 ## 1.1.1 - 修复安装时参数错误 #545 - 移除部分数据表的本地缓存功能 ## 1.1.0 - 新增 RSS 定时导入支持 - 新增上传到 AWS S3 支持 - 安装界面增加邮箱输入支持 - 默认主题修改了目录样式 - 修复 sitemap 缺少文章和页面数据的问题 - 修复 hexo 导出标签出错问题 #541 - 修复推送文章更新报错并增加推送封面图支持 #540 - 修复中文分类跳转的问题 #437 - 修复又拍云上传的兼容问题 ## 1.0.4 - 后台文章分类勾选新增父子分类联动 - 修复 0.x 迁移导致的一些BUG - 修复 #520 simtemap.xml 生成问题 - 修复 #530 后台用户删除问题 - 修复导入数据可能导致的安全问题 ## 1.0.3 - 增加 DISALLOW_FILE_EDIT 禁止编辑主题配置项 - 修复文件上传跨磁盘报错的问题 - 修复子分类列表页404问题 ## 1.0.2 - 增加内网登录支持,具体实现可参考[如何实现内网登录](https://github.com/firekylin/firekylin/wiki/%E9%97%AE%E9%A2%98%E8%A7%A3%E7%AD%94#%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%86%85%E7%BD%91%E7%99%BB%E5%BD%95) - 模板分类数据增加二级分类输出 - 修复 #512 数据导出错误 - 修复 #508 评论模块数据相同问题 ## 1.0.1 - 发布文章支持选择作者功能 - 修复 #502,七牛上传等多个上传问题 - 修复 #503 主题保存问题 ## 1.0.0 - 使用 ThinkJS3 重构项目,0.x 进入版本维护阶段 ## 0.15.18 - 新增 LDAP 登录支持 - 修复文件上传的安全漏洞 ## 0.15.17 - 新增 [sm.ms](http://sm.ms) 上传支持 - 新增 [gitalk](https://gitalk.github.io/) 评论支持 - referrer 校验仅校验主域部分,避免端口和协议不同导致的 `REFERRER_ERROR` 报错 - 安装允许 MySQL 密码为空 - 修复封面图片无法删除问题 - 修复 Markdown 上传导致的安全问题 ## 0.15.16 - 新增阿里云 OSS 上传支持 - 修复上传文件报错问题 - 修复标签缓存不生效问题 ## 0.15.15 - 修复多个安全漏洞 ## 0.15.14 - 更新 ThinkJS 依赖修复安全漏洞 - 修复默认主题图片懒加载失败问题 - Fix #431 后台搜索分页逻辑错误 - Fix #427 后台用户邮箱修改判断错误 - Fix #436 `qrcode-react` 升级造成的安装错误 ## 0.15.13 - 代码高亮优化 - BUG 修复 ## 0.15.12 - 新增文章/页面前台预览功能 - 新增文章封面图选项 - 新增找回密码功能 - Fix #395 编辑器自适应高度 - Fix 导出不正常错误 ## 0.15.11 - 紧急修复安装时无法输入数据库账号问题 - Hexo 导出增强 ## 0.15.10 - 新增导出到 WordPress, Hexo, Jekyll 功能 - 新增代码行号显示,语言显示以及高亮功能 - Fix #355 表格数学公式不生效以及摘要问题 - Fix #375 页面单选复选框被隐藏问题 - Fix #380 安装时自动创建数据库 - Fix #382 编辑器高度问题 ## 0.15.9 - 新增数学公式的支持,目前暂不支持后台实时渲染,语法为: - ``` `$E=mc^2$` ``` - ` ```math E=mc^2 ``` ` - 增加导出功能,目前支持导出为 Markdown - 重构安装流程,检测到旧数据后不删除,安装时自动检测 `utf8mb4` - 新增 Hello World 文章数据 - Fix #338 Markdown导入错误 - Fix #345 部分不可见字符导致 RSS 错误 ## 0.15.8 - 紧急修复 0.15.7 版本安装包没有默认主题的BUG ## 0.15.7 - 【重要】使用自定义主题者请将主题内 `tag.html` 中的 `for tag in list` 改为 `for tag in tags` - #306 - 文章页模板增加作者邮箱数据 - 菜单管理增加编辑功能 - 后台文章列表增加分类过滤功能 - 增加 `opensearch.xml` 支持 - #306 模板增加 `lastPostList` 最近文章和 `tags` 标签列表变量 - Fix #279 首页去除 stc 编译修复后台修改模板文件不生效问题 - Fix 推送 `modelInstance` 定义报错失败问题 - Fix #303,#304 自定义首页不生效 - Fix 标签、分类为空时页面500问题 - Fix 文章页面标签跳转失败问题 ## 0.15.6 - 增加审核通过时更新发文时间功能 #259 - 增加文章自动生成摘要功能 #252 - 默认主题增加图片懒加载 #278 - 优化 SEO `sitemap.xml` 增加多个页面索引 #280 - 优化 URL 图片抓取功能,支持上传到又拍/七牛 - Fix #263 增加公安部备案选项 - Fix 搜索页分页 #269 - Fix #286 禁止删除当前用户 ## 0.15.5 - 【重要】修复主题接口安全漏洞 - 修复文章和页面地址相同时无法添加内容的问题 - Fix #254 编辑主题内容丢失问题 - Fix #248 WordPress 导入失败问题 - 第三方评论增加网易云跟帖的支持 ## 0.15.4 - 修复编辑修改文章时会发布文章的权限判断问题 - 修复文章推送报错问题 - Fix #249 Ghost 导入失败 - Fix #225 #246 编辑器增加字数统计显示以及同滚功能 ## 0.15.3 - Fix #240 粘贴图片无后缀 - 图片上传增加类型和 5M 大小限制 - 第三方评论增加畅言的支持 - 修复草稿在列表显示顺序错误的问题,之前的草稿需要自行设置下发布时间 ## 0.15.2 - Fix #230 后台编辑用户无法显示用户数据 - Fix 文章内单引号被替换成双引号的问题 - Fix 文章推送失败的问题 - 编译取消默认模板的代码压缩 ## 0.15.1 - 导入数据增加 Hexo, Jekyll, Markdown文件的支持,使用方法参考:<https://github.com/firekylin/firekylin/wiki/导入> - 修复页面编辑无法编辑内容的问题 ## 0.15.0 - 增加 `/sitemap.xml` 和 `/rss.xml` 两个路由 - 增加后台在线编辑主题功能 - 增加自定义错误页功能 - 页面编辑增加自定义主题功能 - 增加自定义站点首页功能,使用方法参考:https://imnerd.org/firekylin-custom-index.html ## 0.14.4 - 紧急修复页面管理无法保存问题 ## 0.14.3 - 提前祝大家鸡年大吉! - 用户列表新增文章数和评论数显示 - 文章列表增加是否公开显示,去除更新日期显示仅显示发布日期,未来发布的文章会显示为“即将发布”,文章排序从之前的 ID 排序修改为发布日期排序 - 阅读设置新增是否关闭自动生成TOC功能,关闭后在文章内可添加 `<!--toc-->` 再次开启 - Fix RSS数据错误问题 - Fix WP文件导入错误 - Fix 安装后无默认导航菜单数据 - Fix 安装后 `npm start` 账号错误 - Fix 主题设置编辑器不正常问题 ## 0.14.2 - 🎄祝大家圣诞快乐 - Fix #198 后台本地上传文件报错 - Fix #199 RSS 页面报错 - Fix #200 非管理员无法修改密码的问题 ## 0.14.1 - 增加阅读设置,支持设置每页显示文章数和聚合输出方式 - 修改 TOC 目录在文章开头插入,并在摘要中忽略 TOC - 修改编辑器工具栏样式支持拖拽调整编辑器长度 - 修改编辑器弹窗增加 ESC 和 Enter 快捷键支持 ## 0.14.0 - 增加从 Ghost 导入功能 - 增加在线更新功能 - 增加 CHANGELOG 并在更新提示中增加链接方便查看 - 编辑器上传图片增加上传中提示 - 重构了上传文件和导入博客数据的代码 - Fix #186 删除用户后文章页面列表显示不正常 ## 0.13.1 - 紧急修复七牛/又拍图片无法上传的BUG - 后台编辑器增加粘贴上传功能 - 概况页增加"新增页面"和"修改外观"的链接 ## 0.13.0 - 上传图片增加七牛和又拍云的支持 - 后台代码分块压缩减少首次加载的 JS 体积,提升加载速度 - 修复获取主题接口有其它非正常主题文件时的BUG - Fix #139 修复文章审核通过报错的问题 - Fix #177 修复评论设置不更新的问题 - Fix #173 允许非管理员上传图片 - 修复新建文章页面推送网站不显示的问题 - 修复清空标题编辑页面不正常的BUG
welefen/firekylin
CHANGELOG.md
Markdown
mit
9,978
Date.CultureInfo = { /* Culture Name */ name: "fr-FR", englishName: "French (France)", nativeName: "français (France)", /* Day Name Strings */ dayNames: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], abbreviatedDayNames: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], shortestDayNames: ["di", "lu", "ma", "me", "je", "ve", "sa"], firstLetterDayNames: ["d", "l", "m", "m", "j", "v", "s"], /* Month Name Strings */ monthNames: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], abbreviatedMonthNames: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."], /* AM/PM Designators */ amDesignator: "", pmDesignator: "", firstDayOfWeek: 1, twoDigitYearMax: 2029, /** * The dateElementOrder is based on the order of the * format specifiers in the formatPatterns.DatePattern. * * Example: <pre> shortDatePattern dateElementOrder ------------------ ---------------- "M/d/yyyy" "mdy" "dd/MM/yyyy" "dmy" "yyyy-MM-dd" "ymd" </pre> * * The correct dateElementOrder is required by the parser to * determine the expected order of the date elements in the * string being parsed. */ dateElementOrder: "dmy", /* Standard date and time format patterns */ formatPatterns: { shortDate: "dd/MM/yyyy", longDate: "dddd d MMMM yyyy", shortTime: "HH:mm", longTime: "HH:mm:ss", fullDateTime: "dddd d MMMM yyyy HH:mm:ss", sortableDateTime: "yyyy-MM-ddTHH:mm:ss", universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ", rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT", monthDay: "d MMMM", yearMonth: "MMMM yyyy" }, /** * NOTE: If a string format is not parsing correctly, but * you would expect it parse, the problem likely lies below. * * The following regex patterns control most of the string matching * within the parser. * * The Month name and Day name patterns were automatically generated * and in general should be (mostly) correct. * * Beyond the month and day name patterns are natural language strings. * Example: "next", "today", "months" * * These natural language string may NOT be correct for this culture. * If they are not correct, please translate and edit this file * providing the correct regular expression pattern. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Forum located at http://www.datejs.com/forums/. * * Please mark the subject of the post with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark) * * We will add the modified patterns to the master source files. * * As well, please review the list of "Future Strings" section below. */ regexPatterns: { jan: /^janv(\.|ier)?/i, feb: /^févr(\.|ier)?/i, mar: /^mars/i, apr: /^avr(\.|il)?/i, may: /^mai/i, jun: /^juin/i, jul: /^juil(\.|let)?/i, aug: /^août/i, sep: /^sept(\.|embre)?/i, oct: /^oct(\.|obre)?/i, nov: /^nov(\.|embre)?/i, dec: /^déc(\.|embre)?/i, sun: /^di(\.|m|m\.|anche)?/i, mon: /^lu(\.|n|n\.|di)?/i, tue: /^ma(\.|r|r\.|di)?/i, wed: /^me(\.|r|r\.|credi)?/i, thu: /^je(\.|u|u\.|di)?/i, fri: /^ve(\.|n|n\.|dredi)?/i, sat: /^sa(\.|m|m\.|edi)?/i, future: /^next/i, past: /^last|past|prev(ious)?/i, add: /^(\+|aft(er)?|from|hence)/i, subtract: /^(\-|bef(ore)?|ago)/i, yesterday: /^yes(terday)?/i, today: /^t(od(ay)?)?/i, tomorrow: /^tom(orrow)?/i, now: /^n(ow)?/i, millisecond: /^ms|milli(second)?s?/i, second: /^sec(ond)?s?/i, minute: /^mn|min(ute)?s?/i, hour: /^h(our)?s?/i, week: /^w(eek)?s?/i, month: /^m(onth)?s?/i, day: /^d(ay)?s?/i, year: /^y(ear)?s?/i, shortMeridian: /^(a|p)/i, longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i, timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i, ordinalSuffix: /^\s*(st|nd|rd|th)/i, timeContext: /^\s*(\:|a(?!u|p)|p)/i }, timezones: [{name:"UTC", offset:"-000"}, {name:"GMT", offset:"-000"}, {name:"EST", offset:"-0500"}, {name:"EDT", offset:"-0400"}, {name:"CST", offset:"-0600"}, {name:"CDT", offset:"-0500"}, {name:"MST", offset:"-0700"}, {name:"MDT", offset:"-0600"}, {name:"PST", offset:"-0800"}, {name:"PDT", offset:"-0700"}] }; /******************** ** Future Strings ** ******************** * * The following list of strings may not be currently being used, but * may be incorporated into the Datejs library later. * * We would appreciate any help translating the strings below. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Forum located at http://www.datejs.com/forums/. * * Please mark the subject of the post with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b * * English Name Translated * ------------------ ----------------- * about about * ago ago * date date * time time * calendar calendar * show show * hourly hourly * daily daily * weekly weekly * bi-weekly bi-weekly * fortnight fortnight * monthly monthly * bi-monthly bi-monthly * quarter quarter * quarterly quarterly * yearly yearly * annual annual * annually annually * annum annum * again again * between between * after after * from now from now * repeat repeat * times times * per per * min (abbrev minute) min * morning morning * noon noon * night night * midnight midnight * mid-night mid-night * evening evening * final final * future future * spring spring * summer summer * fall fall * winter winter * end of end of * end end * long long * short short */
TDXDigital/TPS
js/Datejs-master/src/globalization/fr-FR.js
JavaScript
mit
6,781
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <base href="../../../" /> <script src="list.js"></script> <script src="page.js"></script> <link type="text/css" rel="stylesheet" href="page.css" /> </head> <body> <h1>[name]</h1> <p class="desc">Class representing a 3D [link:https://en.wikipedia.org/wiki/Vector_space vector]. A 3D vector is an ordered triplet of numbers (labeled x, y, and z), which can be used to represent a number of things, such as: </p> <ul> <li> A point in 3D space. </li> <li> A direction and length in 3D space. In three.js the length will always be the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean distance] (straight-line distance) from (0, 0, 0) to (x, y, z) and the direction is also measured from (0, 0, 0) towards (x, y, z). </li> <li> Any arbitrary ordered triplet of numbers. </li> </ul> <p> There are other things a 3D vector can be used to represent, such as momentum vectors and so on, however these are the most common uses in three.js. </p> <h2>Example</h2> <code> var a = new THREE.Vector3( 0, 1, 0 ); //no arguments; will be initialised to (0, 0, 0) var b = new THREE.Vector3( ); var d = a.distanceTo( b ); </code> <h2>Constructor</h2> <h3>[name]( [param:Float x], [param:Float y], [param:Float z] )</h3> <p> [page:Float x] - the x value of the vector. Default is *0*.<br /> [page:Float y] - the y value of the vector. Default is *0*.<br /> [page:Float z] - the z value of the vector. Default is *0*.<br /><br /> Creates a new [name]. </p> <h2>Properties</h2> <h3>[property:Boolean isVector3]</h3> <p> Used to check whether this or derived classes are Vector3s. Default is *true*.<br /><br /> You should not change this, as it is used internally for optimisation. </p> <h3>[property:Float x]</h3> <h3>[property:Float y]</h3> <h3>[property:Float z]</h3> <h2>Methods</h2> <h3>[method:this add]( [param:Vector3 v] )</h3> <p>Adds [page:Vector3 v] to this vector.</p> <h3>[method:this addScalar]( [param:Float s] )</h3> <p>Adds the scalar value s to this vector's [page:.x x], [page:.y y] and [page:.z z] values.</p> <h3>[method:this addScaledVector]( [param:Vector3 v], [param:Float s] )</h3> <p>Adds the multiple of [page:Vector3 v] and [page:Float s] to this vector.</p> <h3>[method:this addVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector to [page:Vector3 a] + [page:Vector3 b].</p> <h3>[method:this applyAxisAngle]( [param:Vector3 axis], [param:Float angle] )</h3> <p> [page:Vector3 axis] - A normalized [page:Vector3].<br /> [page:Float angle] - An angle in radians.<br /><br /> Applies a rotation specified by an axis and an angle to this vector. </p> <h3>[method:this applyEuler]( [param:Euler euler] )</h3> <p> Applies euler transform to this vector by converting the [page:Euler] object to a [page:Quaternion] and applying. </p> <h3>[method:this applyMatrix3]( [param:Matrix3 m] )</h3> <p>Multiplies this vector by [page:Matrix3 m]</p> <h3>[method:this applyMatrix4]( [param:Matrix4 m] )</h3> <p> Multiplies this vector (with an implicit 1 in the 4th dimension) and m, and divides by perspective. </p> <h3>[method:this applyQuaternion]( [param:Quaternion quaternion] )</h3> <p> Applies a [page:Quaternion] transform to this vector. </p> <h3>[method:Float angleTo]( [param:Vector3 v] )</h3> <p> Returns the angle between this vector and vector [page:Vector3 v] in radians. </p> <h3>[method:this ceil]()</h3> <p> The [page:.x x], [page:.y y] and [page:.z z] components of the vector are rounded up to the nearest integer value. </p> <h3>[method:this clamp]( [param:Vector3 min], [param:Vector3 max] )</h3> <p> [page:Vector3 min] - the minimum [page:.x x], [page:.y y] and [page:.z z] values.<br /> [page:Vector3 max] - the maximum [page:.x x], [page:.y y] and [page:.z z] values in the desired range<br /><br /> If this vector's x, y or z value is greater than the max vector's x, y or z value, it is replaced by the corresponding value. <br /><br /> If this vector's x, y or z value is less than the min vector's x, y or z value, it is replaced by the corresponding value. </p> <h3>[method:this clampLength]( [param:Float min], [param:Float max] )</h3> <p> [page:Float min] - the minimum value the length will be clamped to <br /> [page:Float max] - the maximum value the length will be clamped to<br /><br /> If this vector's length is greater than the max value, it is replaced by the max value. <br /><br /> If this vector's length is less than the min value, it is replaced by the min value. </p> <h3>[method:this clampScalar]( [param:Float min], [param:Float max] )</h3> <p> [page:Float min] - the minimum value the components will be clamped to <br /> [page:Float max] - the maximum value the components will be clamped to<br /><br /> If this vector's x, y or z values are greater than the max value, they are replaced by the max value. <br /><br /> If this vector's x, y or z values are less than the min value, they are replaced by the min value. </p> <h3>[method:Vector3 clone]()</h3> <p> Returns a new vector3 with the same [page:.x x], [page:.y y] and [page:.z z] values as this one. </p> <h3>[method:this copy]( [param:Vector3 v] )</h3> <p> Copies the values of the passed vector3's [page:.x x], [page:.y y] and [page:.z z] properties to this vector3. </p> <h3>[method:this cross]( [param:Vector3 v] )</h3> <p> Sets this vector to [link:https://en.wikipedia.org/wiki/Cross_product cross product] of itself and [page:Vector3 v]. </p> <h3>[method:this crossVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p> Sets this vector to [link:https://en.wikipedia.org/wiki/Cross_product cross product] of [page:Vector3 a] and [page:Vector3 b]. </p> <h3>[method:Float distanceTo]( [param:Vector3 v] )</h3> <p>Computes the distance from this vector to [page:Vector3 v].</p> <h3>[method:Float manhattanDistanceTo]( [param:Vector3 v] )</h3> <p> Computes the [link:https://en.wikipedia.org/wiki/Taxicab_geometry Manhattan distance] from this vector to [page:Vector3 v]. </p> <h3>[method:Float distanceToSquared]( [param:Vector3 v] )</h3> <p> Computes the squared distance from this vector to [page:Vector3 v]. If you are just comparing the distance with another distance, you should compare the distance squared instead as it is slightly more efficient to calculate. </p> <h3>[method:this divide]( [param:Vector3 v] )</h3> <p>Divides this vector by [page:Vector3 v].</p> <h3>[method:this divideScalar]( [param:Float s] )</h3> <p> Divides this vector by scalar [page:Float s].<br /> Sets vector to *( 0, 0, 0 )* if *[page:Float s] = 0*. </p> <h3>[method:Float dot]( [param:Vector3 v] )</h3> <p> Calculate the [link:https://en.wikipedia.org/wiki/Dot_product dot product] of this vector and [page:Vector3 v]. </p> <h3>[method:Boolean equals]( [param:Vector3 v] )</h3> <p>Checks for strict equality of this vector and [page:Vector3 v].</p> <h3>[method:this floor]()</h3> <p>The components of the vector are rounded down to the nearest integer value.</p> <h3>[method:this fromArray]( [param:Array array], [param:Integer offset] )</h3> <p> [page:Array array] - the source array.<br /> [page:Integer offset] - ( optional) offset into the array. Default is 0.<br /><br /> Sets this vector's [page:.x x] value to be array[ offset + 0 ], [page:.y y] value to be array[ offset + 1 ] and [page:.z z] value to be array[ offset + 2 ]. </p> <h3>[method:this fromBufferAttribute]( [param:BufferAttribute attribute], [param:Integer index] )</h3> <p> [page:BufferAttribute attribute] - the source attribute.<br /> [page:Integer index] - index in the attribute.<br /><br /> Sets this vector's [page:.x x], [page:.y y] and [page:.z z] values from the [page:BufferAttribute attribute]. </p> <h3>[method:Float getComponent]( [param:Integer index] )</h3> <p> [page:Integer index] - 0, 1 or 2.<br /><br /> If index equals 0 returns the [page:.x x] value. <br /> If index equals 1 returns the [page:.y y] value. <br /> If index equals 2 returns the [page:.z z] value. </p> <h3>[method:Float length]()</h3> <p>Computes the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length] (straight-line length) from (0, 0, 0) to (x, y, z).</p> <h3>[method:Float manhattanLength]()</h3> <p> Computes the [link:http://en.wikipedia.org/wiki/Taxicab_geometry Manhattan length] of this vector. </p> <h3>[method:Float lengthSq]()</h3> <p> Computes the square of the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length] (straight-line length) from (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should compare the length squared instead as it is slightly more efficient to calculate. </p> <h3>[method:this lerp]( [param:Vector3 v], [param:Float alpha] )</h3> <p> [page:Vector3 v] - [page:Vector3] to interpolate towards.<br /> [page:Float alpha] - interpolation factor, typically in the closed interval [0, 1].<br /><br /> Linearly interpolate between this vector and [page:Vector3 v], where alpha is the percent distance along the line - alpha = 0 will be this vector, and alpha = 1 will be [page:Vector3 v]. </p> <h3>[method:this lerpVectors]( [param:Vector3 v1], [param:Vector3 v2], [param:Float alpha] )</h3> <p> [page:Vector3 v1] - the starting [page:Vector3].<br /> [page:Vector3 v2] - [page:Vector3] to interpolate towards.<br /> [page:Float alpha] - interpolation factor, typically in the closed interval [0, 1].<br /><br /> Sets this vector to be the vector linearly interpolated between [page:Vector3 v1] and [page:Vector3 v2] where alpha is the percent distance along the line connecting the two vectors - alpha = 0 will be [page:Vector3 v1], and alpha = 1 will be [page:Vector3 v2]. </p> <h3>[method:this max]( [param:Vector3 v] )</h3> <p> If this vector's x, y or z value is less than [page:Vector3 v]'s x, y or z value, replace that value with the corresponding max value. </p> <h3>[method:this min]( [param:Vector3 v] )</h3> <p> If this vector's x, y or z value is greater than [page:Vector3 v]'s x, y or z value, replace that value with the corresponding min value. </p> <h3>[method:this multiply]( [param:Vector3 v] )</h3> <p>Multiplies this vector by [page:Vector3 v].</p> <h3>[method:this multiplyScalar]( [param:Float s] )</h3> <p>Multiplies this vector by scalar [page:Float s].</p> <h3>[method:this multiplyVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector equal to [page:Vector3 a] * [page:Vector3 b], component-wise.</p> <h3>[method:this negate]()</h3> <p>Inverts this vector - i.e. sets x = -x, y = -y and z = -z.</p> <h3>[method:this normalize]()</h3> <p> Convert this vector to a [link:https://en.wikipedia.org/wiki/Unit_vector unit vector] - that is, sets it equal to the vector with the same direction as this one, but [page:.length length] 1. </p> <h3>[method:this project]( [param:Camera camera] )</h3> <p> [page:Camera camera] — camera to use in the projection.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Projects] the vector with the camera. </p> <h3>[method:this projectOnPlane]( [param:Vector3 planeNormal] )</h3> <p> [page:Vector3 planeNormal] - A vector representing a plane normal.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Projects] this vector onto a plane by subtracting this vector projected onto the plane's normal from this vector. </p> <h3>[method:this projectOnVector]( [param:Vector3] )</h3> <p>[link:https://en.wikipedia.org/wiki/Vector_projection Projects] this vector onto another vector.</p> <h3>[method:this reflect]( [param:Vector3 normal] )</h3> <p> [page:Vector3 normal] - the normal to the reflecting plane<br /><br /> Reflect the vector off of plane orthogonal to [page:Vector3 normal]. Normal is assumed to have unit length. </p> <h3>[method:this round]()</h3> <p>The components of the vector are rounded to the nearest integer value.</p> <h3>[method:this roundToZero]()</h3> <p> The components of the vector are rounded towards zero (up if negative, down if positive) to an integer value. </p> <h3>[method:this set]( [param:Float x], [param:Float y], [param:Float z] )</h3> <p>Sets the [page:.x x], [page:.y y] and [page:.z z] components of this vector.</p> <h3>[method:null setComponent]( [param:Integer index], [param:Float value] )</h3> <p> [page:Integer index] - 0, 1 or 2.<br /> [page:Float value] - [page:Float]<br /><br /> If index equals 0 set [page:.x x] to [page:Float value].<br /> If index equals 1 set [page:.y y] to [page:Float value].<br /> If index equals 2 set [page:.z z] to [page:Float value] </p> <h3>[method:this setFromCylindrical]( [param:Cylindrical c] )</h3> <p> Sets this vector from the cylindrical coordinates [page:Cylindrical c]. </p> <h3>[method:this setFromCylindricalCoords]( [param:Float radius], [param:Float theta], [param:Float y] )</h3> <p>Sets this vector from the cylindrical coordinates [page:Cylindrical radius], [page:Cylindrical theta] and [page:Cylindrical y].</p> <h3>[method:this setFromMatrixColumn]( [param:Matrix4 matrix], [param:Integer index] )</h3> <p> Sets this vector's [page:.x x], [page:.y y] and [page:.z z] equal to the column of the [page:Matrix4 matrix] specified by the [page:Integer index]. </p> <h3>[method:this setFromMatrixPosition]( [param:Matrix4 m] )</h3> <p> Sets this vector to the position elements of the [link:https://en.wikipedia.org/wiki/Transformation_matrix transformation matrix] [page:Matrix4 m]. </p> <h3>[method:this setFromMatrixScale]( [param:Matrix4 m] )</h3> <p> Sets this vector to the scale elements of the [link:https://en.wikipedia.org/wiki/Transformation_matrix transformation matrix] [page:Matrix4 m]. </p> <h3>[method:this setFromSpherical]( [param:Spherical s] )</h3> <p> Sets this vector from the spherical coordinates [page:Spherical s]. </p> <h3>[method:this setFromSphericalCoords]( [param:Float radius], [param:Float phi], [param:Float theta] )</h3> <p>Sets this vector from the spherical coordinates [page:Spherical radius], [page:Spherical phi] and [page:Spherical theta].</p> <h3>[method:this setLength]( [param:Float l] )</h3> <p> Set this vector to the vector with the same direction as this one, but [page:.length length] [page:Float l]. </p> <h3>[method:this setScalar]( [param:Float scalar] )</h3> <p> Set the [page:.x x], [page:.y y] and [page:.z z] values of this vector both equal to [page:Float scalar]. </p> <h3>[method:this setX]( [param:Float x] )</h3> <p>Replace this vector's [page:.x x] value with [page:Float x].</p> <h3>[method:this setY]( [param:Float y] )</h3> <p>Replace this vector's [page:.y y] value with [page:Float y].</p> <h3>[method:this setZ]( [param:Float z] )</h3> <p>Replace this vector's [page:.z z] value with [page:Float z].</p> <h3>[method:this sub]( [param:Vector3 v] )</h3> <p>Subtracts [page:Vector3 v] from this vector.</p> <h3>[method:this subScalar]( [param:Float s] )</h3> <p>Subtracts [page:Float s] from this vector's [page:.x x], [page:.y y] and [page:.z z] compnents.</p> <h3>[method:this subVectors]( [param:Vector3 a], [param:Vector3 b] )</h3> <p>Sets this vector to [page:Vector3 a] - [page:Vector3 b].</p> <h3>[method:Array toArray]( [param:Array array], [param:Integer offset] )</h3> <p> [page:Array array] - (optional) array to store the vector to. If this is not provided a new array will be created.<br /> [page:Integer offset] - (optional) optional offset into the array.<br /><br /> Returns an array [x, y, z], or copies x, y and z into the provided [page:Array array]. </p> <h3>[method:this transformDirection]( [param:Matrix4 m] )</h3> <p> Transforms the direction of this vector by a matrix (the upper left 3 x 3 subset of a [page:Matrix4 m]) and then [page:.normalize normalizes] the result. </p> <h3>[method:this unproject]( [param:Camera camera] )</h3> <p> [page:Camera camera] — camera to use in the projection.<br /><br /> [link:https://en.wikipedia.org/wiki/Vector_projection Unprojects] the vector with the camera's projection matrix. </p> <h2>Source</h2> [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js] </body> </html>
cadenasgmbh/three.js
docs/api/en/math/Vector3.html
HTML
mit
16,776
testMipmap = function() local f = {0} local g = {} local h = {6} local k = {0} f[1] = f[1] + 1 k[1] = h[1] - f[1]; g[1] = k[1]^2 print (g[1]) end testMipmap()
Nau3D/nau
projects/path tracing/ttt.lua
Lua
mit
180
#include "UniformBuffer.hpp" #include <iostream> #include <cstring> UniformBuffer::UniformBuffer(const void* data, unsigned int size, VkDevice device, VkPhysicalDevice physicalDevice, VkDescriptorPool descriptorPool, VkShaderStageFlags flags) : Buffer(device, physicalDevice, descriptorPool) { this->device = device; this->physicalDevice = physicalDevice; this->descriptorPool = descriptorPool; createBuffer(size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &buffer, &bufferMemory); // Copy data to mapped memory. setData(data, size); // Create descriptor set. createDescriptorSetLayout(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, flags); createDescriptorSet(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, buffer, size); } UniformBuffer::~UniformBuffer() { vkDestroyBuffer(device, buffer, nullptr); vkFreeMemory(device, bufferMemory, nullptr); } void UniformBuffer::setData(const void* data, unsigned int size) { void* mappedMemory; vkMapMemory(device, bufferMemory, 0, size, 0, &mappedMemory); memcpy(mappedMemory, data, size); vkUnmapMemory(device, bufferMemory); }
Chainsawkitten/AsyncCompute
src/UniformBuffer.cpp
C++
mit
1,194
class Test { public static int[] test() { return null; } public static void main(String[] args) { int [] arr = test(); System.out.println(arr); }
parin2092/cook
Test.java
Java
mit
154
// // ColorInfoView.h // ASCFlatUIColors // // Created by André Schneider on 02.05.14. // Copyright (c) 2014 André Schneider. All rights reserved. // #import <UIKit/UIKit.h> @interface ColorInfoView : UIView - (void)showWithTitle:(NSString *)title forColorAtIndexPath:(NSIndexPath *)indexPath; - (void)hide; @end
schneiderandre/ASCFlatUIColor
Example/ASCFlatUIColors/ColorInfoView.h
C
mit
323
import { Component, ViewChild, ElementRef } from '@angular/core'; import { jqxButtonGroupComponent } from '../../../../../jqwidgets-ts/angular_jqxbuttongroup'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('myButtonGroup') myButtonGroup: jqxButtonGroupComponent; @ViewChild('myLog') myLog: ElementRef; myDefaultModeButtonChecked(): void { this.myButtonGroup.mode('default'); }; myRadioModeButtonChecked(): void { this.myButtonGroup.mode('radio'); }; myCheckBoxModeButtonChecked(): void { this.myButtonGroup.mode('checkbox'); }; groupOnBtnClick(event: any): void { let clickedButton = event.args.button; this.myLog.nativeElement.innerHTML = `Clicked: ${clickedButton[0].id}`; } }
juannelisalde/holter
assets/jqwidgets/demos/angular/app/buttongroup/defaultfunctionality/app.component.ts
TypeScript
mit
844
-- MENUS DELETE FROM `sys_menu_items` WHERE `set_name`='sys_account_dashboard' AND `name`='dashboard-massmailer'; SET @iMoAccountDashboard = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name`='sys_account_dashboard' LIMIT 1); INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `editable`, `order`) VALUES ('sys_account_dashboard', @sName, 'dashboard-massmailer', '_bx_massmailer_menu_item_title_system_admt_mailer', '_bx_massmailer_menu_item_title_admt_mailer', 'page.php?i=massmailer-campaigns', '', '', 'envelope col-red', '', '', 128, 1, 0, 1, @iMoAccountDashboard + 1); -- GRIDS DELETE FROM `sys_grid_fields` WHERE `object`='bx_massmailer_campaigns'; INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable`, `chars_limit`, `params`, `order`) VALUES ('bx_massmailer_campaigns', 'checkbox', '_sys_select', '2%', 0, '', '', 1), ('bx_massmailer_campaigns', 'title', '_bx_massmailer_grid_column_title_adm_title', '26%', 0, '22', '', 2), ('bx_massmailer_campaigns', 'author', '_bx_massmailer_grid_column_title_adm_author', '8%', 0, '22', '', 3), ('bx_massmailer_campaigns', 'segments', '_bx_massmailer_grid_column_title_adm_segment', '10%', 0, '22', '', 4), ('bx_massmailer_campaigns', 'is_one_per_account', '_bx_massmailer_grid_column_title_adm_is_one_per_account', '10%', 0, '0', '', 5), ('bx_massmailer_campaigns', 'added', '_bx_massmailer_grid_column_title_adm_date_created', '10%', 0, '15', '', 6), ('bx_massmailer_campaigns', 'date_sent', '_bx_massmailer_grid_column_title_adm_date_sent', '10%', 0, '22', '', 7), ('bx_massmailer_campaigns', 'actions', '', '24%', 0, '', '', 8);
unaio/una
modules/boonex/massmailer/updates/9.0.2_9.0.3/install/sql/enable.sql
SQL
mit
1,772
<?php declare(strict_types=1); /** * Copyright (c) 2013-2018 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Test\Integration\Http\Action\Signup; use OpenCFP\Test\Integration\WebTestCase; final class PrivacyActionTest extends WebTestCase { /** * @test */ public function privacyPolicyRenders() { $response = $this->get('/privacy'); $this->assertResponseIsSuccessful($response); $this->assertResponseBodyContains('Privacy Policy', $response); $this->assertResponseBodyContains('General Data Protection Regulation', $response); } }
localheinz/opencfp
tests/Integration/Http/Action/Signup/PrivacyActionTest.php
PHP
mit
752
using System; using System.Windows.Input; namespace CustomBA.Commands { /// <summary> /// Based on http://wpftutorial.net/DelegateCommand.html /// </summary> public class DelegateCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action<object> execute) : this(execute, null) { } public DelegateCommand(Action<object> execute, Predicate<object> canExecute) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } }
Sufflavus/WixExamples
CustomBurnUiWithOptionsOnPureWpf/Source/CustomBA/Commands/DelegateCommand.cs
C#
mit
1,268
export declare class SampleComponent { constructor(); }
UrbanRiskSlumRedevelopment/Maya
node_modules/ng2-bootstrap-grid/dist/src/sample.component.d.ts
TypeScript
mit
63
# SSH ## SSH keys An SSH key allows you to establish a secure connection between your computer and GitLab. Before generating an SSH key in your shell, check if your system already has one by running the following command: ```bash cat ~/.ssh/id_rsa.pub ``` If you see a long string starting with `ssh-rsa` or `ssh-dsa`, you can skip the `ssh-keygen` step. Note: It is a best practice to use a password for an SSH key, but it is not required and you can skip creating a password by pressing enter. Note that the password you choose here can't be altered or retrieved. To generate a new SSH key, use the following commandGitLab```bash ssh-keygen -t rsa -C "$your_email" ``` This command will prompt you for a location and filename to store the key pair and for a password. When prompted for the location and filename, you can press enter to use the default. Use the command below to show your public key: ```bash cat ~/.ssh/id_rsa.pub ``` Copy-paste the key to the 'My SSH Keys' section under the 'SSH' tab in your user profile. Please copy the complete key starting with `ssh-` and ending with your username and host. To copy your public key to the clipboard, use code below. Depending on your OS you'll need to use a different command: **Windows:** ```bash clip < ~/.ssh/id_rsa.pub ``` **Mac:** ```bash pbcopy < ~/.ssh/id_rsa.pub ``` **GNU/Linux (requires xclip):** ```bash xclip -sel clip < ~/.ssh/id_rsa.pub ``` ## Deploy keys Deploy keys allow read-only access to multiple projects with a single SSH key. This is really useful for cloning repositories to your Continuous Integration (CI) server. By using deploy keys, you don't have to setup a dummy user account. If you are a project master or owner, you can add a deploy key in the project settings under the section 'Deploy Keys'. Press the 'New Deploy Key' button and upload a public SSH key. After this, the machine that uses the corresponding private key has read-only access to the project. You can't add the same deploy key twice with the 'New Deploy Key' option. If you want to add the same key to another project, please enable it in the list that says 'Deploy keys from projects available to you'. All the deploy keys of all the projects you have access to are available. This project access can happen through being a direct member of the project, or through a group. See `def accessible_deploy_keys` in `app/models/user.rb` for more information. Deploy keys can be shared between projects, you just need to add them to each project. ## Applications ### Eclipse How to add your ssh key to Eclipse: https://wiki.eclipse.org/EGit/User_Guide#Eclipse_SSH_Configuration ## Tip: Non-default OpenSSH key file names or locations If, for whatever reason, you decide to specify a non-default location and filename for your GitLab SSH key pair, you must configure your SSH client to find your GitLab SSH private key for connections to your GitLab server (perhaps gitlab.com). For OpenSSH clients, this is handled in the `~/.ssh/config` file with a stanza similar to the following: ``` # # Main gitlab.com server # Host gitlab.com RSAAuthentication yes IdentityFile ~/my-ssh-key-directory/my-gitlab-private-key-filename User mygitlabusername ``` Another example ``` # # Our company's internal GitLab server # Host my-gitlab.company.com RSAAuthentication yes IdentityFile ~/my-ssh-key-directory/company-com-private-key-filename ``` Note in the gitlab.com example above a username was specified to override the default chosen by OpenSSH (your local username). This is only required if your local and remote usernames differ. Due to the wide variety of SSH clients and their very large number of configuration options, further explanation of these topics is beyond the scope of this document. Public SSH keys need to be unique, as they will bind to your account. Your SSH key is the only identifier you'll have when pushing code via SSH. That's why it needs to uniquely map to a single user.
ferdinandrosario/gitlabhq
doc/ssh/README.md
Markdown
mit
3,968
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Fri Nov 26 15:38:56 EST 2010 --> <TITLE> Xerces Native Interface: Package org.apache.xerces.xni </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../org/apache/xerces/xni/package-summary.html" TARGET="classFrame">org.apache.xerces.xni</A></FONT> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Augmentations.html" TARGET="classFrame"><I>Augmentations</I></A> <BR> <A HREF="NamespaceContext.html" TARGET="classFrame"><I>NamespaceContext</I></A> <BR> <A HREF="XMLAttributes.html" TARGET="classFrame"><I>XMLAttributes</I></A> <BR> <A HREF="XMLDocumentFragmentHandler.html" TARGET="classFrame"><I>XMLDocumentFragmentHandler</I></A> <BR> <A HREF="XMLDocumentHandler.html" TARGET="classFrame"><I>XMLDocumentHandler</I></A> <BR> <A HREF="XMLDTDContentModelHandler.html" TARGET="classFrame"><I>XMLDTDContentModelHandler</I></A> <BR> <A HREF="XMLDTDHandler.html" TARGET="classFrame"><I>XMLDTDHandler</I></A> <BR> <A HREF="XMLLocator.html" TARGET="classFrame"><I>XMLLocator</I></A> <BR> <A HREF="XMLResourceIdentifier.html" TARGET="classFrame"><I>XMLResourceIdentifier</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="QName.html" TARGET="classFrame">QName</A> <BR> <A HREF="XMLString.html" TARGET="classFrame">XMLString</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Exceptions</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="XNIException.html" TARGET="classFrame">XNIException</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
jsalla/jatintest
lib/xerces-2_11_0/docs/javadocs/xni/org/apache/xerces/xni/package-frame.html
HTML
mit
2,115
#ifndef _WLC_CONTEXT_H_ #define _WLC_CONTEXT_H_ #include <stdbool.h> #include <EGL/egl.h> #include <EGL/eglext.h> struct wl_display; struct wlc_backend_surface; struct ctx; struct wlc_context_api { void (*terminate)(struct ctx *context); bool (*bind)(struct ctx *context); bool (*bind_to_wl_display)(struct ctx *context, struct wl_display *display); void (*swap)(struct ctx *context, struct wlc_backend_surface *bsurface); void* (*get_proc_address)(struct ctx *context, const char *procname); // EGL EGLBoolean (*query_buffer)(struct ctx *context, struct wl_resource *buffer, EGLint attribute, EGLint *value); EGLImageKHR (*create_image)(struct ctx *context, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); EGLBoolean (*destroy_image)(struct ctx *context, EGLImageKHR image); }; struct wlc_context { void *context; // internal surface context (EGL, etc) struct wlc_context_api api; }; void* wlc_context_get_proc_address(struct wlc_context *context, const char *procname); EGLBoolean wlc_context_query_buffer(struct wlc_context *context, struct wl_resource *buffer, EGLint attribute, EGLint *value); EGLImageKHR wlc_context_create_image(struct wlc_context *context, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); EGLBoolean wlc_context_destroy_image(struct wlc_context *context, EGLImageKHR image); bool wlc_context_bind(struct wlc_context *context); bool wlc_context_bind_to_wl_display(struct wlc_context *context, struct wl_display *display); void wlc_context_swap(struct wlc_context *context, struct wlc_backend_surface *bsurface); void wlc_context_release(struct wlc_context *context); bool wlc_context(struct wlc_context *context, struct wlc_backend_surface *bsurface); #endif /* _WLC_CONTEXT_H_ */
SirCmpwn/wlc
src/platform/context/context.h
C
mit
1,784
import {Component} from '@angular/core'; @Component({ selector: 'not-found', templateUrl: 'app/404.component/404.component.html', styleUrls: ['app/404.component/404.component.css'], }) export class NotFoundComponent {}
Nandtel/spring-boot-angular2-starter
src/main/javascript/app/404.component/404.component.ts
TypeScript
mit
231
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_33) on Tue Aug 20 12:20:59 EDT 2013 --> <TITLE> mars.util Class Hierarchy </TITLE> <META NAME="date" CONTENT="2013-08-20"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="mars.util Class Hierarchy"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../mars/tools/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../mars/venus/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?mars/util/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package mars.util </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">mars.util.<A HREF="../../mars/util/Binary.html" title="class in mars.util"><B>Binary</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/EditorFont.html" title="class in mars.util"><B>EditorFont</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/FilenameFinder.html" title="class in mars.util"><B>FilenameFinder</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/MemoryDump.html" title="class in mars.util"><B>MemoryDump</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/PropertiesFile.html" title="class in mars.util"><B>PropertiesFile</B></A><LI TYPE="circle">mars.util.<A HREF="../../mars/util/SystemIO.html" title="class in mars.util"><B>SystemIO</B></A></UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../mars/tools/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../mars/venus/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?mars/util/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
gon1332/mars
src/main/resources/docs/mars/util/package-tree.html
HTML
mit
6,316
call target.bat %1\haxe.exe %2\compile-%TARGET%.hxml
silentorb/garden
compile.bat
Batchfile
mit
57
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>type_mat3x2.hpp Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.8.0 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">type_mat3x2.hpp</div> </div> </div><!--header--> <div class="contents"> <a href="a00101.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <a name="l00002"></a>00002 <a name="l00003"></a>00003 <a name="l00004"></a>00004 <a name="l00005"></a>00005 <a name="l00006"></a>00006 <a name="l00007"></a>00007 <a name="l00008"></a>00008 <a name="l00009"></a>00009 <a name="l00010"></a>00010 <a name="l00011"></a>00011 <a name="l00012"></a>00012 <a name="l00013"></a>00013 <a name="l00014"></a>00014 <a name="l00015"></a>00015 <a name="l00016"></a>00016 <a name="l00017"></a>00017 <a name="l00018"></a>00018 <a name="l00019"></a>00019 <a name="l00020"></a>00020 <a name="l00021"></a>00021 <a name="l00022"></a>00022 <a name="l00023"></a>00023 <a name="l00024"></a>00024 <a name="l00025"></a>00025 <a name="l00026"></a>00026 <a name="l00027"></a>00027 <a name="l00028"></a>00028 <a name="l00029"></a>00029 <span class="preprocessor">#ifndef glm_core_type_mat3x2</span> <a name="l00030"></a>00030 <span class="preprocessor"></span><span class="preprocessor">#define glm_core_type_mat3x2</span> <a name="l00031"></a>00031 <span class="preprocessor"></span> <a name="l00032"></a>00032 <span class="preprocessor">#include &quot;<a class="code" href="a00097.html" title="OpenGL Mathematics (glm.g-truc.net)">type_mat.hpp</a>&quot;</span> <a name="l00033"></a>00033 <a name="l00034"></a>00034 <span class="keyword">namespace </span>glm{ <a name="l00035"></a>00035 <span class="keyword">namespace </span>detail <a name="l00036"></a>00036 { <a name="l00037"></a>00037 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec1; <a name="l00038"></a>00038 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec2; <a name="l00039"></a>00039 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec3; <a name="l00040"></a>00040 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tvec4; <a name="l00041"></a>00041 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x2; <a name="l00042"></a>00042 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x3; <a name="l00043"></a>00043 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat2x4; <a name="l00044"></a>00044 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x2; <a name="l00045"></a>00045 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x3; <a name="l00046"></a>00046 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat3x4; <a name="l00047"></a>00047 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x2; <a name="l00048"></a>00048 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x3; <a name="l00049"></a>00049 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct </span>tmat4x4; <a name="l00050"></a>00050 <a name="l00051"></a>00051 <span class="comment">// \brief Template for 3 columns and 2 rows matrix of floating-point numbers.</span> <a name="l00052"></a>00052 <span class="comment">// \ingroup core_template</span> <a name="l00053"></a>00053 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00054"></a>00054 <span class="keyword">struct </span>tmat3x2 <a name="l00055"></a>00055 { <a name="l00056"></a>00056 <span class="keyword">enum</span> ctor{null}; <a name="l00057"></a>00057 <span class="keyword">typedef</span> T value_type; <a name="l00058"></a>00058 <span class="keyword">typedef</span> std::size_t size_type; <a name="l00059"></a>00059 <span class="keyword">typedef</span> tvec2&lt;T&gt; col_type; <a name="l00060"></a>00060 <span class="keyword">typedef</span> tvec3&lt;T&gt; row_type; <a name="l00061"></a>00061 GLM_FUNC_DECL size_type <a class="code" href="a00129.html#ga282360c8bb80b80d3c7f5bc00766d873" title="Returns the length of x, i.e., sqrt(x * x).">length</a>() <span class="keyword">const</span>; <a name="l00062"></a>00062 <span class="keyword">static</span> GLM_FUNC_DECL size_type col_size(); <a name="l00063"></a>00063 <span class="keyword">static</span> GLM_FUNC_DECL size_type row_size(); <a name="l00064"></a>00064 <a name="l00065"></a>00065 <span class="keyword">typedef</span> tmat3x2&lt;T&gt; type; <a name="l00066"></a>00066 <span class="keyword">typedef</span> tmat2x3&lt;T&gt; transpose_type; <a name="l00067"></a>00067 <a name="l00068"></a>00068 <span class="keyword">private</span>: <a name="l00069"></a>00069 <span class="comment">// Data</span> <a name="l00070"></a>00070 col_type value[3]; <a name="l00071"></a>00071 <a name="l00072"></a>00072 <span class="keyword">public</span>: <a name="l00073"></a>00073 <span class="comment">// Constructors</span> <a name="l00074"></a>00074 GLM_FUNC_DECL tmat3x2(); <a name="l00075"></a>00075 GLM_FUNC_DECL tmat3x2(tmat3x2 <span class="keyword">const</span> &amp; m); <a name="l00076"></a>00076 <a name="l00077"></a>00077 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00078"></a>00078 ctor); <a name="l00079"></a>00079 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00080"></a>00080 value_type <span class="keyword">const</span> &amp; s); <a name="l00081"></a>00081 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00082"></a>00082 value_type <span class="keyword">const</span> &amp; x0, value_type <span class="keyword">const</span> &amp; y0, <a name="l00083"></a>00083 value_type <span class="keyword">const</span> &amp; x1, value_type <span class="keyword">const</span> &amp; y1, <a name="l00084"></a>00084 value_type <span class="keyword">const</span> &amp; x2, value_type <span class="keyword">const</span> &amp; y2); <a name="l00085"></a>00085 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00086"></a>00086 col_type <span class="keyword">const</span> &amp; v0, <a name="l00087"></a>00087 col_type <span class="keyword">const</span> &amp; v1, <a name="l00088"></a>00088 col_type <span class="keyword">const</span> &amp; v2); <a name="l00089"></a>00089 <a name="l00091"></a>00091 <span class="comment">// Conversions</span> <a name="l00092"></a>00092 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00093"></a>00093 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00094"></a>00094 U <span class="keyword">const</span> &amp; x); <a name="l00095"></a>00095 <a name="l00096"></a>00096 <span class="keyword">template</span> <a name="l00097"></a>00097 &lt; <a name="l00098"></a>00098 <span class="keyword">typename</span> X1, <span class="keyword">typename</span> Y1, <a name="l00099"></a>00099 <span class="keyword">typename</span> X2, <span class="keyword">typename</span> Y2, <a name="l00100"></a>00100 <span class="keyword">typename</span> X3, <span class="keyword">typename</span> Y3 <a name="l00101"></a>00101 &gt; <a name="l00102"></a>00102 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00103"></a>00103 X1 <span class="keyword">const</span> &amp; x1, Y1 <span class="keyword">const</span> &amp; y1, <a name="l00104"></a>00104 X2 <span class="keyword">const</span> &amp; x2, Y2 <span class="keyword">const</span> &amp; y2, <a name="l00105"></a>00105 X3 <span class="keyword">const</span> &amp; x3, Y3 <span class="keyword">const</span> &amp; y3); <a name="l00106"></a>00106 <a name="l00107"></a>00107 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> V1, <span class="keyword">typename</span> V2, <span class="keyword">typename</span> V3&gt; <a name="l00108"></a>00108 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2( <a name="l00109"></a>00109 tvec2&lt;V1&gt; <span class="keyword">const</span> &amp; v1, <a name="l00110"></a>00110 tvec2&lt;V2&gt; <span class="keyword">const</span> &amp; v2, <a name="l00111"></a>00111 tvec2&lt;V3&gt; <span class="keyword">const</span> &amp; v3); <a name="l00112"></a>00112 <a name="l00113"></a>00113 <span class="comment">// Matrix conversions</span> <a name="l00114"></a>00114 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00115"></a>00115 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00116"></a>00116 <a name="l00117"></a>00117 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x2&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00118"></a>00118 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00119"></a>00119 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00120"></a>00120 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00121"></a>00121 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat2x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00122"></a>00122 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat3x4&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00123"></a>00123 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x2&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00124"></a>00124 GLM_FUNC_DECL <span class="keyword">explicit</span> tmat3x2(tmat4x3&lt;T&gt; <span class="keyword">const</span> &amp; x); <a name="l00125"></a>00125 <a name="l00126"></a>00126 <span class="comment">// Accesses</span> <a name="l00127"></a>00127 GLM_FUNC_DECL col_type &amp; operator[](size_type i); <a name="l00128"></a>00128 GLM_FUNC_DECL col_type <span class="keyword">const</span> &amp; operator[](size_type i) <span class="keyword">const</span>; <a name="l00129"></a>00129 <a name="l00130"></a>00130 <span class="comment">// Unary updatable operators</span> <a name="l00131"></a>00131 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator= (tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00132"></a>00132 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00133"></a>00133 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00134"></a>00134 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00135"></a>00135 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator+= (U <span class="keyword">const</span> &amp; s); <a name="l00136"></a>00136 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00137"></a>00137 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator+= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00138"></a>00138 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00139"></a>00139 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-= (U <span class="keyword">const</span> &amp; s); <a name="l00140"></a>00140 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00141"></a>00141 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00142"></a>00142 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00143"></a>00143 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator*= (U <span class="keyword">const</span> &amp; s); <a name="l00144"></a>00144 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00145"></a>00145 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator*= (tmat3x2&lt;U&gt; <span class="keyword">const</span> &amp; m); <a name="l00146"></a>00146 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> U&gt; <a name="l00147"></a>00147 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator/= (U <span class="keyword">const</span> &amp; s); <a name="l00148"></a>00148 <a name="l00149"></a>00149 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator++ (); <a name="l00150"></a>00150 GLM_FUNC_DECL tmat3x2&lt;T&gt; &amp; operator-- (); <a name="l00151"></a>00151 }; <a name="l00152"></a>00152 <a name="l00153"></a>00153 <span class="comment">// Binary operators</span> <a name="l00154"></a>00154 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00155"></a>00155 tmat3x2&lt;T&gt; operator+ ( <a name="l00156"></a>00156 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00157"></a>00157 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00158"></a>00158 <a name="l00159"></a>00159 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00160"></a>00160 tmat3x2&lt;T&gt; operator+ ( <a name="l00161"></a>00161 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00162"></a>00162 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00163"></a>00163 <a name="l00164"></a>00164 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00165"></a>00165 tmat3x2&lt;T&gt; operator- ( <a name="l00166"></a>00166 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00167"></a>00167 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00168"></a>00168 <a name="l00169"></a>00169 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00170"></a>00170 tmat3x2&lt;T&gt; operator- ( <a name="l00171"></a>00171 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00172"></a>00172 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00173"></a>00173 <a name="l00174"></a>00174 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00175"></a>00175 tmat3x2&lt;T&gt; operator* ( <a name="l00176"></a>00176 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00177"></a>00177 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00178"></a>00178 <a name="l00179"></a>00179 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00180"></a>00180 tmat3x2&lt;T&gt; operator* ( <a name="l00181"></a>00181 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s, <a name="l00182"></a>00182 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00183"></a>00183 <a name="l00184"></a>00184 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00185"></a>00185 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::col_type operator* ( <a name="l00186"></a>00186 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00187"></a>00187 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::row_type <span class="keyword">const</span> &amp; v); <a name="l00188"></a>00188 <a name="l00189"></a>00189 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00190"></a>00190 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::row_type operator* ( <a name="l00191"></a>00191 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::col_type <span class="keyword">const</span> &amp; v, <a name="l00192"></a>00192 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00193"></a>00193 <a name="l00194"></a>00194 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00195"></a>00195 tmat2x2&lt;T&gt; operator* ( <a name="l00196"></a>00196 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00197"></a>00197 tmat2x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00198"></a>00198 <a name="l00199"></a>00199 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00200"></a>00200 tmat3x2&lt;T&gt; operator* ( <a name="l00201"></a>00201 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00202"></a>00202 tmat3x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00203"></a>00203 <a name="l00204"></a>00204 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00205"></a>00205 tmat4x2&lt;T&gt; operator* ( <a name="l00206"></a>00206 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m1, <a name="l00207"></a>00207 tmat4x3&lt;T&gt; <span class="keyword">const</span> &amp; m2); <a name="l00208"></a>00208 <a name="l00209"></a>00209 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00210"></a>00210 tmat3x2&lt;T&gt; operator/ ( <a name="l00211"></a>00211 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00212"></a>00212 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s); <a name="l00213"></a>00213 <a name="l00214"></a>00214 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00215"></a>00215 tmat3x2&lt;T&gt; operator/ ( <a name="l00216"></a>00216 <span class="keyword">typename</span> tmat3x2&lt;T&gt;::value_type <span class="keyword">const</span> &amp; s, <a name="l00217"></a>00217 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00218"></a>00218 <a name="l00219"></a>00219 <span class="comment">// Unary constant operators</span> <a name="l00220"></a>00220 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00221"></a>00221 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator- ( <a name="l00222"></a>00222 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m); <a name="l00223"></a>00223 <a name="l00224"></a>00224 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00225"></a>00225 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator-- ( <a name="l00226"></a>00226 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00227"></a>00227 <span class="keywordtype">int</span>); <a name="l00228"></a>00228 <a name="l00229"></a>00229 <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <a name="l00230"></a>00230 tmat3x2&lt;T&gt; <span class="keyword">const</span> operator++ ( <a name="l00231"></a>00231 tmat3x2&lt;T&gt; <span class="keyword">const</span> &amp; m, <a name="l00232"></a>00232 <span class="keywordtype">int</span>); <a name="l00233"></a>00233 <a name="l00234"></a>00234 } <span class="comment">//namespace detail</span> <a name="l00235"></a>00235 <a name="l00238"></a>00238 <a name="l00244"></a><a class="code" href="a00141.html#ga745259412efbd5e07b1a4062190e3135">00244</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;lowp_float&gt; <a class="code" href="a00141.html#ga745259412efbd5e07b1a4062190e3135" title="3 columns of 2 components matrix of low precision floating-point numbers.">lowp_mat3x2</a>; <a name="l00245"></a>00245 <a name="l00251"></a><a class="code" href="a00141.html#ga08c1cebbdb2cdfa0a62b23981db1c059">00251</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;mediump_float&gt; <a class="code" href="a00141.html#ga08c1cebbdb2cdfa0a62b23981db1c059" title="3 columns of 2 components matrix of medium precision floating-point numbers.">mediump_mat3x2</a>; <a name="l00252"></a>00252 <a name="l00258"></a><a class="code" href="a00141.html#gae5e017b25e88ff5c61f4538a2dd5647a">00258</a> <span class="keyword">typedef</span> detail::tmat3x2&lt;highp_float&gt; <a class="code" href="a00141.html#gae5e017b25e88ff5c61f4538a2dd5647a" title="3 columns of 2 components matrix of high precision floating-point numbers.">highp_mat3x2</a>; <a name="l00259"></a>00259 <a name="l00261"></a>00261 }<span class="comment">//namespace glm</span> <a name="l00262"></a>00262 <a name="l00263"></a>00263 <span class="preprocessor">#ifndef GLM_EXTERNAL_TEMPLATE</span> <a name="l00264"></a>00264 <span class="preprocessor"></span><span class="preprocessor">#include &quot;type_mat3x2.inl&quot;</span> <a name="l00265"></a>00265 <span class="preprocessor">#endif</span> <a name="l00266"></a>00266 <span class="preprocessor"></span> <a name="l00267"></a>00267 <span class="preprocessor">#endif //glm_core_type_mat3x2</span> </pre></div></div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.0 </small></address> </body> </html>
phaser/KRAL_libs
glm/0.9.3.3/docs/html/a00101_source.html
HTML
mit
25,628
<?php require_once('library/HTML5/Parser.php'); require_once('library/HTMLPurifier.auto.php'); function arr_add_hashes(&$item,$k) { $item = '#' . $item; } function parse_url_content(&$a) { $text = null; $str_tags = ''; if(x($_GET,'binurl')) $url = trim(hex2bin($_GET['binurl'])); else $url = trim($_GET['url']); if($_GET['title']) $title = strip_tags(trim($_GET['title'])); if($_GET['description']) $text = strip_tags(trim($_GET['description'])); if($_GET['tags']) { $arr_tags = str_getcsv($_GET['tags']); if(count($arr_tags)) { array_walk($arr_tags,'arr_add_hashes'); $str_tags = '<br />' . implode(' ',$arr_tags) . '<br />'; } } logger('parse_url: ' . $url); $template = "<br /><a class=\"bookmark\" href=\"%s\" >%s</a>%s<br />"; $arr = array('url' => $url, 'text' => ''); call_hooks('parse_link', $arr); if(strlen($arr['text'])) { echo $arr['text']; killme(); } if($url && $title && $text) { $text = '<br /><br /><blockquote>' . $text . '</blockquote><br />'; $title = str_replace(array("\r","\n"),array('',''),$title); $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags; logger('parse_url (unparsed): returns: ' . $result); echo $result; killme(); } if($url) { $s = fetch_url($url); } else { echo ''; killme(); } // logger('parse_url: data: ' . $s, LOGGER_DATA); if(! $s) { echo sprintf($template,$url,$url,'') . $str_tags; killme(); } $matches = ''; $c = preg_match('/\<head(.*?)\>(.*?)\<\/head\>/ism',$s,$matches); if($c) { // logger('parse_url: header: ' . $matches[2], LOGGER_DATA); try { $domhead = HTML5_Parser::parse($matches[2]); } catch (DOMException $e) { logger('scrape_dfrn: parse error: ' . $e); } if($domhead) logger('parsed header'); } if(! $title) { if(strpos($s,'<title>')) { $title = substr($s,strpos($s,'<title>')+7,64); if(strpos($title,'<') !== false) $title = strip_tags(substr($title,0,strpos($title,'<'))); } } $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $purifier = new HTMLPurifier($config); $s = $purifier->purify($s); // logger('purify_output: ' . $s); try { $dom = HTML5_Parser::parse($s); } catch (DOMException $e) { logger('scrape_dfrn: parse error: ' . $e); } if(! $dom) { echo sprintf($template,$url,$url,'') . $str_tags; killme(); } $items = $dom->getElementsByTagName('title'); if($items) { foreach($items as $item) { $title = trim($item->textContent); break; } } if(! $text) { $divs = $dom->getElementsByTagName('div'); if($divs) { foreach($divs as $div) { $class = $div->getAttribute('class'); if($class && (stristr($class,'article') || stristr($class,'content'))) { $items = $div->getElementsByTagName('p'); if($items) { foreach($items as $item) { $text = $item->textContent; if(stristr($text,'<script')) { $text = ''; continue; } $text = strip_tags($text); if(strlen($text) < 100) { $text = ''; continue; } $text = substr($text,0,250) . '...' ; break; } } } if($text) break; } } if(! $text) { $items = $dom->getElementsByTagName('p'); if($items) { foreach($items as $item) { $text = $item->textContent; if(stristr($text,'<script')) continue; $text = strip_tags($text); if(strlen($text) < 100) { $text = ''; continue; } $text = substr($text,0,250) . '...' ; break; } } } } if(! $text) { logger('parsing meta'); $items = $domhead->getElementsByTagName('meta'); if($items) { foreach($items as $item) { $property = $item->getAttribute('property'); if($property && (stristr($property,':description'))) { $text = $item->getAttribute('content'); if(stristr($text,'<script')) { $text = ''; continue; } $text = strip_tags($text); $text = substr($text,0,250) . '...' ; } if($property && (stristr($property,':image'))) { $image = $item->getAttribute('content'); if(stristr($text,'<script')) { $image = ''; continue; } $image = strip_tags($image); $i = fetch_url($image); if($i) { require_once('include/Photo.php'); $ph = new Photo($i); if($ph->is_valid()) { if($ph->getWidth() > 300 || $ph->getHeight() > 300) { $ph->scaleImage(300); $new_width = $ph->getWidth(); $new_height = $ph->getHeight(); $image = '<br /><br /><img height="' . $new_height . '" width="' . $new_width . '" src="' .$image . '" alt="photo" />'; } else $image = '<br /><br /><img src="' . $image . '" alt="photo" />'; } else $image = ''; } } } } } if(strlen($text)) { $text = '<br /><br /><blockquote>' . $text . '</blockquote><br />'; } if($image) { $text = $image . '<br />' . $text; } $title = str_replace(array("\r","\n"),array('',''),$title); $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags; logger('parse_url: returns: ' . $result); echo $result; killme(); }
kyriakosbrastianos/friendica-deb
mod/parse_url.php
PHP
mit
5,224
package com.example.exampleeureka; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ExampleEurekaApplicationTests { @Test public void contextLoads() { } }
ko-sasaki/springboot-example
springboot-eureka-server/src/test/java/com/example/exampleeureka/ExampleEurekaApplicationTests.java
Java
mit
349
using System.Runtime.Serialization; namespace BungieNetPlatform.Enums { [DataContract] public enum ForumPostSort { [EnumMember] Default = 0, [EnumMember] OldestFirst = 1 } }
dazarobbo/BungieNetPlatform-CSharp
BungieNetPlatform/BungieNetPlatform/Enums/ForumPostSort.cs
C#
mit
193
A GLMListPresentation simply shows the given elements within a list. Instance Variables tagsBlock: <Object> tagsFilterBlock: <Object> tagsBlock - xxxxx tagsFilterBlock - xxxxx
vineetreddyrajula/pharo
src/Glamour-Presentations.package/GLMListPresentation.class/README.md
Markdown
mit
185
using System.Net.Http; using System.Threading.Tasks; namespace WebApiContrib.IoC.Mef.Tests.Parts { public class PrecannedMessageHandler : DelegatingHandler { private readonly HttpResponseMessage _response; public PrecannedMessageHandler(HttpResponseMessage response) { _response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { if (request.Method == HttpMethod.Get) { _response.RequestMessage = request; var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(_response); return tcs.Task; } return null; } } }
WebApiContrib/WebApiContrib.IoC.Mef
test/WebApiContrib.IoC.Mef.Tests/Helpers/PrecannedMessageHandler.cs
C#
mit
826
#include "gamelib/components/editor/LineBrushComponent.hpp" #include "gamelib/components/geometry/Polygon.hpp" #include "gamelib/components/rendering/MeshRenderer.hpp" #include "gamelib/core/ecs/Entity.hpp" #include "gamelib/properties/PropComponent.hpp" namespace gamelib { LineBrushComponent::LineBrushComponent() : _linewidth(32) { auto cb = +[](const ComponentReference<PolygonCollider>* val, LineBrushComponent* self) { self->_line = *val; self->regenerate(); }; _props.registerProperty("linewidth", _linewidth, PROP_METHOD(_linewidth, setWidth), this); registerProperty(_props, "line", _line, *this, cb); } void LineBrushComponent::setWidth(int width) { if (_linewidth == width) return; _linewidth = width; regenerate(); } int LineBrushComponent::getWidth() const { return _linewidth; } PolygonCollider* LineBrushComponent::getBrushPolygon() const { return _line.get(); } void LineBrushComponent::regenerate() const { if (!_shape || !_pol || !_line || _line->size() == 0) return; math::Vec2f lastd, dir; bool start = true; auto cb = [&](const math::Line2f& seg) { float area = 0; auto norm = seg.d.normalized(); if (start) { start = false; lastd = seg.d; } else { // Compute if the line turns clockwise or counter clockwise // Total hours wasted here because I didn't google the // problem / didn't knew what exactly to google for: 11 auto p1 = seg.p - lastd; auto p3 = seg.p + seg.d; // Break if the direction hasn't changed if (lastd.normalized() == norm) return false; area = (seg.p.x - p1.x) * (seg.p.y + p1.y) + (p3.x - seg.p.x) * (p3.y + seg.p.y) + (p1.x - p3.x) * (p1.y + p3.y); } dir = (norm + lastd.normalized()).right().normalized(); dir *= (_linewidth / 2.0) / dir.angle_cos(lastd.right()); _pol->add(seg.p - dir); _pol->add(seg.p + dir); // depending on clockwise or counter clockwise line direction, // different vertices have to be added. if (area != 0) { auto len = norm.right() * _linewidth; if (area > 0) // clockwise { _pol->add(seg.p - dir); _pol->add(seg.p - dir + len); } else // counter clockwise { _pol->add(seg.p + dir - len); _pol->add(seg.p + dir); } } lastd = seg.d; return false; }; auto& linepol = _line->getLocal(); _pol->clear(); linepol.foreachSegment(cb); dir = lastd.right().normalized() * (_linewidth / 2.0); _pol->add(linepol.get(linepol.size() - 1) - dir); _pol->add(linepol.get(linepol.size() - 1) + dir); _shape->fetch(_pol->getLocal(), sf::TriangleStrip); } }
mall0c/TileEngine
src/gamelib/components/editor/LineBrushComponent.cpp
C++
mit
3,353
/////////////////////// /// UTILS /// /////////////////////// var u = {}; u.distance = function (p1, p2) { var dx = p2.x - p1.x; var dy = p2.y - p1.y; return Math.sqrt((dx * dx) + (dy * dy)); }; u.angle = function(p1, p2) { var dx = p2.x - p1.x; var dy = p2.y - p1.y; return u.degrees(Math.atan2(dy, dx)); }; u.findCoord = function(p, d, a) { var b = {x: 0, y: 0}; a = u.radians(a); b.x = p.x - d * Math.cos(a); b.y = p.y - d * Math.sin(a); return b; }; u.radians = function(a) { return a * (Math.PI / 180); }; u.degrees = function(a) { return a * (180 / Math.PI); }; u.bindEvt = function (el, type, handler) { if (el.addEventListener) { el.addEventListener(type, handler, false); } else if (el.attachEvent) { el.attachEvent(type, handler); } }; u.unbindEvt = function (el, type, handler) { if (el.removeEventListener) { el.removeEventListener(type, handler); } else if (el.detachEvent) { el.detachEvent(type, handler); } }; u.trigger = function (el, type, data) { var evt = new CustomEvent(type, data); el.dispatchEvent(evt); }; u.prepareEvent = function (evt) { evt.preventDefault(); return isTouch ? evt.changedTouches : evt; }; u.getScroll = function () { var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body) .scrollLeft; var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body) .scrollTop; return { x: x, y: y }; }; u.applyPosition = function (el, pos) { if (pos.x && pos.y) { el.style.left = pos.x + 'px'; el.style.top = pos.y + 'px'; } else if (pos.top || pos.right || pos.bottom || pos.left) { el.style.top = pos.top; el.style.right = pos.right; el.style.bottom = pos.bottom; el.style.left = pos.left; } }; u.getTransitionStyle = function (property, values, time) { var obj = u.configStylePropertyObject(property); for (var i in obj) { if (obj.hasOwnProperty(i)) { if (typeof values === 'string') { obj[i] = values + ' ' + time; } else { var st = ''; for (var j = 0, max = values.length; j < max; j += 1) { st += values[j] + ' ' + time + ', '; } obj[i] = st.slice(0, -2); } } } return obj; }; u.getVendorStyle = function (property, value) { var obj = u.configStylePropertyObject(property); for (var i in obj) { if (obj.hasOwnProperty(i)) { obj[i] = value; } } return obj; }; u.configStylePropertyObject = function (prop) { var obj = {}; obj[prop] = ''; var vendors = ['webkit', 'Moz', 'o']; vendors.forEach(function (vendor) { obj[vendor + prop.charAt(0).toUpperCase() + prop.slice(1)] = ''; }); return obj; }; u.extend = function (objA, objB) { for (var i in objB) { if (objB.hasOwnProperty(i)) { objA[i] = objB[i]; } } };
Antariano/nipplejs
src/utils.js
JavaScript
mit
3,278
# coding: utf-8 unless defined?(CARDS_CONF) File.open(File.expand_path("../../cards_config.rb", __FILE__)) { |f| CARDS_CONF = eval(f.read()) if(CARDS_CONF.class == Hash) then f.close() end } end
wzup/cards
config/initializers/01_init_cards_config.rb
Ruby
mit
207
package styles import ( "github.com/alecthomas/chroma" ) // Doom One 2 style. Inspired by Atom One and Doom Emacs's Atom One theme var DoomOne2 = Register(chroma.MustNewStyle("doom-one2", chroma.StyleEntries{ chroma.Text: "#b0c4de", chroma.Error: "#b0c4de", chroma.Comment: "italic #8a93a5", chroma.CommentHashbang: "bold", chroma.Keyword: "#76a9f9", chroma.KeywordConstant: "#e5c07b", chroma.KeywordType: "#e5c07b", chroma.Operator: "#54b1c7", chroma.OperatorWord: "bold #b756ff", chroma.Punctuation: "#abb2bf", chroma.Name: "#aa89ea", chroma.NameAttribute: "#cebc3a", chroma.NameBuiltin: "#e5c07b", chroma.NameClass: "#ca72ff", chroma.NameConstant: "bold", chroma.NameDecorator: "#e5c07b", chroma.NameEntity: "#bda26f", chroma.NameException: "bold #fd7474", chroma.NameFunction: "#00b1f7", chroma.NameProperty: "#cebc3a", chroma.NameLabel: "#f5a40d", chroma.NameNamespace: "#ca72ff", chroma.NameTag: "#76a9f9", chroma.NameVariable: "#DCAEEA", chroma.NameVariableClass: "#DCAEEA", chroma.NameVariableGlobal: "bold #DCAEEA", chroma.NameVariableInstance: "#e06c75", chroma.NameVariableMagic: "#DCAEEA", chroma.Literal: "#98c379", chroma.LiteralDate: "#98c379", chroma.Number: "#d19a66", chroma.NumberBin: "#d19a66", chroma.NumberFloat: "#d19a66", chroma.NumberHex: "#d19a66", chroma.NumberInteger: "#d19a66", chroma.NumberIntegerLong: "#d19a66", chroma.NumberOct: "#d19a66", chroma.String: "#98c379", chroma.StringAffix: "#98c379", chroma.StringBacktick: "#98c379", chroma.StringDelimiter: "#98c379", chroma.StringDoc: "#7e97c3", chroma.StringDouble: "#63c381", chroma.StringEscape: "bold #d26464", chroma.StringHeredoc: "#98c379", chroma.StringInterpol: "#98c379", chroma.StringOther: "#70b33f", chroma.StringRegex: "#56b6c2", chroma.StringSingle: "#98c379", chroma.StringSymbol: "#56b6c2", chroma.Generic: "#b0c4de", chroma.GenericDeleted: "#b0c4de", chroma.GenericEmph: "italic", chroma.GenericHeading: "bold #a2cbff", chroma.GenericInserted: "#a6e22e", chroma.GenericOutput: "#a6e22e", chroma.GenericUnderline: "underline", chroma.GenericPrompt: "#a6e22e", chroma.GenericStrong: "bold", chroma.GenericSubheading: "#a2cbff", chroma.GenericTraceback: "#a2cbff", chroma.Background: "#b0c4de bg:#282c34", }))
xyproto/algernon
vendor/github.com/alecthomas/chroma/styles/doom-one2.go
GO
mit
2,793
#include "multi_modelstruct.h" #include "multivar_support.h" #include <math.h> #include <assert.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> /** * ccs, 05.06.2012 * \todo this all needs to be checked carefully against an example that works in R * \todo valgrind for mem-leaks * \bug no error checking in linalg * \bug no error checking in alloc * \bug is there error checking in file handles? * * ccs, 19.06.2012 * if you allocate a multi_modelstruct m * then m->pca_model_array[i]->xmodel == m->xmodel * the value in the pca_model_array is just a pointer to m, do we really want this? */ /** * allocates a multi_modelstruct, like alloc_modelstruct_2, * but for multivariate models with t output values at each location * * @param model_in: (n x d) matrix of the design * @param training_matrix: (n x t) matrix of the values of the training values at each of the n locations * @param cov_fn_index: POWEREXPCOVFN, MATERN32, or MATERN52 * @param regression_order: 0, 1, 2, or 3 * @param varfrac: the minimum fractional variance that should be retained during the PCA decomp * * applies a pca decomp to training_matrix to reduce the dimensionality * */ multi_modelstruct* alloc_multimodelstruct(gsl_matrix *xmodel_in, gsl_matrix *training_matrix_in, int cov_fn_index, int regression_order, double varfrac) { assert(training_matrix_in->size1 == xmodel_in->size1); assert(training_matrix_in->size1 > 0); assert(training_matrix_in->size2 > 0); assert(xmodel_in->size2 > 0); int i; double mean_temp = 0.0; int nt = training_matrix_in->size2; int nmodel_points = xmodel_in->size1; int nparams = xmodel_in->size2; gsl_vector_view col_view; /* use default if out of range */ if (regression_order < 0 || regression_order > 3) regression_order = 0; /* use a sensible default for the variance fraction */ if(varfrac < 0 || varfrac > 1) varfrac = 0.95; /* ntheta is a function of cov_fn_index and nparams */ int nthetas; if ((cov_fn_index == MATERN32) || (cov_fn_index == MATERN52)) { nthetas = 3; } else if (cov_fn_index == POWEREXPCOVFN) { nthetas = nparams + 2; } else { cov_fn_index = POWEREXPCOVFN; nthetas = nparams + 2; } // this doesn't seem to be allocating correctly, seems to be a broken defn of MallocChecked // strangely, code will build in this case... //multi_modelstruct * model = (multi_modelstruct*)MallocChecked(sizeof(multi_modelstruct)); multi_modelstruct * model = (multi_modelstruct*)malloc(sizeof(multi_modelstruct)); // fill in model->nt = nt; model->nr = 0; // init at zero model->nmodel_points = nmodel_points; model->nparams = nparams; model->xmodel = xmodel_in; model->training_matrix = training_matrix_in; model->training_mean = gsl_vector_alloc(nt); model->regression_order = regression_order; model->cov_fn_index = cov_fn_index; /* fill in the mean vector, should probably sum this more carefully... */ for(i = 0; i < nt; i++){ col_view = gsl_matrix_column(model->training_matrix, i); mean_temp = vector_elt_sum(&col_view.vector, nmodel_points); //printf("%lf\n", (mean_temp/((double)nmodel_points))); gsl_vector_set(model->training_mean, i, (mean_temp/((double)nmodel_points)) ); } /* carry out the pca decomp on this model, this is defined in multivar_support for now * this will fill in nr, pca_eigenvalues, pca_eigenvectors, pca_evals_r, pca_evecs_r * * this is making a mess if nt = 1 */ gen_pca_decomp(model, varfrac); /* fill in pca_model_array */ gen_pca_model_array(model); return model; } /** * fill in pca_model_array * requires: * - the pca decomp to have been calculated, so nr and all the pca_... fields are allocated and filled in * - m to have been allocated up to: nt, nmodel_points, and xmodel * * is it possible we could start running out of memory doing all these allocs? */ void gen_pca_model_array(multi_modelstruct *m) { int nr = m->nr; int i; gsl_vector_view col_view; gsl_vector* temp_train_vector = gsl_vector_alloc(m->nmodel_points); //gsl_matrix* temp_xmodel = gsl_matrix_alloc(m->nmodel_points, m->nparams); //gsl_matrix_mempcy(temp_xmodel, m->xmodel); // alloc the array of nr model structs //m->pca_model_array = (modelstruct**)MallocChecked(sizeof(modelstruct*)*nr); m->pca_model_array = (modelstruct**)malloc(sizeof(modelstruct*)*nr); // fill in the modelstructs correctly for(i = 0; i < nr; i++){ col_view = gsl_matrix_column(m->pca_zmatrix, i); gsl_vector_memcpy(temp_train_vector, &(col_view.vector)); // this isn't copying in the training vector correctly for somereason m->pca_model_array[i] = alloc_modelstruct_2(m->xmodel, temp_train_vector, m->cov_fn_index, m->regression_order); // see if brute forcing it will work m->pca_model_array[i]->training_vector = gsl_vector_alloc(m->nmodel_points); gsl_vector_memcpy(m->pca_model_array[i]->training_vector, temp_train_vector); } gsl_vector_free(temp_train_vector); } /** * carries out a pca decomp on m->training_matrix; * setting m->nr, m->pca_eigenvalues, m->pca_eigenvectors and * initializing m->pca_model_array * * the pca decomp is pretty simple: * let Y_ij = m->y_training * let mu_i = (1/nmodel_points) sum_{j=1}^{nmodel_points} Y_{ij} // the sample mean * let ysub_i = Y_i - rep(mu_i,nmodel_points) //subtract the sample means from each column * let sigma_ij = (1/nmodel_points) ( ysub * t(ysub)) // this is the covariance matrix * * then all we need to do is compute the eigendecomposition * * sigma_ij = U^{-1} Lambda U * * where Lambda is a diagonal matrix of t eigenvalues and U is a t x t matrix with the eigenvectors as columns * * requires: * - 0 < vfrac < 1 (0.95 is a good value) * - m to have allocated and filled out, nt, nmodel_points, trianing_matrix, (doesn't need xmodel explicitly) */ void gen_pca_decomp(multi_modelstruct *m, double vfrac) { FILE *fptr; // for debug output int i,j; int nt = m->nt; int retval; double total_variance = 0.0, frac = 0.0; gsl_matrix *pca_zmatrix_temp; gsl_matrix *y_sub_mat = gsl_matrix_alloc(m->nmodel_points, nt); gsl_matrix *y_temp_mat = gsl_matrix_alloc(m->nmodel_points, nt); gsl_matrix *y_cov_mat = gsl_matrix_alloc(nt, nt); gsl_vector *evals_temp = gsl_vector_alloc(nt); gsl_matrix *evecs_temp = gsl_matrix_alloc(nt,nt); gsl_eigen_symmv_workspace *ework = gsl_eigen_symmv_alloc(nt); gsl_vector_view col_view; // why is this here? gsl_matrix_memcpy(y_sub_mat, m->training_matrix); // subtract out the mean for(i = 0; i < nt; i++){ //col_view = gsl_matrix_column(y_sub_mat, i); printf("# y(%d) mean: %lf\n", i, gsl_vector_get(m->training_mean, i)); for(j = 0; j < m->nmodel_points; j++){ gsl_matrix_set(y_sub_mat, j, i, gsl_matrix_get(y_sub_mat, j, i) - gsl_vector_get(m->training_mean, i)); } } // compute the sample-variance, by multiplying y_sub_mat, with itself transposed gsl_matrix_memcpy(y_temp_mat, y_sub_mat); gsl_matrix_set_zero(y_cov_mat); /** — Function: int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) (always forget this one)*/ /* want C (nt x nt ) so we need to do: (nt x nmodel_points) * (nmodel_points x nt) */ /** * this is strange, the upper triangle is not obviously correct */ //retval = gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, y_temp_mat, y_sub_mat, 0.0, y_cov_mat); retval = gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, y_sub_mat, y_temp_mat, 0.0, y_cov_mat); if(retval){ printf("# gen_pca_decomp:gsl_blas_dgemm %s\n", gsl_strerror(retval)); exit(EXIT_FAILURE); } gsl_matrix_scale(y_cov_mat, (1.0/((double)m->nmodel_points))); /** * debug output */ #ifdef DEBUGPCA fptr = fopen("pca-debug.dat","w"); fprintf(fptr, "# ycov:\n"); for(j = 0; j < nt; j++){ for(i = 0; i < nt; i++) fprintf(fptr, "%lf ", gsl_matrix_get(y_cov_mat, i, j)); fprintf(fptr, "\n"); } #endif /** now the eigendecomp * y_cov_mat is symmetric and better be real so we can use gsl_eigen_symmv, * note that the ?upper? triangle of y_cov_mat is borked during this process * also: the evals are not sorted by order, but the evectors are in the order of the evalues. * so we need to sort the evalues and the evectors correctly before we can use them * using * — Function: int gsl_eigen_symmv_sort (gsl_vector * eval, gsl_matrix * evec, gsl_eigen_sort_t sort_type) * sort them into descending order (biggest first) */ gsl_eigen_symmv(y_cov_mat, evals_temp, evecs_temp, ework); gsl_eigen_symmv_sort(evals_temp, evecs_temp, GSL_EIGEN_SORT_VAL_DESC); /** * eigenvectors are stored in columns of pca_evecs*/ total_variance = vector_elt_sum(evals_temp, nt); #ifdef DEBUGPCA fprintf(fptr, "# evals:\n"); for(i = 0; i < nt; i++) fprintf(fptr, "%lf %lf\n", gsl_vector_get(evals_temp, i), gsl_vector_get(evals_temp, i) / total_variance); fprintf(fptr, "# evecs:\n"); for(j = 0; j < nt; j++){ for(i = 0; i < nt; i++) fprintf(fptr, "%lf ", gsl_matrix_get(evecs_temp, i, j)); fprintf(fptr, "\n"); } #endif i=0; while( frac < vfrac && (i+1) < nt){ frac = (1.0/total_variance) * vector_elt_sum(evals_temp, i); i++; } m->nr = i; if(nt == 1){ //printf("# 1d case, nr=1\n"); m->nr = 1; } m->pca_evals_r = gsl_vector_alloc(m->nr); m->pca_evecs_r = gsl_matrix_alloc(m->nt, m->nr); // debug... fprintf(stderr, "# nr: %d frac: %lf\n", m->nr, frac); for(i = 0; i < m->nr; i++){ gsl_vector_set(m->pca_evals_r, i, gsl_vector_get(evals_temp, i)); col_view = gsl_matrix_column(evecs_temp, i); gsl_matrix_set_col(m->pca_evecs_r, i, &col_view.vector); } // fill in pca_zmatrix m->pca_zmatrix = gsl_matrix_alloc(m->nmodel_points, m->nr); pca_zmatrix_temp = gsl_matrix_alloc(m->nmodel_points, m->nr); // zmat: (nmodel_points x nr) = (nmodel_points x nt) * ( nt x nr ) /** — Function: int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C) (always forget this one)*/ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, y_sub_mat, m->pca_evecs_r, 0.0, m->pca_zmatrix); #ifdef DEBUGPCA fprintf(fptr, "# evecs R:\n"); for(i = 0; i < m->nt; i++){ for(j = 0; j < m->nr; j++) fprintf(fptr, "%lf ", gsl_matrix_get(m->pca_evecs_r, i, j)); fprintf(fptr, "\n"); } #endif gsl_matrix_free(y_temp_mat); y_temp_mat = gsl_matrix_alloc(m->nr, m->nr); for(i = 0; i < m->nr; i++) // scale the diagonal by the evalue */ gsl_matrix_set(y_temp_mat, i, i, 1.0/(sqrt(gsl_vector_get(m->pca_evals_r, i)))); //print_matrix(y_temp_mat, m->nr, m->nr); // if nr != nt this won't work! //gsl_matrix_memcpy(y_sub_mat, m->pca_zmatrix); gsl_matrix_memcpy(pca_zmatrix_temp, m->pca_zmatrix); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, pca_zmatrix_temp, y_temp_mat, 0.0, m->pca_zmatrix); #ifdef DEBUGPCA fprintf(fptr, "# zmat:\n"); for(i = 0; i < 5; i++){ for(j = 0; j < m->nr; j++) fprintf(fptr, "%lf ", gsl_matrix_get(m->pca_zmatrix, i, j)); fprintf(fptr, "\n"); } fclose(fptr); #endif gsl_vector_free(evals_temp); gsl_matrix_free(evecs_temp); gsl_matrix_free(pca_zmatrix_temp); gsl_eigen_symmv_free(ework); gsl_matrix_free(y_sub_mat); gsl_matrix_free(y_temp_mat); gsl_matrix_free(y_cov_mat); } /** * dump the multimodelstruct to fptr, follows from dump_modelstruct_2 * we first dump the new fields and then iterate through the nr additional models which are dumped as before * so we dump a lot of the same info, but this is probably ok, the advantage is that each section defining * a model can be pulled out and worked on separately... */ void dump_multi_modelstruct(FILE* fptr, multi_modelstruct *m){ assert(fptr); int i,j; int nt = m->nt; int nr = m->nr; int nparams = m->nparams; int nmodel_points = m->nmodel_points; int cov_fn_index = m->cov_fn_index; int regression_order = m->regression_order; fprintf(fptr, "%d\n", nt); fprintf(fptr, "%d\n", nr); fprintf(fptr, "%d\n", nparams); fprintf(fptr, "%d\n", nmodel_points); fprintf(fptr, "%d\n", cov_fn_index); fprintf(fptr, "%d\n", regression_order); // multimodel thetas are inside pca_model_array... for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nparams; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->xmodel, i, j)); fprintf(fptr, "\n"); } for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nt; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->training_matrix, i, j)); fprintf(fptr, "\n"); } // now the rest of the pca information for(i = 0; i < nr; i++) fprintf(fptr, "%.17lf ", gsl_vector_get(m->pca_evals_r, i)); fprintf(fptr, "\n"); for(i = 0; i < nt; i++){ for(j = 0; j < nr; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->pca_evecs_r, i, j)); fprintf(fptr, "\n"); } for(i = 0; i < nmodel_points; i++){ for(j = 0; j < nr; j++) fprintf(fptr, "%.17lf ", gsl_matrix_get(m->pca_zmatrix, i, j)); fprintf(fptr, "\n"); } // now the pca_model_array // these could go in separate files... for(i = 0; i < nr; i++){ dump_modelstruct_2(fptr, m->pca_model_array[i]); } } /** * loads a multivariate modelstructure from fptr */ multi_modelstruct *load_multi_modelstruct(FILE* fptr){ multi_modelstruct *m = (multi_modelstruct*)malloc(sizeof(multi_modelstruct)); int i,j; int nt, nr; int nparams, nmodel_points; int cov_fn_index; int regression_order; double mean_temp; gsl_vector_view col_view; fscanf(fptr, "%d%*c", & nt); fscanf(fptr, "%d%*c", & nr); fscanf(fptr, "%d%*c", & nparams); fscanf(fptr, "%d%*c", & nmodel_points); fscanf(fptr, "%d%*c", & cov_fn_index); fscanf(fptr, "%d%*c", & regression_order); m->nt = nt; m->nr = nr; m->nparams = nparams; m->nmodel_points = nmodel_points; m->cov_fn_index = cov_fn_index; m->regression_order = regression_order; // now we can allocate everything in m m->xmodel = gsl_matrix_alloc(nmodel_points, nparams); m->training_matrix = gsl_matrix_alloc(nmodel_points, nt); m->training_mean = gsl_vector_alloc(nt); // do we need this? (yes!) m->pca_model_array = (modelstruct**)malloc(sizeof(modelstruct*)*nr); m->pca_evals_r = gsl_vector_alloc(nr); m->pca_evecs_r = gsl_matrix_alloc(nt, nr); m->pca_zmatrix = gsl_matrix_alloc(nmodel_points, nr); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nparams; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->xmodel, i, j)); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nt; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->training_matrix, i, j)); // now the rest of the pca information for(i = 0; i < nr; i++) fscanf(fptr, "%lf%*c", gsl_vector_ptr(m->pca_evals_r, i)); for(i = 0; i < nt; i++) for(j = 0; j < nr; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->pca_evecs_r, i, j)); for(i = 0; i < nmodel_points; i++) for(j = 0; j < nr; j++) fscanf(fptr, "%lf%*c", gsl_matrix_ptr(m->pca_zmatrix, i, j)); for(i = 0; i < nr; i++) m->pca_model_array[i] = load_modelstruct_2(fptr); /* fill in the mean vector */ for(i = 0; i < nt; i++){ col_view = gsl_matrix_column(m->training_matrix, i); mean_temp = vector_elt_sum(&col_view.vector, nmodel_points); gsl_vector_set(m->training_mean, i, (mean_temp/((double)nmodel_points)) ); } return m; } /** * return the sum of the elements of vec from 0:nstop */ double vector_elt_sum(gsl_vector* vec, int nstop) { assert(nstop >= 0); assert((unsigned)nstop <= vec->size); int i; double sum = 0.0; for(i = 0; i < nstop; i++){ sum += gsl_vector_get(vec, i); } return(sum); } /** * this free's everything in m */ void free_multimodelstruct(multi_modelstruct *m) { int i; gsl_vector_free(m->training_mean); for(i = 0; i < m->nr; i++){ free_modelstruct_2(m->pca_model_array[i]); //gsl_matrix_free(m->pca_model_array[i]->xmodel); } free(m->pca_model_array); gsl_matrix_free(m->xmodel); gsl_matrix_free(m->training_matrix); gsl_vector_free(m->pca_evals_r); gsl_matrix_free(m->pca_evecs_r); gsl_matrix_free(m->pca_zmatrix); }
MADAI/MADAIEmulator
src/multi_modelstruct.c
C
mit
16,184
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `strpbrk` fn in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, strpbrk"> <title>libc::strpbrk - Rust</title> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'strpbrk', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='index.html'>libc</a>::<wbr><a class='fn' href=''>strpbrk</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-217' class='srclink' href='../src/libc/lib.rs.html#233' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn strpbrk(cs: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a>, ct: <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a>) -&gt; <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*mut </a><a class='type' href='../libc/type.c_char.html' title='libc::c_char'>c_char</a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
CasualX/CasualX.github.io
docs/pupil-rs/0.1.3/libc/fn.strpbrk.html
HTML
mit
4,678
#!/bin/sh sudo apt-get install xorg-dev libglu1-mesa-dev -y # sfml-window sudo apt-get install libx11-dev -y sudo apt-get install libxcb1-dev -y sudo apt-get install libx11-xcb-dev -y sudo apt-get install libxcb-randr0-dev -y sudo apt-get install libxcb-image0-dev -y sudo apt-get install libgl1-mesa-dev -y sudo apt-get install libudev-dev -y # sfml-graphics sudo apt-get install libfreetype6-dev -y sudo apt-get install libjpeg-dev -y # sfml-audio sudo apt-get install libopenal-dev -y sudo apt-get install libflac-dev -y sudo apt-get install libvorbis-dev -y
P-ainters/Drawing-Board-Alpha
Utility/DependencyInstall.sh
Shell
mit
565
const core = require('brigadehub-core') var pkg = require('./package.json') var brigade = require('./brigade')()[0] const bhConfig = { dotenv: require('./dotenv')(), info: '[Brigadehub]', version: pkg.version, brigade: brigade } core(bhConfig)
therebelrobot/brigadehub
app.js
JavaScript
mit
253
#include <assert.h> #include <stdint.h> #include <OpenP2P/Buffer.hpp> #include <OpenP2P/Stream/BinaryStream.hpp> #include <OpenP2P/Event/Source.hpp> #include <OpenP2P/Event/Wait.hpp> #include <OpenP2P/RootNetwork/Endpoint.hpp> #include <OpenP2P/RootNetwork/Packet.hpp> #include <OpenP2P/RootNetwork/PacketSocket.hpp> #include <OpenP2P/RootNetwork/SignedPacket.hpp> namespace OpenP2P { namespace RootNetwork { PacketSocket::PacketSocket(Socket<UDP::Endpoint, Buffer>& udpSocket) : udpSocket_(udpSocket) { } bool PacketSocket::isValid() const { return udpSocket_.isValid(); } Event::Source PacketSocket::eventSource() const { return udpSocket_.eventSource(); } bool PacketSocket::receive(Endpoint& endpoint, SignedPacket& signedPacket) { UDP::Endpoint udpEndpoint; Buffer buffer; if (!udpSocket_.receive(udpEndpoint, buffer)) { return false; } endpoint.kind = Endpoint::UDPIPV6; endpoint.udpEndpoint = udpEndpoint; BufferIterator bufferIterator(buffer); BinaryIStream blockingReader(bufferIterator); signedPacket.packet = ReadPacket(blockingReader); signedPacket.signature = ReadSignature(blockingReader); return true; } bool PacketSocket::send(const Endpoint& endpoint, const SignedPacket& signedPacket) { assert(endpoint.kind == Endpoint::UDPIPV6); Buffer buffer; BufferBuilder bufferBuilder(buffer); BinaryOStream blockingWriter(bufferBuilder); WritePacket(blockingWriter, signedPacket.packet); WriteSignature(blockingWriter, signedPacket.signature); return udpSocket_.send(endpoint.udpEndpoint, buffer); } } }
goodspeed24e/2014iOT
test/openp2p/src/OpenP2P/RootNetwork/PacketSocket.cpp
C++
mit
1,642
/* -*- C++ -*- */ #include <QtGlobal> #include <QtAlgorithms> #include <QChar> #include <QDebug> #include <QList> #include <QMap> #include <QPointer> #include <QRegExp> #include <QSettings> #include <QSharedData> #include <QSharedDataPointer> #include "qluaapplication.h" #include "qtluaengine.h" #include "qluamainwindow.h" #include "qluatextedit.h" #include "qluamode.h" #include <string.h> #include <ctype.h> #define DEBUG 0 // ======================================== // USERDATA namespace { enum TokenType { // generic tokens Other, Identifier, Number, String, // tokens SemiColon, ThreeDots, Comma, Dot, Colon, LParen, RParen, LBracket, RBracket, LBrace, RBrace, // keywords Kand, Kfalse, Kfunction, Knil, Knot, Kor, Ktrue, Kin, // keywords that kill statements Kbreak, Kdo, Kelse, Kelseif, Kend, Kfor, Kif, Klocal, Krepeat, Kreturn, Kthen, Kuntil, Kwhile, // special Eof, Chunk, Statement, StatementCont, FunctionBody, FunctionName, FirstKeyword = Kand, FirstStrictKeyword = Kbreak, }; struct Keywords { const char *text; TokenType type; }; Keywords skeywords[] = { {"and", Kand}, {"break", Kbreak}, {"do", Kdo}, {"else", Kelse}, {"elseif", Kelseif}, {"end", Kend}, {"false", Kfalse}, {"for", Kfor}, {"function", Kfunction}, {"if", Kif}, {"in", Kin}, {"local", Klocal}, {"nil", Knil}, {"not", Knot}, {"or", Kor}, {"repeat", Krepeat}, {"return", Kreturn}, {"then", Kthen}, {"true", Ktrue}, {"until", Kuntil}, {"while", Kwhile}, {";", SemiColon}, {"...", ThreeDots}, {",", Comma}, {".", Dot}, {":", Colon}, {"(", LParen}, {")", RParen}, {"[", LBracket}, {"]", RBracket}, {"{", LBrace}, {"}", RBrace}, {0} }; struct Node; struct PNode : public QSharedDataPointer<Node> { PNode(); PNode(TokenType t, int p, int l, PNode n); PNode(TokenType t, int p, int l, int i, PNode n); TokenType type() const; int pos() const; int len() const; int indent() const; PNode next() const; }; struct Node : public QSharedData { Node(TokenType t, int p, int l, PNode n) : next(n), type(t),pos(p),len(l),indent(-1) {} Node(TokenType t, int p, int l, int i, PNode n) : next(n), type(t),pos(p),len(l),indent(i) {} PNode next; TokenType type; int pos; int len; int indent; }; PNode::PNode() : QSharedDataPointer<Node>() {} PNode::PNode(TokenType t, int p, int l, PNode n) : QSharedDataPointer<Node>(new Node(t,p,l,n)) {} PNode::PNode(TokenType t, int p, int l, int i, PNode n) : QSharedDataPointer<Node>(new Node(t,p,l,i,n)) {} inline TokenType PNode::type() const { const Node *n = constData(); return (n) ? n->type : Chunk; } inline int PNode::pos() const { const Node *n = constData(); return (n) ? n->pos : 0; } inline int PNode::len() const { const Node *n = constData(); return (n) ? n->len : 0; } inline int PNode::indent() const { const Node *n = constData(); return (n) ? n->indent : 0; } inline PNode PNode::next() const { const Node *n = constData(); return (n) ? n->next : PNode(); } struct UserData : public QLuaModeUserData { // lexical state int lexState; int lexPos; int lexN; // parser state PNode nodes; int lastPos; // initialize UserData() : lexState(0), lexPos(0), lexN(0), lastPos(0) {} virtual int highlightState() { return (lexState<<16)^lexN; } }; } // ======================================== // QLUAMODELUA class QLuaModeLua : public QLuaMode { Q_OBJECT public: QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e); void gotLine(UserData *d, int pos, int len, QString); void gotToken(UserData *d, int pos, int len, QString, TokenType); bool supportsComplete() { return true; } bool supportsLua() { return true; } virtual void parseBlock(int pos, const QTextBlock &block, const QLuaModeUserData *idata, QLuaModeUserData *&odata ); QStringList computeFileCompletions(QString s, bool escape, QString &stem); QStringList computeSymbolCompletions(QString s, QString &stem); virtual bool doComplete(); private: QMap<QString,TokenType> keywords; QRegExp reNum, reSym, reId; int bi; }; QLuaModeLua::QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e) : QLuaMode(f,e), reNum("^(0x[0-9a-fA-F]+|\\.[0-9]+|[0-9]+(\\.[0-9]*)?([Ee][-+]?[0-9]*)?)"), reSym("^(\\.\\.\\.|<=|>=|==|~=|.)"), reId("^[A-Za-z_][A-Za-z0-9_]*"), bi(3) { // basic indent QSettings s; s.beginGroup("luaMode"); bi = s.value("basicIndent", 3).toInt(); // tokens for (int i=0; skeywords[i].text; i++) keywords[QString(skeywords[i].text)] = skeywords[i].type; } void QLuaModeLua::parseBlock(int pos, const QTextBlock &block, const QLuaModeUserData *idata, QLuaModeUserData *&odata ) { QString text = block.text(); UserData *data = new UserData; // input state if (idata) *data = *static_cast<const UserData*>(idata); // hack for statements that seem complete if (data->nodes.type() == Statement) setIndent(data->lastPos, data->nodes.next().indent()); // process line gotLine(data, pos, block.length(), block.text()); // flush parser stack on last block if (! block.next().isValid()) gotToken(data, data->lastPos+1, 0, QString(), Eof); // output state odata = data; } // ======================================== // QLUAMODELUA - LEXICAL ANALYSIS void QLuaModeLua::gotLine(UserData *d, int pos, int len, QString s) { // default indent if (pos == 0) setIndent(-1, 0); // lexical analysis int p = 0; int n = d->lexN; int r = d->lexPos - pos; int state = d->lexState; int slen = s.size(); while (p < len) { int c = (p < slen) ? s[p].toAscii() : '\n'; switch(state) { case 0: state = -1; if (c == '#') { r = p; n = 0; state = -4; } continue; default: case -1: if (isspace(c)) { break; } if (isalpha(c) || c=='_') { r = p; state = -2; } else if (c=='\'') { setIndentOverlay(pos+p+1, -1); r = p; n = -c; state = -3; } else if (c=='\"') { setIndentOverlay(pos+p+1, -1); r = p; n = -c; state = -3; } else if (c=='[') { r = p; n = 0; state = -3; int t = p + 1; while (t < slen && s[t] == '=') t += 1; if (t < slen && s[t] == '[') { n = t - p; setIndentOverlay(pos+p, -1); } else { state = -1; gotToken(d, pos+p, 1, QString(), LBracket); } } else if (c=='-' && p+1 < slen && s[p+1]=='-') { r = p; n = 0; state = -4; if (p+2 < slen && s[p+2]=='[') { int t = p + 3; while (t < slen && s[t] == '=') t += 1; if (t < slen && s[t] == '[') { n = t - p - 2; setIndentOverlay(pos+p, 0); setIndentOverlay(pos+t+1, (n > 1) ? -1 : e->indentAfter(pos+t+1, +1) ); } } } else if (reNum.indexIn(s,p,QRegExp::CaretAtOffset)>=0) { int l = reNum.matchedLength(); QString m = s.mid(p,l); setFormat(pos+p, l, "number"); gotToken(d, pos+p, l, m, Number); p += l - 1; } else if (reSym.indexIn(s,p,QRegExp::CaretAtOffset)>=0) { int l = reSym.matchedLength(); QString m = s.mid(p,l); if (keywords.contains(m)) gotToken(d, pos+p, l, QString(), keywords[m]); else gotToken(d, pos+p, l, m, Other); p += l - 1; } break; case -2: // identifier if (!isalnum(c) && c!='_') { QString m = s.mid(r, p-r); if (keywords.contains(m)) { setFormat(pos+r, p-r, "keyword"); gotToken(d, pos+r, p-r, QString(), keywords[m]); } else gotToken(d, pos+r, p-r, m, Identifier); state = -1; continue; } break; case -3: // string if (n <= 0 && (c == -n || c == '\n' || c == '\r')) { setFormat(pos+r,p-r+1,"string"); setIndentOverlay(pos+p+1); gotToken(d, pos+r,p-r+1, QString(), String); state = -1; } else if (n <= 0 && c=='\\') { p += 1; } else if (n > 0 && c==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < slen && s[t] == '=') t += 1; if (t == p) { setFormat(pos+r,p-r+1,"string"); setIndentOverlay(pos+p+1); gotToken(d, pos+r,p-r+1,QString(),String); state = -1; } } break; case -4: // comment if (n <= 0 && (c == '\n' || c == '\r')) { setFormat(pos+r, p-r, "comment"); state = -1; } else if (n > 0 && c==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < slen && s[t] == '=') t += 1; if (t == p) { setFormat(pos+r, p-r+1, "comment"); setIndentOverlay(pos+p-n, 2); setIndentOverlay(pos+p+1); state = -1; } } break; } p += 1; } // save state d->lexN = n; d->lexPos = r + pos; d->lexState = state; // format incomplete tokens if (state == -4) setFormat(qMax(pos,pos+r),qMin(len,len-r),"comment"); else if (state == -3) setFormat(qMax(pos,pos+r),qMin(len,len-r),"string"); } // ======================================== // QLUAMODELUA - PARSING #if DEBUG QDebug operator<<(QDebug d, const TokenType &t) { d.nospace(); # define DO(x) if (t==x) d << #x; else DO(Other) DO(Identifier) DO(Number) DO(String) DO(SemiColon) DO(ThreeDots) DO(Comma) DO(Dot) DO(Colon) DO(LParen) DO(RParen) DO(LBracket) DO(RBracket) DO(LBrace) DO(RBrace) DO(Kand) DO(Kfalse) DO(Kfunction) DO(Knil) DO(Knot) DO(Kor) DO(Ktrue) DO(Kin) DO(Kbreak) DO(Kdo) DO(Kelse) DO(Kelseif) DO(Kend) DO(Kfor) DO(Kif) DO(Klocal) DO(Krepeat) DO(Kreturn) DO(Kthen) DO(Kuntil) DO(Kwhile) DO(Statement) DO(StatementCont) DO(Chunk) DO(FunctionBody) DO(FunctionName) DO(Eof) # undef DO d << "<Unknown>"; return d.space(); } #endif void QLuaModeLua::gotToken(UserData *d, int pos, int len, QString s, TokenType ltype) { PNode &n = d->nodes; TokenType ntype = n.type(); #if DEBUG qDebug() << " node:" << n << ntype << n.pos() << n.len() << n.indent() << n.next().type() << n.next().next().type(); if (s.isEmpty()) qDebug() << " token:" << pos << len << ltype; else qDebug() << " token:" << pos << len << ltype << s; #endif // close statements if ( ((ntype==Statement) && (ltype==Identifier || ltype==Kfunction) ) || ((ntype==Statement || ntype==StatementCont || ntype==Klocal || ntype==Kreturn ) && (ltype==SemiColon || ltype>=FirstStrictKeyword) ) ) { int epos = (ltype==SemiColon) ? pos+len : d->lastPos; int spos = n.pos(); n = n.next(); setBalance(spos, epos, n.type()==Chunk); setIndent(epos, n.indent()); } if ((ntype == FunctionName || ntype == Kfunction) && (ltype!=Identifier && ltype!=Dot && ltype!=Colon) ) { if (ntype == FunctionName) n=n.next(); ntype = n->type = FunctionBody; setIndent(pos, n.indent()); } ntype = n.type(); // fixup hacked indents if (ntype == StatementCont) n->type = Statement; if (d->lastPos < pos && ntype == Statement) setIndent(pos, n.indent()); d->lastPos = pos + len; // parse switch (ltype) { badOne: { setIndent(pos, -1); while (n.type() != Chunk && n.len() == 0) n = n.next(); setErrorMatch(pos, len, n.pos(), n.len()); n = n.next(); setIndent(pos+len, n.indent()); break; } case RParen: if (ntype != LParen) goto badOne; goto rightOne; case RBracket: if (ntype != LBracket) goto badOne; goto rightOne; case RBrace: if (ntype != LBrace) goto badOne; goto rightOne; case Kend: if (ntype!=Kdo && ntype!=Kelse && ntype!=Kthen && ntype!=Kfunction && ntype!=FunctionBody) goto badOne; rightOne: { setRightMatch(pos, len, n.pos(), n.len()); int fpos = followMatch(n.pos(),n.len()); int indent = n.indent(); n = n.next(); if (ltype < FirstKeyword) indent = qMin(qMax(0,indent-bi),e->indentAt(fpos)); else indent = n.indent(); setIndent(pos, indent); setIndent(pos+len, n.indent()); setBalance(fpos, pos+len, n.type()==Chunk); break; } case Kuntil: if (ntype != Krepeat) goto badOne; { setRightMatch(pos, len, n.pos(), n.len()); setIndent(pos, n.next().indent()); setIndent(pos+len, n.indent()); n->len = 0; n->type = StatementCont; break; } case Kthen: if (ntype!=Kif && ntype!=Kelseif) goto badOne; goto middleOne; case Kelse: case Kelseif: if (ntype!=Kthen) goto badOne; middleOne: { setMiddleMatch(pos, len, n.pos(), n.len()); setIndent(pos, n.next().indent()); setIndent(pos+len, n.indent()); n->type = ltype; n->pos = pos; n->len = len; break; } case Kdo: if (ntype==Kfor || ntype==Kwhile) goto middleOne; goto leftOne; case Kfunction: if (ntype == Klocal) goto middleOne; goto leftOne; case Kfor: case Kif: case Kwhile: case Krepeat: case Klocal: case Kreturn: case LParen: case LBracket: case LBrace: leftOne: { int indent = n.indent() + bi; if (ltype == LBrace && ntype == StatementCont) indent = n.indent(); else if (ltype < FirstKeyword) indent = e->indentAfter(pos+len); setIndent(pos, n.indent()); n = PNode(ltype, pos, len, indent, n); setIndent(pos+len, indent); setLeftMatch(pos, len); break; } case SemiColon: case Eof: break; case Identifier: if (ntype == Kfunction) n = PNode(FunctionName, pos, len, n.indent(), n); if (n.type() == FunctionName) setFormat(pos, len, "function"); goto openStatement; case Dot: case Colon: if (ntype == FunctionName) setFormat(pos, len, "function"); case Kand: case Kor: case Knot: case Kin: case Comma: case Other: if (n.type() == Statement) { n->type = StatementCont; setIndent(pos, n.indent()); } default: openStatement: { if (ntype==Chunk || ntype==Kdo || ntype==Kthen || ntype==Kelse || ntype==Krepeat || ntype==FunctionBody) { int indent = n.indent() + bi; n = PNode(Statement, pos, 0, indent, n); setIndent(pos+len, indent); } else if (ntype==Klocal) n->type = StatementCont; else if (ntype==Kreturn) n->type = Statement; break; } } } // ======================================== // COMPLETION static int comp_lex(QString s, int len, int state, int n, int &q) { QChar z; int p = 0; while (p < len) { switch(state) { default: case -1: // misc if (isalpha(s[p].toAscii()) || s[p]=='_') { q = p; state = -2; } else if (s[p]=='\'') { q = p+1; z = s[p]; n = 0; state = -3; } else if (s[p]=='\"') { q = p+1; z = s[p]; n = 0; state = -3; } else if (s[p]=='[') { n = 0; state = -3; int t = p + 1; while (t < len && s[t] == '=') t += 1; if (t < len && s[t] == '[') { q = t + 1; n = t - p; } else state = -1; } else if (s[p]=='-' && s[p+1]=='-') { n = 0; state = -4; if (s[p+2]=='[') { int t = p + 3; while (t < len && s[t] == '=') t += 1; if (t < len && s[t] == '[') n = t - p - 2; } } break; case -2: // identifier if (!isalnum(s[p].toAscii()) && s[p]!='_' && s[p]!='.' && s[p]!=':') { state = -1; continue; } break; case -3: // string if (n == 0 && s[p] == z) { state = -1; } else if (n == 0 && s[p]=='\\') { p += 1; } else if (n && s[p]==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < len && s[t] == '=') t += 1; if (t == p) state = -1; } break; case -4: // comment if (n == 0 && (s[p] == '\n' || s[p] == '\r')) { state = -1; } else if (n && s[p]==']' && p>=n && s[p-n]==']') { int t = p - n + 1; while (t < len && s[t] == '=') t += 1; if (t == p) state = -1; } break; } p += 1; } return state; } bool QLuaModeLua::doComplete() { QString stem; QStringList completions; QTextCursor c = e->textCursor(); QTextBlock b = c.block(); int len = c.position() - b.position(); QString text = b.text().left(len); int state = -1; int q = 0; int n = 0; QTextBlock pb = b.previous(); if (pb.isValid()) { UserData *data = static_cast<UserData*>(pb.userData()); if (! data) return false; state = data->lexState; n = data->lexN; } state = comp_lex(text, len, state, n, q); if (state == -3 && q >= 0 && q <= len) completions = computeFileCompletions(text.mid(q, len-q), n>0, stem); if (state == -2 && q >= 0 && q <= len) completions = computeSymbolCompletions(text.mid(q, len-q), stem); int selected = 0; if (completions.size() > 1) { qSort(completions.begin(), completions.end()); for (int i=completions.size()-2; i>=0; i--) if (completions[i] == completions[i+1]) completions.removeAt(i); selected = askCompletion(stem, completions); } if (selected >= 0 && selected < completions.size()) { c.insertText(completions[selected]); e->setTextCursor(c); return true; } return false; } static const char *escape1 = "abfnrtv"; static const char *escape2 = "\a\b\f\n\r\t\v"; static QByteArray unescapeString(const char *s) { int c; QByteArray r; while ((c = *s++)) { if (c != '\\') r += c; else { c = *s++; const char *e = strchr(escape1, c); if (e) r += escape2[e - escape1]; else if (c >= '0' && c <= '7') { c = c - '0'; if (*s >= '0' && *s <= '7') c = c * 8 + *s++ - '0'; if (*s >= '0' && *s <= '7') c = c * 8 + *s++ - '0'; r += c; } else r += c; } } return r; } static QString unescapeString(QString s) { return QString::fromLocal8Bit(unescapeString(s.toLocal8Bit().constData())); } static QByteArray escapeString(const char *s) { int c; QByteArray r; while ((c = *s++)) { const char *e; if (! isascii(c)) r += c; else if (iscntrl(c) && (e = strchr(escape2, c))) r += escape1[e - escape2]; else if (isprint(c) || isspace(c)) r += c; else { char buffer[8]; sprintf(buffer, "\\%03o", c); r += buffer; } } return r; } static QString escapeString(QString s) { return QString::fromLocal8Bit(escapeString(s.toLocal8Bit().constData())); } QStringList QLuaModeLua::computeFileCompletions(QString s, bool escape, QString &stem) { QStringList list; s.remove(QRegExp("^.*\\s")); stem = s; if (escape) stem = unescapeString(s); fileCompletion(stem, list); if (escape) { QStringList nl; foreach(QString s, list) nl += escapeString(s); stem = escapeString(stem); list = nl; } return list; } static const char * comp_keywords[] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", 0 }; QStringList QLuaModeLua::computeSymbolCompletions(QString s, QString &stem) { QStringList list; QByteArray f = s.toLocal8Bit(); int flen = f.size(); // stem stem = s.remove(QRegExp("^.*[.:]")); // keywords for (const char **k = comp_keywords; *k; k++) if (!strncmp(f.constData(), *k, flen)) list += QString::fromLocal8Bit(*k + flen); // symbols QtLuaEngine *engine = QLuaApplication::engine(); if (engine) { QtLuaLocker lua(engine, 250); struct lua_State *L = lua; if (lua) { lua_pushcfunction(L, luaQ_complete); lua_pushlstring(L, f.constData(), flen); if (!lua_pcall(L, 1, 1, 0) && lua_istable(L, -1)) { int n = lua_objlen(L, -1); for (int j=1; j<=n; j++) { lua_rawgeti(L, -1, j); list += QString::fromLocal8Bit(lua_tostring(L, -1)); lua_pop(L, 1); } } lua_pop(L, 1); } else { QWidget *w = e->window(); QLuaMainWindow *m = qobject_cast<QLuaMainWindow*>(w); if (m) m->showStatusMessage(tr("Auto-completions is restricted " "while Lua is running.") ); QLuaApplication::beep(); } } return list; } // ======================================== // FACTORY static QLuaModeFactory<QLuaModeLua> textModeFactory("Lua", "lua"); // ======================================== // MOC #include "qluamode_lua.moc" /* ------------------------------------------------------------- Local Variables: c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*") End: ------------------------------------------------------------- */
EliHar/Pattern_recognition
torch1/exe/qtlua/packages/qtide/qluamode_lua.cpp
C++
mit
22,831
// Copyright (c) 2020 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING //Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage) #ifdef DLL_EXPORT #undef DLL_EXPORT #endif // Unity specific includes #include "unity_impl.h" #include "libinit.h" // Standard gulden headers #include "appname.h" #include "clientversion.h" #include "util.h" #include "witnessutil.h" #include "ui_interface.h" #include "unity/appmanager.h" #include "utilmoneystr.h" #include <chain.h> #include "consensus/validation.h" #include "net.h" #include "wallet/mnemonic.h" #include "net_processing.h" #include "wallet/spvscanner.h" #include "sync.h" #include "init.h" // Djinni generated files #include "i_library_controller.hpp" #include "i_library_listener.hpp" #include "qr_code_record.hpp" #include "balance_record.hpp" #include "uri_record.hpp" #include "uri_recipient.hpp" #include "mutation_record.hpp" #include "input_record.hpp" #include "output_record.hpp" #include "address_record.hpp" #include "peer_record.hpp" #include "block_info_record.hpp" #include "monitor_record.hpp" #include "monitor_listener.hpp" #include "payment_result_status.hpp" #include "mnemonic_record.hpp" #ifdef __ANDROID__ #include "djinni_support.hpp" #endif // External libraries #include <boost/algorithm/string.hpp> #include <boost/program_options/parsers.hpp> #include <qrencode.h> #include <memory> #include "pow/pow.h" #include <crypto/hash/sigma/sigma.h> #include <algorithm> std::shared_ptr<ILibraryListener> signalHandler; CCriticalSection cs_monitoringListeners; std::set<std::shared_ptr<MonitorListener> > monitoringListeners; boost::asio::io_context ioctx; boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work = boost::asio::make_work_guard(ioctx); boost::thread run_thread(boost::bind(&boost::asio::io_context::run, boost::ref(ioctx))); static const int64_t nClientStartupTime = GetTime(); std::vector<CAccount*> GetAccountsForAccount(CAccount* forAccount) { std::vector<CAccount*> forAccounts; forAccounts.push_back(forAccount); for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts) { (unused) accountUUID; if (account->getParentUUID() == forAccount->getUUID()) { forAccounts.push_back(account); } } return forAccounts; } TransactionStatus getStatusForTransaction(const CWalletTx* wtx) { TransactionStatus status; int depth = wtx->GetDepthInMainChain(); if (depth < 0) status = TransactionStatus::CONFLICTED; else if (depth == 0) { if (wtx->isAbandoned()) status = TransactionStatus::ABANDONED; else status = TransactionStatus::UNCONFIRMED; } else if (depth < RECOMMENDED_CONFIRMATIONS) { status = TransactionStatus::CONFIRMING; } else { status = TransactionStatus::CONFIRMED; } return status; } std::string getRecipientAddressesForWalletTransaction(CAccount* forAccount, CWallet* pWallet, const CWalletTx* wtx, bool isSentByUs) { std::string address = ""; for (const CTxOut& txout: wtx->tx->vout) { bool isMine = false; if (forAccount && IsMine(*forAccount, txout)) { isMine = true; } if (!forAccount && pWallet && IsMine(*pWallet, txout)) { isMine = true; } if ((isSentByUs && !isMine) || (!isSentByUs && isMine)) { CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { dest = CNoDestination(); } if (addr.Set(dest)) { if (!address.empty()) address += ", "; address += addr.ToString(); } } } return address; } void addMutationsForTransaction(const CWalletTx* wtx, std::vector<MutationRecord>& mutations, CAccount* forAccount) { // exclude generated that are orphaned if (wtx->IsCoinBase() && wtx->GetDepthInMainChain() < 1) return; int64_t subtracted = wtx->GetDebit(ISMINE_SPENDABLE, forAccount, true); int64_t added = wtx->GetCredit(ISMINE_SPENDABLE, forAccount, true) + wtx->GetImmatureCredit(false, forAccount, true); uint64_t time = wtx->nTimeSmart; std::string hash = wtx->GetHash().ToString(); TransactionStatus status = getStatusForTransaction(wtx); int depth = wtx->GetDepthInMainChain(); // if any funds were subtracted the transaction was sent by us if (subtracted > 0) { int64_t fee = subtracted - wtx->tx->GetValueOut(); int64_t change = wtx->GetChange(); std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, true); // detect internal transfer and split it if (subtracted - fee == added) { // amount received mutations.push_back(MutationRecord(added - change, time, hash, recipientAddresses, status, depth)); // amount send including fee mutations.push_back(MutationRecord(change - subtracted, time, hash, recipientAddresses, status, depth)); } else { mutations.push_back(MutationRecord(added - subtracted, time, hash, recipientAddresses, status, depth)); } } else if (added != 0) // nothing subtracted so we received funds { std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, false); mutations.push_back(MutationRecord(added, time, hash, recipientAddresses, status, depth)); } } TransactionRecord calculateTransactionRecordForWalletTransaction(const CWalletTx& wtx, std::vector<CAccount*>& forAccounts, bool& anyInputsOrOutputsAreMine) { CWallet* pwallet = pactiveWallet; std::vector<InputRecord> inputs; std::vector<OutputRecord> outputs; int64_t subtracted=0; int64_t added=0; for (const auto& account : forAccounts) { subtracted += wtx.GetDebit(ISMINE_SPENDABLE, account, true); added += wtx.GetCredit(ISMINE_SPENDABLE, account, true); } CAmount fee = 0; // if any funds were subtracted the transaction was sent by us if (subtracted > 0) fee = subtracted - wtx.tx->GetValueOut(); const CTransaction& tx = *wtx.tx; for (const CTxIn& txin: tx.vin) { std::string address; CNativeAddress addr; CTxDestination dest = CNoDestination(); // Try to extract destination, this is not possible in general. Only if the previous // ouput of our input happens to be in our wallet. Which will usually only be the case for // our own transactions. uint256 txHash; if (txin.GetPrevOut().isHash) { txHash = txin.GetPrevOut().getTransactionHash(); } else { if (!pwallet->GetTxHash(txin.GetPrevOut(), txHash)) { LogPrintf("Transaction with no corresponding hash found, txid [%d] [%d]\n", txin.GetPrevOut().getTransactionBlockNumber(), txin.GetPrevOut().getTransactionIndex()); continue; } } std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(txHash); if (mi != pwallet->mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.GetPrevOut().n < prev.tx->vout.size()) { const auto& prevOut = prev.tx->vout[txin.GetPrevOut().n]; if (!ExtractDestination(prevOut, dest) && !prevOut.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", wtx.GetHash().ToString()); dest = CNoDestination(); } } } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (static_cast<const CExtWallet*>(pwallet)->IsMine(*account, txin)) { isMine = true; anyInputsOrOutputsAreMine = true; } } inputs.push_back(InputRecord(address, label, description, isMine)); } for (const CTxOut& txout: tx.vout) { std::string address; CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", tx.GetHash().ToString()); dest = CNoDestination(); } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (IsMine(*account, txout)) { isMine = true; anyInputsOrOutputsAreMine = true; } } outputs.push_back(OutputRecord(txout.nValue, address, label, description, isMine)); } TransactionStatus status = getStatusForTransaction(&wtx); return TransactionRecord(wtx.GetHash().ToString(), wtx.nTimeSmart, added - subtracted, fee, status, wtx.nHeight, wtx.nBlockTime, wtx.GetDepthInMainChain(), inputs, outputs); } // rate limited balance change notifier static CRateLimit<int>* balanceChangeNotifier=nullptr; // rate limited new mutations notifier static CRateLimit<std::pair<uint256, bool>>* newMutationsNotifier=nullptr; void terminateUnityFrontend() { if (signalHandler) { signalHandler->notifyShutdown(); } // Allow frontend time to clean up and free any references to objects before unloading the library // Otherwise we get a free after close (on macOS at least) while (signalHandler.use_count() > 1) { MilliSleep(50); } signalHandler=nullptr; } #include <boost/chrono/thread_clock.hpp> static float lastProgress=0; void handlePostInitMain() { //fixme: (SIGMA) (PHASE4) Remove this once we have witness-header-sync // Select appropriate verification factor based on devices performance. std::thread([=] { // When available measure thread relative cpu time to avoid effects of thread suspension // which occur when observing system time. #if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY boost::chrono::time_point tpStart = boost::chrono::thread_clock::now(); #else uint64_t nStart = GetTimeMicros(); #endif // note that measurement is on single thread, which makes the measurement more stable // actual verification might use more threads which helps overall app performance sigma_verify_context verify(defaultSigmaSettings, 1); CBlockHeader header; verify.verifyHeader<1>(header); // We want at least 1000 blocks per second #if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY boost::chrono::microseconds ms = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::thread_clock::now() - tpStart); uint64_t nTotal = ms.count(); #else uint64_t nTotal = GetTimeMicros() - nStart; #endif uint64_t nPerSec = 1000000/nTotal; if (nPerSec > 1000) // Fast enough to do most the blocks { verifyFactor = 5; } else if(nPerSec > 0) // Slower so reduce the number of blocks { // 2 in verifyFactor chance of verifying. // We verify 2 in verifyFactor blocks - or target_speed/(num_per_sec/2) verifyFactor = 1000/(nPerSec/2.0); verifyFactor = std::max((uint64_t)5, verifyFactor); verifyFactor = std::min((uint64_t)200, verifyFactor); } LogPrintf("unity: selected verification factor %d", verifyFactor); }).detach(); if (signalHandler) { signalHandler->notifyCoreReady(); } // unified progress notification if (!GetBoolArg("-spv", DEFAULT_SPV)) { static bool haveFinishedHeaderSync=false; static int totalHeaderCount=0; static int startHeight = chainActive.Tip() ? chainActive.Tip()->nHeight : 0; // If tip is relatively recent set progress to "completed" to begin with if (chainActive.Tip() && ((GetTime() - chainActive.Tip()->nTime) < 3600)) { lastProgress = 1.0; } // Weight a full header sync as 20%, blocks as rest uiInterface.NotifyHeaderProgress.connect([=](int currentCount, int probableHeight, int headerTipHeight, int64_t headerTipTime) { totalHeaderCount = currentCount; if (currentCount == probableHeight) { haveFinishedHeaderSync = true; } if (!haveFinishedHeaderSync && signalHandler && IsInitialBlockDownload()) { float progress = ((((float)currentCount-startHeight)/((float)probableHeight-startHeight))*0.20); if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1)) { lastProgress = progress; signalHandler->notifyUnifiedProgress(progress); } } }); uiInterface.NotifyBlockTip.connect([=](bool isInitialBlockDownload, const CBlockIndex* pNewTip) { if (haveFinishedHeaderSync && signalHandler) { float progress = pNewTip->nHeight==totalHeaderCount?1:((0.20+((((float)pNewTip->nHeight-startHeight)/((float)totalHeaderCount-startHeight))*0.80))); if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1)) { lastProgress = progress; signalHandler->notifyUnifiedProgress(progress); } } }); } else { uiInterface.NotifyUnifiedProgress.connect([=](float progress) { if (signalHandler) { signalHandler->notifyUnifiedProgress(progress); } }); // monitoring listeners notifications uiInterface.NotifyHeaderProgress.connect([=](int, int, int, int64_t) { int32_t height, probable_height, offset; { LOCK(cs_main); height = partialChain.Height(); probable_height = GetProbableHeight(); offset = partialChain.HeightOffset(); } LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onPartialChain(height, probable_height, offset); } }); uiInterface.NotifySPVPrune.connect([=](int height) { LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onPruned(height); } }); uiInterface.NotifySPVProgress.connect([=](int /*start_height*/, int processed_height, int /*probable_height*/) { LOCK(cs_monitoringListeners); for (const auto &listener: monitoringListeners) { listener->onProcessedSPVBlocks(processed_height); } }); } // Update transaction/balance changes if (pactiveWallet) { // Fire events for transaction depth changes (up to depth 10 only) pactiveWallet->NotifyTransactionDepthChanged.connect( [&](CWallet* pwallet, const uint256& hash) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { const CWalletTx& wtx = pwallet->mapWallet[hash]; LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str()); if (signalHandler) { std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); bool anyInputsOrOutputsAreMine = false; TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { signalHandler->notifyUpdatedTransaction(walletTransaction); } } } } ); // Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes) pactiveWallet->NotifyTransactionChanged.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { if (status == CT_NEW) { newMutationsNotifier->trigger(std::make_pair(hash, fSelfComitted)); } else if (status == CT_UPDATED && signalHandler) { LogPrintf("unity: notify tx updated %s",hash.ToString().c_str()); const CWalletTx& wtx = pwallet->mapWallet[hash]; std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); bool anyInputsOrOutputsAreMine = false; TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { signalHandler->notifyUpdatedTransaction(walletTransaction); } } //fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted... // else if (status == CT_DELETED) } balanceChangeNotifier->trigger(0); }); // Fire once immediately to update with latest on load. balanceChangeNotifier->trigger(0); } } void handleInitWithExistingWallet() { if (signalHandler) { signalHandler->notifyInitWithExistingWallet(); } AppLifecycleManager::gApp->initialize(); } void handleInitWithoutExistingWallet() { signalHandler->notifyInitWithoutExistingWallet(); } std::string ILibraryController::BuildInfo() { std::string info = FormatThreeDigitVersion(); #if defined(__aarch64__) info += " aarch64"; #elif defined(__arm__) info += " arm (32bit)"; #elif defined(__x86_64__) info += " x86_64"; #elif defined(__i386__) info += " x86"; #endif return info; } bool ILibraryController::InitWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password) { // Refuse to acknowledge an empty recovery phrase, or one that doesn't pass even the most obvious requirement if (phrase.length() < 16) { return false; } //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. SecureString phraseOnly; int phraseBirthNumber = 0; AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), phraseOnly, phraseBirthNumber); if (!checkMnemonic(phraseOnly)) { return false; } // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; AppLifecycleManager::gApp->initialize(); return true; } void DoRescanInternal() { if (pactiveWallet) { ResetSPVStartRescanThread(); } } bool ValidateAndSplitRecoveryPhrase(const std::string & phrase, SecureString& mnemonic, int& birthNumber) { if (phrase.length() < 16) return false; AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), mnemonic, birthNumber); return checkMnemonic(mnemonic) && (birthNumber == 0 || Base10ChecksumDecode(birthNumber, nullptr)); } bool ILibraryController::ContinueWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password) { SecureString phraseOnly; int phraseBirthNumber; if (!ValidateAndSplitRecoveryPhrase(phrase, phraseOnly, phraseBirthNumber)) return false; // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); if (!pactiveWallet) { LogPrintf("ContineWalletFromRecoveryPhrase: No active wallet"); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; CWallet::CreateSeedAndAccountFromPhrase(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::IsValidRecoveryPhrase(const std::string & phrase) { SecureString dummyMnemonic; int dummyNumber; return ValidateAndSplitRecoveryPhrase(phrase, dummyMnemonic, dummyNumber); } #include "base58.h" std::string ILibraryController::GenerateGenesisKeys() { std::string address = GetReceiveAddress(); CNativeAddress addr(address); CTxDestination dest = addr.Get(); CPubKey vchPubKeyDevSubsidy; pactiveWallet->GetPubKey(boost::get<CKeyID>(dest), vchPubKeyDevSubsidy); std::string devSubsidyPubKey = HexStr(vchPubKeyDevSubsidy); std::string devSubsidyPubKeyID = boost::get<CKeyID>(dest).GetHex(); CKey key; key.MakeNewKey(true); CPrivKey vchPrivKey = key.GetPrivKey(); CPubKey vchPubKey = key.GetPubKey(); std::string privkey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()).c_str(); std::string pubKeyID = vchPubKey.GetID().GetHex(); std::string witnessKeys = GLOBAL_APP_URIPREFIX"://witnesskeys?keys=" + CEncodedSecretKey(key).ToString() + strprintf("#%s", GetAdjustedTime()); return "privkey: "+privkey+"\n"+"pubkeyID: "+pubKeyID+"\n"+"witness: "+witnessKeys+"\n"+"dev subsidy addr: "+address+"\n"+"dev subsidy pubkey: "+devSubsidyPubKey+"\n"+"dev subsidy pubkey ID: "+devSubsidyPubKeyID+"\n"; } MnemonicRecord ILibraryController::GenerateRecoveryMnemonic() { std::vector<unsigned char> entropy(16); GetStrongRandBytes(&entropy[0], 16); int64_t birthTime = GetAdjustedTime(); SecureString phraseOnly = mnemonicFromEntropy(entropy, entropy.size()*8); return ComposeRecoveryPhrase(phraseOnly.c_str(), birthTime); } MnemonicRecord ILibraryController::ComposeRecoveryPhrase(const std::string & mnemonic, int64_t birthTime) { const auto& result = AppLifecycleManager::composeRecoveryPhrase(SecureString(mnemonic), birthTime); return MnemonicRecord(result.first.c_str(), mnemonic.c_str(), result.second); } bool ILibraryController::InitWalletLinkedFromURI(const std::string& linked_uri, const std::string& password) { CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->isLink = true; AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->initialize(); return true; } bool ILibraryController::ContinueWalletLinkedFromURI(const std::string & linked_uri, const std::string& password) { if (!pactiveWallet) { LogPrintf("%s: No active wallet", __func__); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("%s: Failed to parse link URI", __func__); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::CreateSeedAndAccountFromLink(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::ReplaceWalletLinkedFromURI(const std::string& linked_uri, const std::string& password) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) { LogPrintf("ReplaceWalletLinkedFromURI: No active wallet"); return false; } // Create ext key for new linked account from parsed data CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to parse link URI"); return false; } // Ensure we have a valid location to send all the funds CNativeAddress address(linkedKey.getPayAccount()); if (!address.IsValid()) { LogPrintf("ReplaceWalletLinkedFromURI: invalid address %s", linkedKey.getPayAccount().c_str()); return false; } // Empty wallet to target address LogPrintf("ReplaceWalletLinkedFromURI: Empty accounts into linked address"); bool fSubtractFeeFromAmount = true; std::vector<std::tuple<CWalletTx*, CReserveKeyOrScript*>> transactionsToCommit; for (const auto& [accountUUID, pAccount] : pactiveWallet->mapAccounts) { CAmount nBalance = pactiveWallet->GetBalance(pAccount, false, true, true); if (nBalance > 0) { LogPrintf("ReplaceWalletLinkedFromURI: Empty account into linked address [%s]", getUUIDAsString(accountUUID).c_str()); std::vector<CRecipient> vecSend; CRecipient recipient = GetRecipientForDestination(address.Get(), nBalance, fSubtractFeeFromAmount, GetPoW2Phase(chainTip())); vecSend.push_back(recipient); CWalletTx* pWallettx = new CWalletTx(); CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript* pReserveKey = new CReserveKeyOrScript(pactiveWallet, pAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, *pWallettx, *pReserveKey, nFeeRequired, nChangePosRet, strError)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to create transaction %s [%d]",strError.c_str(), nBalance); return false; } transactionsToCommit.push_back(std::tuple(pWallettx, pReserveKey)); } else { LogPrintf("ReplaceWalletLinkedFromURI: Account already empty [%s]", getUUIDAsString(accountUUID).c_str()); } } if (!EraseWalletSeedsAndAccounts()) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to erase seed and accounts"); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::CreateSeedAndAccountFromLink(pactiveWallet); for (auto& [pWalletTx, pReserveKey] : transactionsToCommit) { CValidationState state; //NB! We delibritely pass nullptr for connman here to prevent transaction from relaying //We allow the relaying to occur inside DoRescan instead if (!pactiveWallet->CommitTransaction(*pWalletTx, *pReserveKey, nullptr, state)) { LogPrintf("ReplaceWalletLinkedFromURI: Failed to commit transaction"); return false; } delete pWalletTx; delete pReserveKey; } // Allow update of balance for deleted accounts/transactions LogPrintf("ReplaceWalletLinkedFromURI: Update balance and rescan"); balanceChangeNotifier->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::EraseWalletSeedsAndAccounts() { pactiveWallet->EraseWalletSeedsAndAccounts(); return true; } bool ILibraryController::IsValidLinkURI(const std::string& linked_uri) { CEncodedSecretKeyExt<CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) return false; return true; } bool testnet_; bool spvMode_; std::string extraArgs_; std::string staticFilterPath_; int64_t staticFilterOffset_; int64_t staticFilterLength_; int32_t ILibraryController::InitUnityLib(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { balanceChangeNotifier = new CRateLimit<int>([](int) { if (pactiveWallet && signalHandler) { WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); signalHandler->notifyBalanceChange(BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked)); } }, std::chrono::milliseconds(BALANCE_NOTIFY_THRESHOLD_MS)); newMutationsNotifier = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo) { if (pactiveWallet && signalHandler) { const uint256& txHash = txInfo.first; const bool fSelfComitted = txInfo.second; LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end()) { const CWalletTx& wtx = pactiveWallet->mapWallet[txHash]; std::vector<MutationRecord> mutations; addMutationsForTransaction(&wtx, mutations, pactiveWallet->activeAccount); for (auto& m: mutations) { LogPrintf("unity: notify new mutation for tx %s", txHash.ToString().c_str()); signalHandler->notifyNewMutation(m, fSelfComitted); } } } }, std::chrono::milliseconds(NEW_MUTATIONS_NOTIFY_THRESHOLD_MS)); // Force the datadir to specific place on e.g. android devices defaultDataDirOverride = dataDir; signalHandler = signalHandler_; testnet_ = testnet; spvMode_ = spvMode; extraArgs_ = extraArgs; staticFilterPath_ = staticFilterPath; staticFilterOffset_ = staticFilterOffset; staticFilterLength_ = staticFilterLength; return InitUnity(); } void InitAppSpecificConfigParamaters() { if (spvMode_) { // SPV wallets definitely shouldn't be listening for incoming connections at all SoftSetArg("-listen", "0"); // Minimise logging for performance reasons SoftSetArg("-debug", "0"); // Turn SPV mode on SoftSetArg("-fullsync", "0"); SoftSetArg("-spv", "1"); #ifdef DJINNI_NODEJS #ifdef SPV_MULTI_ACCOUNT SoftSetArg("-accountpool", "3"); SoftSetArg("-accountpoolmobi", "1"); SoftSetArg("-accountpoolwitness", "1"); SoftSetArg("-accountpoolmining", "1"); #else SoftSetArg("-accountpool", "0"); SoftSetArg("-accountpoolmobi", "0"); SoftSetArg("-accountpoolwitness", "0"); SoftSetArg("-accountpoolmining", "0"); #endif SoftSetArg("-keypool", "10"); #else // Minimise lookahead size for performance reasons SoftSetArg("-accountpool", "1"); // Minimise background threads and memory consumption SoftSetArg("-par", "-100"); SoftSetArg("-maxsigcachesize", "0"); SoftSetArg("-dbcache", "4"); SoftSetArg("-maxmempool", "5"); SoftSetArg("-maxconnections", "8"); //fixme: (FUT) (UNITY) Reverse headers // Temporarily disable reverse headers for mobile until memory requirements can be reduced. SoftSetArg("-reverseheaders", "false"); #endif } SoftSetArg("-spvstaticfilterfile", staticFilterPath_); SoftSetArg("-spvstaticfilterfileoffset", i64tostr(staticFilterOffset_)); SoftSetArg("-spvstaticfilterfilelength", i64tostr(staticFilterLength_)); // Change client name #if defined(__APPLE__) && TARGET_OS_IPHONE == 1 SoftSetArg("-clientname", GLOBAL_APPNAME" ios"); #elif defined(__ANDROID__) SoftSetArg("-clientname", GLOBAL_APPNAME" android"); #else SoftSetArg("-clientname", GLOBAL_APPNAME" desktop"); #endif // Testnet if (testnet_) { SoftSetArg("-testnet", "S1595347850:60"); SoftSetArg("-addnode", "178.62.195.19"); } else { SoftSetArg("-addnode", "178.62.195.19"); SoftSetArg("-addnode", "149.210.165.218"); } if (!extraArgs_.empty()) { std::vector<const char*> args; auto splitted = boost::program_options::split_unix(extraArgs_); for(const auto& part: splitted) args.push_back(part.c_str()); gArgs.ParseExtraParameters(int(args.size()), args.data()); } } void ILibraryController::InitUnityLibThreaded(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { std::thread([=] { InitUnityLib(dataDir, staticFilterPath, staticFilterOffset, staticFilterLength, testnet, spvMode, signalHandler_, extraArgs); }).detach(); } void ILibraryController::TerminateUnityLib() { // Terminate in thread so we don't block interprocess communication std::thread([=] { work.reset(); ioctx.stop(); AppLifecycleManager::gApp->shutdown(); AppLifecycleManager::gApp->waitForShutDown(); run_thread.join(); }).detach(); } QrCodeRecord ILibraryController::QRImageFromString(const std::string& qr_string, int32_t width_hint) { QRcode* code = QRcode_encodeString(qr_string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { return QrCodeRecord(0, std::vector<uint8_t>()); } else { const int32_t generatedWidth = code->width; const int32_t finalWidth = (width_hint / generatedWidth) * generatedWidth; const int32_t scaleMultiplier = finalWidth / generatedWidth; std::vector<uint8_t> dataVector; dataVector.reserve(finalWidth*finalWidth); int nIndex=0; for (int nRow=0; nRow<generatedWidth; ++nRow) { for (int nCol=0; nCol<generatedWidth; ++nCol) { dataVector.insert(dataVector.end(), scaleMultiplier, (code->data[nIndex++] & 1) * 255); } for (int i=1; i<scaleMultiplier; ++i) { dataVector.insert(dataVector.end(), dataVector.end()-finalWidth, dataVector.end()); } } QRcode_free(code); return QrCodeRecord(finalWidth, dataVector); } } std::string ILibraryController::GetReceiveAddress() { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) return ""; CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_EXTERNAL); CPubKey pubKey; if (receiveAddress->GetReservedKey(pubKey)) { CKeyID keyID = pubKey.GetID(); receiveAddress->ReturnKey(); delete receiveAddress; return CNativeAddress(keyID).ToString(); } else { return ""; } } //fixme: (UNITY) - find a way to use char[] here as well as on the java side. MnemonicRecord ILibraryController::GetRecoveryPhrase() { if (pactiveWallet && pactiveWallet->activeAccount) { LOCK2(cs_main, pactiveWallet->cs_wallet); //WalletModel::UnlockContext ctx(walletModel->requestUnlock()); //if (ctx.isValid()) { int64_t birthTime = pactiveWallet->birthTime(); std::set<SecureString> allPhrases; for (const auto& seedIter : pactiveWallet->mapSeeds) { SecureString phrase = seedIter.second->getMnemonic(); return ComposeRecoveryPhrase(phrase.c_str(), birthTime); } } } return MnemonicRecord("", "", 0); } bool ILibraryController::IsMnemonicWallet() { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); return pactiveWallet->activeSeed != nullptr; } bool ILibraryController::IsMnemonicCorrect(const std::string & phrase) { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); SecureString mnemonicPhrase; int birthNumber; AppLifecycleManager::splitRecoveryPhraseAndBirth(SecureString(phrase), mnemonicPhrase, birthNumber); LOCK2(cs_main, pactiveWallet->cs_wallet); for (const auto& seedIter : pactiveWallet->mapSeeds) { if (mnemonicPhrase == seedIter.second->getMnemonic()) return true; } return false; } std::vector<std::string> ILibraryController::GetMnemonicDictionary() { return getMnemonicDictionary(); } //fixme: (UNITY) HIGH - take a timeout value and always lock again after timeout bool ILibraryController::UnlockWallet(const std::string& password) { if (!pactiveWallet) { LogPrintf("UnlockWallet: No active wallet"); return false; } if (!dynamic_cast<CExtWallet*>(pactiveWallet)->IsCrypted()) { LogPrintf("UnlockWallet: Wallet not encrypted"); return false; } return pactiveWallet->Unlock(password.c_str()); } bool ILibraryController::LockWallet() { if (!pactiveWallet) { LogPrintf("LockWallet: No active wallet"); return false; } if (dynamic_cast<CExtWallet*>(pactiveWallet)->IsLocked()) return true; return dynamic_cast<CExtWallet*>(pactiveWallet)->Lock(); } bool ILibraryController::ChangePassword(const std::string& oldPassword, const std::string& newPassword) { if (!pactiveWallet) { LogPrintf("ChangePassword: No active wallet"); return false; } if (newPassword.length() == 0) { LogPrintf("ChangePassword: Refusing invalid password of length 0"); return false; } return pactiveWallet->ChangeWalletPassphrase(oldPassword.c_str(), newPassword.c_str()); } bool ILibraryController::HaveUnconfirmedFunds() { if (!pactiveWallet) return true; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); if (balances.unconfirmedIncludingLocked > 0 || balances.immatureIncludingLocked > 0) { return true; } return false; } int64_t ILibraryController::GetBalance() { if (!pactiveWallet) return 0; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); return balances.availableIncludingLocked + balances.unconfirmedIncludingLocked + balances.immatureIncludingLocked; } void ILibraryController::DoRescan() { if (!pactiveWallet) return; // Allocate some extra keys //fixme: Persist this across runs in some way static int32_t extraKeys=0; extraKeys += 5; int nKeyPoolTargetDepth = GetArg("-keypool", DEFAULT_ACCOUNT_KEYPOOL_SIZE)+extraKeys; pactiveWallet->TopUpKeyPool(nKeyPoolTargetDepth, 0, nullptr, 1); // Do the rescan DoRescanInternal(); } UriRecipient ILibraryController::IsValidRecipient(const UriRecord & request) { // return if URI is not valid or is no Gulden: URI std::string lowerCaseScheme = boost::algorithm::to_lower_copy(request.scheme); if (lowerCaseScheme != "gulden") return UriRecipient(false, "", "", "", 0); if (!CNativeAddress(request.path).IsValid()) return UriRecipient(false, "", "", "", 0); std::string address = request.path; std::string label = ""; std::string description = ""; CAmount amount = 0; if (request.items.find("amount") != request.items.end()) { ParseMoney(request.items.find("amount")->second, amount); } if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapAddressBook.find(address) != pactiveWallet->mapAddressBook.end()) { const auto& data = pactiveWallet->mapAddressBook[address]; label = data.name; description = data.description; } } return UriRecipient(true, address, label, description, amount); } bool ILibraryController::IsValidNativeAddress(const std::string& address) { CNativeAddress addr(address); return addr.IsValid(); } bool ILibraryController::IsValidBitcoinAddress(const std::string& address) { CNativeAddress addr(address); return addr.IsValidBitcoin(); } int64_t ILibraryController::feeForRecipient(const UriRecipient & request) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("feeForRecipient: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = GetRecipientForDestination(address.Get(), std::min(GetBalance(), request.amount), true, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, NULL, false)) { LogPrintf("feeForRecipient: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to calculate fee\n%s"), strError)); } return nFeeRequired; } PaymentResultStatus ILibraryController::performPaymentToRecipient(const UriRecipient & request, bool substract_fee) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("performPaymentToRecipient: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = GetRecipientForDestination(address.Get(), request.amount, substract_fee, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError)) { if (!substract_fee && request.amount + nFeeRequired > GetBalance()) { return PaymentResultStatus::INSUFFICIENT_FUNDS; } LogPrintf("performPaymentToRecipient: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to create transaction\n%s"), strError)); } CValidationState state; if (!pactiveWallet->CommitTransaction(wtx, reservekey, g_connman.get(), state)) { strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason()); LogPrintf("performPaymentToRecipient: failed to commit transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Transaction rejected, reason: %s"), state.GetRejectReason())); } // Prevent accidental double spends for (const auto &txin : wtx.tx->vin) { pactiveWallet->LockCoin(txin.GetPrevOut()); } return PaymentResultStatus::SUCCESS; } std::vector<TransactionRecord> getTransactionHistoryForAccount(CAccount* forAccount) { std::vector<TransactionRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); std::vector<CAccount*> forAccounts = GetAccountsForAccount(forAccount); for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { bool anyInputsOrOutputsAreMine = false; TransactionRecord tx = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); if (anyInputsOrOutputsAreMine) { ret.push_back(tx); } } std::sort(ret.begin(), ret.end(), [&](TransactionRecord& x, TransactionRecord& y){ return (x.timeStamp > y.timeStamp); }); return ret; } std::vector<TransactionRecord> ILibraryController::getTransactionHistory() { if (!pactiveWallet) return std::vector<TransactionRecord>(); return getTransactionHistoryForAccount(pactiveWallet->activeAccount); } TransactionRecord ILibraryController::getTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) throw std::runtime_error(strprintf("No transaction found for hash [%s]", txHash)); std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount); const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; bool anyInputsOrOutputsAreMine = false; return calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine); } std::string ILibraryController::resendTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) return ""; const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *wtx.tx; std::string strHex = HexStr(ssTx.begin(), ssTx.end()); if(!g_connman) return ""; const uint256& hashTx = wtx.tx->GetHash(); CInv inv(MSG_TX, hashTx); g_connman->ForEachNode([&inv](CNode* pnode) { pnode->PushInventory(inv); }); return strHex; } std::vector<MutationRecord> getMutationHistoryForAccount(CAccount* forAccount) { std::vector<MutationRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); // wallet transactions in reverse chronological ordering std::vector<const CWalletTx*> vWtx; for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { vWtx.push_back(&wtx); } std::sort(vWtx.begin(), vWtx.end(), [&](const CWalletTx* x, const CWalletTx* y){ return (x->nTimeSmart > y->nTimeSmart); }); // build mutation list based on transactions for (const CWalletTx* wtx : vWtx) { addMutationsForTransaction(wtx, ret, forAccount); } return ret; } std::vector<MutationRecord> ILibraryController::getMutationHistory() { if (!pactiveWallet) return std::vector<MutationRecord>(); return getMutationHistoryForAccount(pactiveWallet->activeAccount); } std::vector<AddressRecord> ILibraryController::getAddressBookRecords() { std::vector<AddressRecord> ret; if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); for(const auto& [address, addressData] : pactiveWallet->mapAddressBook) { ret.emplace_back(AddressRecord(address, addressData.name, addressData.description, addressData.purpose)); } } return ret; } void ILibraryController::addAddressBookRecord(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->SetAddressBook(address.address, address.name, address.desc, address.purpose); } } void ILibraryController::deleteAddressBookRecord(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->DelAddressBook(address.address); } } void ILibraryController::PersistAndPruneForSPV() { PersistAndPruneForPartialSync(); } void ILibraryController::ResetUnifiedProgress() { CWallet::ResetUnifiedSPVProgressNotification(); } float ILibraryController::getUnifiedProgress() { if (!GetBoolArg("-spv", DEFAULT_SPV)) { return lastProgress; } else { return CSPVScanner::lastProgressReported; } } std::vector<BlockInfoRecord> ILibraryController::getLastSPVBlockInfos() { std::vector<BlockInfoRecord> ret; LOCK(cs_main); int height = partialChain.Height(); while (ret.size() < 32 && height > partialChain.HeightOffset()) { const CBlockIndex* pindex = partialChain[height]; ret.push_back(BlockInfoRecord(pindex->nHeight, pindex->GetBlockTime(), pindex->GetBlockHashPoW2().ToString())); height--; } return ret; } MonitorRecord ILibraryController::getMonitoringStats() { LOCK(cs_main); int32_t partialHeight_ = partialChain.Height(); int32_t partialOffset_ = partialChain.HeightOffset(); int32_t prunedHeight_ = nPartialPruneHeightDone; int32_t processedSPVHeight_ = CSPVScanner::getProcessedHeight(); int32_t probableHeight_ = GetProbableHeight(); return MonitorRecord(partialHeight_, partialOffset_, prunedHeight_, processedSPVHeight_, probableHeight_); } void ILibraryController::RegisterMonitorListener(const std::shared_ptr<MonitorListener> & listener) { LOCK(cs_monitoringListeners); monitoringListeners.insert(listener); } void ILibraryController::UnregisterMonitorListener(const std::shared_ptr<MonitorListener> & listener) { LOCK(cs_monitoringListeners); monitoringListeners.erase(listener); } std::unordered_map<std::string, std::string> ILibraryController::getClientInfo() { std::unordered_map<std::string, std::string> ret; ret.insert(std::pair("client_version", FormatFullVersion())); ret.insert(std::pair("user_agent", strSubVersion)); ret.insert(std::pair("datadir_path", GetDataDir().string())); std::string logfilePath = (GetDataDir() / "debug.log").string(); ret.insert(std::pair("logfile_path", logfilePath)); ret.insert(std::pair("startup_timestamp", i64tostr(nClientStartupTime))); if (!g_connman->GetNetworkActive()) { ret.insert(std::pair("network_status", "disabled")); ret.insert(std::pair("num_connections_in", "0")); ret.insert(std::pair("num_connections_out", "0")); } else { ret.insert(std::pair("network_status", "enabled")); std::string connectionsIn = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_IN)); std::string connectionsOut = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_OUT)); ret.insert(std::pair("num_connections_in", connectionsIn)); ret.insert(std::pair("num_connections_out", connectionsOut)); } if (fSPV) { if (partialChain.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(partialChain.Height()))); ret.insert(std::pair("chain_tip_time", i64tostr(partialChain.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", partialChain.Tip()->GetBlockHashPoW2().ToString())); ret.insert(std::pair("chain_offset", i64tostr(partialChain.HeightOffset()))); ret.insert(std::pair("chain_pruned_height", i64tostr(nPartialPruneHeightDone))); ret.insert(std::pair("chain_processed_height", i64tostr(CSPVScanner::getProcessedHeight()))); ret.insert(std::pair("chain_probable_height", i64tostr(GetProbableHeight()))); } } else if (chainActive.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(chainActive.Tip()->nHeight))); ret.insert(std::pair("chain_tip_time", i64tostr(chainActive.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", chainActive.Tip()->GetBlockHashPoW2().ToString())); } ret.insert(std::pair("mempool_transaction_count", i64tostr(mempool.size()))); ret.insert(std::pair("mempool_memory_size", i64tostr(mempool.GetTotalTxSize()))); return ret; }
nlgcoin/guldencoin-official
src/unity/unity_impl.cpp
C++
mit
56,495
/* * DBAdapter.h * Main Class to manage DB operations * Created by: Ozgur Pekcagliyan - 2014-09-25 09:28:43 PM EEST * Last edited by: Ozgur Pekcagliyan - 2015-03-01 * Notes: * errorCode will be used to return specific error values back to user; * * Potential error codes are; * * * 0: success * * * 1: user name or password is incorrect * * * 2: db doesn't exist * * * 3: invalid sql query * * * 4: problem with disconnect * * * 5: failed to create sqlfile * * * 6-1000: unknown (reserved) * * * bigger than 1000 - SQL server error system (Ex: 1045000 means 1045) * type will hold the database that will be connected * * possible values are; * * * 1: mysql (default value) * * * 2: oracle * * * 3: sqlite * * * rest of the codes will be added in time by developers * In selectData function, data will be returned in a string vector, fields will be seperated by a user defined char * selectData function appendFlag will decide wethrer returnVal will be cleared or results will be appended to the returnVal * * 0: no append (default val) * * 1: append */ #ifndef DBADAPTER_H #define DBADAPTER_H #include <mysql/mysql.h> #include <sqlite3.h> #include <string> #include <vector> #include <list> #include "Logger.h" #define DEFAULT_SQLITE_DBNAME "defaultSQDB.db" typedef std::vector< std::list< std::string > > SQL_RET_TYPE; class DBAdapter { public: enum db_types_t {MYSQL = 1, ORACLE = 2, SQLITE = 3}; DBAdapter(); //Default constructor explicit DBAdapter(const db_types_t type); //constructor to set db type at initialization, imlicit initialization is not allowed ~DBAdapter(); //Destructor bool setDbType(const int &ty); //function to change db type in runtime, if there is an active connection, this function will not run bool connect (const char *ip, const int port, const char *user, const char *pass, int &errorCode); //connects database and resturns the result bool connect (const char *filename, int &errorCode); //connects database and resturns the result for sqlite bool disconnect (int &errorCode); //disconnect from database and return the result bool selectDB(const std::string &dbName, int &errorCode); //selecting DB to connect //bool execQuery(const string &sql, int &errorCode, char * reason); //execute a specific user written query, also returns a failure reason as set of chars bool execQuery(const std::string &sql, int &errorCode); //overloaded version bool execQuery(const void *sql, const int& querySize, int &errorCode); //overloaded version which accepts binary data bool insertData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); /*inserts data into specific tables Example usage: insertData("name, surname, age", "'john', 'smith', 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string& condition, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); /*select data from specific tables Example usage: selecttData("name, surname, age", "name='john' or age < 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); //overloaded version of select bool deleteData(const std::string& condition, const std::string &table, int &errorCode); /*delete data from specific tables Example usage: deleteData("name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &condition, const std::string &table, int &errorCode); /*inserts data to specific tables Example usage updatetData("name, surname, age", "'john', 'smith', 52", "name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); // overloaded version private: int type; //this variable will hold the type of connection bool isConnected; //holds the status of connection SQL_RET_TYPE *rVal; //MYSQL variables start here ::MYSQL *myConnection, myInit; //used for mysql operations and holds connection, myInit is not a pointer because we don't want to handle memory operations for it - Ozgur //MYSQL_RES *myResult; //holds results of the queries //MYSQL_ROW myRow; //holds rows for each result //ORACLE variables will be here //SQLITE variables will be here sqlite3 *SQlitedb; //Other DB variables will be here //Logger object is here Logger *logger; public: //Here starts special functions friend int callBack(void *data, int argc, char **argv, char **azColName); }; #endif
zgrw/PchoneRemote
ServerApplication/include/Database Connections/DBAdapter.h
C
mit
5,459
<div> <a href="#/templates">Go Back</a> <br><br> <div class="col-md-4"> <img class="img-full" src="img/{{mainImage}}"> <div class="row"> <div ng-repeat="image in template.images | limitTo:4"> <div class="col-md-3"> <img class="img-full" ng-src="img/{{image.name}}" ng-click="setImage(image)"> </div> </div> </div> </div> <div class="col-md-8"> <h3>{{template.name}}</h3> <p>{{template.description}}</p> <p>Type: {{template.type}}</p> <h4>{{template.price}}</h4> <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <!-- Specifies Buy Now Button --> <input type="hidden" name="cmd" value="_xclick"> <!-- PayPal Email --> <input type="hidden" name="business" value="[email protected]"> <!-- Item Name --> <input type="hidden" name="item_name" value="{{template.name}}"> <!-- Item ID --> <input type="hidden" name="item_number" value="{{template.id}}"> <!-- Currency Code --> <input type="hidden" name="currency_code" value="USD"> <!-- Price --> <input type="hidden" name="amount" value="{{template.price}}"> <!-- Specify Shipping --> <input type='hidden' name='no_shipping' value='1'> <!-- Return method --> <input type='hidden' name='rm' value='2'> <!-- Return URL --> <input type="hidden" name="return" value="http://localhost:8000"> <!-- Cancel Return URL --> <input type="hidden" name="cancel_return" value="http://localhost:8000"> <!-- Button --> <input type="image" src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_107x26.png" name="submit" alt="Buy Now"> </form> </div> </div>
marb61a/angularwebstoreapp
app/templates/template-details.html
HTML
mit
1,811
class CreateActiveAdminComments < ActiveRecord::Migration[5.1] def self.up create_table :active_admin_comments do |t| t.string :namespace t.text :body t.string :resource_id, null: false t.string :resource_type, null: false t.references :author, polymorphic: true t.timestamps end add_index :active_admin_comments, [:namespace] add_index :active_admin_comments, [:resource_type, :resource_id] end def self.down drop_table :active_admin_comments end end
Seybo/michaelatwork
db/migrate/20160518090723_create_active_admin_comments.rb
Ruby
mit
521
namespace _03BarracksFactory.Data { using System; using Contracts; using System.Collections.Generic; using System.Text; class UnitRepository : IRepository { private IDictionary<string, int> amountOfUnits; public UnitRepository() { this.amountOfUnits = new SortedDictionary<string, int>(); } public string Statistics { get { StringBuilder statBuilder = new StringBuilder(); foreach (var entry in amountOfUnits) { string formatedEntry = string.Format("{0} -> {1}", entry.Key, entry.Value); statBuilder.AppendLine(formatedEntry); } return statBuilder.ToString().Trim(); } } public void AddUnit(IUnit unit) { string unitType = unit.GetType().Name; if (!this.amountOfUnits.ContainsKey(unitType)) { this.amountOfUnits.Add(unitType, 0); } this.amountOfUnits[unitType]++; } public void RemoveUnit(string unitType) { if (this.amountOfUnits[unitType] > 0) { this.amountOfUnits[unitType]--; } else { throw new ArgumentException("Not enought units."); } } } }
MrPIvanov/SoftUni
06-Csharp OOP Advanced/10-EXERCISE REFLECTION AND ATTRIBUTES/ReflectionExercises/05-BarracksWarsReturnOfTheDependencies/Data/UnitRepository.cs
C#
mit
1,466
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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. #ifndef TLS_T_HPP #define TLS_T_HPP #include <state_save_t.hpp> #include <bsl/array.hpp> #include <bsl/convert.hpp> #include <bsl/cstdint.hpp> #include <bsl/errc_type.hpp> #include <bsl/safe_integral.hpp> #pragma pack(push, 1) namespace mk { /// @brief defines the size of the reserved1 field in the tls_t constexpr auto TLS_T_RESERVED1_SIZE{0x020_umx}; /// @brief defines the size of the reserved2 field in the tls_t constexpr auto TLS_T_RESERVED2_SIZE{0x008_umx}; /// @brief defines the size of the reserved3 field in the tls_t constexpr auto TLS_T_RESERVED3_SIZE{0x007_umx}; /// @brief defines the size of the reserved4 field in the tls_t constexpr auto TLS_T_RESERVED4_SIZE{0x040_umx}; /// IMPORTANT: /// - If the size of the TLS is changed, the mk_main_entry will need to /// be updated to reflect the new size. It might make sense to have a /// header file that defines a constant that both this code and the /// assembly logic can share /// /// @brief defines the the total size of the TLS block constexpr auto TLS_T_SIZE{0x400_umx}; /// <!-- description --> /// @brief Defines the layout of the microkernel's TLS block. This /// should not be confused with the TLS blocks given to an extension, /// for which there are two, the TLS block for thread_local and the /// TLS block provided by the microkernel's ABI. /// struct tls_t final { /// -------------------------------------------------------------------- /// Microkernel State /// -------------------------------------------------------------------- /// @brief stores the value of x18 for the microkernel (0x000) bsl::uintmx mk_x18; /// @brief stores the value of x19 for the microkernel (0x008) bsl::uintmx mk_x19; /// @brief stores the value of x20 for the microkernel (0x010) bsl::uintmx mk_x20; /// @brief stores the value of x21 for the microkernel (0x018) bsl::uintmx mk_x21; /// @brief stores the value of x22 for the microkernel (0x020) bsl::uintmx mk_x22; /// @brief stores the value of x23 for the microkernel (0x028) bsl::uintmx mk_x23; /// @brief stores the value of x24 for the microkernel (0x030) bsl::uintmx mk_x24; /// @brief stores the value of x25 for the microkernel (0x038) bsl::uintmx mk_x25; /// @brief stores the value of x26 for the microkernel (0x040) bsl::uintmx mk_x26; /// @brief stores the value of x27 for the microkernel (0x048) bsl::uintmx mk_x27; /// @brief stores the value of x28 for the microkernel (0x050) bsl::uintmx mk_x28; /// @brief stores the value of x29 for the microkernel (0x058) bsl::uintmx mk_x29; /// @brief stores the value of x30 for the microkernel (0x060) bsl::uintmx mk_x30; /// -------------------------------------------------------------------- /// Extension State /// -------------------------------------------------------------------- /// @brief x0, stores the extension's syscall (0x068) bsl::uintmx ext_syscall; /// @brief x1, stores the value of REG1 for the extension (0x070) bsl::uintmx ext_reg0; /// @brief x2, stores the value of REG1 for the extension (0x078) bsl::uintmx ext_reg1; /// @brief x3, stores the value of REG1 for the extension (0x080) bsl::uintmx ext_reg2; /// @brief x4, stores the value of REG1 for the extension (0x088) bsl::uintmx ext_reg3; /// @brief x5, stores the value of REG1 for the extension (0x090) bsl::uintmx ext_reg4; /// @brief x6, stores the value of REG1 for the extension (0x098) bsl::uintmx ext_reg5; /// @brief x7, stores the value of REG1 for the extension (0x0A0) bsl::uintmx reserved_reg7; /// @brief x8, stores the value of REG1 for the extension (0x0A8) bsl::uintmx reserved_reg8; /// @brief x9, stores the value of REG1 for the extension (0x0B0) bsl::uintmx reserved_reg9; /// @brief x10, stores the value of REG1 for the extension (0x0B8) bsl::uintmx reserved_reg10; /// @brief x11, stores the value of REG1 for the extension (0x0C0) bsl::uintmx reserved_reg11; /// @brief x12, stores the value of REG1 for the extension (0x0C8) bsl::uintmx reserved_reg12; /// @brief x13, stores the value of REG1 for the extension (0x0D0) bsl::uintmx reserved_reg13; /// @brief x14, stores the value of REG1 for the extension (0x0D8) bsl::uintmx reserved_reg14; /// @brief x15, stores the value of REG1 for the extension (0x0E0) bsl::uintmx reserved_reg15; /// @brief x16, stores the value of REG1 for the extension (0x0E8) bsl::uintmx reserved_reg16; /// @brief x17, stores the value of REG1 for the extension (0x0F0) bsl::uintmx reserved_reg17; /// @brief x18, stores the value of REG1 for the extension (0x0F8) bsl::uintmx reserved_reg18; /// @brief x19, stores the value of REG1 for the extension (0x100) bsl::uintmx reserved_reg19; /// @brief x20, stores the value of REG1 for the extension (0x108) bsl::uintmx reserved_reg20; /// @brief x21, stores the value of REG1 for the extension (0x110) bsl::uintmx reserved_reg21; /// @brief x22, stores the value of REG1 for the extension (0x118) bsl::uintmx reserved_reg22; /// @brief x23, stores the value of REG1 for the extension (0x120) bsl::uintmx reserved_reg23; /// @brief x24, stores the value of REG1 for the extension (0x128) bsl::uintmx reserved_reg24; /// @brief x25, stores the value of REG1 for the extension (0x130) bsl::uintmx reserved_reg25; /// @brief x26, stores the value of REG1 for the extension (0x138) bsl::uintmx reserved_reg26; /// @brief x27, stores the value of REG1 for the extension (0x140) bsl::uintmx reserved_reg27; /// @brief x28, stores the value of REG1 for the extension (0x148) bsl::uintmx reserved_reg28; /// @brief x29, stores the value of REG1 for the extension (0x150) bsl::uintmx reserved_reg29; /// @brief x30, stores the value of REG1 for the extension (0x158) bsl::uintmx reserved_reg30; /// -------------------------------------------------------------------- /// ESR State /// -------------------------------------------------------------------- /// @brief stores the value of x0 for the ESR (0x160) bsl::uintmx esr_x0; /// @brief stores the value of x1 for the ESR (0x168) bsl::uintmx esr_x1; /// @brief stores the value of x2 for the ESR (0x170) bsl::uintmx esr_x2; /// @brief stores the value of x3 for the ESR (0x178) bsl::uintmx esr_x3; /// @brief stores the value of x4 for the ESR (0x180) bsl::uintmx esr_x4; /// @brief stores the value of x5 for the ESR (0x188) bsl::uintmx esr_x5; /// @brief stores the value of x6 for the ESR (0x190) bsl::uintmx esr_x6; /// @brief stores the value of x7 for the ESR (0x198) bsl::uintmx esr_x7; /// @brief stores the value of x8 for the ESR (0x1A0) bsl::uintmx esr_x8; /// @brief stores the value of x9 for the ESR (0x1A8) bsl::uintmx esr_x9; /// @brief stores the value of x10 for the ESR (0x1B0) bsl::uintmx esr_x10; /// @brief stores the value of x11 for the ESR (0x1B8) bsl::uintmx esr_x11; /// @brief stores the value of x12 for the ESR (0x1C0) bsl::uintmx esr_x12; /// @brief stores the value of x13 for the ESR (0x1C8) bsl::uintmx esr_x13; /// @brief stores the value of x14 for the ESR (0x1D0) bsl::uintmx esr_x14; /// @brief stores the value of x15 for the ESR (0x1D8) bsl::uintmx esr_x15; /// @brief stores the value of x16 for the ESR (0x1E0) bsl::uintmx esr_x16; /// @brief stores the value of x17 for the ESR (0x1E8) bsl::uintmx esr_x17; /// @brief stores the value of x18 for the ESR (0x1F0) bsl::uintmx esr_x18; /// @brief stores the value of x19 for the ESR (0x1F8) bsl::uintmx esr_x19; /// @brief stores the value of x20 for the ESR (0x200) bsl::uintmx esr_x20; /// @brief stores the value of x21 for the ESR (0x208) bsl::uintmx esr_x21; /// @brief stores the value of x22 for the ESR (0x210) bsl::uintmx esr_x22; /// @brief stores the value of x23 for the ESR (0x218) bsl::uintmx esr_x23; /// @brief stores the value of x24 for the ESR (0x220) bsl::uintmx esr_x24; /// @brief stores the value of x25 for the ESR (0x228) bsl::uintmx esr_x25; /// @brief stores the value of x26 for the ESR (0x230) bsl::uintmx esr_x26; /// @brief stores the value of x27 for the ESR (0x238) bsl::uintmx esr_x27; /// @brief stores the value of x28 for the ESR (0x240) bsl::uintmx esr_x28; /// @brief stores the value of x29 for the ESR (0x248) bsl::uintmx esr_x29; /// @brief stores the value of x30 for the ESR (0x250) bsl::uintmx esr_x30; /// @brief stores the value of sp for the ESR (0x258) bsl::uintmx esr_sp; /// @brief stores the value of ip for the ESR (0x260) bsl::uintmx esr_ip; /// @brief stores the value of the ESR vector (0x268) bsl::uintmx esr_vector; /// @brief stores the value of the ESR error code (0x270) bsl::uintmx esr_error_code; /// @brief stores the value of far for the ESR (0x278) bsl::uintmx esr_pf_addr; /// @brief stores the value of esr for the ESR (0x280) bsl::uintmx esr_esr; /// @brief stores the value of SPSR for the ESR (0x288) bsl::uintmx esr_spsr; /// -------------------------------------------------------------------- /// Fast Fail Information /// -------------------------------------------------------------------- /// @brief stores the current fast fail address (0x290) bsl::uintmx current_fast_fail_ip; /// @brief stores the current fast fail stack (0x298) bsl::uintmx current_fast_fail_sp; /// @brief stores the mk_main fast fail address (0x2A0) bsl::uintmx mk_main_fast_fail_ip; /// @brief stores the mk_main fast fail stack (0x2A8) bsl::uintmx mk_main_fast_fail_sp; /// @brief stores the call_ext fast fail address (0x2B0) bsl::uintmx call_ext_fast_fail_ip; /// @brief stores the call_ext fast fail stack (0x2B8) bsl::uintmx call_ext_fast_fail_sp; /// @brief stores the dispatch_syscall fast fail address (0x2C0) bsl::uintmx dispatch_syscall_fast_fail_ip; /// @brief stores the dispatch_syscall fast fail stack (0x2C8) bsl::uintmx dispatch_syscall_fast_fail_sp; /// @brief stores the vmexit loop address (0x2D0) bsl::uintmx vmexit_loop_ip; /// @brief stores the vmexit loop stack (0x2D8) bsl::uintmx vmexit_loop_sp; /// @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, TLS_T_RESERVED1_SIZE.get()> reserved1; /// -------------------------------------------------------------------- /// Context Information /// -------------------------------------------------------------------- /// @brief stores the virtual address of this TLS block (0x300) tls_t *self; /// @brief stores the currently active VMID (0x308) bsl::uint16 ppid; /// @brief stores the total number of online PPs (0x30A) bsl::uint16 online_pps; /// @brief reserved (0x30C) bsl::uint16 reserved_padding0; /// @brief reserved (0x30E) bsl::uint16 reserved_padding1; /// @brief stores the currently active extension (0x310) void *ext; /// @brief stores the extension registered for VMExits (0x318) void *ext_vmexit; /// @brief stores the extension registered for fast fail events (0x320) void *ext_fail; /// @brief stores the loader provided state for the microkernel (0x328) loader::state_save_t *mk_state; /// @brief stores the loader provided state for the root VP (0x330) loader::state_save_t *root_vp_state; /// @brief stores the currently active extension ID (0x338) bsl::uint16 active_extid; /// @brief stores the currently active VMID (0x33A) bsl::uint16 active_vmid; /// @brief stores the currently active VPID (0x33C) bsl::uint16 active_vpid; /// @brief stores the currently active VSID (0x33E) bsl::uint16 active_vsid; /// @brief stores the sp used by extensions for callbacks (0x340) bsl::uintmx sp; /// @brief stores the tps used by extensions for callbacks (0x348) bsl::uintmx tp; /// @brief used to store a return address for unsafe ops (0x350) bsl::uintmx unsafe_rip; /// @brief reserved (0x358) bsl::uintmx reserved_padding2; /// @brief reserved (0x360) bsl::uintmx reserved_padding3; /// @brief stores whether or not the first launch succeeded (0x368) bsl::uintmx first_launch_succeeded; /// @brief stores the currently active root page table (0x370) void *active_rpt; /// @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, TLS_T_RESERVED2_SIZE.get()> reserved2; }; /// @brief make sure the tls_t is the size of a page static_assert(sizeof(tls_t) == TLS_T_SIZE); } #pragma pack(pop) #endif
rianquinn/hypervisor
kernel/include/arm/aarch64/tls_t.hpp
C++
mit
15,304
package com.github.bachelorpraktikum.visualisierbar.model; import com.github.bachelorpraktikum.visualisierbar.model.Element.State; import com.github.bachelorpraktikum.visualisierbar.model.Element.Type; public class ElementShapeableTest extends ShapeableImplementationTest { @Override protected Shapeable<?> getShapeable() { Context context = new Context(); Node node = Node.in(context).create("node", new Coordinates(0, 0)); return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT); } }
Bachelorpraktikum/VisualisierbaR
src/test/java/com/github/bachelorpraktikum/visualisierbar/model/ElementShapeableTest.java
Java
mit
551
/** * @license Angular v4.0.3 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ import { Compiler, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Inject, Injector, NgModule, NgZone, ReflectiveInjector, SimpleChange, Testability, Version } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the common package. */ /** * \@stable */ const VERSION = new Version('4.0.3'); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @return {?} */ function noNg() { throw new Error('AngularJS v1.x is not loaded!'); } let angular = ({ bootstrap: noNg, module: noNg, element: noNg, version: noNg, resumeBootstrap: noNg, getTestability: noNg }); try { if (window.hasOwnProperty('angular')) { angular = ((window)).angular; } } catch (e) { } /** * Resets the AngularJS library. * * Used when angularjs is loaded lazily, and not available on `window`. * * \@stable * @param {?} ng * @return {?} */ /** * Returns the current version of the AngularJS library. * * \@stable * @return {?} */ const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config); const module$1 = (prefix, dependencies) => angular.module(prefix, dependencies); const element = (e) => angular.element(e); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const $COMPILE = '$compile'; const $CONTROLLER = '$controller'; const $HTTP_BACKEND = '$httpBackend'; const $INJECTOR = '$injector'; const $PARSE = '$parse'; const $ROOT_SCOPE = '$rootScope'; const $SCOPE = '$scope'; const $TEMPLATE_CACHE = '$templateCache'; const $$TESTABILITY = '$$testability'; const COMPILER_KEY = '$$angularCompiler'; const INJECTOR_KEY = '$$angularInjector'; const NG_ZONE_KEY = '$$angularNgZone'; const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY; const REQUIRE_NG_MODEL = '?ngModel'; /** * A `PropertyBinding` represents a mapping between a property name * and an attribute name. It is parsed from a string of the form * `"prop: attr"`; or simply `"propAndAttr" where the property * and attribute have the same identifier. */ class PropertyBinding { /** * @param {?} prop * @param {?} attr */ constructor(prop, attr) { this.prop = prop; this.attr = attr; this.parseBinding(); } /** * @return {?} */ parseBinding() { this.bracketAttr = `[${this.attr}]`; this.parenAttr = `(${this.attr})`; this.bracketParenAttr = `[(${this.attr})]`; const /** @type {?} */ capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.substr(1); this.onAttr = `on${capitalAttr}`; this.bindAttr = `bind${capitalAttr}`; this.bindonAttr = `bindon${capitalAttr}`; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} e * @return {?} */ function onError(e) { // TODO: (misko): We seem to not have a stack trace here! if (console.error) { console.error(e, e.stack); } else { // tslint:disable-next-line:no-console console.log(e, e.stack); } throw e; } /** * @param {?} name * @return {?} */ function controllerKey(name) { return '$' + name + 'Controller'; } /** * @param {?} node * @return {?} */ /** * @param {?} component * @return {?} */ function getComponentName(component) { // Return the name of the component or the first line of its stringified version. return ((component)).overriddenName || component.name || component.toString().split('\n')[0]; } class Deferred { constructor() { this.promise = new Promise((res, rej) => { this.resolve = res; this.reject = rej; }); } } /** * @param {?} component * @return {?} Whether the passed-in component implements the subset of the * `ControlValueAccessor` interface needed for AngularJS `ng-model` * compatibility. */ function supportsNgModel(component) { return typeof component.writeValue === 'function' && typeof component.registerOnChange === 'function'; } /** * Glue the AngularJS `NgModelController` (if it exists) to the component * (if it implements the needed subset of the `ControlValueAccessor` interface). * @param {?} ngModel * @param {?} component * @return {?} */ function hookupNgModel(ngModel, component) { if (ngModel && supportsNgModel(component)) { ngModel.$render = () => { component.writeValue(ngModel.$viewValue); }; component.registerOnChange(ngModel.$setViewValue.bind(ngModel)); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const INITIAL_VALUE = { __UNINITIALIZED__: true }; class DowngradeComponentAdapter { /** * @param {?} id * @param {?} element * @param {?} attrs * @param {?} scope * @param {?} ngModel * @param {?} parentInjector * @param {?} $injector * @param {?} $compile * @param {?} $parse * @param {?} componentFactory */ constructor(id, element, attrs, scope, ngModel, parentInjector, $injector, $compile, $parse, componentFactory) { this.id = id; this.element = element; this.attrs = attrs; this.scope = scope; this.ngModel = ngModel; this.parentInjector = parentInjector; this.$injector = $injector; this.$compile = $compile; this.$parse = $parse; this.componentFactory = componentFactory; this.inputChangeCount = 0; this.inputChanges = null; this.componentRef = null; this.component = null; this.changeDetector = null; this.element[0].id = id; this.componentScope = scope.$new(); } /** * @return {?} */ compileContents() { const /** @type {?} */ compiledProjectableNodes = []; const /** @type {?} */ projectableNodes = this.groupProjectableNodes(); const /** @type {?} */ linkFns = projectableNodes.map(nodes => this.$compile(nodes)); this.element.empty(); linkFns.forEach(linkFn => { linkFn(this.scope, (clone) => { compiledProjectableNodes.push(clone); this.element.append(clone); }); }); return compiledProjectableNodes; } /** * @param {?} projectableNodes * @return {?} */ createComponent(projectableNodes) { const /** @type {?} */ childInjector = ReflectiveInjector.resolveAndCreate([{ provide: $SCOPE, useValue: this.componentScope }], this.parentInjector); this.componentRef = this.componentFactory.create(childInjector, projectableNodes, this.element[0]); this.changeDetector = this.componentRef.changeDetectorRef; this.component = this.componentRef.instance; hookupNgModel(this.ngModel, this.component); } /** * @return {?} */ setupInputs() { const /** @type {?} */ attrs = this.attrs; const /** @type {?} */ inputs = this.componentFactory.inputs || []; for (let /** @type {?} */ i = 0; i < inputs.length; i++) { const /** @type {?} */ input = new PropertyBinding(inputs[i].propName, inputs[i].templateName); let /** @type {?} */ expr = null; if (attrs.hasOwnProperty(input.attr)) { const /** @type {?} */ observeFn = (prop => { let /** @type {?} */ prevValue = INITIAL_VALUE; return (currValue) => { if (prevValue === INITIAL_VALUE) { prevValue = currValue; } this.updateInput(prop, prevValue, currValue); prevValue = currValue; }; })(input.prop); attrs.$observe(input.attr, observeFn); } else if (attrs.hasOwnProperty(input.bindAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bindAttr]; } else if (attrs.hasOwnProperty(input.bracketAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bracketAttr]; } else if (attrs.hasOwnProperty(input.bindonAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bindonAttr]; } else if (attrs.hasOwnProperty(input.bracketParenAttr)) { expr = ((attrs) /** TODO #9100 */)[input.bracketParenAttr]; } if (expr != null) { const /** @type {?} */ watchFn = (prop => (currValue, prevValue) => this.updateInput(prop, prevValue, currValue))(input.prop); this.componentScope.$watch(expr, watchFn); } } const /** @type {?} */ prototype = this.componentFactory.componentType.prototype; if (prototype && ((prototype)).ngOnChanges) { // Detect: OnChanges interface this.inputChanges = {}; this.componentScope.$watch(() => this.inputChangeCount, () => { const /** @type {?} */ inputChanges = this.inputChanges; this.inputChanges = {}; ((this.component)).ngOnChanges(inputChanges); }); } this.componentScope.$watch(() => this.changeDetector && this.changeDetector.detectChanges()); } /** * @return {?} */ setupOutputs() { const /** @type {?} */ attrs = this.attrs; const /** @type {?} */ outputs = this.componentFactory.outputs || []; for (let /** @type {?} */ j = 0; j < outputs.length; j++) { const /** @type {?} */ output = new PropertyBinding(outputs[j].propName, outputs[j].templateName); let /** @type {?} */ expr = null; let /** @type {?} */ assignExpr = false; const /** @type {?} */ bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null; const /** @type {?} */ bracketParenAttr = output.bracketParenAttr ? `[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` : null; if (attrs.hasOwnProperty(output.onAttr)) { expr = ((attrs) /** TODO #9100 */)[output.onAttr]; } else if (attrs.hasOwnProperty(output.parenAttr)) { expr = ((attrs) /** TODO #9100 */)[output.parenAttr]; } else if (attrs.hasOwnProperty(bindonAttr)) { expr = ((attrs) /** TODO #9100 */)[bindonAttr]; assignExpr = true; } else if (attrs.hasOwnProperty(bracketParenAttr)) { expr = ((attrs) /** TODO #9100 */)[bracketParenAttr]; assignExpr = true; } if (expr != null && assignExpr != null) { const /** @type {?} */ getter = this.$parse(expr); const /** @type {?} */ setter = getter.assign; if (assignExpr && !setter) { throw new Error(`Expression '${expr}' is not assignable!`); } const /** @type {?} */ emitter = (this.component[output.prop]); if (emitter) { emitter.subscribe({ next: assignExpr ? ((setter) => (v /** TODO #9100 */) => setter(this.scope, v))(setter) : ((getter) => (v /** TODO #9100 */) => getter(this.scope, { $event: v }))(getter) }); } else { throw new Error(`Missing emitter '${output.prop}' on component '${getComponentName(this.componentFactory.componentType)}'!`); } } } } /** * @return {?} */ registerCleanup() { this.element.bind('$destroy', () => { this.componentScope.$destroy(); this.componentRef.destroy(); }); } /** * @return {?} */ getInjector() { return this.componentRef && this.componentRef.injector; } /** * @param {?} prop * @param {?} prevValue * @param {?} currValue * @return {?} */ updateInput(prop, prevValue, currValue) { if (this.inputChanges) { this.inputChangeCount++; this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue); } this.component[prop] = currValue; } /** * @return {?} */ groupProjectableNodes() { let /** @type {?} */ ngContentSelectors = this.componentFactory.ngContentSelectors; return groupNodesBySelector(ngContentSelectors, this.element.contents()); } } /** * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors. * @param {?} ngContentSelectors * @param {?} nodes * @return {?} */ function groupNodesBySelector(ngContentSelectors, nodes) { const /** @type {?} */ projectableNodes = []; let /** @type {?} */ wildcardNgContentIndex; for (let /** @type {?} */ i = 0, /** @type {?} */ ii = ngContentSelectors.length; i < ii; ++i) { projectableNodes[i] = []; } for (let /** @type {?} */ j = 0, /** @type {?} */ jj = nodes.length; j < jj; ++j) { const /** @type {?} */ node = nodes[j]; const /** @type {?} */ ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors); if (ngContentIndex != null) { projectableNodes[ngContentIndex].push(node); } } return projectableNodes; } /** * @param {?} element * @param {?} ngContentSelectors * @return {?} */ function findMatchingNgContentIndex(element, ngContentSelectors) { const /** @type {?} */ ngContentIndices = []; let /** @type {?} */ wildcardNgContentIndex; for (let /** @type {?} */ i = 0; i < ngContentSelectors.length; i++) { const /** @type {?} */ selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { if (matchesSelector(element, selector)) { ngContentIndices.push(i); } } } ngContentIndices.sort(); if (wildcardNgContentIndex !== undefined) { ngContentIndices.push(wildcardNgContentIndex); } return ngContentIndices.length ? ngContentIndices[0] : null; } let _matches; /** * @param {?} el * @param {?} selector * @return {?} */ function matchesSelector(el, selector) { if (!_matches) { const /** @type {?} */ elProto = (Element.prototype); _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ let downgradeCount = 0; /** * \@whatItDoes * * *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AoT compilation* * * Allows an Angular component to be used from AngularJS. * * \@howToUse * * Let's assume that you have an Angular component called `ng2Heroes` that needs * to be made available in AngularJS templates. * * {\@example upgrade/static/ts/module.ts region="ng2-heroes"} * * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive) * that will make this Angular component available inside AngularJS templates. * The `downgradeComponent()` function returns a factory function that we * can use to define the AngularJS directive that wraps the "downgraded" component. * * {\@example upgrade/static/ts/module.ts region="ng2-heroes-wrapper"} * * \@description * * A helper function that returns a factory function to be used for registering an * AngularJS wrapper directive for "downgrading" an Angular component. * * The parameter contains information about the Component that is being downgraded: * * * `component: Type<any>`: The type of the Component that will be downgraded * * \@experimental * @param {?} info * @return {?} */ function downgradeComponent(info) { const /** @type {?} */ idPrefix = `NG2_UPGRADE_${downgradeCount++}_`; let /** @type {?} */ idCount = 0; const /** @type {?} */ directiveFactory = function ($compile, $injector, $parse) { return { restrict: 'E', terminal: true, require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL], link: (scope, element, attrs, required) => { // We might have to compile the contents asynchronously, because this might have been // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have // been compiled. const /** @type {?} */ parentInjector = required[0] || $injector.get(INJECTOR_KEY); const /** @type {?} */ ngModel = required[1]; const /** @type {?} */ downgradeFn = (injector) => { const /** @type {?} */ componentFactoryResolver = injector.get(ComponentFactoryResolver); const /** @type {?} */ componentFactory = componentFactoryResolver.resolveComponentFactory(info.component); if (!componentFactory) { throw new Error('Expecting ComponentFactory for: ' + getComponentName(info.component)); } const /** @type {?} */ id = idPrefix + (idCount++); const /** @type {?} */ injectorPromise = new ParentInjectorPromise$1(element); const /** @type {?} */ facade = new DowngradeComponentAdapter(id, element, attrs, scope, ngModel, injector, $injector, $compile, $parse, componentFactory); const /** @type {?} */ projectableNodes = facade.compileContents(); facade.createComponent(projectableNodes); facade.setupInputs(); facade.setupOutputs(); facade.registerCleanup(); injectorPromise.resolve(facade.getInjector()); }; if (parentInjector instanceof ParentInjectorPromise$1) { parentInjector.then(downgradeFn); } else { downgradeFn(parentInjector); } } }; }; // bracket-notation because of closure - see #14441 directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE]; return directiveFactory; } /** * Synchronous promise-like object to wrap parent injectors, * to preserve the synchronous nature of Angular 1's $compile. */ class ParentInjectorPromise$1 { /** * @param {?} element */ constructor(element) { this.element = element; this.injectorKey = controllerKey(INJECTOR_KEY); this.callbacks = []; // Store the promise on the element. element.data(this.injectorKey, this); } /** * @param {?} callback * @return {?} */ then(callback) { if (this.injector) { callback(this.injector); } else { this.callbacks.push(callback); } } /** * @param {?} injector * @return {?} */ resolve(injector) { this.injector = injector; // Store the real injector on the element. this.element.data(this.injectorKey, injector); // Release the element to prevent memory leaks. this.element = null; // Run the queued callbacks. this.callbacks.forEach(callback => callback(injector)); this.callbacks.length = 0; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * \@whatItDoes * * *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AoT compilation* * * Allow an Angular service to be accessible from AngularJS. * * \@howToUse * * First ensure that the service to be downgraded is provided in an {\@link NgModule} * that will be part of the upgrade application. For example, let's assume we have * defined `HeroesService` * * {\@example upgrade/static/ts/module.ts region="ng2-heroes-service"} * * and that we have included this in our upgrade app {\@link NgModule} * * {\@example upgrade/static/ts/module.ts region="ng2-module"} * * Now we can register the `downgradeInjectable` factory function for the service * on an AngularJS module. * * {\@example upgrade/static/ts/module.ts region="downgrade-ng2-heroes-service"} * * Inside an AngularJS component's controller we can get hold of the * downgraded service via the name we gave when downgrading. * * {\@example upgrade/static/ts/module.ts region="example-app"} * * \@description * * Takes a `token` that identifies a service provided from Angular. * * Returns a [factory function](https://docs.angularjs.org/guide/di) that can be * used to register the service on an AngularJS module. * * The factory function provides access to the Angular service that * is identified by the `token` parameter. * * \@experimental * @param {?} token * @return {?} */ function downgradeInjectable(token) { const /** @type {?} */ factory = function (i) { return i.get(token); }; ((factory)).$inject = [INJECTOR_KEY]; return factory; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const CAMEL_CASE = /([A-Z])/g; const INITIAL_VALUE$1 = { __UNINITIALIZED__: true }; const NOT_SUPPORTED = 'NOT_SUPPORTED'; class UpgradeNg1ComponentAdapterBuilder { /** * @param {?} name */ constructor(name) { this.name = name; this.inputs = []; this.inputsRename = []; this.outputs = []; this.outputsRename = []; this.propertyOutputs = []; this.checkProperties = []; this.propertyMap = {}; this.linkFn = null; this.directive = null; this.$controller = null; const selector = name.replace(CAMEL_CASE, (all /** TODO #9100 */, next) => '-' + next.toLowerCase()); const self = this; this.type = Directive({ selector: selector, inputs: this.inputsRename, outputs: this.outputsRename }) .Class({ constructor: [ new Inject($SCOPE), ElementRef, function (scope, elementRef) { return new UpgradeNg1ComponentAdapter(self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap); } ], ngOnInit: function () { }, ngOnChanges: function () { }, ngDoCheck: function () { }, ngOnDestroy: function () { }, }); } /** * @param {?} injector * @return {?} */ extractDirective(injector) { const /** @type {?} */ directives = injector.get(this.name + 'Directive'); if (directives.length > 1) { throw new Error('Only support single directive definition for: ' + this.name); } const /** @type {?} */ directive = directives[0]; if (directive.replace) this.notSupported('replace'); if (directive.terminal) this.notSupported('terminal'); const /** @type {?} */ link = directive.link; if (typeof link == 'object') { if (((link)).post) this.notSupported('link.post'); } return directive; } /** * @param {?} feature * @return {?} */ notSupported(feature) { throw new Error(`Upgraded directive '${this.name}' does not support '${feature}'.`); } /** * @return {?} */ extractBindings() { const /** @type {?} */ btcIsObject = typeof this.directive.bindToController === 'object'; if (btcIsObject && Object.keys(this.directive.scope).length) { throw new Error(`Binding definitions on scope and controller at the same time are not supported.`); } const /** @type {?} */ context = (btcIsObject) ? this.directive.bindToController : this.directive.scope; if (typeof context == 'object') { for (const /** @type {?} */ name in context) { if (((context)).hasOwnProperty(name)) { let /** @type {?} */ localName = context[name]; const /** @type {?} */ type = localName.charAt(0); const /** @type {?} */ typeOptions = localName.charAt(1); localName = typeOptions === '?' ? localName.substr(2) : localName.substr(1); localName = localName || name; const /** @type {?} */ outputName = 'output_' + name; const /** @type {?} */ outputNameRename = outputName + ': ' + name; const /** @type {?} */ outputNameRenameChange = outputName + ': ' + name + 'Change'; const /** @type {?} */ inputName = 'input_' + name; const /** @type {?} */ inputNameRename = inputName + ': ' + name; switch (type) { case '=': this.propertyOutputs.push(outputName); this.checkProperties.push(localName); this.outputs.push(outputName); this.outputsRename.push(outputNameRenameChange); this.propertyMap[outputName] = localName; this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = localName; break; case '@': // handle the '<' binding of angular 1.5 components case '<': this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = localName; break; case '&': this.outputs.push(outputName); this.outputsRename.push(outputNameRename); this.propertyMap[outputName] = localName; break; default: let /** @type {?} */ json = JSON.stringify(context); throw new Error(`Unexpected mapping '${type}' in '${json}' in '${this.name}' directive.`); } } } } } /** * @param {?} compile * @param {?} templateCache * @param {?} httpBackend * @return {?} */ compileTemplate(compile, templateCache, httpBackend) { if (this.directive.template !== undefined) { this.linkFn = compileHtml(isFunction(this.directive.template) ? this.directive.template() : this.directive.template); } else if (this.directive.templateUrl) { const /** @type {?} */ url = isFunction(this.directive.templateUrl) ? this.directive.templateUrl() : this.directive.templateUrl; const /** @type {?} */ html = templateCache.get(url); if (html !== undefined) { this.linkFn = compileHtml(html); } else { return new Promise((resolve, err) => { httpBackend('GET', url, null, (status /** TODO #9100 */, response /** TODO #9100 */) => { if (status == 200) { resolve(this.linkFn = compileHtml(templateCache.put(url, response))); } else { err(`GET ${url} returned ${status}: ${response}`); } }); }); } } else { throw new Error(`Directive '${this.name}' is not a component, it is missing template.`); } return null; /** * @param {?} html * @return {?} */ function compileHtml(html /** TODO #9100 */) { const /** @type {?} */ div = document.createElement('div'); div.innerHTML = html; return compile(div.childNodes); } } /** * Upgrade ng1 components into Angular. * @param {?} exportedComponents * @param {?} injector * @return {?} */ static resolve(exportedComponents, injector) { const /** @type {?} */ promises = []; const /** @type {?} */ compile = injector.get($COMPILE); const /** @type {?} */ templateCache = injector.get($TEMPLATE_CACHE); const /** @type {?} */ httpBackend = injector.get($HTTP_BACKEND); const /** @type {?} */ $controller = injector.get($CONTROLLER); for (const /** @type {?} */ name in exportedComponents) { if (((exportedComponents)).hasOwnProperty(name)) { const /** @type {?} */ exportedComponent = exportedComponents[name]; exportedComponent.directive = exportedComponent.extractDirective(injector); exportedComponent.$controller = $controller; exportedComponent.extractBindings(); const /** @type {?} */ promise = exportedComponent.compileTemplate(compile, templateCache, httpBackend); if (promise) promises.push(promise); } } return Promise.all(promises); } } class UpgradeNg1ComponentAdapter { /** * @param {?} linkFn * @param {?} scope * @param {?} directive * @param {?} elementRef * @param {?} $controller * @param {?} inputs * @param {?} outputs * @param {?} propOuts * @param {?} checkProperties * @param {?} propertyMap */ constructor(linkFn, scope, directive, elementRef, $controller, inputs, outputs, propOuts, checkProperties, propertyMap) { this.linkFn = linkFn; this.directive = directive; this.$controller = $controller; this.inputs = inputs; this.outputs = outputs; this.propOuts = propOuts; this.checkProperties = checkProperties; this.propertyMap = propertyMap; this.controllerInstance = null; this.destinationObj = null; this.checkLastValues = []; this.$element = null; this.element = elementRef.nativeElement; this.componentScope = scope.$new(!!directive.scope); this.$element = element(this.element); const controllerType = directive.controller; if (directive.bindToController && controllerType) { this.controllerInstance = this.buildController(controllerType); this.destinationObj = this.controllerInstance; } else { this.destinationObj = this.componentScope; } for (let i = 0; i < inputs.length; i++) { this /** TODO #9100 */[inputs[i]] = null; } for (let j = 0; j < outputs.length; j++) { const emitter = this /** TODO #9100 */[outputs[j]] = new EventEmitter(); this.setComponentProperty(outputs[j], ((emitter /** TODO #9100 */) => (value /** TODO #9100 */) => emitter.emit(value))(emitter)); } for (let k = 0; k < propOuts.length; k++) { this /** TODO #9100 */[propOuts[k]] = new EventEmitter(); this.checkLastValues.push(INITIAL_VALUE$1); } } /** * @return {?} */ ngOnInit() { if (!this.directive.bindToController && this.directive.controller) { this.controllerInstance = this.buildController(this.directive.controller); } if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) { this.controllerInstance.$onInit(); } let /** @type {?} */ link = this.directive.link; if (typeof link == 'object') link = ((link)).pre; if (link) { const /** @type {?} */ attrs = NOT_SUPPORTED; const /** @type {?} */ transcludeFn = NOT_SUPPORTED; const /** @type {?} */ linkController = this.resolveRequired(this.$element, this.directive.require); ((this.directive.link))(this.componentScope, this.$element, attrs, linkController, transcludeFn); } const /** @type {?} */ childNodes = []; let /** @type {?} */ childNode; while (childNode = this.element.firstChild) { this.element.removeChild(childNode); childNodes.push(childNode); } this.linkFn(this.componentScope, (clonedElement, scope) => { for (let /** @type {?} */ i = 0, /** @type {?} */ ii = clonedElement.length; i < ii; i++) { this.element.appendChild(clonedElement[i]); } }, { parentBoundTranscludeFn: (scope /** TODO #9100 */, cloneAttach /** TODO #9100 */) => { cloneAttach(childNodes); } }); if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) { this.controllerInstance.$postLink(); } } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { const /** @type {?} */ ng1Changes = {}; Object.keys(changes).forEach(name => { const /** @type {?} */ change = changes[name]; this.setComponentProperty(name, change.currentValue); ng1Changes[this.propertyMap[name]] = change; }); if (isFunction(this.destinationObj.$onChanges)) { this.destinationObj.$onChanges(ng1Changes); } } /** * @return {?} */ ngDoCheck() { const /** @type {?} */ destinationObj = this.destinationObj; const /** @type {?} */ lastValues = this.checkLastValues; const /** @type {?} */ checkProperties = this.checkProperties; for (let /** @type {?} */ i = 0; i < checkProperties.length; i++) { const /** @type {?} */ value = destinationObj[checkProperties[i]]; const /** @type {?} */ last = lastValues[i]; if (value !== last) { if (typeof value == 'number' && isNaN(value) && typeof last == 'number' && isNaN(last)) { } else { const /** @type {?} */ eventEmitter = ((this) /** TODO #9100 */)[this.propOuts[i]]; eventEmitter.emit(lastValues[i] = value); } } } if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) { this.controllerInstance.$doCheck(); } } /** * @return {?} */ ngOnDestroy() { if (this.controllerInstance && isFunction(this.controllerInstance.$onDestroy)) { this.controllerInstance.$onDestroy(); } } /** * @param {?} name * @param {?} value * @return {?} */ setComponentProperty(name, value) { this.destinationObj[this.propertyMap[name]] = value; } /** * @param {?} controllerType * @return {?} */ buildController(controllerType /** TODO #9100 */) { const /** @type {?} */ locals = { $scope: this.componentScope, $element: this.$element }; const /** @type {?} */ controller = this.$controller(controllerType, locals, null, this.directive.controllerAs); this.$element.data(controllerKey(this.directive.name), controller); return controller; } /** * @param {?} $element * @param {?} require * @return {?} */ resolveRequired($element, require) { if (!require) { return undefined; } else if (typeof require == 'string') { let /** @type {?} */ name = (require); let /** @type {?} */ isOptional = false; let /** @type {?} */ startParent = false; let /** @type {?} */ searchParents = false; if (name.charAt(0) == '?') { isOptional = true; name = name.substr(1); } if (name.charAt(0) == '^') { searchParents = true; name = name.substr(1); } if (name.charAt(0) == '^') { startParent = true; name = name.substr(1); } const /** @type {?} */ key = controllerKey(name); if (startParent) $element = $element.parent(); const /** @type {?} */ dep = searchParents ? $element.inheritedData(key) : $element.data(key); if (!dep && !isOptional) { throw new Error(`Can not locate '${require}' in '${this.directive.name}'.`); } return dep; } else if (require instanceof Array) { const /** @type {?} */ deps = []; for (let /** @type {?} */ i = 0; i < require.length; i++) { deps.push(this.resolveRequired($element, require[i])); } return deps; } throw new Error(`Directive '${this.directive.name}' require syntax unrecognized: ${this.directive.require}`); } } /** * @param {?} value * @return {?} */ function isFunction(value) { return typeof value === 'function'; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ let upgradeCount = 0; /** * Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application. * * The `UpgradeAdapter` allows: * 1. creation of Angular component from AngularJS component directive * (See [UpgradeAdapter#upgradeNg1Component()]) * 2. creation of AngularJS directive from Angular component. * (See [UpgradeAdapter#downgradeNg2Component()]) * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks * coexisting in a single application. * * ## Mental Model * * When reasoning about how a hybrid application works it is useful to have a mental model which * describes what is happening and explains what is happening at the lowest level. * * 1. There are two independent frameworks running in a single application, each framework treats * the other as a black box. * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework * instantiated the element is the owner. Each framework only updates/interacts with its own * DOM elements and ignores others. * 3. AngularJS directives always execute inside AngularJS framework codebase regardless of * where they are instantiated. * 4. Angular components always execute inside Angular framework codebase regardless of * where they are instantiated. * 5. An AngularJS component can be upgraded to an Angular component. This creates an * Angular directive, which bootstraps the AngularJS component directive in that location. * 6. An Angular component can be downgraded to an AngularJS component directive. This creates * an AngularJS directive, which bootstraps the Angular component in that location. * 7. Whenever an adapter component is instantiated the host element is owned by the framework * doing the instantiation. The other framework then instantiates and owns the view for that * component. This implies that component bindings will always follow the semantics of the * instantiation framework. The syntax is always that of Angular syntax. * 8. AngularJS is always bootstrapped first and owns the bottom most view. * 9. The new application is running in Angular zone, and therefore it no longer needs calls to * `$apply()`. * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions); * const module = angular.module('myExample', []); * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component)); * * module.directive('ng1Hello', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * \@Component({ * selector: 'ng2-comp', * inputs: ['name'], * template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)', * directives: * }) * class Ng2Component { * } * * \@NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * * ``` * * \@stable */ class UpgradeAdapter { /** * @param {?} ng2AppModule * @param {?=} compilerOptions */ constructor(ng2AppModule, compilerOptions) { this.ng2AppModule = ng2AppModule; this.compilerOptions = compilerOptions; this.idPrefix = `NG2_UPGRADE_${upgradeCount++}_`; this.downgradedComponents = []; /** * An internal map of ng1 components which need to up upgraded to ng2. * * We can't upgrade until injector is instantiated and we can retrieve the component metadata. * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped. * * \@internal */ this.ng1ComponentsToBeUpgraded = {}; this.upgradedProviders = []; this.moduleRef = null; if (!ng2AppModule) { throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.'); } } /** * Allows Angular Component to be used from AngularJS. * * Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from * Angular Component. The adapter will bootstrap Angular component from within the * AngularJS template. * * ## Mental Model * * 1. The component is instantiated by being listed in AngularJS template. This means that the * host element is controlled by AngularJS, but the component's view will be controlled by * Angular. * 2. Even thought the component is instantiated in AngularJS, it will be using Angular * syntax. This has to be done, this way because we must follow Angular components do not * declare how the attributes should be interpreted. * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component * by way of the `ControlValueAccessor` interface from \@angular/forms. Only components that * implement this interface are eligible. * * ## Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - ng-model: `<comp ng-model="name">` * - Content projection: yes * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * module.directive('greet', adapter.downgradeNg2Component(Greeter)); * * \@Component({ * selector: 'greet', * template: '{{salutation}} {{name}}! - <ng-content></ng-content>' * }) * class Greeter { * \@Input() salutation: string; * \@Input() name: string; * } * * \@NgModule({ * declarations: [Greeter], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text"); * }); * ``` * @param {?} component * @return {?} */ downgradeNg2Component(component) { this.downgradedComponents.push(component); return downgradeComponent({ component }); } /** * Allows AngularJS Component to be used from Angular. * * Use `upgradeNg1Component` to create an Angular component from AngularJS Component * directive. The adapter will bootstrap AngularJS component from within the Angular * template. * * ## Mental Model * * 1. The component is instantiated by being listed in Angular template. This means that the * host element is controlled by Angular, but the component's view will be controlled by * AngularJS. * * ## Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - Transclusion: yes * - Only some of the features of * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are * supported: * - `compile`: not supported because the host element is owned by Angular, which does * not allow modifying DOM structure during compilation. * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.) * - `controllerAs`: supported. * - `bindToController`: supported. * - `link`: supported. (NOTE: only pre-link function is supported.) * - `name`: supported. * - `priority`: ignored. * - `replace`: not supported. * - `require`: supported. * - `restrict`: must be set to 'E'. * - `scope`: supported. * - `template`: supported. * - `templateUrl`: supported. * - `terminal`: ignored. * - `transclude`: supported. * * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * * module.directive('greet', function() { * return { * scope: {salutation: '=', name: '=' }, * template: '{{salutation}} {{name}}! - <span ng-transclude></span>' * }; * }); * * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component)); * * \@Component({ * selector: 'ng2', * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>' * }) * class Ng2Component { * } * * \@NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('greet')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2></ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text"); * }); * ``` * @param {?} name * @return {?} */ upgradeNg1Component(name) { if (((this.ng1ComponentsToBeUpgraded)).hasOwnProperty(name)) { return this.ng1ComponentsToBeUpgraded[name].type; } else { return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name)) .type; } } /** * Registers the adapter's AngularJS upgrade module for unit testing in AngularJS. * Use this instead of `angular.mock.module()` to load the upgrade module into * the AngularJS testing injector. * * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * * // configure the adapter with upgrade/downgrade components and services * upgradeAdapter.downgradeNg2Component(MyComponent); * * let upgradeAdapterRef: UpgradeAdapterRef; * let $compile, $rootScope; * * // We must register the adapter before any calls to `inject()` * beforeEach(() => { * upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']); * }); * * beforeEach(inject((_$compile_, _$rootScope_) => { * $compile = _$compile_; * $rootScope = _$rootScope_; * })); * * it("says hello", (done) => { * upgradeAdapterRef.ready(() => { * const element = $compile("<my-component></my-component>")($rootScope); * $rootScope.$apply(); * expect(element.html()).toContain("Hello World"); * done(); * }) * }); * * ``` * * @param {?=} modules any AngularJS modules that the upgrade module should depend upon * @return {?} an {\@link UpgradeAdapterRef}, which lets you register a `ready()` callback to * run assertions once the Angular components are ready to test through AngularJS. */ registerForNg1Tests(modules) { const /** @type {?} */ windowNgMock = ((window))['angular'].mock; if (!windowNgMock || !windowNgMock.module) { throw new Error('Failed to find \'angular.mock.module\'.'); } this.declareNg1Module(modules); windowNgMock.module(this.ng1Module.name); const /** @type {?} */ upgrade = new UpgradeAdapterRef(); this.ng2BootstrapDeferred.promise.then((ng1Injector) => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }, onError); return upgrade; } /** * Bootstrap a hybrid AngularJS / Angular application. * * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike * AngularJS, this bootstrap is asynchronous. * * ### Example * * ``` * const adapter = new UpgradeAdapter(MyNg2Module); * const module = angular.module('myExample', []); * module.directive('ng2', adapter.downgradeNg2Component(Ng2)); * * module.directive('ng1', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * \@Component({ * selector: 'ng2', * inputs: ['name'], * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)' * }) * class Ng2 { * } * * \@NgModule({ * declarations: [Ng2, adapter.upgradeNg1Component('ng1')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2 name="World">project</ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * ``` * @param {?} element * @param {?=} modules * @param {?=} config * @return {?} */ bootstrap(element$$1, modules, config) { this.declareNg1Module(modules); const /** @type {?} */ upgrade = new UpgradeAdapterRef(); // Make sure resumeBootstrap() only exists if the current bootstrap is deferred const /** @type {?} */ windowAngular = ((window) /** TODO #???? */)['angular']; windowAngular.resumeBootstrap = undefined; this.ngZone.run(() => { bootstrap(element$$1, [this.ng1Module.name], config); }); const /** @type {?} */ ng1BootstrapPromise = new Promise((resolve) => { if (windowAngular.resumeBootstrap) { const /** @type {?} */ originalResumeBootstrap = windowAngular.resumeBootstrap; windowAngular.resumeBootstrap = function () { windowAngular.resumeBootstrap = originalResumeBootstrap; windowAngular.resumeBootstrap.apply(this, arguments); resolve(); }; } else { resolve(); } }); Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => { element(element$$1).data(controllerKey(INJECTOR_KEY), this.moduleRef.injector); this.moduleRef.injector.get(NgZone).run(() => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }); }, onError); return upgrade; } /** * Allows AngularJS service to be accessible from Angular. * * * ### Example * * ``` * class Login { ... } * class Server { ... } * * \@Injectable() * class Example { * constructor(\@Inject('server') server, login: Login) { * ... * } * } * * const module = angular.module('myExample', []); * module.service('server', Server); * module.service('login', Login); * * const adapter = new UpgradeAdapter(MyNg2Module); * adapter.upgradeNg1Provider('server'); * adapter.upgradeNg1Provider('login', {asToken: Login}); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng2Injector.get(Example); * }); * * ``` * @param {?} name * @param {?=} options * @return {?} */ upgradeNg1Provider(name, options) { const /** @type {?} */ token = options && options.asToken || name; this.upgradedProviders.push({ provide: token, useFactory: ($injector) => $injector.get(name), deps: [$INJECTOR] }); } /** * Allows Angular service to be accessible from AngularJS. * * * ### Example * * ``` * class Example { * } * * const adapter = new UpgradeAdapter(MyNg2Module); * * const module = angular.module('myExample', []); * module.factory('example', adapter.downgradeNg2Provider(Example)); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng1Injector.get('example'); * }); * * ``` * @param {?} token * @return {?} */ downgradeNg2Provider(token) { return downgradeInjectable(token); } /** * Declare the AngularJS upgrade module for this adapter without bootstrapping the whole * hybrid application. * * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`. * * @param {?=} modules The AngularJS modules that this upgrade module should depend upon. * @return {?} The AngularJS upgrade module that is declared by this method * * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * upgradeAdapter.declareNg1Module(['heroApp']); * ``` */ declareNg1Module(modules = []) { const /** @type {?} */ delayApplyExps = []; let /** @type {?} */ original$applyFn; let /** @type {?} */ rootScopePrototype; let /** @type {?} */ rootScope; const /** @type {?} */ upgradeAdapter = this; const /** @type {?} */ ng1Module = this.ng1Module = module$1(this.idPrefix, modules); const /** @type {?} */ platformRef = platformBrowserDynamic(); this.ngZone = new NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec') }); this.ng2BootstrapDeferred = new Deferred(); ng1Module.factory(INJECTOR_KEY, () => this.moduleRef.injector.get(Injector)) .constant(NG_ZONE_KEY, this.ngZone) .factory(COMPILER_KEY, () => this.moduleRef.injector.get(Compiler)) .config([ '$provide', '$injector', (provide, ng1Injector) => { provide.decorator($ROOT_SCOPE, [ '$delegate', function (rootScopeDelegate) { // Capture the root apply so that we can delay first call to $apply until we // bootstrap Angular and then we replay and restore the $apply. rootScopePrototype = rootScopeDelegate.constructor.prototype; if (rootScopePrototype.hasOwnProperty('$apply')) { original$applyFn = rootScopePrototype.$apply; rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp); } else { throw new Error('Failed to find \'$apply\' on \'$rootScope\'!'); } return rootScope = rootScopeDelegate; } ]); if (ng1Injector.has($$TESTABILITY)) { provide.decorator($$TESTABILITY, [ '$delegate', function (testabilityDelegate) { const /** @type {?} */ originalWhenStable = testabilityDelegate.whenStable; // Cannot use arrow function below because we need the context const /** @type {?} */ newWhenStable = function (callback) { originalWhenStable.call(this, function () { const /** @type {?} */ ng2Testability = upgradeAdapter.moduleRef.injector.get(Testability); if (ng2Testability.isStable()) { callback.apply(this, arguments); } else { ng2Testability.whenStable(newWhenStable.bind(this, callback)); } }); }; testabilityDelegate.whenStable = newWhenStable; return testabilityDelegate; } ]); } } ]); ng1Module.run([ '$injector', '$rootScope', (ng1Injector, rootScope) => { UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector) .then(() => { // At this point we have ng1 injector and we have lifted ng1 components into ng2, we // now can bootstrap ng2. const /** @type {?} */ DynamicNgUpgradeModule = NgModule({ providers: [ { provide: $INJECTOR, useFactory: () => ng1Injector }, { provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE) }, this.upgradedProviders ], imports: [this.ng2AppModule], entryComponents: this.downgradedComponents }).Class({ constructor: function DynamicNgUpgradeModule() { }, ngDoBootstrap: function () { } }); ((platformRef)) ._bootstrapModuleWithZone(DynamicNgUpgradeModule, this.compilerOptions, this.ngZone) .then((ref) => { this.moduleRef = ref; this.ngZone.run(() => { if (rootScopePrototype) { rootScopePrototype.$apply = original$applyFn; // restore original $apply while (delayApplyExps.length) { rootScope.$apply(delayApplyExps.shift()); } rootScopePrototype = null; } }); }) .then(() => this.ng2BootstrapDeferred.resolve(ng1Injector), onError) .then(() => { let /** @type {?} */ subscription = this.ngZone.onMicrotaskEmpty.subscribe({ next: () => rootScope.$digest() }); rootScope.$on('$destroy', () => { subscription.unsubscribe(); }); }); }) .catch((e) => this.ng2BootstrapDeferred.reject(e)); } ]); return ng1Module; } } /** * Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application. * * \@stable */ class UpgradeAdapterRef { constructor() { this._readyFn = null; this.ng1RootScope = null; this.ng1Injector = null; this.ng2ModuleRef = null; this.ng2Injector = null; } /** * @param {?} ngModuleRef * @param {?} ng1Injector * @return {?} */ _bootstrapDone(ngModuleRef, ng1Injector) { this.ng2ModuleRef = ngModuleRef; this.ng2Injector = ngModuleRef.injector; this.ng1Injector = ng1Injector; this.ng1RootScope = ng1Injector.get($ROOT_SCOPE); this._readyFn && this._readyFn(this); } /** * Register a callback function which is notified upon successful hybrid AngularJS / Angular * application has been bootstrapped. * * The `ready` callback function is invoked inside the Angular zone, therefore it does not * require a call to `$apply()`. * @param {?} fn * @return {?} */ ready(fn) { this._readyFn = fn; } /** * Dispose of running hybrid AngularJS / Angular application. * @return {?} */ dispose() { this.ng1Injector.get($ROOT_SCOPE).$destroy(); this.ng2ModuleRef.destroy(); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the upgrade/dynamic package, allowing * Angular 1 and Angular 2+ to run side by side in the same application. */ // This file only re-exports content of the `src` folder. Keep it that way. /** * Generated bundle index. Do not edit. */ export { VERSION, UpgradeAdapter, UpgradeAdapterRef }; //# sourceMappingURL=upgrade.js.map
snkrishnan1/PivotGridSample
node_modules/@angular/upgrade/@angular/upgrade.js
JavaScript
mit
64,081
package gb import ( "errors" "fmt" "io" "path/filepath" "reflect" "testing" ) func TestExecuteBuildAction(t *testing.T) { tests := []struct { pkg string err error }{{ pkg: "a", err: nil, }, { pkg: "b", // actually command err: nil, }, { pkg: "c", err: nil, }, { pkg: "d.v1", err: nil, }, { pkg: "x", err: errors.New("import cycle detected: x -> y -> x"), }, { pkg: "h", // imports "blank", which is blank, see issue #131 err: fmt.Errorf("no buildable Go source files in %s", filepath.Join(getwd(t), "testdata", "src", "blank")), }} for _, tt := range tests { ctx := testContext(t) pkg, err := ctx.ResolvePackage(tt.pkg) if !sameErr(err, tt.err) { t.Errorf("ctx.ResolvePackage(%v): want %v, got %v", tt.pkg, tt.err, err) continue } if err != nil { continue } action, err := BuildPackages(pkg) if err != nil { t.Errorf("BuildAction(%v): ", tt.pkg, err) continue } if err := Execute(action); !sameErr(err, tt.err) { t.Errorf("Execute(%v): want: %v, got %v", action.Name, tt.err, err) } ctx.Destroy() } } var niltask = TaskFn(func() error { return nil }) var executorTests = []struct { action *Action // root action err error // expected error }{{ action: &Action{ Name: "no error", Task: niltask, }, }, { action: &Action{ Name: "root error", Task: TaskFn(func() error { return io.EOF }), }, err: io.EOF, }, { action: &Action{ Name: "child, child, error", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{&Action{ Name: "child, error", Task: niltask, Deps: []*Action{&Action{ Name: "error", Task: TaskFn(func() error { return io.EOF }), }}, }}, }, err: io.EOF, }, { action: &Action{ Name: "once only", Task: TaskFn(func() error { if c1 != 1 || c2 != 1 || c3 != 1 { return fmt.Errorf("unexpected count, c1: %v, c2: %v, c3: %v", c1, c2, c3) } return nil }), Deps: []*Action{createDag()}, }, }, { action: &Action{ Name: "failure count", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{createFailDag()}, }, err: fmt.Errorf("task3 called 1 time"), }} func createDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return nil }) task3 := TaskFn(func() error { c3++; return nil }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } func createFailDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return fmt.Errorf("task2 called %v time", c2) }) task3 := TaskFn(func() error { c3++; return fmt.Errorf("task3 called %v time", c3) }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } var c1, c2, c3 int func executeReset() { c1 = 0 c2 = 0 c3 = 0 // reset executor test variables } func TestExecute(t *testing.T) { for _, tt := range executorTests { executeReset() got := Execute(tt.action) if !reflect.DeepEqual(got, tt.err) { t.Errorf("Execute: %v: want err: %v, got err %v", tt.action.Name, tt.err, got) } } } func testExecuteConcurrentN(t *testing.T, n int) { for _, tt := range executorTests { executeReset() got := ExecuteConcurrent(tt.action, n) if !reflect.DeepEqual(got, tt.err) { t.Errorf("ExecuteConcurrent(%v): %v: want err: %v, got err %v", n, tt.action.Name, tt.err, got) } } } func TestExecuteConcurrent1(t *testing.T) { testExecuteConcurrentN(t, 1) } func TestExecuteConcurrent2(t *testing.T) { testExecuteConcurrentN(t, 2) } func TestExecuteConcurrent4(t *testing.T) { testExecuteConcurrentN(t, 4) } func TestExecuteConcurrent7(t *testing.T) { testExecuteConcurrentN(t, 7) }
srid/vessel
vendor/src/github.com/constabulary/gb/executor_test.go
GO
mit
4,139
<?php /** * @Created By ECMall PhpCacheServer * @Time:2015-01-23 06:18:10 */ if(filemtime(__FILE__) + 1800 < time())return false; return array ( 'id' => 5553, 'goods' => array ( 'goods_id' => '5553', 'store_id' => '132', 'type' => 'material', 'goods_name' => '百枣纲目夹心枣核桃100g', 'description' => '<p style="text-align: center;"><img src="http://wap.bqmart.cn/data/files/store_132/goods_42/201501191027226980.jpg" alt="6956459400622_01.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027236092.jpg" alt="6956459400622_02.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027234428.jpg" alt="6956459400622_03.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027239736.jpg" alt="6956459400622_04.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027232880.jpg" alt="6956459400622_05.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027276363.jpg" alt="6956459400622_06.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027278226.jpg" alt="6956459400622_07.jpg" /></p>', 'cate_id' => '816', 'cate_name' => '地方特产 山东特产', 'brand' => '百枣纲目', 'spec_qty' => '0', 'spec_name_1' => '', 'spec_name_2' => '', 'if_show' => '1', 'if_seckill' => '0', 'closed' => '0', 'close_reason' => NULL, 'add_time' => '1421605662', 'last_update' => '1421605662', 'default_spec' => '5557', 'default_image' => 'data/files/store_132/goods_20/small_201501191027007132.jpg', 'recommended' => '0', 'cate_id_1' => '815', 'cate_id_2' => '816', 'cate_id_3' => '0', 'cate_id_4' => '0', 'price' => '19.80', 'tags' => array ( 0 => '百枣纲目 夹心枣核桃', ), 'cuxiao_ids' => NULL, 'from_goods_id' => '0', 'quanzhong' => NULL, 'state' => '1', '_specs' => array ( 0 => array ( 'spec_id' => '5557', 'goods_id' => '5553', 'spec_1' => '', 'spec_2' => '', 'color_rgb' => '', 'price' => '19.80', 'stock' => '1000', 'sku' => '6956459400622', ), ), '_images' => array ( 0 => array ( 'image_id' => '5204', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_20/201501191027007132.jpg', 'thumbnail' => 'data/files/store_132/goods_20/small_201501191027007132.jpg', 'sort_order' => '1', 'file_id' => '21028', ), 1 => array ( 'image_id' => '5205', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_24/201501191027045479.jpg', 'thumbnail' => 'data/files/store_132/goods_24/small_201501191027045479.jpg', 'sort_order' => '255', 'file_id' => '21027', ), 2 => array ( 'image_id' => '5206', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_33/201501191027133651.jpg', 'thumbnail' => 'data/files/store_132/goods_33/small_201501191027133651.jpg', 'sort_order' => '255', 'file_id' => '21030', ), ), '_scates' => array ( ), 'views' => '1', 'collects' => '0', 'carts' => '0', 'orders' => '0', 'sales' => '0', 'comments' => '0', 'related_info' => array ( ), ), 'store_data' => array ( 'store_id' => '132', 'store_name' => '大地锐城店', 'owner_name' => '倍全', 'owner_card' => '370832200104057894', 'region_id' => '2213', 'region_name' => '中国 山东 济南 历下区', 'address' => '', 'zipcode' => '', 'tel' => '15666660007', 'sgrade' => '系统默认', 'apply_remark' => '', 'credit_value' => '0', 'praise_rate' => '0.00', 'domain' => '', 'state' => '1', 'close_reason' => '', 'add_time' => '1418929047', 'end_time' => '0', 'certification' => 'autonym,material', 'sort_order' => '65535', 'recommended' => '0', 'theme' => '', 'store_banner' => NULL, 'store_logo' => 'data/files/store_132/other/store_logo.jpg', 'description' => '', 'image_1' => '', 'image_2' => '', 'image_3' => '', 'im_qq' => '', 'im_ww' => '', 'im_msn' => '', 'hot_search' => '', 'business_scope' => '', 'online_service' => array ( ), 'hotline' => '', 'pic_slides' => '', 'pic_slides_wap' => '{"1":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_1.jpg","link":"http://wap.bqmart.cn/index.php?app=zhuanti&id=7"},"2":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_2.jpg","link":"http://wap.bqmart.cn/index.php?keyword= %E6%B4%97%E8%A1%A3%E5%B9%B2%E6%B4%97&app=store&act=search&id=132"},"3":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_3.jpg","link":"http://wap.bqmart.cn/index.php?app=search&cate_id=691&id=132"}}', 'enable_groupbuy' => '0', 'enable_radar' => '1', 'waptheme' => '', 'is_open_pay' => '0', 'area_peisong' => NULL, 'power_coupon' => '0', 's_long' => '117.096102', 's_lat' => '36.68974', 'user_name' => 'bq516', 'email' => '[email protected]', 'certifications' => array ( 0 => 'autonym', 1 => 'material', ), 'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif', 'store_owner' => array ( 'user_id' => '132', 'user_name' => 'bq516', 'email' => '[email protected]', 'password' => '9cbf8a4dcb8e30682b927f352d6559a0', 'real_name' => '新生活家园', 'gender' => '0', 'birthday' => '', 'phone_tel' => NULL, 'phone_mob' => NULL, 'im_qq' => '', 'im_msn' => '', 'im_skype' => NULL, 'im_yahoo' => NULL, 'im_aliww' => NULL, 'reg_time' => '1418928900', 'last_login' => '1421874055', 'last_ip' => '123.233.201.48', 'logins' => '136', 'ugrade' => '0', 'portrait' => NULL, 'outer_id' => '0', 'activation' => NULL, 'feed_config' => NULL, 'uin' => '0', 'parentid' => '0', 'user_level' => '0', 'from_weixin' => '0', 'wx_openid' => NULL, 'wx_nickname' => NULL, 'wx_city' => NULL, 'wx_country' => NULL, 'wx_province' => NULL, 'wx_language' => NULL, 'wx_headimgurl' => NULL, 'wx_subscribe_time' => '0', 'wx_id' => '0', 'from_public' => '0', 'm_storeid' => '0', ), 'store_navs' => array ( ), 'kmenus' => false, 'kmenusinfo' => array ( ), 'radio_new' => 1, 'radio_recommend' => 1, 'radio_hot' => 1, 'goods_count' => '1106', 'store_gcates' => array ( ), 'functions' => array ( 'editor_multimedia' => 'editor_multimedia', 'coupon' => 'coupon', 'groupbuy' => 'groupbuy', 'enable_radar' => 'enable_radar', 'seckill' => 'seckill', ), 'hot_saleslist' => array ( 3043 => array ( 'goods_id' => '3043', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', ), 3650 => array ( 'goods_id' => '3650', 'goods_name' => '美汁源果粒橙450ml果汁', 'default_image' => 'data/files/store_132/goods_5/small_201412181056459752.jpg', 'price' => '3.00', 'sales' => '5', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', ), 3666 => array ( 'goods_id' => '3666', 'goods_name' => '乐百氏脉动水蜜桃600ml', 'default_image' => 'data/files/store_132/goods_101/small_201412181105019926.jpg', 'price' => '4.00', 'sales' => '3', ), 3660 => array ( 'goods_id' => '3660', 'goods_name' => '雪碧清爽柠檬味汽水330ml', 'default_image' => 'data/files/store_132/goods_150/small_201412181102308979.jpg', 'price' => '2.00', 'sales' => '1', ), 3230 => array ( 'goods_id' => '3230', 'goods_name' => '圣牧全程有机奶1X12X250ml', 'default_image' => 'data/files/store_132/goods_69/small_201412171617496624.jpg', 'price' => '98.00', 'sales' => '1', ), 3708 => array ( 'goods_id' => '3708', 'goods_name' => '怡泉+c500ml功能饮料', 'default_image' => 'data/files/store_132/goods_115/small_201412181125154319.jpg', 'price' => '4.00', 'sales' => '1', ), 4012 => array ( 'goods_id' => '4012', 'goods_name' => '【39元区】羊毛外套 羊绒大衣', 'default_image' => 'data/files/store_132/goods_186/small_201501041619467368.jpg', 'price' => '39.00', 'sales' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '大白兔奶糖114g牛奶糖', 'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg', 'price' => '7.50', 'sales' => '0', ), ), 'collect_goodslist' => array ( 5494 => array ( 'goods_id' => '5494', 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'collects' => '1', ), 3570 => array ( 'goods_id' => '3570', 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'collects' => '1', ), 3777 => array ( 'goods_id' => '3777', 'goods_name' => '海天苹果醋450ml', 'default_image' => 'data/files/store_132/goods_47/small_201412181157271271.jpg', 'price' => '6.50', 'collects' => '1', ), 3871 => array ( 'goods_id' => '3871', 'goods_name' => '品食客手抓饼葱香味400g速冻食品', 'default_image' => 'data/files/store_132/goods_103/small_201412181421434694.jpg', 'price' => '11.80', 'collects' => '1', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'collects' => '1', ), 3043 => array ( 'goods_id' => '3043', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'collects' => '1', ), 3800 => array ( 'goods_id' => '3800', 'goods_name' => '蒙牛冠益乳草莓味风味发酵乳450g', 'default_image' => 'data/files/store_132/goods_12/small_201412181310121305.jpg', 'price' => '13.50', 'collects' => '1', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'collects' => '1', ), 3130 => array ( 'goods_id' => '3130', 'goods_name' => '迪士尼巧克力味心宠杯25g', 'default_image' => 'data/files/store_132/goods_110/small_201412171515106856.jpg', 'price' => '2.50', 'collects' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '大白兔奶糖114g牛奶糖', 'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg', 'price' => '7.50', 'collects' => '0', ), ), 'left_rec_goods' => array ( 3043 => array ( 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', 'goods_id' => '3043', ), 3457 => array ( 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', 'goods_id' => '3457', ), 3459 => array ( 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', 'goods_id' => '3459', ), 3570 => array ( 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'sales' => '0', 'goods_id' => '3570', ), 5494 => array ( 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'sales' => '0', 'goods_id' => '5494', ), ), ), 'cur_local' => array ( 0 => array ( 'text' => '所有分类', 'url' => 'index.php?app=category', ), 1 => array ( 'text' => '地方特产', 'url' => 'index.php?app=search&amp;cate_id=815', ), 2 => array ( 'text' => '山东特产', 'url' => 'index.php?app=search&amp;cate_id=816', ), 3 => array ( 'text' => '商品详情', ), ), 'share' => array ( 4 => array ( 'title' => '开心网', 'link' => 'http://www.kaixin001.com/repaste/share.php?rtitle=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E&rurl=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/kaixin001.gif', ), 3 => array ( 'title' => 'QQ书签', 'link' => 'http://shuqian.qq.com/post?from=3&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&jumpback=2&noui=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/qqshuqian.gif', ), 2 => array ( 'title' => '人人网', 'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/renren.gif', ), 1 => array ( 'title' => '百度收藏', 'link' => 'http://cang.baidu.com/do/add?it=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&fr=ien#nw=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/baidushoucang.gif', ), ), ); ?>
guotao2000/ecmall
temp/caches/0496/d282033c16c05294e665c011f6ecac6d.cache.php
PHP
mit
16,153
# Fetching User Objects Fetching user objects is a simple way to get at specific objects that you know the IDs of or to access all user objects. This does not access objects owned by the application. If you know more detail about the object you are looking for, but do not know the object ids, you might find it easier to use the [Object Search](#/javascript#searching-for-user-objects) feature instead. If you want to access all objects stored in your logged in user, use `ws.get()`: ```js // Assuming the ws object is a WebService instance with a logged in user // Lets say you had an object with an id "comedians" an the value of: // { favorite: "Lewis Black", second: "Louis CK" } // and another object with a value of "cheesecake" var response = ws.get(); response.on('success', function(data, response) { // Data returned on success will be keyed by id, unsorted. console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake", // ... and every other object in your application... // } }); ``` {{note "Fetch operations are limited to 50 results by default. To retreive more objects you need to specify a limit, or page through results. See Sorting and Paging for more information."}} To fetch application objects while using a logged in WebService instance: ```js ws.get({applevel: true}).on(function(data, response) { console.log(data); // Contents of data contains all application objects. }); ``` To fetch a single object, simply give the key of the object: ```js ws.get('comedians').on('success', function(data, response) { // Only the comedians object will be returned, but still keyed by the object id. console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake", // ... and every other object in your application... // } }); ``` Or you can give a list of ids to fetch multiple objects: ```js ws.get(['another_object', 'comedians']).on('success', function(data, response) { console.log(data); // { // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // }, // another_object: "cheesecake" // } }); ``` {{caution "Even if you specify a list of more than 50 items, the results will still be limited to the 50 items unless you specify a limit."}} {{jsEvents 'success.ok' 'error.unauthorized.notfound' 'complete'}}
cloudmine/cloudmine-js
docs/4_Users/6_Objects/2_Fetch.md
Markdown
mit
2,490
<html dir="rtl"> <head> <title>Testing textpath</title> <style type="text/css"> @import "../../../../../dojo/resources/dojo.css"; @import "../../../../../dijit/tests/css/dijitTests.css"; </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="../../../../../dojo/dojo.js" djConfig="isDebug: true, gfxRenderer:'canvas'"></script> <script type="text/javascript"> dojo.require("dojox.gfx"); dojo.require("dojox.gfx._gfxBidiSupport"); dojo.require("doh.runner"); var CPD = 30, tp1, tp2, tp3, tp4, tp5, tp6, t1, t2, t3, t4, t5, t6; var g1 = null, g2 = null, g3, g4; var surfaceLTR = null, surfaceRTL = null, surfaceAUTO = null; var placeAnchor = function(surface, x, y){ surface.createLine({x1: x - 2, y1: y, x2: x + 2, y2: y}); surface.createLine({x1: x, y1: y - 2, x2: x, y2: y + 2}); }; var makeText = function(surface, text, font, fill, stroke){ var t = surface.createText(text); if(font) t.setFont(font); if(fill) t.setFill(fill); if(stroke) t.setStroke(stroke); placeAnchor(surface, text.x, text.y); return t; }; makeShapes = function(){ var m = dojox.gfx.matrix; surfaceLTR = dojox.gfx.createSurface("testLTR", 500, 170, "ltr"); console.debug("surfaceLTR created"); var p = surfaceLTR.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 50, 0) ; console.debug("p created"); tp1 = surfaceLTR.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp1 created"); tp2 = surfaceLTR.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" }) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp2 created"); g1 = surfaceLTR.createGroup(); g1.setTextDir("rtl"); // surfaceLTR.setTextDir("ltr"); t1 = makeText(g1, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 150)); t2 = makeText(surfaceLTR, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); surfaceRTL = dojox.gfx.createSurface("testRTL", 500, 170); console.debug("surfaceRTL created"); var p2 = surfaceRTL.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p2 created"); tp3 = surfaceRTL.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; g2 = surfaceRTL.createGroup(); g2.add(tp3); g2.setTextDir("ltr"); g3 = g2.createGroup("rtl"); g4 = surfaceRTL.createGroup("auto"); tp4 = surfaceRTL.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp4 created"); t3 = makeText(g3, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t4 = makeText(surfaceRTL, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 100)); surfaceAUTO = dojox.gfx.createSurface("testAUTO", 500, 170,"auto"); console.debug("surfaceAUTO created"); var p3 = surfaceAUTO.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p3 created"); tp5 = surfaceAUTO.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp5 created"); tp6 = surfaceAUTO.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp6 created"); t5 = makeText(surfaceAUTO, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t6 = makeText(surfaceAUTO, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); }; dojo.addOnLoad(function(){ makeShapes(); doh.register("Test inheritance", [ function surfaces_TextDir(){ doh.is("ltr", surfaceLTR.getTextDir(), "surfaceLTR.getTextDir"); doh.is("rtl", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("auto", surfaceAUTO.getTextDir(), "surfaceAUTO.getTextDir"); }, function groups_TextDir(){ doh.is("rtl", g1.getTextDir(), "g1.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("auto", g4.getTextDir(), "g4.getTextDir"); }, function gfxText_TextDir(){ doh.is("rtl", t1.textDir, "t1.getTextDir"); doh.is("ltr", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", t4.textDir, "t4.getTextDir"); doh.is("auto", t5.textDir, "t5.getTextDir"); doh.is("auto", t6.textDir, "t6h.getTextDir"); }, function gfxTextPath_TextDir(){ doh.is("ltr", tp1.textDir, "tp1.getTextDir"); doh.is("ltr", tp2.textDir, "tp2.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("rtl", tp4.textDir, "tp4.getTextDir"); doh.is("auto", tp5.textDir, "tp5.getTextDir"); doh.is("auto", tp6.textDir, "tp6.getTextDir"); }, function changeSurfaceRTLextDir(){ surfaceRTL.setTextDir("ltr"); doh.is("ltr", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("ltr", g3.getTextDir(), "g3.getTextDir"); doh.is("ltr", g4.getTextDir(), "g4.getTextDir"); doh.is("ltr", t3.textDir, "t3.getTextDir"); doh.is("ltr", t4.textDir, "t4.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("ltr", tp4.textDir, "tp4.getTextDir"); }, function changeGroupTextDir(){ g3.add(tp5); g3.add(t2); g2.setTextDir("rtl"); doh.is("rtl", g2.getTextDir(), "g2.getTextDir"); // son of g2 doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("rtl", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", tp5.textDir, "tp3.getTextDir"); } ]); doh.run(); }); </script> </head> <body> <h1>dojox.gfx Text on a Path test</h1> <h2>LTR TextPath and Text first two are TextPath and two others are Text</h2> <div id="testLTR" style="width: 500px;"></div> <h2>RTL Text Path and Text first two are TextPath and two others are Text</h2> <div id="testRTL" style="width: 500px;"></div> <h2>AUTO Text Path and Text first two are TextPath and two others are Text</h2> <div id="testAUTO" style="width: 500px;"></div> <p>That's all Folks!</p> </body> </html>
synico/springframework
lobtool/src/main/webapp/resources/javascript/dojox/gfx/tests/_gfxBidiSupport/canvas/test_SurfaceGroupCanvas.html
HTML
mit
8,471
/** * The MIT License * * Copyright (c) 2019, Mahmoud Ben Hassine ([email protected]) * * 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. */ package org.jeasy.random; import static org.jeasy.random.FieldPredicates.*; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.jeasy.random.api.ContextAwareRandomizer; import org.jeasy.random.api.RandomizerContext; import org.jeasy.random.beans.*; import org.jeasy.random.beans.exclusion.A; import org.jeasy.random.beans.exclusion.B; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.jeasy.random.beans.exclusion.C; @ExtendWith(MockitoExtension.class) class FieldExclusionTest { private EasyRandom easyRandom; @BeforeEach void setUp() { easyRandom = new EasyRandom(); } @Test void excludedFieldsShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); //then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void excludedFieldsUsingSkipRandomizerShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name").and(ofType(String.class)).and(inClass(Human.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void excludedFieldsUsingFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); // person.name and street.name should be null assertThat(person.getName()).isNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void excludedDottedFieldsShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("name").and(inClass(Street.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void fieldsExcludedWithAnnotationShouldNotBePopulated() { Person person = easyRandom.nextObject(Person.class); assertThat(person).isNotNull(); assertThat(person.getExcluded()).isNull(); } @Test @SuppressWarnings("deprecation") void fieldsExcludedWithAnnotationViaFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(isAnnotatedWith(Deprecated.class)); easyRandom = new EasyRandom(parameters); // when Website website = easyRandom.nextObject(Website.class); // then assertThat(website).isNotNull(); assertThat(website.getProvider()).isNull(); } @Test void fieldsExcludedFromTypeViaFieldDefinitionShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(inClass(Address.class)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); // all fields declared in class Address must be null assertThat(person.getAddress().getCity()).isNull(); assertThat(person.getAddress().getStreet()).isNull(); assertThat(person.getAddress().getZipCode()).isNull(); assertThat(person.getAddress().getCountry()).isNull(); } @Test void testFirstLevelExclusion() { EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("b2").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 must be null assertThat(c.getB2()).isNull(); } @Test void testSecondLevelExclusion() { // goal: exclude only b2.a2 EasyRandomParameters parameters = new EasyRandomParameters() .randomize(ofType(A.class).and(inClass(B.class)), new ContextAwareRandomizer<A>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b2.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNull(); } @Test void testThirdLevelExclusion() { // goal: exclude only b2.a2.s2 EasyRandomParameters parameters = new EasyRandomParameters() .randomize(FieldPredicates.named("s2").and(inClass(A.class)), new ContextAwareRandomizer<String>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public String getRandomValue() { if (context.getCurrentField().equals("b2.a2.s2")) { return null; } return new EasyRandom().nextObject(String.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2.S2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNull(); } @Test void testFirstLevelCollectionExclusion() { EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(FieldPredicates.named("b3").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must be null assertThat(c.getB3()).isNull(); } @Test void testSecondLevelCollectionExclusion() { // b3.a2 does not make sense, should be ignored EasyRandomParameters parameters = new EasyRandomParameters() .randomize(FieldPredicates.named("a2").and(inClass(B.class)), new ContextAwareRandomizer<A>() { private RandomizerContext context; @Override public void setRandomizerContext(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b3.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must not be null assertThat(c.getB3()).isNotNull(); } @Test void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBean.class))); easyRandom = new EasyRandom(parameters); // when InlineInitializationBean bean = easyRandom.nextObject(InlineInitializationBean.class); // then assertThat(bean).isNotNull(); assertThat(bean.getMyList()).isEmpty(); } @Test void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs_EvenIfBeanHasNoPublicConstructor() { // given EasyRandomParameters parameters = new EasyRandomParameters() .excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBeanPrivateConstructor.class))); easyRandom = new EasyRandom(parameters); // when InlineInitializationBeanPrivateConstructor bean = easyRandom.nextObject(InlineInitializationBeanPrivateConstructor.class); // then assertThat(bean.getMyList()).isEmpty(); } @Test void fieldsExcludedWithOneModifierShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void fieldsExcludedWithTwoModifiersShouldNotBePopulated() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PROTECTED)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void fieldsExcludedWithTwoModifiersShouldBePopulatedIfOneModifierIsNotFit() { // given EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PUBLIC)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNotNull(); } public static class InlineInitializationBean { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } public void setMyList(List<String> myList) { this.myList = myList; } } public static class InlineInitializationBeanPrivateConstructor { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } private InlineInitializationBeanPrivateConstructor() {} } }
benas/jPopulator
easy-random-core/src/test/java/org/jeasy/random/FieldExclusionTest.java
Java
mit
16,362
__all__ = [] import pkgutil import inspect # http://stackoverflow.com/questions/22209564/python-qualified-import-all-in-package for loader, name, is_pkg in pkgutil.walk_packages(__path__): module = loader.find_module(name).load_module(name) for name, value in inspect.getmembers(module): if name.startswith('__'): continue globals()[name] = value __all__.append(name)
pawl/CalendarAdmin
application/views/__init__.py
Python
mit
416
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2018 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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 "../gl_driver.h" #include "3rdparty/tinyfiledialogs/tinyfiledialogs.h" #include "common/common.h" #include "strings/string_utils.h" enum GLbufferbitfield { }; DECLARE_REFLECTION_ENUM(GLbufferbitfield); template <> std::string DoStringise(const GLbufferbitfield &el) { RDCCOMPILE_ASSERT(sizeof(GLbufferbitfield) == sizeof(GLbitfield) && sizeof(GLbufferbitfield) == sizeof(uint32_t), "Fake bitfield enum must be uint32_t sized"); BEGIN_BITFIELD_STRINGISE(GLbufferbitfield); { STRINGISE_BITFIELD_BIT(GL_DYNAMIC_STORAGE_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_READ_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_WRITE_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_PERSISTENT_BIT); STRINGISE_BITFIELD_BIT(GL_MAP_COHERENT_BIT); STRINGISE_BITFIELD_BIT(GL_CLIENT_STORAGE_BIT); } END_BITFIELD_STRINGISE(); } #pragma region Buffers template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenBuffers(1, &real); GLResource res = BufferRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(buffer, res); AddResource(buffer, ResourceType::Buffer, "Buffer"); m_Buffers[live].resource = res; m_Buffers[live].curType = eGL_NONE; m_Buffers[live].creationFlags = BufferCategory::NoFlags; } return true; } void WrappedOpenGL::glGenBuffers(GLsizei n, GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glGenBuffers(n, buffers)); for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenBuffers(ser, 1, buffers + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); m_Buffers[id].resource = res; m_Buffers[id].curType = eGL_NONE; m_Buffers[id].creationFlags = BufferCategory::NoFlags; } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateBuffers(1, &real); GLResource res = BufferRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(buffer, res); AddResource(buffer, ResourceType::Buffer, "Buffer"); m_Buffers[live].resource = res; m_Buffers[live].curType = eGL_NONE; m_Buffers[live].creationFlags = BufferCategory::NoFlags; } return true; } void WrappedOpenGL::glCreateBuffers(GLsizei n, GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glCreateBuffers(n, buffers)); for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateBuffers(ser, 1, buffers + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); m_Buffers[id].resource = res; m_Buffers[id].curType = eGL_NONE; m_Buffers[id].creationFlags = BufferCategory::NoFlags; } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffer(SerialiserType &ser, GLenum target, GLuint bufferHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(target == eGL_NONE) { // ... } else if(buffer.name == 0) { m_Real.glBindBuffer(target, 0); } else { // if we're just loading, make sure not to trample state (e.g. element array buffer // binding in a VAO), since this is just a bind-to-create chunk. GLuint prevbuf = 0; if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE) m_Real.glGetIntegerv(BufferBinding(target), (GLint *)&prevbuf); m_Real.glBindBuffer(target, buffer.name); m_Buffers[GetResourceManager()->GetID(buffer)].curType = target; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= MakeBufferCategory(target); if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE) m_Real.glBindBuffer(target, prevbuf); } AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBuffer(GLenum target, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glBindBuffer(target, buffer)); ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); if(IsActiveCapturing(m_State)) { Chunk *chunk = NULL; if(buffer == 0) cd.m_BufferRecord[idx] = NULL; else cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffer(ser, target, buffer); if(cd.m_BufferRecord[idx]) cd.m_BufferRecord[idx]->datatype = target; chunk = scope.Get(); } if(buffer) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } m_ContextRecord->AddChunk(chunk); } if(buffer == 0) { cd.m_BufferRecord[idx] = NULL; return; } if(IsCaptureMode(m_State)) { GLResourceRecord *r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(!r) { RDCERR("Invalid/unrecognised buffer passed: glBindBuffer(%s, %u)", ToStr(target).c_str(), buffer); return; } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r->datatype != target) { Chunk *chunk = NULL; r->LockChunks(); for(;;) { Chunk *end = r->GetLastChunk(); if(end->GetChunkType<GLChunk>() == GLChunk::glBindBuffer || end->GetChunkType<GLChunk>() == GLChunk::glBindBufferARB) { SAFE_DELETE(end); r->PopChunk(); continue; } break; } r->UnlockChunks(); r->datatype = target; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->AddChunk(chunk); } // element array buffer binding is vertex array record state, record there (if we've not just // stopped) if(IsBackgroundCapturing(m_State) && target == eGL_ELEMENT_ARRAY_BUFFER && RecordUpdateCheck(cd.m_VertexArrayRecord)) { GLuint vao = cd.m_VertexArrayRecord->Resource.name; // use glVertexArrayElementBuffer to ensure the vertex array is bound when we bind the // element buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glVertexArrayElementBuffer); Serialise_glVertexArrayElementBuffer(ser, vao, buffer); cd.m_VertexArrayRecord->AddChunk(scope.Get()); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, 0, buffer); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER) { if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(r->GetResourceID()); else m_MissingTracks.insert(r->GetResourceID()); } } else { m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].curType = target; m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].creationFlags |= MakeBufferCategory(target); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferStorageEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr size, const void *data, GLbitfield flags) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); if(ser.IsWriting()) { uint64_t offs = ser.GetWriter()->GetOffset() - bytesize; RDCASSERT((offs % 64) == 0); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer); RDCASSERT(record); record->SetDataOffset(offs); } SERIALISE_ELEMENT_TYPED(GLbufferbitfield, flags); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // remove persistent flag - we will never persistently map so this is a nice // hint. It helps especially when self-hosting, as we don't want tons of // overhead added when we won't use it. flags &= ~GL_MAP_PERSISTENT_BIT; // can't have coherent without persistent, so remove as well flags &= ~GL_MAP_COHERENT_BIT; m_Real.glNamedBufferStorageEXT(buffer.name, (GLsizeiptr)bytesize, data, flags); m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize; AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::Common_glNamedBufferStorageEXT(ResourceId id, GLsizeiptr size, const void *data, GLbitfield flags) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(id); RDCASSERTMSG("Couldn't identify object used in function. Unbound or bad GLuint?", record); if(record == NULL) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageEXT(ser, record->Resource.name, size, data, flags); Chunk *chunk = scope.Get(); { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = (int32_t)size; record->DataInSerialiser = true; } // We immediately map the whole range with appropriate flags, to be copied into whenever we // need to propogate changes. Note: Coherent buffers are not mapped coherent, but this is // because the user code isn't writing into them anyway and we're inserting invisible sync // points - so there's no need for it to be coherently mapped (and there's no requirement // that a buffer declared as coherent must ALWAYS be mapped as coherent). if(flags & GL_MAP_PERSISTENT_BIT) { record->Map.persistentPtr = (byte *)m_Real.glMapNamedBufferRangeEXT( record->Resource.name, 0, size, GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_PERSISTENT_BIT); RDCASSERT(record->Map.persistentPtr); // persistent maps always need both sets of shadow storage, so allocate up front. record->AllocShadowStorage(size); // ensure shadow pointers have up to date data for diffing memcpy(record->GetShadowPtr(0), data, size); memcpy(record->GetShadowPtr(1), data, size); } } else { m_Buffers[id].size = size; } } void WrappedOpenGL::glNamedBufferStorageEXT(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glNamedBufferStorageEXT(buffer, size, data, flags)); Common_glNamedBufferStorageEXT(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer)), size, data, flags); SAFE_DELETE_ARRAY(dummy); } void WrappedOpenGL::glNamedBufferStorage(GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags) { // only difference to EXT function is size parameter, so just upcast glNamedBufferStorageEXT(buffer, size, data, flags); } void WrappedOpenGL::glBufferStorage(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glBufferStorage(target, size, data, flags)); if(IsCaptureMode(m_State)) Common_glNamedBufferStorageEXT(GetCtxData().m_BufferRecord[BufferIdx(target)]->GetResourceID(), size, data, flags); else RDCERR("Internal buffers should be allocated via dsa interfaces"); SAFE_DELETE_ARRAY(dummy); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferDataEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr size, const void *data, GLenum usage) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); if(ser.IsWriting()) { uint64_t offs = ser.GetWriter()->GetOffset() - bytesize; RDCASSERT((offs % 64) == 0); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer); RDCASSERT(record); record->SetDataOffset(offs); } SERIALISE_ELEMENT(usage); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedBufferDataEXT(buffer.name, (GLsizeiptr)bytesize, data, usage); m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize; AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glNamedBufferDataEXT(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glNamedBufferDataEXT(buffer, size, data, usage)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); if(record == NULL) { SAFE_DELETE_ARRAY(dummy); return; } // detect buffer orphaning and just update backing store if(IsBackgroundCapturing(m_State) && record->HasDataPtr() && size == (GLsizeiptr)record->Length && usage == record->usage) { if(data) memcpy(record->GetDataPtr(), data, (size_t)size); else memset(record->GetDataPtr(), 0xbe, (size_t)size); SAFE_DELETE_ARRAY(dummy); return; } // if we're recreating the buffer, clear the record and add new chunks. Normally // we would just mark this record as dirty and pick it up on the capture frame as initial // data, but we don't support (if it's even possible) querying out size etc. // we need to add only the chunks required - glGenBuffers, glBindBuffer to current target, // and this buffer storage. All other chunks have no effect if(IsBackgroundCapturing(m_State) && (record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length))) { // we need to maintain chunk ordering, so fetch the first two chunk IDs. // We should have at least two by this point - glGenBuffers and whatever gave the record // a size before. RDCASSERT(record->NumChunks() >= 2); // remove all but the first two chunks while(record->NumChunks() > 2) { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id2 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id1 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } RDCASSERT(!record->HasChunks()); // add glGenBuffers chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers); Serialise_glGenBuffers(ser, 1, &buffer); record->AddChunk(scope.Get(), id1); } // add glBindBuffer chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, record->datatype, buffer); record->AddChunk(scope.Get(), id2); } // we're about to add the buffer data chunk } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage); Chunk *chunk = scope.Get(); // if we've already created this is a renaming/data updating call. It should go in // the frame record so we can 'update' the buffer as it goes in the frame. // if we haven't created the buffer at all, it could be a mid-frame create and we // should place it in the resource record, to happen before the frame. if(IsActiveCapturing(m_State) && record->HasDataPtr()) { // we could perhaps substitute this for a 'fake' glBufferSubData chunk? m_ContextRecord->AddChunk(chunk); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write); } else { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = (int32_t)size; record->usage = usage; record->DataInSerialiser = true; } } else { m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].size = size; } SAFE_DELETE_ARRAY(dummy); } void WrappedOpenGL::glNamedBufferData(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage) { // only difference to EXT function is size parameter, so just upcast glNamedBufferDataEXT(buffer, size, data, usage); } void WrappedOpenGL::glBufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) { byte *dummy = NULL; if(IsCaptureMode(m_State) && data == NULL) { dummy = new byte[size]; memset(dummy, 0xdd, size); data = dummy; } SERIALISE_TIME_CALL(m_Real.glBufferData(target, size, data, usage)); size_t idx = BufferIdx(target); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[idx]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record == NULL) { SAFE_DELETE_ARRAY(dummy); return; } // detect buffer orphaning and just update backing store if(IsBackgroundCapturing(m_State) && record->HasDataPtr() && size == (GLsizeiptr)record->Length && usage == record->usage) { if(data) memcpy(record->GetDataPtr(), data, (size_t)size); else memset(record->GetDataPtr(), 0xbe, (size_t)size); SAFE_DELETE_ARRAY(dummy); return; } GLuint buffer = record->Resource.name; // if we're recreating the buffer, clear the record and add new chunks. Normally // we would just mark this record as dirty and pick it up on the capture frame as initial // data, but we don't support (if it's even possible) querying out size etc. // we need to add only the chunks required - glGenBuffers, glBindBuffer to current target, // and this buffer storage. All other chunks have no effect if(IsBackgroundCapturing(m_State) && (record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length))) { // we need to maintain chunk ordering, so fetch the first two chunk IDs. // We should have at least two by this point - glGenBuffers and whatever gave the record // a size before. RDCASSERT(record->NumChunks() >= 2); // remove all but the first two chunks while(record->NumChunks() > 2) { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id2 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } int32_t id1 = record->GetLastChunkID(); { Chunk *c = record->GetLastChunk(); SAFE_DELETE(c); record->PopChunk(); } RDCASSERT(!record->HasChunks()); // add glGenBuffers chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers); Serialise_glGenBuffers(ser, 1, &buffer); record->AddChunk(scope.Get(), id1); } // add glBindBuffer chunk { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, record->datatype, buffer); record->AddChunk(scope.Get(), id2); } // we're about to add the buffer data chunk } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage); Chunk *chunk = scope.Get(); // if we've already created this is a renaming/data updating call. It should go in // the frame record so we can 'update' the buffer as it goes in the frame. // if we haven't created the buffer at all, it could be a mid-frame create and we // should place it in the resource record, to happen before the frame. if(IsActiveCapturing(m_State) && record->HasDataPtr()) { // we could perhaps substitute this for a 'fake' glBufferSubData chunk? m_ContextRecord->AddChunk(chunk); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write); } else { record->AddChunk(chunk); record->SetDataPtr(chunk->GetData()); record->Length = size; record->usage = usage; record->DataInSerialiser = true; } } else { RDCERR("Internal buffers should be allocated via dsa interfaces"); } SAFE_DELETE_ARRAY(dummy); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedBufferSubDataEXT(SerialiserType &ser, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr size, const void *data) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size); SERIALISE_ELEMENT_ARRAY(data, bytesize); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedBufferSubDataEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)bytesize, data); } return true; } void WrappedOpenGL::glNamedBufferSubDataEXT(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data) { SERIALISE_TIME_CALL(m_Real.glNamedBufferSubDataEXT(buffer, offset, size, data)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record); if(record == NULL) return; if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferSubDataEXT(ser, buffer, offset, size, data); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { record->AddChunk(chunk); record->UpdateCount++; if(record->UpdateCount > 10) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } } void WrappedOpenGL::glNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data) { // only difference to EXT function is size parameter, so just upcast glNamedBufferSubDataEXT(buffer, offset, size, data); } void WrappedOpenGL::glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) { SERIALISE_TIME_CALL(m_Real.glBufferSubData(target, offset, size, data)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record == NULL) return; GLResource res = record->Resource; if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferSubDataEXT(ser, res.name, offset, size, data); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { record->AddChunk(chunk); record->UpdateCount++; if(record->UpdateCount > 10) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glNamedCopyBufferSubDataEXT(SerialiserType &ser, GLuint readBufferHandle, GLuint writeBufferHandle, GLintptr readOffsetPtr, GLintptr writeOffsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT_LOCAL(readBuffer, BufferRes(GetCtx(), readBufferHandle)); SERIALISE_ELEMENT_LOCAL(writeBuffer, BufferRes(GetCtx(), writeBufferHandle)); SERIALISE_ELEMENT_LOCAL(readOffset, (uint64_t)readOffsetPtr); SERIALISE_ELEMENT_LOCAL(writeOffset, (uint64_t)writeOffsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glNamedCopyBufferSubDataEXT(readBuffer.name, writeBuffer.name, (GLintptr)readOffset, (GLintptr)writeOffset, (GLsizeiptr)size); } return true; } void WrappedOpenGL::glNamedCopyBufferSubDataEXT(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { CoherentMapImplicitBarrier(); SERIALISE_TIME_CALL( m_Real.glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size)); if(IsCaptureMode(m_State)) { GLResourceRecord *readrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), readBuffer)); GLResourceRecord *writerecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), writeBuffer)); RDCASSERT(readrecord && writerecord); if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) && IsBackgroundCapturing(m_State)) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedCopyBufferSubDataEXT(ser, readBuffer, writeBuffer, readOffset, writeOffset, size); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(writerecord->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { writerecord->AddChunk(chunk); writerecord->AddParent(readrecord); writerecord->UpdateCount++; if(writerecord->UpdateCount > 60) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); } } } } void WrappedOpenGL::glCopyNamedBufferSubData(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size); } void WrappedOpenGL::glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { CoherentMapImplicitBarrier(); SERIALISE_TIME_CALL( m_Real.glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size)); if(IsCaptureMode(m_State)) { GLResourceRecord *readrecord = GetCtxData().m_BufferRecord[BufferIdx(readTarget)]; GLResourceRecord *writerecord = GetCtxData().m_BufferRecord[BufferIdx(writeTarget)]; RDCASSERT(readrecord && writerecord); if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() && IsBackgroundCapturing(m_State)) return; if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) && IsBackgroundCapturing(m_State)) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedCopyBufferSubDataEXT( ser, readrecord->Resource.name, writerecord->Resource.name, readOffset, writeOffset, size); Chunk *chunk = scope.Get(); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(chunk); m_MissingTracks.insert(writerecord->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(), eFrameRef_ReadBeforeWrite); } else { writerecord->AddChunk(chunk); writerecord->AddParent(readrecord); writerecord->UpdateCount++; if(writerecord->UpdateCount > 60) { m_HighTrafficResources.insert(writerecord->GetResourceID()); GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBufferBase(SerialiserType &ser, GLenum target, GLuint index, GLuint bufferHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindBufferBase(target, index, buffer.name); AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBufferBase(GLenum target, GLuint index, GLuint buffer) { ContextData &cd = GetCtxData(); SERIALISE_TIME_CALL(m_Real.glBindBufferBase(target, index, buffer)); if(IsCaptureMode(m_State)) { size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffer == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(buffer && IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r && r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, index, buffer); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsActiveCapturing(m_State)) m_MissingTracks.insert(r->GetResourceID()); else GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBufferBase(ser, target, index, buffer); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBufferRange(SerialiserType &ser, GLenum target, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindBufferRange(target, index, buffer.name, (GLintptr)offset, (GLsizeiptr)size); AddResourceInitChunk(buffer); } return true; } void WrappedOpenGL::glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { ContextData &cd = GetCtxData(); SERIALISE_TIME_CALL(m_Real.glBindBufferRange(target, index, buffer, offset, size)); if(IsCaptureMode(m_State)) { size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffer == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); if(buffer && IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(), refType); } // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r && r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffer); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; // use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange); Serialise_glTransformFeedbackBufferRange(ser, feedback, index, buffer, offset, (GLsizei)size); cd.m_FeedbackRecord->AddChunk(scope.Get()); } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsActiveCapturing(m_State)) m_MissingTracks.insert(r->GetResourceID()); else GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBufferRange(ser, target, index, buffer, offset, size); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffersBase(SerialiserType &ser, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); // can't serialise arrays of GL handles since they're not wrapped or typed :(. std::vector<GLResource> buffers; if(ser.IsWriting()) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } SERIALISE_ELEMENT(buffers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; bufs.reserve(count); for(GLsizei i = 0; i < count; i++) { bufs.push_back(buffers[i].name); AddResourceInitChunk(buffers[i]); } m_Real.glBindBuffersBase(target, first, count, bufs.data()); } return true; } void WrappedOpenGL::glBindBuffersBase(GLenum target, GLuint first, GLsizei count, const GLuint *buffers) { SERIALISE_TIME_CALL(m_Real.glBindBuffersBase(target, first, count, buffers)); if(IsCaptureMode(m_State) && buffers && count > 0) { ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); GLResourceRecord *r = NULL; if(buffers[0] == 0) r = cd.m_BufferRecord[idx] = NULL; else r = cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0])); if(IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; for(GLsizei i = 0; i < count; i++) { if(buffers[i]) { ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i])); GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite); m_MissingTracks.insert(id); } } } for(int i = 0; i < count; i++) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(bufrecord->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffers[i]); chunk = scope.Get(); } bufrecord->datatype = target; bufrecord->AddChunk(chunk); } } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; for(int i = 0; i < count; i++) { // use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the // buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase); Serialise_glTransformFeedbackBufferBase(ser, feedback, first + i, buffers[i]); cd.m_FeedbackRecord->AddChunk(scope.Get()); } } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER)) { if(IsBackgroundCapturing(m_State)) { for(int i = 0; i < count; i++) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i])); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffersBase(ser, target, first, count, buffers); m_ContextRecord->AddChunk(scope.Get()); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindBuffersRange(SerialiserType &ser, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsetPtrs, const GLsizeiptr *sizePtrs) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. // Likewise need to upcast the offsets and sizes to 64-bit instead of serialising as-is. std::vector<GLResource> buffers; std::vector<uint64_t> offsets; std::vector<uint64_t> sizes; if(ser.IsWriting() && bufferHandles) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } if(ser.IsWriting() && offsetPtrs) { offsets.reserve(count); for(GLsizei i = 0; i < count; i++) offsets.push_back((uint64_t)offsetPtrs[i]); } if(ser.IsWriting() && sizePtrs) { sizes.reserve(count); for(GLsizei i = 0; i < count; i++) sizes.push_back((uint64_t)sizePtrs[i]); } SERIALISE_ELEMENT(target); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(offsets); SERIALISE_ELEMENT(sizes); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; std::vector<GLintptr> offs; std::vector<GLsizeiptr> sz; if(!buffers.empty()) { bufs.reserve(count); for(GLsizei i = 0; i < count; i++) { bufs.push_back(buffers[i].name); AddResourceInitChunk(buffers[i]); } } if(!offsets.empty()) { offs.reserve(count); for(GLsizei i = 0; i < count; i++) offs.push_back((GLintptr)offsets[i]); } if(!sizes.empty()) { sz.reserve(count); for(GLsizei i = 0; i < count; i++) sz.push_back((GLintptr)sizes[i]); } m_Real.glBindBuffersRange(target, first, count, bufs.empty() ? NULL : bufs.data(), offs.empty() ? NULL : offs.data(), sz.empty() ? NULL : sz.data()); } return true; } void WrappedOpenGL::glBindBuffersRange(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes) { SERIALISE_TIME_CALL(m_Real.glBindBuffersRange(target, first, count, buffers, offsets, sizes)); if(IsCaptureMode(m_State) && buffers && count > 0) { ContextData &cd = GetCtxData(); size_t idx = BufferIdx(target); if(buffers[0] == 0) cd.m_BufferRecord[idx] = NULL; else cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0])); if(IsActiveCapturing(m_State)) { FrameRefType refType = eFrameRef_Read; // these targets write to the buffer if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER || target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_TRANSFORM_FEEDBACK_BUFFER) refType = eFrameRef_ReadBeforeWrite; for(GLsizei i = 0; i < count; i++) { if(buffers[i]) { ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i])); GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite); m_MissingTracks.insert(id); } } } else { for(int i = 0; i < count; i++) { GLResourceRecord *r = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); // it's legal to re-type buffers, generate another BindBuffer chunk to rename if(r->datatype != target) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer); Serialise_glBindBuffer(ser, target, buffers[i]); chunk = scope.Get(); } r->datatype = target; r->AddChunk(chunk); } } } // store as transform feedback record state if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER && RecordUpdateCheck(cd.m_FeedbackRecord)) { GLuint feedback = cd.m_FeedbackRecord->Resource.name; for(int i = 0; i < count; i++) { // use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind // the buffer USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange); Serialise_glTransformFeedbackBufferRange(ser, feedback, first + i, buffers[i], offsets[i], (GLsizei)sizes[i]); cd.m_FeedbackRecord->AddChunk(scope.Get()); } } // immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER || target == eGL_ATOMIC_COUNTER_BUFFER) { if(IsBackgroundCapturing(m_State)) { for(int i = 0; i < count; i++) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i])); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindBuffersRange(ser, target, first, count, buffers, offsets, sizes); m_ContextRecord->AddChunk(scope.Get()); } } } void WrappedOpenGL::glInvalidateBufferData(GLuint buffer) { m_Real.glInvalidateBufferData(buffer); if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); else m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))); } void WrappedOpenGL::glInvalidateBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr length) { m_Real.glInvalidateBufferSubData(buffer, offset, length); if(IsBackgroundCapturing(m_State)) GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer)); else m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))); } #pragma endregion #pragma region Mapping /************************************************************************ * * Mapping tends to be the most complex/dense bit of the capturing process, as there are a lot of * carefully considered use cases and edge cases to be aware of. * * The primary motivation is, obviously, correctness - where we have to sacrifice performance, * clarity for correctness, we do. Second to that, we try and keep things simple/clear where the * performance sacrifice will be minimal, and generally we try to remove overhead entirely for * high-traffic maps, such that we only step in where necessary. * * We'll consider "normal" maps of buffers, and persistent maps, separately. Note that in all cases * we can guarantee that the buffer being mapped has correctly-sized backing store available, * created in the glBufferData or glBufferStorage call. We also only need to consider the case of * glMapNamedBufferRangeEXT, glUnmapNamedBufferEXT and glFlushMappedNamedBufferRange - all other * entry points are mapped to one of these in a fairly simple fashion. * * * glMapNamedBufferRangeEXT: * * For a normal map, we decide to either record/intercept it, or to step out of the way and allow * the application to map directly to the GL buffer. We can only map directly when idle capturing, * when capturing a frame we must capture all maps to be correct. Generally we perform a direct map * either if this resource is being mapped often and we want to remove overhead, or if the map * interception would be more complex than it's worth. * * The first checks are to see if we've already "given up" on a buffer, in which case we map * directly again. * * Next, if the map is for write and the buffer is not invalidated, we also map directly. * [NB: Since our buffer contents should be perfect at this point, we may not need to worry about * non-invalidating maps. Potential future improvement.] * * At this point, if the map is to be done directly, we pass the parameters onto GL and return * the result, marking the map with status GLResourceRecord::Mapped_Ignore_Real. Note that this * means we have no idea what happens with the map, and the buffer contents after that are to us * undefined. * * If not, we will be intercepting the map. If it's read-only this is relatively simple to satisfy, * as we just need to fetch the current buffer contents and return the appropriately offsetted * pointer. [NB: Again our buffer contents should still be perfect here, this fetch may be * redundant.] The map status is recorded as GLResourceRecord::Mapped_Read * * At this point we are intercepting a map for write, and it depends on whether or not we are * capturing a frame or just idle. * * If idle the handling is relatively simple, we just offset the pointer and return, marking the * map as GLResourceRecord::Mapped_Write. Note that here we also increment a counter, and if this * counter reaches a high enough number (arbitrary limit), we mark the buffer as high-traffic so * that we'll stop intercepting maps and reduce overhead on this buffer. * * If frame capturing it is more complex. The backing store of the buffer must be preserved as it * will contain the contents at the start of the frame. Instead we allocate two shadow storage * copies on first use. Shadow storage [1] contains the 'current' contents of the buffer - * when first allocated, if the map is non-invalidating, it will be filled with the buffer contents * at that point. If the map is invalidating, it will be reset to 0xcc to help find bugs caused by * leaving valid data behind in invalidated buffer memory. * * Shadow buffer [0] is the buffer that is returned to the user code. Every time it is updated * with the contents of [1]. This way both buffers are always identical and contain the latest * buffer contents. These buffers are used later in unmap, but Map() will return the appropriately * offsetted pointer, and mark the map as GLResourceRecord::Mapped_Write. * * * glUnmapNamedBufferEXT: * * The unmap becomes an actual chunk for serialisation when necessary, so we'll discuss the handling * of the unmap call, and then how it is serialised. * * Unmap's handling varies depending on the status of the map, as set above in * glMapNamedBufferRangeEXT. * * GLResourceRecord::Unmapped is an error case, indicating we haven't had a corresponding Map() * call. * * GLResourceRecord::Mapped_Read is a no-op as we can just discard it, the pointer we returned from * Map() was into our backing store. * * GLResourceRecord::Mapped_Ignore_Real is likewise a no-op as the GL pointer was updated directly * by user code, we weren't involved. However if we are now capturing a frame, it indicates a Map() * was made before this frame began, so this frame cannot be captured - we will need to try again * next frame, where a map will not be allowed to go into GLResourceRecord::Mapped_Ignore_Real. * * GLResourceRecord::Mapped_Write is the only case that will generate a serialised unmap chunk. If * we are idle, then all we need to do is map the 'real' GL buffer, copy across our backing store, * and unmap. We only map the range that was modified. Then everything is complete as the user code * updated our backing store. If we are capturing a frame, then we go into the serialise function * and serialise out a chunk. * * Finally we set the map status back to GLResourceRecord::Unmapped. * * When serialising out a map, we serialise the details of the map (which buffer, offset, length) * and then for non-invalidating maps of >512 byte buffers we perform a difference compare between * the two shadow storage buffers that were set up in glMapNamedBufferRangeEXT. We then serialise * out a buffer of the difference segment, and on replay we map and update this segment of the * buffer. * * The reason for finding the actual difference segment is that many maps will be of a large region * or even the whole buffer, but only update a small section, perhaps once per drawcall. So * serialising the entirety of a large buffer many many times can rapidly inflate the size of the * log. The savings from this can be many GBs as if a 4MB buffer is updated 1000 times, each time * only updating 1KB, this is a difference between 1MB and 4000MB in written data, most of which is * redundant in the last case. * * * glFlushMappedNamedBufferRangeEXT: * * Now consider the specialisation of the above, for maps that have GL_MAP_FLUSH_EXPLICIT_BIT * enabled. * * For the most part, these maps can be treated very similarly to normal maps, however in the case * of unmapping we will skip creating an unmap chunk and instead just allow the unmap to be * discarded. Instead we will serialise out a chunk for each glFlushMappedNamedBufferRangeEXT call. * We will also include flush explicit maps along with the others that we choose to map directly * when possible - so if we're capturing idle a flush explicit map will go straight to GL and be * handled as with GLResourceRecord::Mapped_Ignore_Real above. * * For this reason, if a map status is GLResourceRecord::Mapped_Ignore_Real then we simply pass the * flush range along to real GL. Again if we are capturing a frame now, this map has been 'missed' * and we must try again next frame to capture. Likewise as with Unmap GLResourceRecord::Unmapped is * an error, and for flushing we do not need to consider GLResourceRecord::Mapped_Read (it doesn't * make sense for this case). * * So we only serialise out a flush chunk if we are capturing a frame, and the map is correctly * GLResourceRecord::Mapped_Write. We clamp the flushed range to the size of the map (in case the * user code didn't do this). Unlike map we do not perform any difference compares, but rely on the * user to only flush the minimal range, and serialise the entire range out as a buffer. We also * update the shadow storage buffers so that if the buffer is subsequently mapped without flush * explicit, we have the 'current' contents to perform accurate compares with. * * * * * * Persistant maps: * * The above process handles "normal" maps that happen between other GL commands that use the buffer * contents. Maps that are persistent need to be handled carefully since there are other knock-ons * for correctness and proper tracking. They come in two major forms - coherent and non-coherent. * * Non-coherent maps are the 'easy' case, and in all cases should be recommended whenever users do * persistent mapping. Indeed because of the implementation details, coherent maps may come at a * performance penalty even when RenderDoc is not used and it is simply the user code using GL * directly. * * The important thing is that persistent maps *must always* be intercepted regardless of * circumstance, as in theory they may never be mapped again. We get hints to help us with these * maps, as the buffers must have been created with glBufferStorage and must have the matching * persistent and optionally coherent bits set in the flags bitfield. * * Note also that non-coherent maps tend to go hand in hand with flush explicit maps (although this * is not guaranteed, it is highly likely). * * Non-coherent mappable buffers are GL-mapped on creation, and remain GL-mapped until their * destruction regardless of what user code does. We keep this 'real' GL-mapped buffer around * permanently but it is never returned to user code. Instead we handle maps otherwise as above * (taking care to always intercept), and return the user a pointer to our backing store. Then every * time a map flush happens instead of temporarily mapping and unmapping the GL buffer, we copy into * the appropriate place in our persistent map pointer. If an unmap happens and the map wasn't * flush-explicit, we copy the mapped region then. In this way we maintain correctness - the copies * are "delayed" by the time between user code writing into our memory, and us copying into the real * memory. However this is valid as it happens synchronously with a flush, unmap or other event and * by definition non-coherent maps aren't visible to the GPU until after those operations. * * There is also the function glMemoryBarrier with bit GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT. This has * the effect of acting as if all currently persistent-mapped regions were simultaneously flushed. * This is exactly how we implement it - we store a list of all current user persistent maps and any * time this bit is passed to glMemoryBarrier, we manually call into * glFlushMappedNamedBufferRangeEXT() with the appropriate parameters and handling is otherwise * identical. * * The final piece of the puzzle is coherent mapped buffers. Since we must break the coherency * carefully (see below), we map coherent buffers as non-coherent at creation time, the same as * above. * * To satisfy the demands of being coherent, we need to transparently propogate any changes between * the user written data and the 'real' memory, without any call to intercept - there would be no * need to call glMemoryBarrier or glFlushMappedNamedBufferRangeEXT. To do this, we have shadow * storage allocated as in the "normal" mapping path all the time, and we insert a manual call to * essentially the same code as glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT) in every * intercepted function call that could depend on the results of the buffer. We then check if any * write/change has happened by comparing to the shadow storage, and if so we perform a manual flush * of that changed region and update the shadow storage for next time. * * This "fake coherency" is the reason we can map the buffer as non-coherent, since we will be * performing copies and flushes manually to emulate the coherency to allow our interception in the * middle. * * By definition, there will be *many* of these places where the buffer results could be used, not * least any buffer copy, any texture copy (since a texture buffer could be created), any draw or * dispatch, etc. At each of these points there will be a cost for each coherent map of checking for * changes and it will scale with the size of the buffers. This is a large performance penalty but * one that can't be easily avoided. This is another reason why coherent maps should be avoided. * * Note that this also involves a behaviour change that affects correctness - a user write to memory * is not visible as soon as the write happens, but only on the next api point where the write could * have an effect. In correct code this should not be a problem as relying on any other behaviour * would be impossible - if you wrote into memory expecting commands in flight to be affected you * could not ensure correct ordering. However, obvious from that description, this is precisely a * race condition bug if user code did do that - which means race condition bugs will be hidden by * the nature of this tracing. This is unavoidable without the extreme performance hit of making all * coherent maps read-write, and performing a read-back at every sync point to find every change. * Which by itself may also hide race conditions anyway. * * * Implementation notes: * * The record->Map.ptr is the *offsetted* pointer, ie. a pointer to the beginning of the mapped * region, at record->Map.offset bytes from the start of the buffer. * * record->Map.persistentPtr points to the *base* of the buffer, not offsetted by any current map. * * Likewise the shadow storage pointers point to the base of a buffer-sized allocation each. * ************************************************************************/ void *WrappedOpenGL::glMapNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access) { // see above for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); bool directMap = false; // first check if we've already given up on these buffers if(IsBackgroundCapturing(m_State) && m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end()) directMap = true; if(!directMap && IsBackgroundCapturing(m_State) && GetResourceManager()->IsResourceDirty(record->GetResourceID())) directMap = true; bool invalidateMap = (access & (GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_INVALIDATE_RANGE_BIT)) != 0; bool flushExplicitMap = (access & GL_MAP_FLUSH_EXPLICIT_BIT) != 0; // if this map is writing and doesn't invalidate, or is flush explicit, map directly if(!directMap && (!invalidateMap || flushExplicitMap) && (access & GL_MAP_WRITE_BIT) && IsBackgroundCapturing(m_State)) directMap = true; // persistent maps must ALWAYS be intercepted if((access & GL_MAP_PERSISTENT_BIT) || record->Map.persistentPtr) directMap = false; bool verifyWrite = (RenderDoc::Inst().GetCaptureOptions().verifyMapWrites != 0); // must also intercept to verify writes if(verifyWrite) directMap = false; if(directMap) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } record->Map.offset = offset; record->Map.length = length; record->Map.access = access; record->Map.invalidate = invalidateMap; record->Map.verifyWrite = verifyWrite; // store a list of all persistent maps, and subset of all coherent maps if(access & GL_MAP_PERSISTENT_BIT) { Atomic::Inc64(&record->Map.persistentMaps); m_PersistentMaps.insert(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.insert(record); } // if we're doing a direct map, pass onto GL and return if(directMap) { record->Map.ptr = (byte *)m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access); record->Map.status = GLResourceRecord::Mapped_Ignore_Real; return record->Map.ptr; } // only squirrel away read-only maps, read-write can just be treated as write-only if((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == GL_MAP_READ_BIT) { byte *ptr = record->GetDataPtr(); if(record->Map.persistentPtr) ptr = record->GetShadowPtr(0); RDCASSERT(ptr); ptr += offset; m_Real.glGetNamedBufferSubDataEXT(buffer, offset, length, ptr); record->Map.ptr = ptr; record->Map.status = GLResourceRecord::Mapped_Read; return ptr; } // below here, handle write maps to the backing store byte *ptr = record->GetDataPtr(); RDCASSERT(ptr); { // persistent maps get particular handling if(access & GL_MAP_PERSISTENT_BIT) { // persistent pointers are always into the shadow storage, this way we can use the backing // store for 'initial' buffer contents as with any other buffer. We also need to keep a // comparison & modified buffer in case the application calls glMemoryBarrier(..) at any // time. // if we're invalidating, mark the whole range as 0xcc if(invalidateMap) { memset(record->GetShadowPtr(0) + offset, 0xcc, length); memset(record->GetShadowPtr(1) + offset, 0xcc, length); } record->Map.ptr = ptr = record->GetShadowPtr(0) + offset; record->Map.status = GLResourceRecord::Mapped_Write; } else if(IsActiveCapturing(m_State)) { byte *shadow = (byte *)record->GetShadowPtr(0); // if we don't have a shadow pointer, need to allocate & initialise if(shadow == NULL) { GLint buflength; m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength); // allocate our shadow storage record->AllocShadowStorage(buflength); shadow = (byte *)record->GetShadowPtr(0); // if we're not invalidating, we need the existing contents if(!invalidateMap) { // need to fetch the whole buffer's contents, not just the mapped range, // as next time we won't re-fetch and might need the rest of the contents if(GetResourceManager()->IsResourceDirty(record->GetResourceID())) { // Perhaps we could get these contents from the frame initial state buffer? m_Real.glGetNamedBufferSubDataEXT(buffer, 0, buflength, shadow); } else { memcpy(shadow, record->GetDataPtr(), buflength); } } // copy into second shadow buffer ready for comparison later memcpy(record->GetShadowPtr(1), shadow, buflength); } // if we're invalidating, mark the whole range as 0xcc if(invalidateMap) { memset(shadow + offset, 0xcc, length); memset(record->GetShadowPtr(1) + offset, 0xcc, length); } record->Map.ptr = ptr = shadow + offset; record->Map.status = GLResourceRecord::Mapped_Write; } else if(IsBackgroundCapturing(m_State)) { if(verifyWrite) { byte *shadow = record->GetShadowPtr(0); GLint buflength; m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength); // if we don't have a shadow pointer, need to allocate & initialise if(shadow == NULL) { // allocate our shadow storage record->AllocShadowStorage(buflength); shadow = (byte *)record->GetShadowPtr(0); } // if we're not invalidating, we need the existing contents if(!invalidateMap) memcpy(shadow, record->GetDataPtr(), buflength); else memset(shadow + offset, 0xcc, length); ptr = shadow; } // return buffer backing store pointer, offsetted ptr += offset; record->Map.ptr = ptr; record->Map.status = GLResourceRecord::Mapped_Write; record->UpdateCount++; // mark as high-traffic if we update it often enough if(record->UpdateCount > 60) { m_HighTrafficResources.insert(record->GetResourceID()); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } return ptr; } return m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access); } void *WrappedOpenGL::glMapNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access) { // only difference to EXT function is size parameter, so just upcast return glMapNamedBufferRangeEXT(buffer, offset, length, access); } void *WrappedOpenGL::glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record) return glMapNamedBufferRangeEXT(record->Resource.name, offset, length, access); RDCERR("glMapBufferRange: Couldn't get resource record for target %x - no buffer bound?", target); } return m_Real.glMapBufferRange(target, offset, length, access); } // the glMapBuffer functions are equivalent to glMapBufferRange - so we just pass through void *WrappedOpenGL::glMapNamedBufferEXT(GLuint buffer, GLenum access) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); if(record) { GLbitfield accessBits = 0; if(access == eGL_READ_ONLY) accessBits = eGL_MAP_READ_BIT; else if(access == eGL_WRITE_ONLY) accessBits = eGL_MAP_WRITE_BIT; else if(access == eGL_READ_WRITE) accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT; return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length, accessBits); } RDCERR("glMapNamedBufferEXT: Couldn't get resource record for buffer %x!", buffer); } return m_Real.glMapNamedBufferEXT(buffer, access); } void *WrappedOpenGL::glMapBuffer(GLenum target, GLenum access) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; if(record) { GLbitfield accessBits = 0; if(access == eGL_READ_ONLY) accessBits = eGL_MAP_READ_BIT; else if(access == eGL_WRITE_ONLY) accessBits = eGL_MAP_WRITE_BIT; else if(access == eGL_READ_WRITE) accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT; return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length, accessBits); } RDCERR("glMapBuffer: Couldn't get resource record for target %s - no buffer bound?", ToStr(target).c_str()); } return m_Real.glMapBuffer(target, access); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glUnmapNamedBufferEXT(SerialiserType &ser, GLuint bufferHandle) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled GLResourceRecord *record = NULL; if(ser.IsWriting()) record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)record->Map.offset); SERIALISE_ELEMENT_LOCAL(length, (uint64_t)record->Map.length); uint64_t diffStart = 0; uint64_t diffEnd = (size_t)length; byte *MapWrittenData = NULL; if(ser.IsWriting()) { MapWrittenData = record->Map.ptr; if(IsActiveCapturing(m_State) && // don't bother checking diff range for tiny buffers length > 512 && // if the map has a sub-range specified, trust the user to have specified // a minimal range, similar to glFlushMappedBufferRange, so don't find diff // range. record->Map.offset == 0 && length == record->Length && // similarly for invalidate maps, we want to update the whole buffer !record->Map.invalidate) { size_t s = (size_t)diffStart; size_t e = (size_t)diffEnd; bool found = FindDiffRange(record->Map.ptr, record->GetShadowPtr(1) + offset, (size_t)length, s, e); diffStart = (uint64_t)s; diffEnd = (uint64_t)e; if(found) { #if ENABLED(RDOC_DEVEL) static uint64_t saved = 0; saved += length - (diffEnd - diffStart); RDCDEBUG( "Mapped resource size %llu, difference: %llu -> %llu. Total bytes saved so far: %llu", length, diffStart, diffEnd, saved); #endif length = diffEnd - diffStart; } else { diffStart = 0; diffEnd = 0; length = 1; } // update the data pointer to be rebased to the start of the diff data. MapWrittenData += diffStart; } // update shadow stores for future diff'ing if(IsActiveCapturing(m_State) && record->GetShadowPtr(1)) { memcpy(record->GetShadowPtr(1) + (size_t)offset + (size_t)diffStart, MapWrittenData, size_t(diffEnd - diffStart)); } } SERIALISE_ELEMENT(diffStart); SERIALISE_ELEMENT(diffEnd); SERIALISE_ELEMENT_ARRAY(MapWrittenData, length); SERIALISE_CHECK_READ_ERRORS(); if(!IsStructuredExporting(m_State) && diffEnd > diffStart) { if(record && record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + (size_t)offset + (size_t)diffStart, record->Map.ptr + (size_t)diffStart, size_t(diffEnd - diffStart)); m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, GLintptr(offset + diffStart), GLsizeiptr(diffEnd - diffStart)); } else if(MapWrittenData && length > 0) { void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)(offset + diffStart), GLsizeiptr(diffEnd - diffStart), GL_MAP_WRITE_BIT); memcpy(ptr, MapWrittenData, size_t(diffEnd - diffStart)); m_Real.glUnmapNamedBufferEXT(buffer.name); } } return true; } GLboolean WrappedOpenGL::glUnmapNamedBufferEXT(GLuint buffer) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); auto status = record->Map.status; if(IsActiveCapturing(m_State)) { m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); } GLboolean ret = GL_TRUE; switch(status) { case GLResourceRecord::Unmapped: RDCERR("Unmapped buffer being passed to glUnmapBuffer"); break; case GLResourceRecord::Mapped_Read: // can ignore break; case GLResourceRecord::Mapped_Ignore_Real: if(IsActiveCapturing(m_State)) { RDCERR( "Failed to cap frame - we saw an Unmap() that we didn't capture the corresponding " "Map() for"); m_SuccessfulCapture = false; m_FailureReason = CaptureFailed_UncappedUnmap; } // need to do the real unmap ret = m_Real.glUnmapNamedBufferEXT(buffer); break; case GLResourceRecord::Mapped_Write: { if(record->Map.verifyWrite) { if(!record->VerifyShadowStorage()) { string msg = StringFormat::Fmt( "Overwrite of %llu byte Map()'d buffer detected\n" "Breakpoint now to see callstack,\nor click 'Yes' to debugbreak.", record->Length); int res = tinyfd_messageBox("Map() overwrite detected!", msg.c_str(), "yesno", "error", 1); if(res == 1) { OS_DEBUG_BREAK(); } } // copy from shadow to backing store, so we're consistent memcpy(record->GetDataPtr() + record->Map.offset, record->Map.ptr, record->Map.length); } if(record->Map.access & GL_MAP_FLUSH_EXPLICIT_BIT) { // do nothing, any flushes that happened were handled, // and we won't do any other updates here or make a chunk. } else if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glUnmapNamedBufferEXT(ser, buffer); m_ContextRecord->AddChunk(scope.Get()); } else if(IsBackgroundCapturing(m_State)) { if(record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + record->Map.offset, record->Map.ptr, record->Map.length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer, record->Map.offset, record->Map.length); // update shadow storage memcpy(record->GetShadowPtr(1) + record->Map.offset, record->Map.ptr, record->Map.length); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } else { // if we are here for background capturing, the app wrote directly into our backing // store memory. Just need to copy the data across to GL, no other work needed void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer, (GLintptr)record->Map.offset, GLsizeiptr(record->Map.length), GL_MAP_WRITE_BIT); memcpy(ptr, record->Map.ptr, record->Map.length); m_Real.glUnmapNamedBufferEXT(buffer); } } break; } } // keep list of persistent & coherent maps up to date if we've // made the last unmap to a buffer if(record->Map.access & GL_MAP_PERSISTENT_BIT) { int64_t ref = Atomic::Dec64(&record->Map.persistentMaps); if(ref == 0) { m_PersistentMaps.erase(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.erase(record); } } record->Map.status = GLResourceRecord::Unmapped; return ret; } return m_Real.glUnmapNamedBufferEXT(buffer); } GLboolean WrappedOpenGL::glUnmapBuffer(GLenum target) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; if(record) return glUnmapNamedBufferEXT(record->Resource.name); RDCERR("glUnmapBuffer: Couldn't get resource record for target %s - no buffer bound?", ToStr(target).c_str()); } return m_Real.glUnmapBuffer(target); } // offsetPtr here is from the start of the buffer, not the mapped region template <typename SerialiserType> bool WrappedOpenGL::Serialise_glFlushMappedNamedBufferRangeEXT(SerialiserType &ser, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr lengthPtr) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(length, (uint64_t)lengthPtr); GLResourceRecord *record = NULL; byte *FlushedData = NULL; if(ser.IsWriting()) { record = GetResourceManager()->GetResourceRecord(buffer); FlushedData = record->Map.ptr + offset - record->Map.offset; // update the comparison buffer in case this buffer is subsequently mapped and we want to find // the difference region if(IsActiveCapturing(m_State) && record->GetShadowPtr(1)) { memcpy(record->GetShadowPtr(1) + (size_t)offset, FlushedData, (size_t)length); } } SERIALISE_ELEMENT_ARRAY(FlushedData, length); SERIALISE_CHECK_READ_ERRORS(); if(record && record->Map.persistentPtr) { // if we have a persistent mapped pointer, copy the range into the 'real' memory and // do a flush. Note the persistent pointer is always to the base of the buffer so we // need to account for the offset memcpy(record->Map.persistentPtr + (size_t)offset, record->Map.ptr + (size_t)(offset - record->Map.offset), (size_t)length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length); } else if(buffer.name && FlushedData && length > 0) { // perform a map of the range and copy the data, to emulate the modified region being flushed void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length, GL_MAP_WRITE_BIT); memcpy(ptr, FlushedData, (size_t)length); m_Real.glUnmapNamedBufferEXT(buffer.name); } return true; } void WrappedOpenGL::glFlushMappedNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length) { // see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record, buffer); // only need to pay attention to flushes when in capframe. Otherwise (see above) we // treat the map as a normal map, and let ALL modified regions go through, flushed or not, // as this is legal - modified but unflushed regions are 'undefined' so we can just say // that modifications applying is our undefined behaviour. // note that we only want to flush the range with GL if we've actually // mapped it. Otherwise the map is 'virtual' and just pointing to our backing store data if(record && record->Map.status == GLResourceRecord::Mapped_Ignore_Real) { m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length); } if(IsActiveCapturing(m_State)) { if(record) { m_MissingTracks.insert(record->GetResourceID()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_ReadBeforeWrite); if(record->Map.status == GLResourceRecord::Unmapped) { RDCWARN("Unmapped buffer being flushed, ignoring"); } else if(record->Map.status == GLResourceRecord::Mapped_Ignore_Real) { RDCERR( "Failed to cap frame - we saw an FlushMappedBuffer() that we didn't capture the " "corresponding Map() for"); m_SuccessfulCapture = false; m_FailureReason = CaptureFailed_UncappedUnmap; } else if(record->Map.status == GLResourceRecord::Mapped_Write) { if(offset < 0 || offset + length > record->Map.length) { RDCWARN("Flushed buffer range is outside of mapped range, clamping"); // maintain the length/end boundary of the flushed range if the flushed offset // is below the mapped range if(offset < 0) { offset = 0; length += offset; } // clamp the length if it's beyond the mapped range. if(offset + length > record->Map.length) { length = (record->Map.length - offset); } } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glFlushMappedNamedBufferRangeEXT(ser, buffer, record->Map.offset + offset, length); m_ContextRecord->AddChunk(scope.Get()); } // other statuses is GLResourceRecord::Mapped_Read } } else if(IsBackgroundCapturing(m_State)) { // if this is a flush of a persistent map, we need to copy through to // the real pointer and perform a real flush. if(record && record->Map.persistentPtr) { memcpy(record->Map.persistentPtr + record->Map.offset + offset, record->Map.ptr + offset, length); m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length); GetResourceManager()->MarkDirtyResource(record->GetResourceID()); } } } void WrappedOpenGL::glFlushMappedNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length) { // only difference to EXT function is size parameter, so just upcast glFlushMappedNamedBufferRangeEXT(buffer, offset, length); } void WrappedOpenGL::glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) { if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)]; RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record, target); if(record) return glFlushMappedNamedBufferRangeEXT(record->Resource.name, offset, length); RDCERR( "glFlushMappedBufferRange: Couldn't get resource record for target %x - no buffer bound?", target); } return m_Real.glFlushMappedBufferRange(target, offset, length); } void WrappedOpenGL::PersistentMapMemoryBarrier(const set<GLResourceRecord *> &maps) { PUSH_CURRENT_CHUNK; // this function iterates over all the maps, checking for any changes between // the shadow pointers, and propogates that to 'real' GL for(set<GLResourceRecord *>::const_iterator it = maps.begin(); it != maps.end(); ++it) { GLResourceRecord *record = *it; RDCASSERT(record && record->Map.persistentPtr); size_t diffStart = 0, diffEnd = 0; bool found = FindDiffRange(record->GetShadowPtr(0), record->GetShadowPtr(1), (size_t)record->Length, diffStart, diffEnd); if(found) { // update the modified region in the 'comparison' shadow buffer for next check memcpy(record->GetShadowPtr(1) + diffStart, record->GetShadowPtr(0) + diffStart, diffEnd - diffStart); // we use our own flush function so it will serialise chunks when necessary, and it // also handles copying into the persistent mapped pointer and flushing the real GL // buffer gl_CurChunk = GLChunk::glFlushMappedNamedBufferRangeEXT; glFlushMappedNamedBufferRangeEXT(record->Resource.name, GLintptr(diffStart), GLsizeiptr(diffEnd - diffStart)); } } } #pragma endregion #pragma region Transform Feedback template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenTransformFeedbacks(1, &real); m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, real); m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, 0); GLResource res = FeedbackRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(feedback, res); AddResource(feedback, ResourceType::StateObject, "Transform Feedback"); } return true; } void WrappedOpenGL::glGenTransformFeedbacks(GLsizei n, GLuint *ids) { SERIALISE_TIME_CALL(m_Real.glGenTransformFeedbacks(n, ids)); for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenTransformFeedbacks(ser, 1, ids + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateTransformFeedbacks(1, &real); GLResource res = FeedbackRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(feedback, res); AddResource(feedback, ResourceType::StateObject, "Transform Feedback"); } return true; } void WrappedOpenGL::glCreateTransformFeedbacks(GLsizei n, GLuint *ids) { SERIALISE_TIME_CALL(m_Real.glCreateTransformFeedbacks(n, ids)); for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateTransformFeedbacks(ser, 1, ids + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteTransformFeedbacks(GLsizei n, const GLuint *ids) { for(GLsizei i = 0; i < n; i++) { GLResource res = FeedbackRes(GetCtx(), ids[i]); if(GetResourceManager()->HasCurrentResource(res)) { GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteTransformFeedbacks(n, ids); } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glTransformFeedbackBufferBase(SerialiserType &ser, GLuint xfbHandle, GLuint index, GLuint bufferHandle) { SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the trivial way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glTransformFeedbackBufferBase(xfb.name, index, buffer.name); } return true; } void WrappedOpenGL::glTransformFeedbackBufferBase(GLuint xfb, GLuint index, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferBase(xfb, index, buffer)); if(IsCaptureMode(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTransformFeedbackBufferBase(ser, xfb, index, buffer); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer), eFrameRef_ReadBeforeWrite); } else if(xfb != 0) { GLResourceRecord *fbrecord = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb)); fbrecord->AddChunk(scope.Get()); if(buffer != 0) fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer))); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glTransformFeedbackBufferRange(SerialiserType &ser, GLuint xfbHandle, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr) { SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glTransformFeedbackBufferRange(xfb.name, index, buffer.name, (GLintptr)offset, (GLsizei)size); } return true; } void WrappedOpenGL::glTransformFeedbackBufferRange(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferRange(xfb, index, buffer, offset, size)); if(IsCaptureMode(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTransformFeedbackBufferRange(ser, xfb, index, buffer, offset, size); if(IsActiveCapturing(m_State)) { m_ContextRecord->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer), eFrameRef_ReadBeforeWrite); } else if(xfb != 0) { GLResourceRecord *fbrecord = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb)); fbrecord->AddChunk(scope.Get()); if(buffer != 0) fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer))); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindTransformFeedback(SerialiserType &ser, GLenum target, GLuint xfbHandle) { SERIALISE_ELEMENT(target); SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBindTransformFeedback(target, xfb.name); } return true; } void WrappedOpenGL::glBindTransformFeedback(GLenum target, GLuint id) { SERIALISE_TIME_CALL(m_Real.glBindTransformFeedback(target, id)); GLResourceRecord *record = NULL; if(IsCaptureMode(m_State)) { if(id == 0) { GetCtxData().m_FeedbackRecord = record = NULL; } else { GetCtxData().m_FeedbackRecord = record = GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), id)); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindTransformFeedback(ser, target, id); m_ContextRecord->AddChunk(scope.Get()); if(record) GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBeginTransformFeedback(SerialiserType &ser, GLenum primitiveMode) { SERIALISE_ELEMENT(primitiveMode); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { m_Real.glBeginTransformFeedback(primitiveMode); m_ActiveFeedback = true; } return true; } void WrappedOpenGL::glBeginTransformFeedback(GLenum primitiveMode) { SERIALISE_TIME_CALL(m_Real.glBeginTransformFeedback(primitiveMode)); m_ActiveFeedback = true; if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBeginTransformFeedback(ser, primitiveMode); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glPauseTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glPauseTransformFeedback(); } return true; } void WrappedOpenGL::glPauseTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glPauseTransformFeedback()); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glPauseTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glResumeTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glResumeTransformFeedback(); } return true; } void WrappedOpenGL::glResumeTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glResumeTransformFeedback()); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glResumeTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glEndTransformFeedback(SerialiserType &ser) { if(IsReplayingAndReading()) { m_Real.glEndTransformFeedback(); m_ActiveFeedback = false; } return true; } void WrappedOpenGL::glEndTransformFeedback() { SERIALISE_TIME_CALL(m_Real.glEndTransformFeedback()); m_ActiveFeedback = false; if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEndTransformFeedback(ser); m_ContextRecord->AddChunk(scope.Get()); } } #pragma endregion #pragma region Vertex Arrays // NOTE: In each of the vertex array object functions below, we might not have the live buffer // resource if it's is a pre-capture chunk, and the buffer was never referenced at all in the actual // frame. // The reason for this is that the VAO record doesn't add a parent of the buffer record - because // that parent tracking quickly becomes stale with high traffic VAOs ignoring updates etc, so we // don't rely on the parent connection and manually reference the buffer wherever it is actually // used. template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribOffsetEXT( SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj.name, buffer.name, index, size, type, // normalized, stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, index, size, type, normalized, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj, buffer, index, size, type, normalized, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribOffsetEXT(ser, vaobj, buffer, index, size, type, normalized, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribPointer(index, size, type, normalized, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribOffsetEXT( ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, normalized, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIOffsetEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type, // stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, index, size, type, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribIOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj, buffer, index, size, type, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, vaobj, buffer, index, size, type, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribIPointer(index, size, type, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLOffsetEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offsetPtr) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(stride); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE) // unless the VAO is also bound when performing EXT_dsa functions :( GLuint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO); m_Real.glBindVertexArray(vaobj.name); // seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO // initial states. Since the spec defines how this function should work in terms of new style // bindings, just do that ourselves. // m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type, // stride, (GLintptr)offset); m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, index, size, type, 0); m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index); if(stride == 0) { GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA; stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type); } if(buffer.name == 0) { // ES allows client-memory pointers, which we override with temp buffers during capture. // For replay, discard these pointers to prevent driver complaining about "negative offsets". offset = 0; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride); m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribLOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribLOffsetEXT(vaobj, buffer, index, size, type, stride, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, vaobj, buffer, index, size, type, stride, offset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer) { SERIALISE_TIME_CALL(m_Real.glVertexAttribLPointer(index, size, type, stride, pointer)); if(IsCaptureMode(m_State)) { ContextData &cd = GetCtxData(); GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)]; GLResourceRecord *varecord = cd.m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0, index, size, type, stride, (GLintptr)pointer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribBindingEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLuint bindingindex) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(bindingindex); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, attribindex, bindingindex); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribBindingEXT(GLuint vaobj, GLuint attribindex, GLuint bindingindex) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribBindingEXT(vaobj, attribindex, bindingindex)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribBindingEXT(ser, vaobj, attribindex, bindingindex); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribBinding(GLuint attribindex, GLuint bindingindex) { SERIALISE_TIME_CALL(m_Real.glVertexAttribBinding(attribindex, bindingindex)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribBindingEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, bindingindex); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, attribindex, size, type, normalized, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribFormatEXT(vaobj, attribindex, size, type, normalized, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribFormatEXT(ser, vaobj, attribindex, size, type, normalized, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexAttribFormat(attribindex, size, type, normalized, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, normalized, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, attribindex, size, type, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribIFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj, attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIFormatEXT(ser, vaobj, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexAttribIFormat(attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribIFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLFormatEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(attribindex); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(relativeoffset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, attribindex, size, type, relativeoffset); } return true; } void WrappedOpenGL::glVertexArrayVertexAttribLFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj, attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLFormatEXT(ser, vaobj, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribLFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset) { SERIALISE_TIME_CALL(m_Real.glVertexAttribLFormat(attribindex, size, type, relativeoffset)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribLFormatEXT(ser, varecord ? varecord->Resource.name : 0, attribindex, size, type, relativeoffset); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribDivisorEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index, GLuint divisor) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_ELEMENT(divisor); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // at the time of writing, AMD driver seems to not have this entry point if(m_Real.glVertexArrayVertexAttribDivisorEXT) { m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj.name, index, divisor); } else { GLuint VAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO); m_Real.glBindVertexArray(vaobj.name); m_Real.glVertexAttribDivisor(index, divisor); m_Real.glBindVertexArray(VAO); } } return true; } void WrappedOpenGL::glVertexArrayVertexAttribDivisorEXT(GLuint vaobj, GLuint index, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj, index, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribDivisorEXT(ser, vaobj, index, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexAttribDivisor(GLuint index, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexAttribDivisor(index, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexAttribDivisorEXT(ser, varecord ? varecord->Resource.name : 0, index, divisor); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glEnableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; GLint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO); m_Real.glEnableVertexArrayAttribEXT(vaobj.name, index); // nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it // seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled. m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glEnableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { SERIALISE_TIME_CALL(m_Real.glEnableVertexArrayAttribEXT(vaobj, index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEnableVertexArrayAttribEXT(ser, vaobj, index); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glEnableVertexAttribArray(GLuint index) { SERIALISE_TIME_CALL(m_Real.glEnableVertexAttribArray(index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glEnableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glDisableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint index) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(index); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; GLint prevVAO = 0; m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO); m_Real.glDisableVertexArrayAttribEXT(vaobj.name, index); // nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it // seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled. m_Real.glBindVertexArray(prevVAO); } return true; } void WrappedOpenGL::glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { SERIALISE_TIME_CALL(m_Real.glDisableVertexArrayAttribEXT(vaobj, index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glDisableVertexArrayAttribEXT(ser, vaobj, index); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glDisableVertexAttribArray(GLuint index) { SERIALISE_TIME_CALL(m_Real.glDisableVertexAttribArray(index)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glDisableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glGenVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glGenVertexArrays(1, &real); m_Real.glBindVertexArray(real); m_Real.glBindVertexArray(0); GLResource res = VertexArrayRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(array, res); AddResource(array, ResourceType::StateObject, "Vertex Array"); } return true; } void WrappedOpenGL::glGenVertexArrays(GLsizei n, GLuint *arrays) { SERIALISE_TIME_CALL(m_Real.glGenVertexArrays(n, arrays)); for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenVertexArrays(ser, 1, arrays + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glCreateVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays))) .TypedAs("GLResource"); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint real = 0; m_Real.glCreateVertexArrays(1, &real); GLResource res = VertexArrayRes(GetCtx(), real); m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(array, res); AddResource(array, ResourceType::StateObject, "Vertex Array"); } return true; } void WrappedOpenGL::glCreateVertexArrays(GLsizei n, GLuint *arrays) { SERIALISE_TIME_CALL(m_Real.glCreateVertexArrays(n, arrays)); for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateVertexArrays(ser, 1, arrays + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glBindVertexArray(SerialiserType &ser, GLuint vaobjHandle) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glBindVertexArray(vaobj.name); } return true; } void WrappedOpenGL::glBindVertexArray(GLuint array) { SERIALISE_TIME_CALL(m_Real.glBindVertexArray(array)); GLResourceRecord *record = NULL; if(IsCaptureMode(m_State)) { if(array == 0) { GetCtxData().m_VertexArrayRecord = record = NULL; } else { GetCtxData().m_VertexArrayRecord = record = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), array)); } } if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glBindVertexArray(ser, array); m_ContextRecord->AddChunk(scope.Get()); if(record) GetResourceManager()->MarkVAOReferenced(record->Resource, eFrameRef_ReadBeforeWrite); } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayElementBuffer(SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; // might not have the live resource if this is a pre-capture chunk, and the buffer was never // referenced at all in the actual frame if(buffer.name) { m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ELEMENT_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Index; } // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glVertexArrayElementBuffer(vaobj.name, buffer.name); } return true; } void WrappedOpenGL::glVertexArrayElementBuffer(GLuint vaobj, GLuint buffer) { SERIALISE_TIME_CALL(m_Real.glVertexArrayElementBuffer(vaobj, buffer)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayElementBuffer(ser, vaobj, buffer); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayBindVertexBufferEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bindingindex, GLuint bufferHandle, GLintptr offsetPtr, GLsizei stride) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(bindingindex); SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr); SERIALISE_ELEMENT(stride); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; if(buffer.name) { m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Vertex; } m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, bindingindex, buffer.name, (GLintptr)offset, (GLsizei)stride); } return true; } void WrappedOpenGL::glVertexArrayBindVertexBufferEXT(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride) { SERIALISE_TIME_CALL( m_Real.glVertexArrayBindVertexBufferEXT(vaobj, bindingindex, buffer, offset, stride)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayBindVertexBufferEXT(ser, vaobj, bindingindex, buffer, offset, stride); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride) { SERIALISE_TIME_CALL(m_Real.glBindVertexBuffer(bindingindex, buffer, offset, stride)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); if(IsActiveCapturing(m_State) && bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayBindVertexBufferEXT(ser, varecord ? varecord->Resource.name : 0, bindingindex, buffer, offset, stride); r->AddChunk(scope.Get()); } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexBuffers(SerialiserType &ser, GLuint vaobjHandle, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsetPtrs, const GLsizei *strides) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. // Likewise need to upcast the offsets to 64-bit instead of serialising as-is. std::vector<GLResource> buffers; std::vector<uint64_t> offsets; if(ser.IsWriting() && bufferHandles) { buffers.reserve(count); for(GLsizei i = 0; i < count; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles[i])); } if(ser.IsWriting() && offsetPtrs) { offsets.reserve(count); for(GLsizei i = 0; i < count; i++) offsets.push_back((uint64_t)offsetPtrs[i]); } SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(first); SERIALISE_ELEMENT(count); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(offsets); SERIALISE_ELEMENT_ARRAY(strides, count); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { std::vector<GLuint> bufs; std::vector<GLintptr> offs; if(!buffers.empty()) { bufs.reserve(count); for(GLsizei i = 0; i < count; i++) bufs.push_back(buffers[i].name); } if(!offsets.empty()) { offs.reserve(count); for(GLsizei i = 0; i < count; i++) offs.push_back((GLintptr)offsets[i]); } if(vaobj.name == 0) vaobj.name = m_FakeVAO; // use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If // we are running without ARB_dsa support, these functions are emulated in the obvious way. This // is necessary since these functions can be serialised even if ARB_dsa was not used originally, // and we need to support this case. m_Real.glVertexArrayVertexBuffers(vaobj.name, first, count, bufs.empty() ? NULL : bufs.data(), offs.empty() ? NULL : offs.data(), strides); if(IsLoading(m_State)) { for(GLsizei i = 0; i < count; i++) { m_Buffers[GetResourceManager()->GetID(buffers[i])].curType = eGL_ARRAY_BUFFER; m_Buffers[GetResourceManager()->GetID(buffers[i])].creationFlags |= BufferCategory::Vertex; } } } return true; } void WrappedOpenGL::glVertexArrayVertexBuffers(GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides) { SERIALISE_TIME_CALL( m_Real.glVertexArrayVertexBuffers(vaobj, first, count, buffers, offsets, strides)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBuffers(ser, vaobj, first, count, buffers, offsets, strides); r->AddChunk(scope.Get()); } if(IsActiveCapturing(m_State)) { for(GLsizei i = 0; i < count; i++) { if(buffers != NULL && buffers[i] != 0) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); if(bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); } } } } } } void WrappedOpenGL::glBindVertexBuffers(GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides) { SERIALISE_TIME_CALL(m_Real.glBindVertexBuffers(first, count, buffers, offsets, strides)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBuffers(ser, varecord ? varecord->Resource.name : 0, first, count, buffers, offsets, strides); r->AddChunk(scope.Get()); } if(IsActiveCapturing(m_State)) { for(GLsizei i = 0; i < count; i++) { if(buffers != NULL && buffers[i] != 0) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i])); if(bufrecord) GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read); } } } } } } template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexArrayVertexBindingDivisorEXT(SerialiserType &ser, GLuint vaobjHandle, GLuint bindingindex, GLuint divisor) { SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle)); SERIALISE_ELEMENT(bindingindex); SERIALISE_ELEMENT(divisor); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(vaobj.name == 0) vaobj.name = m_FakeVAO; m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj.name, bindingindex, divisor); } return true; } void WrappedOpenGL::glVertexArrayVertexBindingDivisorEXT(GLuint vaobj, GLuint bindingindex, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj, bindingindex, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj)); GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBindingDivisorEXT(ser, vaobj, bindingindex, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glVertexBindingDivisor(GLuint bindingindex, GLuint divisor) { SERIALISE_TIME_CALL(m_Real.glVertexBindingDivisor(bindingindex, divisor)); if(IsCaptureMode(m_State)) { GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord; GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord; if(r) { if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord)) return; if(IsActiveCapturing(m_State) && varecord) GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite); { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glVertexArrayVertexBindingDivisorEXT(ser, varecord ? varecord->Resource.name : 0, bindingindex, divisor); r->AddChunk(scope.Get()); } } } } void WrappedOpenGL::glDeleteBuffers(GLsizei n, const GLuint *buffers) { for(GLsizei i = 0; i < n; i++) { GLResource res = BufferRes(GetCtx(), buffers[i]); if(GetResourceManager()->HasCurrentResource(res)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(res); if(record) { // if we have a persistent pointer, make sure to unmap it if(record->Map.persistentPtr) { m_PersistentMaps.erase(record); if(record->Map.access & GL_MAP_COHERENT_BIT) m_CoherentMaps.erase(record); m_Real.glUnmapNamedBufferEXT(res.name); } // free any shadow storage record->FreeShadowStorage(); } GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteBuffers(n, buffers); } void WrappedOpenGL::glDeleteVertexArrays(GLsizei n, const GLuint *arrays) { for(GLsizei i = 0; i < n; i++) { GLResource res = VertexArrayRes(GetCtx(), arrays[i]); if(GetResourceManager()->HasCurrentResource(res)) { GetResourceManager()->MarkCleanResource(res); if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } m_Real.glDeleteVertexArrays(n, arrays); } #pragma endregion #pragma region Horrible glVertexAttrib variants template <typename SerialiserType> bool WrappedOpenGL::Serialise_glVertexAttrib(SerialiserType &ser, GLuint index, int count, GLenum type, GLboolean normalized, const void *value, AttribType attribtype) { // this is used to share serialisation code amongst the brazillion variations SERIALISE_ELEMENT(attribtype).Hidden(); AttribType attr = AttribType(attribtype & Attrib_typemask); // this is the number of components in the attribute (1,2,3,4). We hide it because it's part of // the function signature SERIALISE_ELEMENT(count).Hidden(); SERIALISE_ELEMENT(index); // only serialise the type and normalized flags for packed commands if(attr == Attrib_packed) { SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_TYPED(bool, normalized); } // create a union of all the value types - since we can only have up to 4, we can just make it // fixed size union { double d[4]; float f[4]; int32_t i32[4]; uint32_t u32[4]; int16_t i16[4]; uint16_t u16[4]; int8_t i8[4]; uint8_t u8[4]; } v; if(ser.IsWriting()) { uint32_t byteCount = count; if(attr == Attrib_GLbyte) byteCount *= sizeof(char); else if(attr == Attrib_GLshort) byteCount *= sizeof(int16_t); else if(attr == Attrib_GLint) byteCount *= sizeof(int32_t); else if(attr == Attrib_GLubyte) byteCount *= sizeof(unsigned char); else if(attr == Attrib_GLushort) byteCount *= sizeof(uint16_t); else if(attr == Attrib_GLuint || attr == Attrib_packed) byteCount *= sizeof(uint32_t); RDCEraseEl(v); memcpy(v.f, value, byteCount); } // Serialise the array with the right type. We don't want to allocate new storage switch(attr) { case Attrib_GLdouble: ser.Serialise("values", v.d, SerialiserFlags::NoFlags); break; case Attrib_GLfloat: ser.Serialise("values", v.f, SerialiserFlags::NoFlags); break; case Attrib_GLint: ser.Serialise("values", v.i32, SerialiserFlags::NoFlags); break; case Attrib_packed: case Attrib_GLuint: ser.Serialise("values", v.u32, SerialiserFlags::NoFlags); break; case Attrib_GLshort: ser.Serialise("values", v.i16, SerialiserFlags::NoFlags); break; case Attrib_GLushort: ser.Serialise("values", v.u16, SerialiserFlags::NoFlags); break; case Attrib_GLbyte: ser.Serialise("values", v.i8, SerialiserFlags::NoFlags); break; default: case Attrib_GLubyte: ser.Serialise("values", v.u8, SerialiserFlags::NoFlags); break; } SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { if(attr == Attrib_packed) { if(count == 1) m_Real.glVertexAttribP1uiv(index, type, normalized, v.u32); else if(count == 2) m_Real.glVertexAttribP2uiv(index, type, normalized, v.u32); else if(count == 3) m_Real.glVertexAttribP3uiv(index, type, normalized, v.u32); else if(count == 4) m_Real.glVertexAttribP4uiv(index, type, normalized, v.u32); } else if(attribtype & Attrib_I) { if(count == 1) { if(attr == Attrib_GLint) m_Real.glVertexAttribI1iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI1uiv(index, v.u32); } else if(count == 2) { if(attr == Attrib_GLint) m_Real.glVertexAttribI2iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI2uiv(index, v.u32); } else if(count == 3) { if(attr == Attrib_GLint) m_Real.glVertexAttribI3iv(index, v.i32); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI3uiv(index, v.u32); } else { if(attr == Attrib_GLbyte) m_Real.glVertexAttribI4bv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttribI4sv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttribI4iv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttribI4ubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttribI4usv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttribI4uiv(index, v.u32); } } else if(attribtype & Attrib_L) { if(count == 1) m_Real.glVertexAttribL1dv(index, v.d); else if(count == 2) m_Real.glVertexAttribL2dv(index, v.d); else if(count == 3) m_Real.glVertexAttribL3dv(index, v.d); else if(count == 4) m_Real.glVertexAttribL4dv(index, v.d); } else if(attribtype & Attrib_N) { if(attr == Attrib_GLbyte) m_Real.glVertexAttrib4Nbv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib4Nsv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttrib4Niv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttrib4Nubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttrib4Nusv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttrib4Nuiv(index, v.u32); } else { if(count == 1) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib1dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib1fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib1sv(index, v.i16); } else if(count == 2) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib2dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib2fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib2sv(index, v.i16); } else if(count == 3) { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib3dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib3fv(index, v.f); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib3sv(index, v.i16); } else { if(attr == Attrib_GLdouble) m_Real.glVertexAttrib4dv(index, v.d); else if(attr == Attrib_GLfloat) m_Real.glVertexAttrib4fv(index, v.f); else if(attr == Attrib_GLbyte) m_Real.glVertexAttrib4bv(index, v.i8); else if(attr == Attrib_GLshort) m_Real.glVertexAttrib4sv(index, v.i16); else if(attr == Attrib_GLint) m_Real.glVertexAttrib4iv(index, v.i32); else if(attr == Attrib_GLubyte) m_Real.glVertexAttrib4ubv(index, v.u8); else if(attr == Attrib_GLushort) m_Real.glVertexAttrib4usv(index, v.u16); else if(attr == Attrib_GLuint) m_Real.glVertexAttrib4uiv(index, v.u32); } } } return true; } #define ATTRIB_FUNC(count, suffix, TypeOr, paramtype, ...) \ \ void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, __VA_ARGS__) \ \ { \ SERIALISE_TIME_CALL(m_Real.CONCAT(glVertexAttrib, suffix)(index, ARRAYLIST)); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ const paramtype vals[] = {ARRAYLIST}; \ Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, vals, \ AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } #define ARRAYLIST x ATTRIB_FUNC(1, 1f, 0, GLfloat, GLfloat x) ATTRIB_FUNC(1, 1s, 0, GLshort, GLshort x) ATTRIB_FUNC(1, 1d, 0, GLdouble, GLdouble x) ATTRIB_FUNC(1, L1d, Attrib_L, GLdouble, GLdouble x) ATTRIB_FUNC(1, I1i, Attrib_I, GLint, GLint x) ATTRIB_FUNC(1, I1ui, Attrib_I, GLuint, GLuint x) #undef ARRAYLIST #define ARRAYLIST x, y ATTRIB_FUNC(2, 2f, 0, GLfloat, GLfloat x, GLfloat y) ATTRIB_FUNC(2, 2s, 0, GLshort, GLshort x, GLshort y) ATTRIB_FUNC(2, 2d, 0, GLdouble, GLdouble x, GLdouble y) ATTRIB_FUNC(2, L2d, Attrib_L, GLdouble, GLdouble x, GLdouble y) ATTRIB_FUNC(2, I2i, Attrib_I, GLint, GLint x, GLint y) ATTRIB_FUNC(2, I2ui, Attrib_I, GLuint, GLuint x, GLuint y) #undef ARRAYLIST #define ARRAYLIST x, y, z ATTRIB_FUNC(3, 3f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z) ATTRIB_FUNC(3, 3s, 0, GLshort, GLshort x, GLshort y, GLshort z) ATTRIB_FUNC(3, 3d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z) ATTRIB_FUNC(3, L3d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z) ATTRIB_FUNC(3, I3i, Attrib_I, GLint, GLint x, GLint y, GLint z) ATTRIB_FUNC(3, I3ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z) #undef ARRAYLIST #define ARRAYLIST x, y, z, w ATTRIB_FUNC(4, 4f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z, GLfloat w) ATTRIB_FUNC(4, 4s, 0, GLshort, GLshort x, GLshort y, GLshort z, GLshort w) ATTRIB_FUNC(4, 4d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w) ATTRIB_FUNC(4, L4d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w) ATTRIB_FUNC(4, I4i, Attrib_I, GLint, GLint x, GLint y, GLint z, GLint w) ATTRIB_FUNC(4, I4ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z, GLuint w) ATTRIB_FUNC(4, 4Nub, Attrib_N, GLubyte, GLubyte x, GLubyte y, GLubyte z, GLubyte w) #undef ATTRIB_FUNC #define ATTRIB_FUNC(count, suffix, TypeOr, paramtype) \ \ void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, const paramtype *value) \ \ { \ m_Real.CONCAT(glVertexAttrib, suffix)(index, value); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, value, \ AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } ATTRIB_FUNC(1, 1dv, 0, GLdouble) ATTRIB_FUNC(2, 2dv, 0, GLdouble) ATTRIB_FUNC(3, 3dv, 0, GLdouble) ATTRIB_FUNC(4, 4dv, 0, GLdouble) ATTRIB_FUNC(1, 1sv, 0, GLshort) ATTRIB_FUNC(2, 2sv, 0, GLshort) ATTRIB_FUNC(3, 3sv, 0, GLshort) ATTRIB_FUNC(4, 4sv, 0, GLshort) ATTRIB_FUNC(1, 1fv, 0, GLfloat) ATTRIB_FUNC(2, 2fv, 0, GLfloat) ATTRIB_FUNC(3, 3fv, 0, GLfloat) ATTRIB_FUNC(4, 4fv, 0, GLfloat) ATTRIB_FUNC(4, 4bv, 0, GLbyte) ATTRIB_FUNC(4, 4iv, 0, GLint) ATTRIB_FUNC(4, 4uiv, 0, GLuint) ATTRIB_FUNC(4, 4usv, 0, GLushort) ATTRIB_FUNC(4, 4ubv, 0, GLubyte) ATTRIB_FUNC(1, L1dv, Attrib_L, GLdouble) ATTRIB_FUNC(2, L2dv, Attrib_L, GLdouble) ATTRIB_FUNC(3, L3dv, Attrib_L, GLdouble) ATTRIB_FUNC(4, L4dv, Attrib_L, GLdouble) ATTRIB_FUNC(1, I1iv, Attrib_I, GLint) ATTRIB_FUNC(1, I1uiv, Attrib_I, GLuint) ATTRIB_FUNC(2, I2iv, Attrib_I, GLint) ATTRIB_FUNC(2, I2uiv, Attrib_I, GLuint) ATTRIB_FUNC(3, I3iv, Attrib_I, GLint) ATTRIB_FUNC(3, I3uiv, Attrib_I, GLuint) ATTRIB_FUNC(4, I4bv, Attrib_I, GLbyte) ATTRIB_FUNC(4, I4iv, Attrib_I, GLint) ATTRIB_FUNC(4, I4sv, Attrib_I, GLshort) ATTRIB_FUNC(4, I4ubv, Attrib_I, GLubyte) ATTRIB_FUNC(4, I4uiv, Attrib_I, GLuint) ATTRIB_FUNC(4, I4usv, Attrib_I, GLushort) ATTRIB_FUNC(4, 4Nbv, Attrib_N, GLbyte) ATTRIB_FUNC(4, 4Niv, Attrib_N, GLint) ATTRIB_FUNC(4, 4Nsv, Attrib_N, GLshort) ATTRIB_FUNC(4, 4Nubv, Attrib_N, GLubyte) ATTRIB_FUNC(4, 4Nuiv, Attrib_N, GLuint) ATTRIB_FUNC(4, 4Nusv, Attrib_N, GLushort) #undef ATTRIB_FUNC #define ATTRIB_FUNC(count, suffix, funcparam, passparam) \ \ void WrappedOpenGL::CONCAT(CONCAT(glVertexAttribP, count), suffix)( \ GLuint index, GLenum type, GLboolean normalized, funcparam) \ \ { \ m_Real.CONCAT(CONCAT(glVertexAttribP, count), suffix)(index, type, normalized, value); \ \ if(IsActiveCapturing(m_State)) \ { \ USE_SCRATCH_SERIALISER(); \ SCOPED_SERIALISE_CHUNK(gl_CurChunk); \ Serialise_glVertexAttrib(ser, index, count, type, normalized, passparam, Attrib_packed); \ \ m_ContextRecord->AddChunk(scope.Get()); \ } \ } ATTRIB_FUNC(1, ui, GLuint value, &value) ATTRIB_FUNC(2, ui, GLuint value, &value) ATTRIB_FUNC(3, ui, GLuint value, &value) ATTRIB_FUNC(4, ui, GLuint value, &value) ATTRIB_FUNC(1, uiv, const GLuint *value, value) ATTRIB_FUNC(2, uiv, const GLuint *value, value) ATTRIB_FUNC(3, uiv, const GLuint *value, value) ATTRIB_FUNC(4, uiv, const GLuint *value, value) #pragma endregion INSTANTIATE_FUNCTION_SERIALISED(void, glGenBuffers, GLsizei n, GLuint *buffers); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateBuffers, GLsizei n, GLuint *buffers); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffer, GLenum target, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferStorageEXT, GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferDataEXT, GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferSubDataEXT, GLuint buffer, GLintptr offsetPtr, GLsizeiptr size, const void *data); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedCopyBufferSubDataEXT, GLuint readBufferHandle, GLuint writeBufferHandle, GLintptr readOffsetPtr, GLintptr writeOffsetPtr, GLsizeiptr sizePtr); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferBase, GLenum target, GLuint index, GLuint buffer); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferRange, GLenum target, GLuint index, GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersBase, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles); INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersRange, GLenum target, GLuint first, GLsizei count, const GLuint *bufferHandles, const GLintptr *offsets, const GLsizeiptr *sizes); INSTANTIATE_FUNCTION_SERIALISED(void, glUnmapNamedBufferEXT, GLuint buffer); INSTANTIATE_FUNCTION_SERIALISED(void, glFlushMappedNamedBufferRangeEXT, GLuint buffer, GLintptr offset, GLsizeiptr length); INSTANTIATE_FUNCTION_SERIALISED(void, glGenTransformFeedbacks, GLsizei n, GLuint *ids); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateTransformFeedbacks, GLsizei n, GLuint *ids); INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferBase, GLuint xfbHandle, GLuint index, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferRange, GLuint xfbHandle, GLuint index, GLuint bufferHandle, GLintptr offset, GLsizeiptr size); INSTANTIATE_FUNCTION_SERIALISED(void, glBindTransformFeedback, GLenum target, GLuint xfbHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glBeginTransformFeedback, GLenum primitiveMode); INSTANTIATE_FUNCTION_SERIALISED(void, glPauseTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glResumeTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glEndTransformFeedback); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLOffsetEXT, GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr pointer); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribBindingEXT, GLuint vaobj, GLuint attribindex, GLuint bindingindex); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLFormatEXT, GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribDivisorEXT, GLuint vaobj, GLuint index, GLuint divisor); INSTANTIATE_FUNCTION_SERIALISED(void, glEnableVertexArrayAttribEXT, GLuint vaobj, GLuint index); INSTANTIATE_FUNCTION_SERIALISED(void, glDisableVertexArrayAttribEXT, GLuint vaobj, GLuint index); INSTANTIATE_FUNCTION_SERIALISED(void, glGenVertexArrays, GLsizei n, GLuint *arrays); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateVertexArrays, GLsizei n, GLuint *arrays); INSTANTIATE_FUNCTION_SERIALISED(void, glBindVertexArray, GLuint arrayHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayElementBuffer, GLuint vaobjHandle, GLuint bufferHandle); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayBindVertexBufferEXT, GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBuffers, GLuint vaobjHandle, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBindingDivisorEXT, GLuint vaobj, GLuint bindingindex, GLuint divisor); INSTANTIATE_FUNCTION_SERIALISED(void, glVertexAttrib, GLuint index, int count, GLenum type, GLboolean normalized, const void *value, AttribType attribtype);
etnlGD/renderdoc
renderdoc/driver/gl/wrappers/gl_buffer_funcs.cpp
C++
mit
180,105
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Diagnostics.CodeAnalysis; using System.Text; using static Kernel32; /// <content> /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// </content> [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")] public static partial class Hid { public static Guid HidD_GetHidGuid() { Guid guid; HidD_GetHidGuid(out guid); return guid; } public static HiddAttributes HidD_GetAttributes(SafeObjectHandle hFile) { var result = HiddAttributes.Create(); if (!HidD_GetAttributes(hFile, ref result)) { throw new Win32Exception(); } return result; } public static SafePreparsedDataHandle HidD_GetPreparsedData(SafeObjectHandle hDevice) { SafePreparsedDataHandle preparsedDataHandle; if (!HidD_GetPreparsedData(hDevice, out preparsedDataHandle)) { throw new Win32Exception(); } return preparsedDataHandle; } public static HidpCaps HidP_GetCaps(SafePreparsedDataHandle preparsedData) { var hidCaps = default(HidpCaps); var result = HidP_GetCaps(preparsedData, ref hidCaps); switch (result.Value) { case NTSTATUS.Code.HIDP_STATUS_SUCCESS: return hidCaps; case NTSTATUS.Code.HIDP_STATUS_INVALID_PREPARSED_DATA: throw new ArgumentException("The specified preparsed data is invalid.", nameof(preparsedData)); default: result.ThrowOnError(); throw new InvalidOperationException("HidP_GetCaps returned an unexpected success value"); } } public static bool HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetManufacturerString(hidDeviceObject, sb, sb.Capacity), out result); } public static bool HidD_GetProductString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetProductString(hidDeviceObject, sb, sb.Capacity), out result); } public static bool HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => HidD_GetSerialNumberString(hidDeviceObject, sb, sb.Capacity), out result); } public static string HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetManufacturerString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string HidD_GetProductString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetProductString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject) { string result; if (!HidD_GetSerialNumberString(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } private static bool GrowStringBuffer(Func<StringBuilder, bool> nativeMethod, out string result) { // USB Hid maximum size is 126 wide chars + '\0' = 254 bytes, allocating 256 bytes we should never grow // until another HID standard decide otherwise. var stringBuilder = new StringBuilder(256); // If we ever resize over this value something got really wrong const int maximumRealisticSize = 1 * 1024 * 2014; while (stringBuilder.Capacity < maximumRealisticSize) { if (nativeMethod(stringBuilder)) { result = stringBuilder.ToString(); return true; } if (GetLastError() != Win32ErrorCode.ERROR_INVALID_USER_BUFFER) { result = null; return false; } stringBuilder.Capacity = stringBuilder.Capacity * 2; } result = null; return false; } } }
vbfox/pinvoke
src/Hid/Hid.Helpers.cs
C#
mit
5,014
#!/bin/sh java -jar sprint0.jar
CSC301H-Fall2013/ultrasound-in-remote-maternal-healthcare
sprints/sprint0/runSprint0.sh
Shell
mit
31
var searchData= [ ['player',['player',['../classplayer.html#a4c43d838817775e2a2b0241d30de4abc',1,'player']]] ];
gawag/Spooky-Urho-Sample
doxygen/html/search/functions_6.js
JavaScript
mit
114
// // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // using System; namespace nanoFramework.Tools.Debugger.Usb { // This class is kept here for reference only. // It was to provide backwards compatibility with NETMF WinUSB devices of v4.4 // In the current nanoFramework implementation USB connection with devices is carried using USB CDC public class STM_Discovery4 { public const UInt16 DeviceVid = 0x0483; public const UInt16 DevicePid = 0xA08F; /// <summary> /// USB device interface class GUID. For NETMF debug capable devices this must be {D32D1D64-963D-463E-874A-8EC8C8082CBF}. /// </summary> public static Guid DeviceInterfaceClass = new Guid("{D32D1D64-963D-463E-874A-8EC8C8082CBF}"); /// <summary> /// ID string for the device /// </summary> public static String IDString { get { return String.Format("VID_{0:X4}&PID_{1:X4}", DeviceVid, DevicePid); } } public static new string ToString() { return "ST Discovery4"; } } }
nanoframework/nf-debugger
nanoFramework.Tools.DebugLibrary.Shared/SupportedUSBDevices/STM_Discovery4.cs
C#
mit
1,181