text stringlengths 1 1.05M |
|---|
; A186575: Expansion of (1 + 2*x + 6*x^2)/(1 - x - x^2 - 2*x^3) in powers of x.
; 1,3,10,15,31,66,127,255,514,1023,2047,4098,8191,16383,32770,65535,131071,262146,524287,1048575,2097154,4194303,8388607,16777218,33554431,67108863,134217730,268435455,536870911,1073741826,2147483647,4294967295,8589934594,17179869183,34359738367,68719476738,137438953471,274877906943,549755813890,1099511627775,2199023255551,4398046511106,8796093022207,17592186044415,35184372088834,70368744177663,140737488355327,281474976710658,562949953421311,1125899906842623,2251799813685250,4503599627370495
mov $5,$0
mov $0,2
mov $2,3
mov $4,4
add $5,3
pow $0,$5
add $0,2
lpb $0
add $0,1
mov $1,$0
mov $0,2
mul $2,$1
mul $4,2
add $1,$4
add $1,10
mov $3,$4
add $3,6
gcd $3,$2
add $3,105
mul $3,2
lpe
add $1,$3
sub $1,241
div $1,4
add $1,1
mov $0,$1
|
; A301673: Partial sums of A301672.
; 1,5,13,26,43,63,88,118,151,188,230,276,326,380,438,501,568,638,713,793,876,963,1055,1151,1251,1355,1463,1576,1693,1813,1938,2068,2201,2338,2480,2626,2776,2930,3088,3251,3418,3588,3763,3943,4126,4313,4505,4701,4901,5105,5313,5526,5743,5963,6188,6418,6651
mov $1,2
lpb $0
sub $0,1
add $1,5
lpe
lpb $1
add $4,$1
sub $1,1
lpe
lpb $2,6
add $1,1
trn $4,6
lpe
|
/*
* Copyright (c) 2013-2016, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Tobias Kunz <tobias@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* 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.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_CYLINDERSHAPE_HPP_
#define DART_DYNAMICS_CYLINDERSHAPE_HPP_
#include "dart/dynamics/Shape.hpp"
namespace dart {
namespace dynamics {
class CylinderShape : public Shape {
public:
// To get byte-aligned Eigen vectors
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/// \brief Constructor.
CylinderShape(double _radius, double _height);
/// \brief
double getRadius() const;
/// \brief
void setRadius(double _radius);
/// \brief
double getHeight() const;
/// \brief
void setHeight(double _height);
/// \brief Compute volume from given properties
static double computeVolume(double radius, double height);
/// \brief Compute moments of inertia of a cylinder
static Eigen::Matrix3d computeInertia(
double radius, double height, double mass);
// Documentation inherited.
Eigen::Matrix3d computeInertia(double mass) const override;
protected:
// Documentation inherited.
void updateVolume() override;
private:
/// \brief
void _updateBoundingBoxDim();
/// \brief
double mRadius;
/// \brief Height along z-axis.
double mHeight;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_CYLINDERSHAPE_HPP_
|
; vim:filetype=nasm ts=8
; libFLAC - Free Lossless Audio Codec library
; Copyright (C) 2001-2009 Josh Coalson
; Copyright (C) 2011-2013 Xiph.Org Foundation
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
;
; - Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
;
; - Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
;
; - Neither the name of the Xiph.org Foundation nor the names of its
; contributors may be used to endorse or promote products derived from
; this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
; EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%include "nasm.h"
data_section
cglobal precompute_partition_info_sums_32bit_asm_ia32_
code_section
; **********************************************************************
;
; void FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
; void precompute_partition_info_sums_32bit_(
; const FLAC__int32 residual[],
; FLAC__uint64 abs_residual_partition_sums[],
; unsigned blocksize,
; unsigned predictor_order,
; unsigned min_partition_order,
; unsigned max_partition_order
; )
;
ALIGN 16
cident precompute_partition_info_sums_32bit_asm_ia32_
;; peppered throughout the code at major checkpoints are keys like this as to where things are at that point in time
;; [esp + 4] const FLAC__int32 residual[]
;; [esp + 8] FLAC__uint64 abs_residual_partition_sums[]
;; [esp + 12] unsigned blocksize
;; [esp + 16] unsigned predictor_order
;; [esp + 20] unsigned min_partition_order
;; [esp + 24] unsigned max_partition_order
push ebp
push ebx
push esi
push edi
sub esp, 8
;; [esp + 28] const FLAC__int32 residual[]
;; [esp + 32] FLAC__uint64 abs_residual_partition_sums[]
;; [esp + 36] unsigned blocksize
;; [esp + 40] unsigned predictor_order
;; [esp + 44] unsigned min_partition_order
;; [esp + 48] unsigned max_partition_order
;; [esp] partitions
;; [esp + 4] default_partition_samples
mov ecx, [esp + 48]
mov eax, 1
shl eax, cl
mov [esp], eax ; [esp] <- partitions = 1u << max_partition_order;
mov eax, [esp + 36]
shr eax, cl
mov [esp + 4], eax ; [esp + 4] <- default_partition_samples = blocksize >> max_partition_order;
;
; first do max_partition_order
;
mov edi, [esp + 4]
sub edi, [esp + 40] ; edi <- end = (unsigned)(-(int)predictor_order) + default_partition_samples
xor esi, esi ; esi <- residual_sample = 0
xor ecx, ecx ; ecx <- partition = 0
mov ebp, [esp + 28] ; ebp <- residual[]
xor ebx, ebx ; ebx <- abs_residual_partition_sum = 0;
; note we put the updates to 'end' and 'abs_residual_partition_sum' at the end of loop0 and in the initialization above so we could align loop0 and loop1
ALIGN 16
.loop0: ; for(partition = residual_sample = 0; partition < partitions; partition++) {
.loop1: ; for( ; residual_sample < end; residual_sample++)
mov eax, [ebp + esi * 4]
cdq
xor eax, edx
sub eax, edx
add ebx, eax ; abs_residual_partition_sum += abs(residual[residual_sample]);
;@@@@@@ check overflow flag and abort here?
add esi, byte 1
cmp esi, edi ; /* since the loop will always run at least once, we can put the loop check down here */
jb .loop1
.next1:
add edi, [esp + 4] ; end += default_partition_samples;
mov eax, [esp + 32]
mov [eax + ecx * 8], ebx ; abs_residual_partition_sums[partition] = abs_residual_partition_sum;
mov [eax + ecx * 8 + 4], dword 0
xor ebx, ebx ; abs_residual_partition_sum = 0;
add ecx, byte 1
cmp ecx, [esp] ; /* since the loop will always run at least once, we can put the loop check down here */
jb .loop0
.next0: ; }
;
; now merge partitions for lower orders
;
mov esi, [esp + 32] ; esi <- abs_residual_partition_sums[from_partition==0];
mov eax, [esp]
lea edi, [esi + eax * 8] ; edi <- abs_residual_partition_sums[to_partition==partitions];
mov ecx, [esp + 48]
sub ecx, byte 1 ; ecx <- partition_order = (int)max_partition_order - 1;
ALIGN 16
.loop2: ; for(; partition_order >= (int)min_partition_order; partition_order--) {
cmp ecx, [esp + 44]
jl .next2
mov edx, 1
shl edx, cl ; const unsigned partitions = 1u << partition_order;
ALIGN 16
.loop3: ; for(i = 0; i < partitions; i++) {
mov eax, [esi]
mov ebx, [esi + 4]
add eax, [esi + 8]
adc ebx, [esi + 12]
mov [edi], eax
mov [edi + 4], ebx ; a_r_p_s[to_partition] = a_r_p_s[from_partition] + a_r_p_s[from_partition+1];
add esi, byte 16
add edi, byte 8
sub edx, byte 1
jnz .loop3 ; }
sub ecx, byte 1
jmp .loop2 ; }
.next2:
add esp, 8
pop edi
pop esi
pop ebx
pop ebp
ret
end
|
; A340757: Counterexamples to a conjecture of Ramanujan about congruences related to the partition function.
; Submitted by Jon Maiga
; 243,586,1272,2301,2644,2987,3673,4702,5045,5388,6074,7103,7446,7789,8475,9504,9847,10190,10876,11905,12248,12591,13277,14306,14649,14992,15678,16707,17050,17393,18079,19108,19451,19794,20480,21509,21852,22195,22881,23910
mov $1,$0
mul $0,6
add $0,$1
mod $1,4
bin $1,2
add $0,$1
div $0,4
mul $0,343
add $0,243
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x14088, %rsi
lea addresses_D_ht+0x1d95a, %rdi
nop
nop
nop
xor $46290, %rbx
mov $116, %rcx
rep movsw
nop
cmp %r14, %r14
lea addresses_WT_ht+0x378a, %rax
nop
nop
nop
add $22573, %r8
mov $0x6162636465666768, %rbx
movq %rbx, %xmm6
movups %xmm6, (%rax)
cmp $22408, %rsi
lea addresses_normal_ht+0x647a, %r14
nop
nop
nop
nop
inc %rax
mov $0x6162636465666768, %r8
movq %r8, %xmm5
and $0xffffffffffffffc0, %r14
movaps %xmm5, (%r14)
add $14235, %rsi
lea addresses_D_ht+0x1bf8a, %rdi
nop
nop
nop
nop
nop
add %rcx, %rcx
mov $0x6162636465666768, %r8
movq %r8, %xmm1
vmovups %ymm1, (%rdi)
nop
nop
nop
nop
cmp $26641, %rax
lea addresses_normal_ht+0x1638a, %rsi
lea addresses_WC_ht+0x4cea, %rdi
nop
nop
nop
nop
dec %r12
mov $49, %rcx
rep movsl
nop
nop
xor %rax, %rax
lea addresses_normal_ht+0x278a, %r12
nop
nop
xor $16527, %r14
movb (%r12), %al
nop
and %r12, %r12
lea addresses_D_ht+0x6daa, %rsi
lea addresses_WC_ht+0x13dda, %rdi
nop
nop
cmp %rax, %rax
mov $51, %rcx
rep movsq
nop
nop
nop
nop
nop
and $20778, %rcx
lea addresses_WC_ht+0xa8a2, %rsi
nop
nop
dec %rax
movups (%rsi), %xmm7
vpextrq $1, %xmm7, %rcx
nop
nop
nop
nop
nop
cmp %r14, %r14
lea addresses_UC_ht+0x1e38a, %rsi
lea addresses_D_ht+0x71e, %rdi
nop
nop
nop
nop
nop
cmp %r12, %r12
mov $40, %rcx
rep movsl
nop
nop
nop
nop
nop
add %rbx, %rbx
lea addresses_WT_ht+0x1dcaa, %rbx
nop
nop
lfence
movl $0x61626364, (%rbx)
nop
nop
nop
xor %rsi, %rsi
lea addresses_WT_ht+0x1c58a, %rbx
nop
nop
nop
nop
xor $3133, %rax
mov (%rbx), %si
nop
nop
and $54121, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r8
push %rax
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WC+0x1bf8a, %rsi
clflush (%rsi)
nop
nop
dec %rax
mov $0x5152535455565758, %rdi
movq %rdi, %xmm4
vmovups %ymm4, (%rsi)
sub $14067, %rax
// Load
lea addresses_RW+0x146fc, %rsi
nop
nop
nop
nop
nop
xor $15356, %rdx
mov (%rsi), %edi
nop
nop
nop
and %r10, %r10
// Store
lea addresses_D+0x1278a, %rax
xor $31103, %r8
movl $0x51525354, (%rax)
nop
nop
and $2780, %r11
// Store
lea addresses_WC+0x1bd9a, %rsi
and %rdi, %rdi
mov $0x5152535455565758, %r11
movq %r11, (%rsi)
sub $3744, %rdi
// Store
lea addresses_UC+0xe48a, %r8
nop
nop
xor $13283, %rdi
mov $0x5152535455565758, %rdx
movq %rdx, %xmm3
movups %xmm3, (%r8)
add $56556, %r11
// Faulty Load
mov $0xf8a, %r11
add $25885, %rax
movups (%r11), %xmm3
vpextrq $1, %xmm3, %r8
lea oracles, %rdx
and $0xff, %r8
shlq $12, %r8
mov (%rdx,%r8,1), %r8
pop %rsi
pop %rdx
pop %rdi
pop %rax
pop %r8
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 7}}
{'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 3}}
[Faulty Load]
{'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 16, 'NT': False, 'same': True, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 11}}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}}
{'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 1}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 5}}
{'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'size': 2, 'NT': False, 'same': False, 'congruent': 7}, 'OP': 'LOAD'}
{'48': 29, 'ff': 8, '00': 95}
00 00 00 48 00 00 00 ff 00 00 48 48 00 00 48 48 00 48 48 00 48 48 00 00 00 48 00 00 00 00 48 00 00 48 ff 00 00 00 00 00 00 00 00 00 00 00 00 ff 00 00 00 00 00 00 48 00 00 00 00 00 00 ff 00 48 00 48 00 00 00 00 ff 48 48 00 00 48 00 00 ff 00 00 00 00 00 00 00 00 00 48 00 00 48 00 00 00 48 48 ff 48 00 00 48 ff 00 48 00 00 00 00 00 00 00 48 48 00 00 48 00 00 00 00 00 00 00 00 00 00 48 00 00 00 00
*/
|
; A168119: n*(n^10+1)/2.
; 0,1,1025,88575,2097154,24414065,181398531,988663375,4294967300,15690529809,50000000005,142655835311,371504185350,896080197025,2024782584839,4324877929695,8796093022216,17135948153825,32134205039625,58245129449119,102400000000010,175138750271121,292159150705675,476404878956975,760840571584524,1192092895507825,1835172243493901,2779530283277775,4146754733735950,6100254882852929,8857350000000015,12704238448202431,18014398509482000,25271053256863425,35094421819016209,48274578686523455,65810851921133586,88958810889730225,119286025111776275,158737918661236239,209715200000000020,275164515858124241,358684160555234325,464646869735611375,598341940645199894,766139150610351585,975677192103861271,1236079607542006175,1558201490605080600,1954910524291494049,2441406250000000025,3035581807604131551,3758432754675482650,4634517964686095825,5692478020152855579,6965616958276367215,8492553694691196956,10317949946521400625,12493322000082768925,15077944222368921359,18139852800000000030,21756958805717919361,26018280341918546975,31025304194276411775,36893488147419103264,43753915870043945345,51755117070056260641,61065066452484008575,71873375885345161250,84393695092589213169,98866337150000000035,115561146060850782671,134780624734481547300,156863342784179854225,182187644702167462949,211175680160522460975,244297779428917772326,282077198194568725025,325095257418211777575,373996905263760464479,429496729600000000040,492385451091805616481,563536928477438403625,643915709269042918175,734585160817119854634,836716218448071289105,951596789218532052011,1080641851732745244975,1225404294441369337900,1387586536883495170289,1569052980450000000045,1771843337437388915791,1998186889428707835950,2250517728383713298625,2531491036246028598319,2844000461382299804735,3191196652759205019696,3576507015440402063425,4003656753748979762225,4476691271293582225599
mov $2,$0
add $0,2
pow $2,11
add $0,$2
sub $0,2
div $0,2
|
;*****************************************************************************
;* x86-optimized functions for ssim filter
;*
;* Copyright (C) 2015 Ronald S. Bultje <rsbultje@gmail.com>
;*
;* This file is part of FFmpeg.
;*
;* FFmpeg is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* FFmpeg is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with FFmpeg; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************
%include "libavutil/x86/x86util.asm"
SECTION_RODATA
pw_1: times 8 dw 1
ssim_c1: times 4 dd 416 ;(.01*.01*255*255*64 + .5)
ssim_c2: times 4 dd 235963 ;(.03*.03*255*255*64*63 + .5)
SECTION .text
%macro SSIM_4X4_LINE 1
%if ARCH_X86_64
cglobal ssim_4x4_line, 6, 8, %1, buf, buf_stride, ref, ref_stride, sums, w, buf_stride3, ref_stride3
%else
cglobal ssim_4x4_line, 5, 7, %1, buf, buf_stride, ref, ref_stride, sums, buf_stride3, ref_stride3
%define wd r5mp
%endif
lea ref_stride3q, [ref_strideq*3]
lea buf_stride3q, [buf_strideq*3]
%if notcpuflag(xop)
pxor m7, m7
mova m15, [pw_1]
%endif
.loop:
%if cpuflag(xop)
pmovzxbw m0, [bufq+buf_strideq*0]
pmovzxbw m1, [refq+ref_strideq*0]
pmaddwd m4, m0, m0
pmaddwd m6, m0, m1
pmovzxbw m2, [bufq+buf_strideq*1]
vpmadcswd m4, m1, m1, m4
pmovzxbw m3, [refq+ref_strideq*1]
paddw m0, m2
vpmadcswd m4, m2, m2, m4
vpmadcswd m6, m2, m3, m6
paddw m1, m3
vpmadcswd m4, m3, m3, m4
pmovzxbw m2, [bufq+buf_strideq*2]
pmovzxbw m3, [refq+ref_strideq*2]
vpmadcswd m4, m2, m2, m4
vpmadcswd m6, m2, m3, m6
pmovzxbw m5, [bufq+buf_stride3q]
pmovzxbw m7, [refq+ref_stride3q]
vpmadcswd m4, m3, m3, m4
vpmadcswd m6, m5, m7, m6
paddw m0, m2
paddw m1, m3
vpmadcswd m4, m5, m5, m4
paddw m0, m5
paddw m1, m7
vpmadcswd m4, m7, m7, m4
%else
movh m0, [bufq+buf_strideq*0] ; a1
movh m1, [refq+ref_strideq*0] ; b1
movh m2, [bufq+buf_strideq*1] ; a2
movh m3, [refq+ref_strideq*1] ; b2
punpcklbw m0, m7 ; s1 [word]
punpcklbw m1, m7 ; s2 [word]
punpcklbw m2, m7 ; s1 [word]
punpcklbw m3, m7 ; s2 [word]
pmaddwd m4, m0, m0 ; a1 * a1
pmaddwd m5, m1, m1 ; b1 * b1
pmaddwd m8, m2, m2 ; a2 * a2
pmaddwd m9, m3, m3 ; b2 * b2
paddd m4, m5 ; ss
paddd m8, m9 ; ss
pmaddwd m6, m0, m1 ; a1 * b1 = ss12
pmaddwd m5, m2, m3 ; a2 * b2 = ss12
paddw m0, m2
paddw m1, m3
paddd m6, m5 ; s12
paddd m4, m8 ; ss
movh m2, [bufq+buf_strideq*2] ; a3
movh m3, [refq+ref_strideq*2] ; b3
movh m5, [bufq+buf_stride3q] ; a4
movh m8, [refq+ref_stride3q] ; b4
punpcklbw m2, m7 ; s1 [word]
punpcklbw m3, m7 ; s2 [word]
punpcklbw m5, m7 ; s1 [word]
punpcklbw m8, m7 ; s2 [word]
pmaddwd m9, m2, m2 ; a3 * a3
pmaddwd m10, m3, m3 ; b3 * b3
pmaddwd m12, m5, m5 ; a4 * a4
pmaddwd m13, m8, m8 ; b4 * b4
pmaddwd m11, m2, m3 ; a3 * b3 = ss12
pmaddwd m14, m5, m8 ; a4 * b4 = ss12
paddd m9, m10
paddd m12, m13
paddw m0, m2
paddw m1, m3
paddw m0, m5
paddw m1, m8
paddd m6, m11
paddd m4, m9
paddd m6, m14
paddd m4, m12
%endif
; m0 = [word] s1 a,a,a,a,b,b,b,b
; m1 = [word] s2 a,a,a,a,b,b,b,b
; m4 = [dword] ss a,a,b,b
; m6 = [dword] s12 a,a,b,b
%if cpuflag(xop)
vphaddwq m0, m0 ; [dword] s1 a, 0, b, 0
vphaddwq m1, m1 ; [dword] s2 a, 0, b, 0
vphadddq m4, m4 ; [dword] ss a, 0, b, 0
vphadddq m6, m6 ; [dword] s12 a, 0, b, 0
punpckhdq m2, m0, m1 ; [dword] s1 b, s2 b, 0, 0
punpckldq m0, m1 ; [dword] s1 a, s2 a, 0, 0
punpckhdq m3, m4, m6 ; [dword] ss b, s12 b, 0, 0
punpckldq m4, m6 ; [dword] ss a, s12 a, 0, 0
punpcklqdq m1, m2, m3 ; [dword] b s1, s2, ss, s12
punpcklqdq m0, m4 ; [dword] a s1, s2, ss, s12
%else
pmaddwd m0, m15 ; [dword] s1 a,a,b,b
pmaddwd m1, m15 ; [dword] s2 a,a,b,b
phaddd m0, m4 ; [dword] s1 a, b, ss a, b
phaddd m1, m6 ; [dword] s2 a, b, s12 a, b
punpckhdq m2, m0, m1 ; [dword] ss a, s12 a, ss b, s12 b
punpckldq m0, m1 ; [dword] s1 a, s2 a, s1 b, s2 b
punpckhqdq m1, m0, m2 ; [dword] b s1, s2, ss, s12
punpcklqdq m0, m2 ; [dword] a s1, s2, ss, s12
%endif
mova [sumsq+ 0], m0
mova [sumsq+mmsize], m1
add bufq, mmsize/2
add refq, mmsize/2
add sumsq, mmsize*2
sub wd, mmsize/8
jg .loop
RET
%endmacro
%if ARCH_X86_64
INIT_XMM ssse3
SSIM_4X4_LINE 16
%endif
%if HAVE_XOP_EXTERNAL
INIT_XMM xop
SSIM_4X4_LINE 8
%endif
INIT_XMM sse4
cglobal ssim_end_line, 3, 3, 6, sum0, sum1, w
pxor m0, m0
.loop:
mova m1, [sum0q+mmsize*0]
mova m2, [sum0q+mmsize*1]
mova m3, [sum0q+mmsize*2]
mova m4, [sum0q+mmsize*3]
paddd m1, [sum1q+mmsize*0]
paddd m2, [sum1q+mmsize*1]
paddd m3, [sum1q+mmsize*2]
paddd m4, [sum1q+mmsize*3]
paddd m1, m2
paddd m2, m3
paddd m3, m4
paddd m4, [sum0q+mmsize*4]
paddd m4, [sum1q+mmsize*4]
TRANSPOSE4x4D 1, 2, 3, 4, 5
; m1 = fs1, m2 = fs2, m3 = fss, m4 = fs12
pslld m3, 6
pslld m4, 6
pmulld m5, m1, m2 ; fs1 * fs2
pmulld m1, m1 ; fs1 * fs1
pmulld m2, m2 ; fs2 * fs2
psubd m3, m1
psubd m4, m5 ; covariance
psubd m3, m2 ; variance
; m1 = fs1 * fs1, m2 = fs2 * fs2, m3 = variance, m4 = covariance, m5 = fs1 * fs2
paddd m4, m4 ; 2 * covariance
paddd m5, m5 ; 2 * fs1 * fs2
paddd m1, m2 ; fs1 * fs1 + fs2 * fs2
paddd m3, [ssim_c2] ; variance + ssim_c2
paddd m4, [ssim_c2] ; 2 * covariance + ssim_c2
paddd m5, [ssim_c1] ; 2 * fs1 * fs2 + ssim_c1
paddd m1, [ssim_c1] ; fs1 * fs1 + fs2 * fs2 + ssim_c1
; convert to float
cvtdq2ps m3, m3
cvtdq2ps m4, m4
cvtdq2ps m5, m5
cvtdq2ps m1, m1
mulps m4, m5
mulps m3, m1
divps m4, m3 ; ssim_endl
addps m0, m4 ; ssim
add sum0q, mmsize*4
add sum1q, mmsize*4
sub wd, 4
jg .loop
; subps the ones we added too much
test wd, wd
jz .end
add wd, 4
test wd, 2
jz .skip2
psrldq m4, 8
.skip2:
test wd, 1
jz .skip1
psrldq m4, 4
.skip1:
subps m0, m4
.end:
movhlps m4, m0
addps m0, m4
movss m4, m0
shufps m0, m0, 1
addss m0, m4
%if ARCH_X86_32
movss r0m, m0
fld r0mp
%endif
RET
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>socketcall_sendmsg(vararg_0, vararg_1, vararg_2, vararg_3, vararg_4) -> str
Invokes the syscall socketcall_sendmsg.
See 'man 2 socketcall_sendmsg' for more information.
Arguments:
vararg(int): vararg
Returns:
long
</%docstring>
<%page args="vararg_0=None, vararg_1=None, vararg_2=None, vararg_3=None, vararg_4=None"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['vararg_0', 'vararg_1', 'vararg_2', 'vararg_3', 'vararg_4']
argument_values = [vararg_0, vararg_1, vararg_2, vararg_3, vararg_4]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_socketcall_sendmsg']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* socketcall_sendmsg(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
; A076632: Solve 2^n - 2 = 7(x^2 - x) + (y^2 - y) for (x,y) with x>0, y>0; sequence gives value of x.
; 1,1,1,2,1,3,4,2,9,6,12,23,1,46,45,47,136,43,229,314,144,771,484,1058,2025,91,4140,3959,4321,12238,3597,20879,28072,13686,69829,42458,97200,182115,12285,376514,351945,401083,1104972,302807
add $0,2
seq $0,78020 ; Expansion of (1-x)/(1-x+2*x^2).
gcd $0,$0
div $0,4
add $0,1
|
#include "rx/core/serialize/encoder.h"
#include "rx/core/math/shape.h"
#include "rx/core/utility/byte_swap.h"
namespace Rx::Serialize {
using namespace Rx::Utility;
Optional<Encoder> Encoder::create(Memory::Allocator& _allocator,
Stream::Context& _stream)
{
if (!(_stream.flags() & Stream::WRITE)) {
// Stream does not support writing to.
return nullopt;
}
auto buffer = Stream::BufferedStream::create(_allocator);
if (!buffer || !buffer->attach(_stream)) {
// Couldn't create buffered stream or attach this one.
return nullopt;
}
return Encoder { Utility::move(*buffer) };
}
template<typename T>
static bool write(auto&& stream_, const T& _value) {
const auto data = reinterpret_cast<const Byte*>(&_value);
return stream_.write(data, sizeof _value) == sizeof _value;
}
static constexpr bool is_big_endian() { return false; }
static constexpr bool is_little_endian() { return true; }
bool Encoder::put_u8(Uint8 _value) {
return write(m_stream, _value);
}
bool Encoder::put_s8(Sint8 _value) {
return write(m_stream, _value);
}
bool Encoder::put_u16le(Uint16 _value) {
return write(m_stream, is_big_endian() ? swap_u16(_value) : _value);
}
bool Encoder::put_s16le(Sint16 _value) {
return write(m_stream, is_big_endian() ? swap_s16(_value) : _value);
}
bool Encoder::put_u16be(Uint16 _value) {
return write(m_stream, is_little_endian() ? swap_u16(_value) : _value);
}
bool Encoder::put_s16be(Sint16 _value) {
return write(m_stream, is_little_endian() ? swap_s16(_value) : _value);
}
bool Encoder::put_u32le(Uint32 _value) {
return write(m_stream, is_big_endian() ? swap_u32(_value) : _value);
}
bool Encoder::put_s32le(Sint32 _value) {
return write(m_stream, is_big_endian() ? swap_s32(_value) : _value);
}
bool Encoder::put_u32be(Uint32 _value) {
return write(m_stream, is_little_endian() ? swap_u32(_value) : _value);
}
bool Encoder::put_s32be(Sint32 _value) {
return write(m_stream, is_little_endian() ? swap_s32(_value) : _value);
}
bool Encoder::put_u64le(Uint64 _value) {
return write(m_stream, is_big_endian() ? swap_u64(_value) : _value);
}
bool Encoder::put_s64le(Uint64 _value) {
return write(m_stream, is_big_endian() ? swap_s64(_value) : _value);
}
bool Encoder::put_u64be(Uint64 _value) {
return write(m_stream, is_little_endian() ? swap_u64(_value) : _value);
}
bool Encoder::put_s64be(Uint64 _value) {
return write(m_stream, is_little_endian() ? swap_s64(_value) : _value);
}
bool Encoder::put_f32le(Float32 _value) {
return put_u32le(Math::Shape{_value}.as_u32);
}
bool Encoder::put_f32be(Float32 _value) {
return put_u32be(Math::Shape{_value}.as_u32);
}
bool Encoder::put_f64le(Float64 _value) {
return put_u64le(Math::Shape{_value}.as_u64);
}
bool Encoder::put_f64be(Float64 _value) {
return put_u64be(Math::Shape{_value}.as_u64);
}
} // namespace Rx::Serialize |
#include "Platform.inc"
#include "FarCalls.inc"
#include "Timer0.inc"
#include "Smps.inc"
#include "TestFixture.inc"
radix decimal
IsEnabledAfterDisabledTest code
global testArrange
testArrange:
fcall initialiseTimer0
fcall initialiseSmps
fcall disableSmps
fcall pollSmps
fcall enableSmps
waitUntilSmpsIsEnabled:
fcall pollSmps
fcall isSmpsEnabled
xorlw 0
btfsc STATUS, Z
goto waitUntilSmpsIsEnabled
testAct:
fcall disableSmps
fcall pollSmps
testAssert:
fcall isSmpsEnabled
.aliasWForAssert _a
.assert "_a == 0, 'Expected SMPS to be disabled.'"
return
end
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/opsworks/model/AutoScalingThresholds.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace OpsWorks
{
namespace Model
{
AutoScalingThresholds::AutoScalingThresholds() :
m_instanceCount(0),
m_instanceCountHasBeenSet(false),
m_thresholdsWaitTime(0),
m_thresholdsWaitTimeHasBeenSet(false),
m_ignoreMetricsTime(0),
m_ignoreMetricsTimeHasBeenSet(false),
m_cpuThreshold(0.0),
m_cpuThresholdHasBeenSet(false),
m_memoryThreshold(0.0),
m_memoryThresholdHasBeenSet(false),
m_loadThreshold(0.0),
m_loadThresholdHasBeenSet(false),
m_alarmsHasBeenSet(false)
{
}
AutoScalingThresholds::AutoScalingThresholds(const JsonValue& jsonValue) :
m_instanceCount(0),
m_instanceCountHasBeenSet(false),
m_thresholdsWaitTime(0),
m_thresholdsWaitTimeHasBeenSet(false),
m_ignoreMetricsTime(0),
m_ignoreMetricsTimeHasBeenSet(false),
m_cpuThreshold(0.0),
m_cpuThresholdHasBeenSet(false),
m_memoryThreshold(0.0),
m_memoryThresholdHasBeenSet(false),
m_loadThreshold(0.0),
m_loadThresholdHasBeenSet(false),
m_alarmsHasBeenSet(false)
{
*this = jsonValue;
}
AutoScalingThresholds& AutoScalingThresholds::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("InstanceCount"))
{
m_instanceCount = jsonValue.GetInteger("InstanceCount");
m_instanceCountHasBeenSet = true;
}
if(jsonValue.ValueExists("ThresholdsWaitTime"))
{
m_thresholdsWaitTime = jsonValue.GetInteger("ThresholdsWaitTime");
m_thresholdsWaitTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("IgnoreMetricsTime"))
{
m_ignoreMetricsTime = jsonValue.GetInteger("IgnoreMetricsTime");
m_ignoreMetricsTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("CpuThreshold"))
{
m_cpuThreshold = jsonValue.GetDouble("CpuThreshold");
m_cpuThresholdHasBeenSet = true;
}
if(jsonValue.ValueExists("MemoryThreshold"))
{
m_memoryThreshold = jsonValue.GetDouble("MemoryThreshold");
m_memoryThresholdHasBeenSet = true;
}
if(jsonValue.ValueExists("LoadThreshold"))
{
m_loadThreshold = jsonValue.GetDouble("LoadThreshold");
m_loadThresholdHasBeenSet = true;
}
if(jsonValue.ValueExists("Alarms"))
{
Array<JsonValue> alarmsJsonList = jsonValue.GetArray("Alarms");
for(unsigned alarmsIndex = 0; alarmsIndex < alarmsJsonList.GetLength(); ++alarmsIndex)
{
m_alarms.push_back(alarmsJsonList[alarmsIndex].AsString());
}
m_alarmsHasBeenSet = true;
}
return *this;
}
JsonValue AutoScalingThresholds::Jsonize() const
{
JsonValue payload;
if(m_instanceCountHasBeenSet)
{
payload.WithInteger("InstanceCount", m_instanceCount);
}
if(m_thresholdsWaitTimeHasBeenSet)
{
payload.WithInteger("ThresholdsWaitTime", m_thresholdsWaitTime);
}
if(m_ignoreMetricsTimeHasBeenSet)
{
payload.WithInteger("IgnoreMetricsTime", m_ignoreMetricsTime);
}
if(m_cpuThresholdHasBeenSet)
{
payload.WithDouble("CpuThreshold", m_cpuThreshold);
}
if(m_memoryThresholdHasBeenSet)
{
payload.WithDouble("MemoryThreshold", m_memoryThreshold);
}
if(m_loadThresholdHasBeenSet)
{
payload.WithDouble("LoadThreshold", m_loadThreshold);
}
if(m_alarmsHasBeenSet)
{
Array<JsonValue> alarmsJsonList(m_alarms.size());
for(unsigned alarmsIndex = 0; alarmsIndex < alarmsJsonList.GetLength(); ++alarmsIndex)
{
alarmsJsonList[alarmsIndex].AsString(m_alarms[alarmsIndex]);
}
payload.WithArray("Alarms", std::move(alarmsJsonList));
}
return payload;
}
} // namespace Model
} // namespace OpsWorks
} // namespace Aws |
; A207597: Number of n X 6 0..1 arrays avoiding 0 0 0 and 0 1 0 horizontally and 0 0 1 and 1 0 1 vertically.
; 25,625,3025,9025,21025,42025,75625,126025,198025,297025,429025,600625,819025,1092025,1428025,1836025,2325625,2907025,3591025,4389025,5313025,6375625,7590025,8970025,10530025,12285025,14250625,16443025,18879025,21576025,24552025,27825625,31416025,35343025,39627025,44289025,49350625,54834025,60762025,67158025,74046025,81450625,89397025,97911025,107019025,116748025,127125625,138180025,149940025,162435025,175695025,189750625,204633025,220374025,237006025,254562025,273075625,292581025,313113025,334707025,357399025,381225625,406224025,432432025,459888025,488631025,518700625,550137025,582981025,617274025,653058025,690375625,729270025,769785025,811965025,855855025,901500625,948948025,998244025,1049436025,1102572025,1157700625,1214871025,1274133025,1335537025,1399134025,1464975625,1533114025,1603602025,1676493025,1751841025,1829700625,1910127025,1993176025,2078904025,2167368025,2258625625,2352735025,2449755025,2549745025,2652765025,2758875625,2868138025,2980614025,3096366025,3215457025,3337950625,3463911025,3593403025,3726492025,3863244025,4003725625,4148004025,4296147025,4448223025,4604301025,4764450625,4928742025,5097246025,5270034025,5447178025,5628750625,5814825025,6005475025,6200775025,6400800025,6605625625,6815328025,7029984025,7249671025,7474467025,7704450625,7939701025,8180298025,8426322025,8677854025,8934975625,9197769025,9466317025,9740703025,10021011025,10307325625,10599732025,10898316025,11203164025,11514363025,11832000625,12156165025,12486945025,12824430025,13168710025,13519875625,13878018025,14243229025,14615601025,14995227025,15382200625,15776616025,16178568025,16588152025,17005464025,17430600625,17863659025,18304737025,18753933025,19211346025,19677075625,20151222025,20633886025,21125169025,21625173025,22134000625,22651755025,23178540025,23714460025,24259620025,24814125625,25378083025,25951599025,26534781025,27127737025,27730575625,28343406025,28966338025,29599482025,30242949025,30896850625,31561299025,32236407025,32922288025,33619056025,34326825625,35045712025,35775831025,36517299025,37270233025,38034750625,38810970025,39599010025,40398990025,41211030025,42035250625,42871773025,43720719025,44582211025,45456372025,46343325625,47243196025,48156108025,49082187025
sub $1,$0
bin $1,4
mul $1,600
add $1,25
|
; A035021: One seventh of 9-factorial numbers.
; 1,16,400,13600,584800,30409600,1854985600,129848992000,10258070368000,902710192384000,87562888661248000,9281666198092288000,1067391612780613120000,132356559984796026880000
mov $1,1
mov $2,7
lpb $0
sub $0,1
add $2,9
mul $1,$2
lpe
mov $0,$1
|
// Copyright David Stone 2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "value_ptr.hpp"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <tuple>
#include <utility>
#include <vector>
using namespace smart_pointer;
namespace {
class Tester {
public:
Tester() {
++default_constructed;
}
Tester(Tester const &) {
++copy_constructed;
}
Tester(Tester &&) noexcept {
++move_constructed;
}
Tester & operator=(Tester const &) = delete;
Tester & operator=(Tester &&) noexcept = delete;
~Tester() noexcept {
++destructed;
}
static std::size_t default_constructed;
static std::size_t copy_constructed;
static std::size_t move_constructed;
static std::size_t copy_assigned;
static std::size_t move_assigned;
static std::size_t destructed;
};
std::size_t Tester::default_constructed = 0;
std::size_t Tester::copy_constructed = 0;
std::size_t Tester::move_constructed = 0;
std::size_t Tester::copy_assigned = 0;
std::size_t Tester::move_assigned = 0;
std::size_t Tester::destructed = 0;
static_assert(sizeof(value_ptr<Tester>) == sizeof(Tester *), "value_ptr wrong size!");
static_assert(sizeof(value_ptr<Tester[]>) == sizeof(Tester *), "value_ptr array wrong size!");
#define CHECK_EQUALS(condition1, condition2) do { \
if ((condition1) != (condition2)) { \
std::cerr << (condition1) << ", " << (condition2) << '\n'; \
assert((condition1) == (condition2)); \
} \
} while(false)
template<typename T>
class Verify {
public:
void operator()() const {
CHECK_EQUALS(T::default_constructed, default_constructed);
CHECK_EQUALS(T::copy_constructed, copy_constructed);
CHECK_EQUALS(T::move_constructed, move_constructed);
CHECK_EQUALS(T::copy_assigned, 0);
CHECK_EQUALS(T::move_assigned, 0);
CHECK_EQUALS(T::destructed, destructed);
}
void default_construct() {
++default_constructed;
}
void copy_construct() {
++copy_constructed;
}
void move_construct() {
++move_constructed;
}
void destruct() {
++destructed;
}
private:
std::size_t default_constructed = 0;
std::size_t copy_constructed = 0;
std::size_t move_constructed = 0;
std::size_t destructed = 0;
};
class Base {};
class Derived : public Base {};
void test_constructors(Verify<Tester> & verify) {
verify();
{
value_ptr<Tester> p;
}
verify();
{
value_ptr<Tester> p(new Tester);
verify.default_construct();
verify();
p.reset(nullptr);
verify.destruct();
verify();
}
verify();
Tester t;
verify.default_construct();
auto p = value_ptr<Tester>(t);
verify.copy_construct();
verify();
std::vector<value_ptr<Tester>> v;
v.emplace_back(std::move(p));
verify();
for (size_t n = 0; n != 10; ++n) {
v.emplace_back(value_ptr<Tester>(new Tester));
verify.default_construct();
}
verify();
using std::swap;
swap(v[1], v[2]);
verify();
value_ptr<Tester> d(v[3]);
verify.copy_construct();
verify();
constexpr std::size_t size = 5;
value_ptr<Tester[]> array(new Tester[size]);
for (std::size_t n = 0; n != size; ++n) {
verify.default_construct();
}
verify();
auto moved_to = value_ptr<Tester>(std::move(t));
verify.move_construct();
verify();
verify.destruct(); // moved_to
verify.destruct(); // t
verify.destruct(); // p
for (std::size_t n = 0; n != v.size(); ++n) {
verify.destruct();
}
for (std::size_t n = 0; n != size; ++n) {
verify.destruct();
}
value_ptr<Base> vb(new Derived{});
value_ptr<Base> vexplicit(value_ptr<Derived>(new Derived{}));
value_ptr<Base> vmake(make_value<Derived>());
}
void test_assignment(Verify<Tester> & verify) {
verify();
value_ptr<Tester> p;
p = make_value<Tester>();
verify.default_construct();
verify();
p = Tester{};
verify.default_construct();
verify.destruct();
verify.move_construct();
verify.destruct();
verify();
}
void test_array_semantics() {
constexpr std::size_t size = 10;
auto a = make_value<std::size_t[]>(size);
std::iota(a.get(), a.get() + size, 0);
for (size_t n = 0; n != size; ++n) {
CHECK_EQUALS(a[n], n);
}
}
class C {
public:
int get() const {
return 4;
}
};
void test_semantics() {
value_ptr<int> a(new int(5));
value_ptr<int> b(new int(7));
CHECK_EQUALS(*a + *b, 12);
value_ptr<C> c(new C);
CHECK_EQUALS(*a + c->get(), 9);
test_array_semantics();
std::vector<value_ptr<int>> temp;
temp.emplace_back(make_value<int>(5));
temp.emplace_back(make_value<int>(3));
temp.emplace_back(make_value<int>(1));
temp.emplace_back(make_value<int>(2));
temp.emplace_back(make_value<int>(4));
std::sort(std::begin(temp), std::end(temp), [](value_ptr<int> const & lhs, value_ptr<int> const & rhs) {
return *lhs < *rhs;
});
}
class VirtualBase {
public:
virtual ~VirtualBase() = default;
};
class VirtualDerived : public VirtualBase {
};
void test_virtual_cloning() {
value_ptr<VirtualBase> ptr(new VirtualDerived{});
static_cast<void>(ptr);
// value_ptr<VirtualBase> other(ptr);
// static_cast<void>(other);
}
} // namespace
int main() {
Verify<Tester> verify;
test_constructors(verify);
verify();
test_assignment(verify);
test_semantics();
test_virtual_cloning();
}
|
#include "test/common/tcp_proxy/tcp_proxy_test_base.h"
namespace Envoy {
namespace TcpProxy {
namespace {
TEST(ConfigTest, DefaultTimeout) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_EQ(std::chrono::hours(1), config_obj.sharedConfig()->idleTimeout().value());
}
TEST(ConfigTest, DisabledTimeout) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
idle_timeout: 0s
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_FALSE(config_obj.sharedConfig()->idleTimeout().has_value());
}
TEST(ConfigTest, CustomTimeout) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
idle_timeout: 1s
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_EQ(std::chrono::seconds(1), config_obj.sharedConfig()->idleTimeout().value());
}
TEST(ConfigTest, MaxDownstreamConnectionDuration) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
max_downstream_connection_duration: 10s
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_EQ(std::chrono::seconds(10), config_obj.maxDownstreamConnectionDuration().value());
}
TEST(ConfigTest, NoRouteConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
EXPECT_THROW(constructConfigFromYaml(yaml, factory_context), EnvoyException);
}
// Tests that it's not possible to define a weighted cluster with 0 weight.
TEST(ConfigTest, WeightedClusterWithZeroWeightConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
weighted_clusters:
clusters:
- name: cluster1
weight: 1
- name: cluster2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
EXPECT_THROW(constructConfigFromYaml(yaml, factory_context), EnvoyException);
}
// Tests that it is possible to define a list of weighted clusters.
TEST(ConfigTest, WeightedClustersConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
weighted_clusters:
clusters:
- name: cluster1
weight: 1
- name: cluster2
weight: 2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
NiceMock<Network::MockConnection> connection;
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(0));
EXPECT_EQ(std::string("cluster1"), config_obj.getRouteFromEntries(connection)->clusterName());
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(2));
EXPECT_EQ(std::string("cluster2"), config_obj.getRouteFromEntries(connection)->clusterName());
}
// Tests that it is possible to define a list of weighted clusters with independent endpoint
// selectors.
TEST(ConfigTest, WeightedClustersWithMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
weighted_clusters:
clusters:
- name: cluster1
weight: 1
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
- name: cluster2
weight: 2
metadata_match:
filter_metadata:
envoy.lb:
k3: v3
k4: v4
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
{
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
NiceMock<Network::MockConnection> connection;
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(0));
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("cluster1", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k1", criterions[0]->name());
EXPECT_EQ(hv1, criterions[0]->value());
EXPECT_EQ("k2", criterions[1]->name());
EXPECT_EQ(hv2, criterions[1]->value());
}
{
ProtobufWkt::Value v3, v4;
v3.set_string_value("v3");
v4.set_string_value("v4");
HashedValue hv3(v3), hv4(v4);
NiceMock<Network::MockConnection> connection;
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(2));
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("cluster2", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k3", criterions[0]->name());
EXPECT_EQ(hv3, criterions[0]->value());
EXPECT_EQ("k4", criterions[1]->name());
EXPECT_EQ(hv4, criterions[1]->value());
}
}
// Tests that an individual endpoint selector of a weighted cluster gets merged with the top-level
// endpoint selector.
TEST(ConfigTest, WeightedClustersWithMetadataMatchAndTopLevelMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
weighted_clusters:
clusters:
- name: cluster1
weight: 1
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
- name: cluster2
weight: 2
metadata_match:
filter_metadata:
envoy.lb:
k3: v3
k4: v4
metadata_match:
filter_metadata:
envoy.lb:
k0: v00
k1: v01
k4: v04
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
ProtobufWkt::Value v00, v01, v04;
v00.set_string_value("v00");
v01.set_string_value("v01");
v04.set_string_value("v04");
HashedValue hv00(v00), hv01(v01), hv04(v04);
{
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
NiceMock<Network::MockConnection> connection;
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(0));
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("cluster1", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(4, criterions.size());
EXPECT_EQ("k0", criterions[0]->name());
EXPECT_EQ(hv00, criterions[0]->value());
EXPECT_EQ("k1", criterions[1]->name());
EXPECT_EQ(hv1, criterions[1]->value());
EXPECT_EQ("k2", criterions[2]->name());
EXPECT_EQ(hv2, criterions[2]->value());
EXPECT_EQ("k4", criterions[3]->name());
EXPECT_EQ(hv04, criterions[3]->value());
}
{
ProtobufWkt::Value v3, v4;
v3.set_string_value("v3");
v4.set_string_value("v4");
HashedValue hv3(v3), hv4(v4);
NiceMock<Network::MockConnection> connection;
EXPECT_CALL(factory_context.api_.random_, random()).WillOnce(Return(2));
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("cluster2", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(4, criterions.size());
EXPECT_EQ("k0", criterions[0]->name());
EXPECT_EQ(hv00, criterions[0]->value());
EXPECT_EQ("k1", criterions[1]->name());
EXPECT_EQ(hv01, criterions[1]->value());
EXPECT_EQ("k3", criterions[2]->name());
EXPECT_EQ(hv3, criterions[2]->value());
EXPECT_EQ("k4", criterions[3]->name());
EXPECT_EQ(hv4, criterions[3]->value());
}
}
// Tests that a weighted cluster gets the top-level endpoint selector.
TEST(ConfigTest, WeightedClustersWithTopLevelMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
weighted_clusters:
clusters:
- name: cluster1
weight: 1
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
NiceMock<Network::MockConnection> connection;
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("cluster1", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k1", criterions[0]->name());
EXPECT_EQ(hv1, criterions[0]->value());
EXPECT_EQ("k2", criterions[1]->name());
EXPECT_EQ(hv2, criterions[1]->value());
}
// Tests that it is possible to define the top-level endpoint selector.
TEST(ConfigTest, TopLevelMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
const auto* criteria = config_obj.metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k1", criterions[0]->name());
EXPECT_EQ(hv1, criterions[0]->value());
EXPECT_EQ("k2", criterions[1]->name());
EXPECT_EQ(hv2, criterions[1]->value());
}
// Tests that a regular cluster gets the top-level endpoint selector.
TEST(ConfigTest, ClusterWithTopLevelMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
NiceMock<Network::MockConnection> connection;
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("foo", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k1", criterions[0]->name());
EXPECT_EQ(hv1, criterions[0]->value());
EXPECT_EQ("k2", criterions[1]->name());
EXPECT_EQ(hv2, criterions[1]->value());
}
// Tests that a per connection cluster gets the top-level endpoint selector.
TEST(ConfigTest, PerConnectionClusterWithTopLevelMetadataMatchConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
metadata_match:
filter_metadata:
envoy.lb:
k1: v1
k2: v2
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
ProtobufWkt::Value v1, v2;
v1.set_string_value("v1");
v2.set_string_value("v2");
HashedValue hv1(v1), hv2(v2);
NiceMock<Network::MockConnection> connection;
connection.stream_info_.filterState()->setData(
"envoy.tcp_proxy.cluster", std::make_unique<PerConnectionCluster>("filter_state_cluster"),
StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::Connection);
const auto route = config_obj.getRouteFromEntries(connection);
EXPECT_NE(nullptr, route);
EXPECT_EQ("filter_state_cluster", route->clusterName());
const auto* criteria = route->metadataMatchCriteria();
EXPECT_NE(nullptr, criteria);
const auto& criterions = criteria->metadataMatchCriteria();
EXPECT_EQ(2, criterions.size());
EXPECT_EQ("k1", criterions[0]->name());
EXPECT_EQ(hv1, criterions[0]->value());
EXPECT_EQ("k2", criterions[1]->name());
EXPECT_EQ(hv2, criterions[1]->value());
}
TEST(ConfigTest, HashWithSourceIpConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
hash_policy:
- source_ip: {}
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_NE(nullptr, config_obj.hashPolicy());
}
TEST(ConfigTest, HashWithSourceIpDefaultConfig) {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: foo
)EOF";
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
Config config_obj(constructConfigFromYaml(yaml, factory_context));
EXPECT_EQ(nullptr, config_obj.hashPolicy());
}
TEST(ConfigTest, AccessLogConfig) {
envoy::extensions::filters::network::tcp_proxy::v3::TcpProxy config;
envoy::config::accesslog::v3::AccessLog* log = config.mutable_access_log()->Add();
log->set_name("envoy.access_loggers.file");
{
envoy::extensions::access_loggers::file::v3::FileAccessLog file_access_log;
file_access_log.set_path("some_path");
file_access_log.mutable_log_format()->mutable_text_format_source()->set_inline_string(
"the format specifier");
log->mutable_typed_config()->PackFrom(file_access_log);
}
log = config.mutable_access_log()->Add();
log->set_name("envoy.access_loggers.file");
{
envoy::extensions::access_loggers::file::v3::FileAccessLog file_access_log;
file_access_log.set_path("another path");
log->mutable_typed_config()->PackFrom(file_access_log);
}
NiceMock<Server::Configuration::MockFactoryContext> factory_context_;
Config config_obj(config, factory_context_);
EXPECT_EQ(2, config_obj.accessLogs().size());
}
class TcpProxyNonDeprecatedConfigRoutingTest : public testing::Test {
public:
void setup() {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: fake_cluster
)EOF";
factory_context_.cluster_manager_.initializeThreadLocalClusters({"fake_cluster"});
config_ = std::make_shared<Config>(constructConfigFromYaml(yaml, factory_context_));
}
void initializeFilter() {
EXPECT_CALL(filter_callbacks_, connection()).WillRepeatedly(ReturnRef(connection_));
filter_ = std::make_unique<Filter>(config_, factory_context_.cluster_manager_);
filter_->initializeReadFilterCallbacks(filter_callbacks_);
}
NiceMock<Server::Configuration::MockFactoryContext> factory_context_;
ConfigSharedPtr config_;
NiceMock<Network::MockConnection> connection_;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks_;
std::unique_ptr<Filter> filter_;
};
TEST_F(TcpProxyNonDeprecatedConfigRoutingTest, ClusterNameSet) {
setup();
initializeFilter();
// Port 9999 is within the specified destination port range.
connection_.stream_info_.downstream_address_provider_->setLocalAddress(
std::make_shared<Network::Address::Ipv4Instance>("1.2.3.4", 9999));
// Expect filter to try to open a connection to specified cluster.
EXPECT_CALL(factory_context_.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _))
.WillOnce(Return(absl::nullopt));
absl::optional<Upstream::ClusterInfoConstSharedPtr> cluster_info;
EXPECT_CALL(connection_.stream_info_, setUpstreamClusterInfo(_))
.WillOnce(
Invoke([&cluster_info](const Upstream::ClusterInfoConstSharedPtr& upstream_cluster_info) {
cluster_info = upstream_cluster_info;
}));
EXPECT_CALL(connection_.stream_info_, upstreamClusterInfo())
.WillOnce(ReturnPointee(&cluster_info));
filter_->onNewConnection();
EXPECT_EQ(connection_.stream_info_.upstreamClusterInfo().value()->name(), "fake_cluster");
}
class TcpProxyHashingTest : public testing::Test {
public:
void setup() {
const std::string yaml = R"EOF(
stat_prefix: name
cluster: fake_cluster
hash_policy:
- source_ip: {}
)EOF";
factory_context_.cluster_manager_.initializeThreadLocalClusters({"fake_cluster"});
config_ = std::make_shared<Config>(constructConfigFromYaml(yaml, factory_context_));
}
void initializeFilter() {
EXPECT_CALL(filter_callbacks_, connection()).WillRepeatedly(ReturnRef(connection_));
filter_ = std::make_unique<Filter>(config_, factory_context_.cluster_manager_);
filter_->initializeReadFilterCallbacks(filter_callbacks_);
}
Event::TestTimeSystem& timeSystem() { return factory_context_.timeSystem(); }
NiceMock<Server::Configuration::MockFactoryContext> factory_context_;
ConfigSharedPtr config_;
NiceMock<Network::MockConnection> connection_;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks_;
std::unique_ptr<Filter> filter_;
};
// Test TCP proxy use source IP to hash.
TEST_F(TcpProxyHashingTest, HashWithSourceIp) {
setup();
initializeFilter();
EXPECT_CALL(factory_context_.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _))
.WillOnce(Invoke([](Upstream::ResourcePriority, Upstream::LoadBalancerContext* context) {
EXPECT_TRUE(context->computeHashKey().has_value());
return absl::nullopt;
}));
connection_.stream_info_.downstream_address_provider_->setRemoteAddress(
std::make_shared<Network::Address::Ipv4Instance>("1.2.3.4", 1111));
connection_.stream_info_.downstream_address_provider_->setLocalAddress(
std::make_shared<Network::Address::Ipv4Instance>("2.3.4.5", 2222));
filter_->onNewConnection();
}
} // namespace
} // namespace TcpProxy
} // namespace Envoy
|
; A134142: List of quadruples: 2*(-4)^n, -3*(-4)^n, 2*(-4^n), 2*(-4)^n, n >= 0.
; 2,-3,2,2,-8,12,-8,-8,32,-48,32,32,-128,192,-128,-128,512,-768,512,512,-2048,3072,-2048,-2048,8192,-12288,8192,8192,-32768,49152,-32768,-32768,131072,-196608,131072,131072,-524288,786432,-524288,-524288,2097152,-3145728,2097152,2097152,-8388608
mov $1,4
mov $2,$0
mov $4,4
lpb $2
add $4,$1
add $1,1
mov $3,2
add $3,$1
mov $1,0
sub $1,$4
mul $1,2
sub $2,1
add $3,7
mov $4,$3
lpe
sub $1,4
div $1,20
mul $1,5
add $1,2
mov $0,$1
|
; A189735: a(1)=3, a(2)=1, a(n)=3*a(n-1) + a(n-2)
; 3,1,6,19,63,208,687,2269,7494,24751,81747,269992,891723,2945161,9727206,32126779,106107543,350449408,1157455767,3822816709,12625905894,41700534391,137727509067,454883061592,1502376693843,4962013143121,16388416123206,54127261512739,178770200661423,590437863497008,1950083791152447,6440689236954349
mov $7,2
mov $8,$0
lpb $7
mov $0,$8
sub $7,1
add $0,$7
sub $0,1
mov $3,4
mov $6,2
lpb $0
sub $0,1
sub $3,2
add $3,$6
mov $4,$3
mov $3,$6
add $3,4
add $4,$6
mov $5,0
add $5,$4
add $5,6
add $6,$5
lpe
mov $2,$7
add $3,1
mov $5,1
add $5,$3
mov $9,$5
lpb $2
mov $1,$9
sub $2,1
lpe
lpe
lpb $8
sub $1,$9
mov $8,0
lpe
sub $1,2
div $1,2
add $1,1
|
; z_address !byte 0,0,0
; z_address_temp !byte 0
set_z_address
stx z_address + 2
sta z_address + 1
lda #$0
sta z_address
rts
+make_acorn_screen_hole
dec_z_address
pha
dec z_address + 2
lda z_address + 2
cmp #$ff
bne +
dec z_address + 1
lda z_address + 1
cmp #$ff
bne +
dec z_address
+ pla
rts
+make_acorn_screen_hole
set_z_himem_address
stx z_address + 2
sta z_address + 1
sty z_address
rts
skip_bytes_z_address
; skip <a> bytes
clc
adc z_address + 2
sta z_address + 2
lda z_address + 1
adc #0
sta z_address + 1
lda z_address
adc #0
sta z_address
rts
!ifdef DEBUG {
print_z_address
jsr dollar
lda z_address + 1 ; low
jsr print_byte_as_hex
lda z_address + 2 ; high
jsr print_byte_as_hex
jmp newline
}
get_z_address
; input:
; output: a,x
; side effects:
; used registers: a,x
ldx z_address + 2 ; low
lda z_address + 1 ; high
rts
get_z_himem_address
ldx z_address + 2
lda z_address + 1
ldy z_address
rts
read_next_byte
; input:
; output: a
; side effects: z_address
; used registers: a,x
sty z_address_temp
lda z_address
ldx z_address + 1
ldy z_address + 2
jsr read_byte_at_z_address
inc z_address + 2
bne +
inc z_address + 1
bne +
inc z_address
+ ldy z_address_temp
rts
set_z_paddress
; convert a/x to paddr in z_address
; input: a,x
; output:
; side effects: z_address
; used registers: a,x
; example: $031b -> $00, $0c, $6c (Z5)
sta z_address + 1
txa
asl
sta z_address + 2
rol z_address + 1
lda #$0
rol
!ifdef Z4PLUS {
asl z_address + 2
rol z_address + 1
rol
}
!ifdef Z8 {
asl z_address + 2
rol z_address + 1
rol
}
sta z_address
rts
|
; A099453: Expansion of 1/(1 - 7*x + 11*x^2).
; Submitted by Jamie Morken(s2)
; 1,7,38,189,905,4256,19837,92043,426094,1970185,9104261,42057792,194257673,897167999,4143341590,19134543141,88365044497,408075336928,1884511869029,8702754376995,40189650079646,185597252410577,857094615997933,3958092535469184,18278606972307025,84411230915988151,389813939716539782,1800174037939908813,8313264928697424089,38390940083542971680,177290666369129136781,818734323664931268987,3780942935594098378318,17460522988844444689369,80633288630376030664085,372367267535343323065536
mov $2,$0
mov $3,1
mov $4,1
lpb $2
mov $0,$3
mul $0,5
sub $2,1
add $3,$4
add $3,$0
sub $4,$0
lpe
mov $0,$3
|
// Copyright (c) OpenMMLab. All rights reserved.
#include <cuda_runtime.h>
#include "core/utils/device_utils.h"
#include "preprocess/transform/crop.h"
using namespace std;
namespace mmdeploy {
namespace cuda {
template <typename T, int channels>
void Crop(const T* src, int src_w, T* dst, int dst_h, int dst_w, int offset_h, int offset_w,
cudaStream_t stream);
class CenterCropImpl : public ::mmdeploy::CenterCropImpl {
public:
explicit CenterCropImpl(const Value& args) : ::mmdeploy::CenterCropImpl(args) {}
protected:
Result<Tensor> CropImage(const Tensor& tensor, int top, int left, int bottom,
int right) override {
OUTCOME_TRY(auto device_tensor, MakeAvailableOnDevice(tensor, device_, stream_));
auto stream = GetNative<cudaStream_t>(stream_);
auto desc = device_tensor.desc();
int h = bottom - top + 1;
int w = right - left + 1;
int c = desc.shape[3];
auto type = desc.data_type;
TensorShape shape{1, bottom - top + 1, right - left + 1, tensor.desc().shape[3]};
TensorDesc dst_desc{device_, tensor.desc().data_type, shape, desc.name};
Tensor dst_tensor{dst_desc};
assert(device_.is_device());
if (DataType::kINT8 == type) {
uint8_t* input = device_tensor.data<uint8_t>();
uint8_t* output = dst_tensor.data<uint8_t>();
if (3 == c) {
Crop<uint8_t, 3>(input, desc.shape[2], output, h, w, top, left, stream);
} else if (1 == c) {
Crop<uint8_t, 1>(input, desc.shape[2], output, h, w, top, left, stream);
} else {
ERROR("unsupported channels {}", c);
return Status(eNotSupported);
}
} else if (DataType::kFLOAT == type) {
float* input = static_cast<float*>(device_tensor.buffer().GetNative());
float* output = static_cast<float*>(dst_tensor.buffer().GetNative());
if (3 == c) {
Crop<float, 3>(input, desc.shape[2], output, h, w, top, left, stream);
} else if (1 == c) {
Crop<float, 1>(input, desc.shape[2], output, h, w, top, left, stream);
} else {
ERROR("unsupported channels {}", c);
return Status(eNotSupported);
}
} else {
ERROR("unsupported channels {}", c);
return Status(eNotSupported);
}
return dst_tensor;
}
};
class CenterCropImplCreator : public Creator<::mmdeploy::CenterCropImpl> {
public:
const char* GetName() const override { return "cuda"; }
int GetVersion() const override { return 1; }
ReturnType Create(const Value& args) override { return make_unique<CenterCropImpl>(args); }
private:
int version_{1};
};
} // namespace cuda
} // namespace mmdeploy
using ::mmdeploy::CenterCropImpl;
using ::mmdeploy::cuda::CenterCropImplCreator;
REGISTER_MODULE(CenterCropImpl, CenterCropImplCreator);
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatsub/MDbM7x13a.cpp
// \brief Source file for the MDbM7x13a dense matrix/dense matrix subtraction math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MDbM7x13a'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::DynamicMatrix<TypeB> MDb;
typedef blaze::StaticMatrix<TypeA,7UL,13UL> M7x13a;
// Creator type definitions
typedef blazetest::Creator<MDb> CMDb;
typedef blazetest::Creator<M7x13a> CM7x13a;
// Running the tests
RUN_DMATDMATSUB_OPERATION_TEST( CMDb( 7UL, 13UL ), CM7x13a() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
; A281746: Nonnegative numbers k such that k == 0 (mod 3) or k == 0 (mod 5).
; 0,3,5,6,9,10,12,15,18,20,21,24,25,27,30,33,35,36,39,40,42,45,48,50,51,54,55,57,60,63,65,66,69,70,72,75,78,80,81,84,85,87,90,93,95,96,99,100,102,105,108,110,111,114,115,117,120,123,125,126,129,130,132,135,138,140,141,144,145,147,150,153,155,156,159,160,162,165,168,170,171,174,175,177,180,183,185,186,189,190,192,195,198,200,201,204,205,207,210,213,215,216,219,220,222,225,228,230,231,234,235,237,240,243,245,246,249,250,252,255,258,260,261,264,265,267,270,273,275,276,279,280,282,285,288,290,291,294,295,297,300,303,305,306,309,310,312,315,318,320,321,324,325,327,330,333,335,336,339,340,342,345,348,350,351,354,355,357,360,363,365,366,369,370,372,375,378,380,381,384,385,387,390,393,395,396,399,400,402,405,408,410,411,414,415,417,420,423,425,426,429,430,432,435,438,440,441,444,445,447,450,453,455,456,459,460,462,465,468,470,471,474,475,477,480,483,485,486,489,490,492,495,498,500,501,504,505,507,510,513,515,516,519,520,522,525,528,530,531,534
mov $3,$0
mov $9,$0
lpb $3,1
mov $0,$9
sub $3,1
sub $0,$3
mov $2,$0
mov $4,2
mov $5,4
mov $6,4
mov $7,3
add $7,$0
sub $7,2
lpb $2,1
add $6,$7
lpb $4,1
sub $4,1
add $5,1
add $6,8
mov $8,1
lpe
mov $7,7
lpb $5,1
mov $2,$0
mod $2,7
sub $2,$8
add $7,$6
sub $7,$5
sub $5,$8
lpe
lpb $6,1
add $2,1
mov $6,8
div $7,2
lpe
mov $0,3
mul $0,$7
trn $2,1
mov $4,5
sub $4,$2
mov $6,$5
mov $5,10
lpe
mov $7,$4
sub $7,2
add $1,$7
lpe
|
//
// 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2018-2019 NVIDIA Corporation. All rights reserved.
#include "ApexVertexFormat.h"
#include "ApexSDKIntl.h"
#include <ParamArray.h>
namespace nvidia
{
namespace apex
{
// Local functions and definitions
PX_INLINE char* apex_strdup(const char* input)
{
if (input == NULL)
{
return NULL;
}
size_t len = strlen(input);
char* result = (char*)PX_ALLOC(sizeof(char) * (len + 1), PX_DEBUG_EXP("apex_strdup"));
#ifdef WIN32
strncpy_s(result, len + 1, input, len);
#else
strncpy(result, input, len);
#endif
return result;
}
PX_INLINE uint32_t hash(const char* string)
{
// "DJB" string hash
uint32_t h = 5381;
char c;
while ((c = *string++) != '\0')
{
h = ((h << 5) + h) ^ c;
}
return h;
}
struct SemanticNameAndID
{
SemanticNameAndID(const char* name, VertexFormat::BufferID id) : m_name(name), m_id(id)
{
PX_ASSERT(m_id != 0 || nvidia::strcmp(m_name, "SEMANTIC_INVALID") == 0);
}
const char* m_name;
VertexFormat::BufferID m_id;
};
#define SEMANTIC_NAME_AND_ID( name ) SemanticNameAndID( name, (VertexFormat::BufferID)hash( name ) )
static const SemanticNameAndID sSemanticNamesAndIDs[] =
{
SEMANTIC_NAME_AND_ID("SEMANTIC_POSITION"),
SEMANTIC_NAME_AND_ID("SEMANTIC_NORMAL"),
SEMANTIC_NAME_AND_ID("SEMANTIC_TANGENT"),
SEMANTIC_NAME_AND_ID("SEMANTIC_BINORMAL"),
SEMANTIC_NAME_AND_ID("SEMANTIC_COLOR"),
SEMANTIC_NAME_AND_ID("SEMANTIC_TEXCOORD0"),
SEMANTIC_NAME_AND_ID("SEMANTIC_TEXCOORD1"),
SEMANTIC_NAME_AND_ID("SEMANTIC_TEXCOORD2"),
SEMANTIC_NAME_AND_ID("SEMANTIC_TEXCOORD3"),
SEMANTIC_NAME_AND_ID("SEMANTIC_BONE_INDEX"),
SEMANTIC_NAME_AND_ID("SEMANTIC_BONE_WEIGHT"),
SEMANTIC_NAME_AND_ID("SEMANTIC_DISPLACEMENT_TEXCOORD"),
SEMANTIC_NAME_AND_ID("SEMANTIC_DISPLACEMENT_FLAGS"),
SemanticNameAndID("SEMANTIC_INVALID", (VertexFormat::BufferID)0)
};
// VertexFormat implementation
void ApexVertexFormat::reset()
{
if (mParams != NULL)
{
mParams->winding = 0;
mParams->hasSeparateBoneBuffer = 0;
}
clearBuffers();
}
void ApexVertexFormat::setWinding(RenderCullMode::Enum winding)
{
mParams->winding = winding;
}
void ApexVertexFormat::setHasSeparateBoneBuffer(bool hasSeparateBoneBuffer)
{
mParams->hasSeparateBoneBuffer = hasSeparateBoneBuffer;
}
RenderCullMode::Enum ApexVertexFormat::getWinding() const
{
return (RenderCullMode::Enum)mParams->winding;
}
bool ApexVertexFormat::hasSeparateBoneBuffer() const
{
return mParams->hasSeparateBoneBuffer;
}
const char* ApexVertexFormat::getSemanticName(RenderVertexSemantic::Enum semantic) const
{
PX_ASSERT((uint32_t)semantic < RenderVertexSemantic::NUM_SEMANTICS);
return (uint32_t)semantic < RenderVertexSemantic::NUM_SEMANTICS ? sSemanticNamesAndIDs[semantic].m_name : NULL;
}
VertexFormat::BufferID ApexVertexFormat::getSemanticID(RenderVertexSemantic::Enum semantic) const
{
PX_ASSERT((uint32_t)semantic < RenderVertexSemantic::NUM_SEMANTICS);
return (uint32_t)semantic < RenderVertexSemantic::NUM_SEMANTICS ? sSemanticNamesAndIDs[semantic].m_id : (BufferID)0;
}
VertexFormat::BufferID ApexVertexFormat::getID(const char* name) const
{
if (name == NULL)
{
return (BufferID)0;
}
const BufferID id = hash(name);
return id ? id : (BufferID)1; // We reserve 0 for an invalid ID
}
int32_t ApexVertexFormat::addBuffer(const char* name)
{
if (name == NULL)
{
return -1;
}
const BufferID id = getID(name);
int32_t index = getBufferIndexFromID(id);
if (index >= 0)
{
return index;
}
int32_t semantic = 0;
for (; semantic < RenderVertexSemantic::NUM_SEMANTICS; ++semantic)
{
if (getSemanticID((RenderVertexSemantic::Enum)semantic) == id)
{
break;
}
}
if (semantic == RenderVertexSemantic::NUM_SEMANTICS)
{
semantic = RenderVertexSemantic::CUSTOM;
}
NvParameterized::Handle handle(*mParams);
mParams->getParameterHandle("bufferFormats", handle);
mParams->getArraySize(handle, index);
mParams->resizeArray(handle, index + 1);
NvParameterized::Handle elementHandle(*mParams);
handle.getChildHandle(index, elementHandle);
NvParameterized::Handle subElementHandle(*mParams);
elementHandle.getChildHandle(mParams, "name", subElementHandle);
mParams->setParamString(subElementHandle, name);
elementHandle.getChildHandle(mParams, "semantic", subElementHandle);
mParams->setParamI32(subElementHandle, semantic);
elementHandle.getChildHandle(mParams, "id", subElementHandle);
mParams->setParamU32(subElementHandle, (uint32_t)id);
elementHandle.getChildHandle(mParams, "format", subElementHandle);
mParams->setParamU32(subElementHandle, (uint32_t)RenderDataFormat::UNSPECIFIED);
elementHandle.getChildHandle(mParams, "access", subElementHandle);
mParams->setParamU32(subElementHandle, (uint32_t)RenderDataAccess::STATIC);
elementHandle.getChildHandle(mParams, "serialize", subElementHandle);
mParams->setParamBool(subElementHandle, true);
return index;
}
bool ApexVertexFormat::bufferReplaceWithLast(uint32_t index)
{
PX_ASSERT((int32_t)index < mParams->bufferFormats.arraySizes[0]);
if ((int32_t)index < mParams->bufferFormats.arraySizes[0])
{
ParamArray<VertexFormatParametersNS::BufferFormat_Type> bufferFormats(mParams, "bufferFormats", reinterpret_cast<ParamDynamicArrayStruct*>(&mParams->bufferFormats));
bufferFormats.replaceWithLast(index);
return true;
}
return false;
}
bool ApexVertexFormat::setBufferFormat(uint32_t index, RenderDataFormat::Enum format)
{
if (index < getBufferCount())
{
mParams->bufferFormats.buf[index].format = format;
return true;
}
return false;
}
bool ApexVertexFormat::setBufferAccess(uint32_t index, RenderDataAccess::Enum access)
{
if (index < getBufferCount())
{
mParams->bufferFormats.buf[index].access = access;
return true;
}
return false;
}
bool ApexVertexFormat::setBufferSerialize(uint32_t index, bool serialize)
{
if (index < getBufferCount())
{
mParams->bufferFormats.buf[index].serialize = serialize;
return true;
}
return false;
}
const char* ApexVertexFormat::getBufferName(uint32_t index) const
{
return index < getBufferCount() ? (const char*)mParams->bufferFormats.buf[index].name : NULL;
}
RenderVertexSemantic::Enum ApexVertexFormat::getBufferSemantic(uint32_t index) const
{
return index < getBufferCount() ? (RenderVertexSemantic::Enum)mParams->bufferFormats.buf[index].semantic : RenderVertexSemantic::NUM_SEMANTICS;
}
VertexFormat::BufferID ApexVertexFormat::getBufferID(uint32_t index) const
{
return index < getBufferCount() ? (BufferID)mParams->bufferFormats.buf[index].id : (BufferID)0;
}
RenderDataFormat::Enum ApexVertexFormat::getBufferFormat(uint32_t index) const
{
return index < getBufferCount() ? (RenderDataFormat::Enum)mParams->bufferFormats.buf[index].format : RenderDataFormat::UNSPECIFIED;
}
RenderDataAccess::Enum ApexVertexFormat::getBufferAccess(uint32_t index) const
{
return index < getBufferCount() ? (RenderDataAccess::Enum)mParams->bufferFormats.buf[index].access : RenderDataAccess::ACCESS_TYPE_COUNT;
}
bool ApexVertexFormat::getBufferSerialize(uint32_t index) const
{
return index < getBufferCount() ? mParams->bufferFormats.buf[index].serialize : false;
}
uint32_t ApexVertexFormat::getBufferCount() const
{
return (uint32_t)mParams->bufferFormats.arraySizes[0];
}
uint32_t ApexVertexFormat::getCustomBufferCount() const
{
PX_ASSERT(mParams != NULL);
uint32_t customBufferCount = 0;
for (int32_t i = 0; i < mParams->bufferFormats.arraySizes[0]; ++i)
{
if (mParams->bufferFormats.buf[i].semantic == RenderVertexSemantic::CUSTOM)
{
++customBufferCount;
}
}
return customBufferCount;
}
int32_t ApexVertexFormat::getBufferIndexFromID(BufferID id) const
{
for (int32_t i = 0; i < mParams->bufferFormats.arraySizes[0]; ++i)
{
if (mParams->bufferFormats.buf[i].id == (uint32_t)id)
{
return i;
}
}
return -1;
}
// ApexVertexFormat functions
ApexVertexFormat::ApexVertexFormat()
{
NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
mParams = DYNAMIC_CAST(VertexFormatParameters*)(traits->createNvParameterized(VertexFormatParameters::staticClassName()));
mOwnsParams = mParams != NULL;
}
ApexVertexFormat::ApexVertexFormat(VertexFormatParameters* params) : mParams(params), mOwnsParams(false)
{
}
ApexVertexFormat::ApexVertexFormat(const ApexVertexFormat& f) : VertexFormat(f)
{
NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
mParams = DYNAMIC_CAST(VertexFormatParameters*)(traits->createNvParameterized(VertexFormatParameters::staticClassName()));
mOwnsParams = mParams != NULL;
if (mParams)
{
copy(f);
}
}
ApexVertexFormat::~ApexVertexFormat()
{
if (mOwnsParams && mParams != NULL)
{
mParams->destroy();
}
}
bool ApexVertexFormat::operator == (const VertexFormat& format) const
{
if (getWinding() != format.getWinding())
{
return false;
}
if (hasSeparateBoneBuffer() != format.hasSeparateBoneBuffer())
{
return false;
}
if (getBufferCount() != format.getBufferCount())
{
return false;
}
for (uint32_t thisIndex = 0; thisIndex < getBufferCount(); ++thisIndex)
{
BufferID id = getBufferID(thisIndex);
const int32_t thatIndex = format.getBufferIndexFromID(id);
if (thatIndex < 0)
{
return false;
}
if (getBufferFormat(thisIndex) != format.getBufferFormat((uint32_t)thatIndex))
{
return false;
}
if (getBufferAccess(thisIndex) != format.getBufferAccess((uint32_t)thatIndex))
{
return false;
}
}
return true;
}
void ApexVertexFormat::copy(const ApexVertexFormat& other)
{
reset();
setWinding(other.getWinding());
setHasSeparateBoneBuffer(other.hasSeparateBoneBuffer());
for (uint32_t i = 0; i < other.getBufferCount(); ++i)
{
const char* name = other.getBufferName(i);
const uint32_t index = (uint32_t)addBuffer(name);
setBufferFormat(index, other.getBufferFormat(i));
setBufferAccess(index, other.getBufferAccess(i));
setBufferSerialize(index, other.getBufferSerialize(i));
}
}
void ApexVertexFormat::clearBuffers()
{
if (mParams)
{
NvParameterized::Handle handle(*mParams);
mParams->getParameterHandle("bufferFormats", handle);
handle.resizeArray(0);
}
}
}
} // end namespace nvidia::apex
|
/**
* Copyright [2013-2014] [OHsystem]
*
* We spent a lot of time writing this code, so show some respect:
* - Do not remove this copyright notice anywhere (bot, website etc.)
* - We do not provide support to those who removed copyright notice
*
* OHSystem is free software: You can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You can contact the developers on: admin@ohsystem.net
* or join us directly here: http://forum.ohsystem.net/
*
* Visit us also on http://ohsystem.net/ and keep track always of the latest
* features and changes.
*
*
* This is modified from GHOST++: http://ghostplusplus.googlecode.com/
*/
#include "ghost.h"
#include "util.h"
#include "ghostdb.h"
#include "gameplayer.h"
#include "gameprotocol.h"
#include "game_base.h"
#include "stats.h"
#include "statsw3mmd.h"
//
// CStatsW3MMD
//
CStatsW3MMD :: CStatsW3MMD( CBaseGame *nGame, string nCategory ) : CStats( nGame ), m_Category( nCategory ), m_NextValueID( 0 ), m_NextCheckID( 0 )
{
CONSOLE_Print( "[STATSW3MMD] using Warcraft 3 Map Meta Data stats parser version 1" );
CONSOLE_Print( "[STATSW3MMD] using map_statsw3mmdcategory [" + nCategory + "]" );
}
CStatsW3MMD :: ~CStatsW3MMD( )
{
}
bool CStatsW3MMD :: ProcessAction( CIncomingAction *Action )
{
unsigned int i = 0;
BYTEARRAY *ActionData = Action->GetAction( );
BYTEARRAY MissionKey;
BYTEARRAY Key;
BYTEARRAY Value;
while( ActionData->size( ) >= i + 9 )
{
if( (*ActionData)[i] == 'k' &&
(*ActionData)[i + 1] == 'M' &&
(*ActionData)[i + 2] == 'M' &&
(*ActionData)[i + 3] == 'D' &&
(*ActionData)[i + 4] == '.' &&
(*ActionData)[i + 5] == 'D' &&
(*ActionData)[i + 6] == 'a' &&
(*ActionData)[i + 7] == 't' &&
(*ActionData)[i + 8] == 0x00 )
{
if( ActionData->size( ) >= i + 10 )
{
MissionKey = UTIL_ExtractCString( *ActionData, i + 9 );
if( ActionData->size( ) >= i + 11 + MissionKey.size( ) )
{
Key = UTIL_ExtractCString( *ActionData, i + 10 + MissionKey.size( ) );
if( ActionData->size( ) >= i + 15 + MissionKey.size( ) + Key.size( ) )
{
Value = BYTEARRAY( ActionData->begin( ) + i + 11 + MissionKey.size( ) + Key.size( ), ActionData->begin( ) + i + 15 + MissionKey.size( ) + Key.size( ) );
string MissionKeyString = string( MissionKey.begin( ), MissionKey.end( ) );
string KeyString = string( Key.begin( ), Key.end( ) );
uint32_t ValueInt = UTIL_ByteArrayToUInt32( Value, false );
// CONSOLE_Print( "[STATSW3MMD] DEBUG: mkey [" + MissionKeyString + "], key [" + KeyString + "], value [" + UTIL_ToString( ValueInt ) + "]" );
if( MissionKeyString.size( ) > 4 && MissionKeyString.substr( 0, 4 ) == "val:" )
{
string ValueIDString = MissionKeyString.substr( 4 );
uint32_t ValueID = UTIL_ToUInt32( ValueIDString );
vector<string> Tokens = TokenizeKey( KeyString );
if( !Tokens.empty( ) )
{
if( Tokens[0] == "init" && Tokens.size( ) >= 2 )
{
if( Tokens[1] == "version" && Tokens.size( ) == 4 )
{
// Tokens[2] = minimum
// Tokens[3] = current
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] map is using Warcraft 3 Map Meta Data library version [" + Tokens[3] + "]" );
if( UTIL_ToUInt32( Tokens[2] ) > 1 )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] warning - parser version 1 is not compatible with this map, minimum version [" + Tokens[2] + "]" );
}
else if( Tokens[1] == "pid" && Tokens.size( ) == 4 )
{
// Tokens[2] = pid
// Tokens[3] = name
uint32_t PID = UTIL_ToUInt32( Tokens[2] );
if( m_PIDToName.find( PID ) != m_PIDToName.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] overwriting previous name [" + m_PIDToName[PID] + "] with new name [" + Tokens[3] + "] for PID [" + Tokens[2] + "]" );
m_PIDToName[PID] = Tokens[3];
}
}
else if( Tokens[0] == "DefVarP" && Tokens.size( ) == 5 )
{
// Tokens[1] = name
// Tokens[2] = value type
// Tokens[3] = goal type (ignored here)
// Tokens[4] = suggestion (ignored here)
if( m_DefVarPs.find( Tokens[1] ) != m_DefVarPs.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] duplicate DefVarP [" + KeyString + "] found, ignoring" );
else
{
if( Tokens[2] == "int" || Tokens[2] == "real" || Tokens[2] == "string" )
m_DefVarPs[Tokens[1]] = Tokens[2];
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown DefVarP [" + KeyString + "] found, ignoring" );
}
}
else if( Tokens[0] == "VarP" && Tokens.size( ) == 5 )
{
// Tokens[1] = pid
// Tokens[2] = name
// Tokens[3] = operation
// Tokens[4] = value
if( m_DefVarPs.find( Tokens[2] ) == m_DefVarPs.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] VarP [" + KeyString + "] found without a corresponding DefVarP, ignoring" );
else
{
string ValueType = m_DefVarPs[Tokens[2]];
if( ValueType == "int" )
{
VarP VP = VarP( UTIL_ToUInt32( Tokens[1] ), Tokens[2] );
if( Tokens[3] == "=" )
m_VarPInts[VP] = UTIL_ToInt32( Tokens[4] );
else if( Tokens[3] == "+=" )
{
if( m_VarPInts.find( VP ) != m_VarPInts.end( ) )
m_VarPInts[VP] += UTIL_ToInt32( Tokens[4] );
else
{
// CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] int VarP [" + KeyString + "] found with relative operation [+=] without a previously assigned value, ignoring" );
m_VarPInts[VP] = UTIL_ToInt32( Tokens[4] );
}
}
else if( Tokens[3] == "-=" )
{
if( m_VarPInts.find( VP ) != m_VarPInts.end( ) )
m_VarPInts[VP] -= UTIL_ToInt32( Tokens[4] );
else
{
// CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] int VarP [" + KeyString + "] found with relative operation [-=] without a previously assigned value, ignoring" );
m_VarPInts[VP] = -UTIL_ToInt32( Tokens[4] );
}
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown int VarP [" + KeyString + "] operation [" + Tokens[3] + "] found, ignoring" );
}
else if( ValueType == "real" )
{
VarP VP = VarP( UTIL_ToUInt32( Tokens[1] ), Tokens[2] );
if( Tokens[3] == "=" )
m_VarPReals[VP] = UTIL_ToDouble( Tokens[4] );
else if( Tokens[3] == "+=" )
{
if( m_VarPReals.find( VP ) != m_VarPReals.end( ) )
m_VarPReals[VP] += UTIL_ToDouble( Tokens[4] );
else
{
// CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] real VarP [" + KeyString + "] found with relative operation [+=] without a previously assigned value, ignoring" );
m_VarPReals[VP] = UTIL_ToDouble( Tokens[4] );
}
}
else if( Tokens[3] == "-=" )
{
if( m_VarPReals.find( VP ) != m_VarPReals.end( ) )
m_VarPReals[VP] -= UTIL_ToDouble( Tokens[4] );
else
{
// CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] real VarP [" + KeyString + "] found with relative operation [-=] without a previously assigned value, ignoring" );
m_VarPReals[VP] = -UTIL_ToDouble( Tokens[4] );
}
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown real VarP [" + KeyString + "] operation [" + Tokens[3] + "] found, ignoring" );
}
else
{
VarP VP = VarP( UTIL_ToUInt32( Tokens[1] ), Tokens[2] );
if( Tokens[3] == "=" )
m_VarPStrings[VP] = Tokens[4];
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown string VarP [" + KeyString + "] operation [" + Tokens[3] + "] found, ignoring" );
}
}
}
else if( Tokens[0] == "FlagP" && Tokens.size( ) == 3 )
{
// Tokens[1] = pid
// Tokens[2] = flag
if( Tokens[2] == "winner" || Tokens[2] == "loser" || Tokens[2] == "drawer" || Tokens[2] == "leaver" || Tokens[2] == "practicing" )
{
uint32_t PID = UTIL_ToUInt32( Tokens[1] );
if( Tokens[2] == "leaver" )
m_FlagsLeaver[PID] = true;
else if( Tokens[2] == "practicing" )
m_FlagsPracticing[PID] = true;
else
{
if( m_Flags.find( PID ) != m_Flags.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] overwriting previous flag [" + m_Flags[PID] + "] with new flag [" + Tokens[2] + "] for PID [" + Tokens[1] + "]" );
m_Flags[PID] = Tokens[2];
}
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown flag [" + Tokens[2] + "] found, ignoring" );
}
else if( Tokens[0] == "DefEvent" && Tokens.size( ) >= 4 )
{
// Tokens[1] = name
// Tokens[2] = # of arguments (n)
// Tokens[3..n+3] = arguments
// Tokens[n+3] = format
if( m_DefEvents.find( Tokens[1] ) != m_DefEvents.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] duplicate DefEvent [" + KeyString + "] found, ignoring" );
else
{
uint32_t Arguments = UTIL_ToUInt32( Tokens[2] );
if( Tokens.size( ) == Arguments + 4 )
m_DefEvents[Tokens[1]] = vector<string>( Tokens.begin( ) + 3, Tokens.end( ) );
}
}
else if( Tokens[0] == "Event" && Tokens.size( ) >= 2 )
{
// Tokens[1] = name
// Tokens[2..n+2] = arguments (where n is the # of arguments in the corresponding DefEvent)
if( m_DefEvents.find( Tokens[1] ) == m_DefEvents.end( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] Event [" + KeyString + "] found without a corresponding DefEvent, ignoring" );
else
{
vector<string> DefEvent = m_DefEvents[Tokens[1]];
if( !DefEvent.empty( ) )
{
string Format = DefEvent[DefEvent.size( ) - 1];
if( Tokens.size( ) - 2 != DefEvent.size( ) - 1 )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] Event [" + KeyString + "] found with " + UTIL_ToString( Tokens.size( ) - 2 ) + " arguments but expected " + UTIL_ToString( DefEvent.size( ) - 1 ) + " arguments, ignoring" );
else
{
// replace the markers in the format string with the arguments
for( uint32_t i = 0; i < Tokens.size( ) - 2; ++i )
{
// check if the marker is a PID marker
if( DefEvent[i].substr( 0, 4 ) == "pid:" )
{
// replace it with the player's name rather than their PID
uint32_t PID = UTIL_ToUInt32( Tokens[i + 2] );
if( m_PIDToName.find( PID ) == m_PIDToName.end( ) )
UTIL_Replace( Format, "{" + UTIL_ToString( i ) + "}", "PID:" + Tokens[i + 2] );
else
UTIL_Replace( Format, "{" + UTIL_ToString( i ) + "}", m_PIDToName[PID] );
}
else
UTIL_Replace( Format, "{" + UTIL_ToString( i ) + "}", Tokens[i + 2] );
}
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] " + Format );
}
}
}
// CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] event [" + KeyString + "]" );
}
else if( Tokens[0] == "Blank" )
{
// ignore
}
else if( Tokens[0] == "Custom" )
{
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] custom [" + KeyString + "]" );
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown message type [" + Tokens[0] + "] found, ignoring" );
}
++m_NextValueID;
}
else if( MissionKeyString.size( ) > 4 && MissionKeyString.substr( 0, 4 ) == "chk:" )
{
string CheckIDString = MissionKeyString.substr( 4 );
uint32_t CheckID = UTIL_ToUInt32( CheckIDString );
// todotodo: cheat detection
++m_NextCheckID;
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unknown mission key [" + MissionKeyString + "] found, ignoring" );
i += 15 + MissionKey.size( ) + Key.size( );
}
else
++i;
}
else
++i;
}
else
++i;
}
else
++i;
}
return false;
}
void CStatsW3MMD :: Save( CGHost *GHost, CGHostDB *DB, uint32_t GameID )
{
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] received " + UTIL_ToString( m_NextValueID ) + "/" + UTIL_ToString( m_NextCheckID ) + " value/check messages" );
if( DB->Begin( ) )
{
// todotodo: there's no reason to create a new callable for each entry in this map
// rewrite ThreadedW3MMDPlayerAdd to act more like ThreadedW3MMDVarAdd
for( map<uint32_t,string> :: iterator i = m_PIDToName.begin( ); i != m_PIDToName.end( ); ++i )
{
string Flags = m_Flags[i->first];
uint32_t Leaver = 0;
uint32_t Practicing = 0;
if( m_FlagsLeaver.find( i->first ) != m_FlagsLeaver.end( ) && m_FlagsLeaver[i->first] )
{
Leaver = 1;
if( !Flags.empty( ) )
Flags += "/";
Flags += "leaver";
}
if( m_FlagsPracticing.find( i->first ) != m_FlagsPracticing.end( ) && m_FlagsPracticing[i->first] )
{
Practicing = 1;
if( !Flags.empty( ) )
Flags += "/";
Flags += "practicing";
}
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] recorded flags [" + Flags + "] for player [" + i->second + "] with PID [" + UTIL_ToString( i->first ) + "]" );
GHost->m_Callables.push_back( DB->ThreadedW3MMDPlayerAdd( m_Category, GameID, i->first, i->second, m_Flags[i->first], Leaver, Practicing ) );
}
if( !m_VarPInts.empty( ) )
GHost->m_Callables.push_back( DB->ThreadedW3MMDVarAdd( GameID, m_VarPInts ) );
if( !m_VarPReals.empty( ) )
GHost->m_Callables.push_back( DB->ThreadedW3MMDVarAdd( GameID, m_VarPReals ) );
if( !m_VarPStrings.empty( ) )
GHost->m_Callables.push_back( DB->ThreadedW3MMDVarAdd( GameID, m_VarPStrings ) );
if( DB->Commit( ) )
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] saving data" );
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unable to commit database transaction, data not saved" );
}
else
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] unable to begin database transaction, data not saved" );
}
vector<string> CStatsW3MMD :: TokenizeKey( string key )
{
vector<string> Tokens;
string Token;
bool Escaping = false;
for( string :: iterator i = key.begin( ); i != key.end( ); ++i )
{
if( Escaping )
{
if( *i == ' ' )
Token += ' ';
else if( *i == '\\' )
Token += '\\';
else
{
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] error tokenizing key [" + key + "], invalid escape sequence found, ignoring" );
return vector<string>( );
}
Escaping = false;
}
else
{
if( *i == ' ' )
{
if( Token.empty( ) )
{
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] error tokenizing key [" + key + "], empty token found, ignoring" );
return vector<string>( );
}
Tokens.push_back( Token );
Token.clear( );
}
else if( *i == '\\' )
Escaping = true;
else
Token += *i;
}
}
if( Token.empty( ) )
{
CONSOLE_Print( "[STATSW3MMD: " + m_Game->GetGameName( ) + "] error tokenizing key [" + key + "], empty token found, ignoring" );
return vector<string>( );
}
Tokens.push_back( Token );
return Tokens;
}
void CStatsW3MMD :: SetWinner( uint32_t nWinner )
{
for( vector<CGamePlayer *> :: iterator i = m_Game->m_Players.begin( ); i != m_Game->m_Players.end( ); i++)
{
unsigned char playerSID = m_Game->GetSIDFromPID( (*i)->GetPID( ) );
if( playerSID < m_Game->m_Slots.size( ) )
{
unsigned char playerTeam = m_Game->m_Slots[playerSID].GetTeam( );
if( playerTeam == nWinner )
m_Flags[m_Game->m_Slots[playerSID].GetColour( )] = "winner";
else
m_Flags[m_Game->m_Slots[playerSID].GetColour( )] = "loser";
}
}
}
|
// Copyright 2015 EssaBlockChain Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "work/WorkManagerImpl.h"
#include "work/Work.h"
#include "work/WorkManager.h"
#include "work/WorkParent.h"
#include "lib/util/format.h"
#include "util/Logging.h"
#include "medida/meter.h"
#include "medida/metrics_registry.h"
namespace essa
{
WorkManager::WorkManager(Application& app) : WorkParent(app)
{
}
WorkManager::~WorkManager()
{
}
WorkManagerImpl::WorkManagerImpl(Application& app) : WorkManager(app)
{
}
WorkManagerImpl::~WorkManagerImpl()
{
}
void
WorkManagerImpl::notify(std::string const& child)
{
auto i = mChildren.find(child);
if (i == mChildren.end())
{
CLOG(WARNING, "Work")
<< "WorkManager notified by unknown child " << child;
return;
}
if (i->second->getState() == Work::WORK_SUCCESS)
{
CLOG(INFO, "Work") << "WorkManager got SUCCESS from " << child;
mApp.getMetrics().NewMeter({"work", "root", "success"}, "unit").Mark();
mChildren.erase(child);
}
else if (i->second->getState() == Work::WORK_FAILURE_RAISE)
{
CLOG(WARNING, "Work") << "WorkManager got FAILURE_RAISE from " << child;
mApp.getMetrics().NewMeter({"work", "root", "failure"}, "unit").Mark();
mChildren.erase(child);
}
else if (i->second->getState() == Work::WORK_FAILURE_FATAL)
{
CLOG(WARNING, "Work") << "WorkManager got FAILURE_FATAL from " << child;
mApp.getMetrics().NewMeter({"work", "root", "failure"}, "unit").Mark();
mChildren.erase(child);
}
advanceChildren();
}
std::shared_ptr<WorkManager>
WorkManager::create(Application& app)
{
return std::make_shared<WorkManagerImpl>(app);
}
}
|
; A134165: Let P(A) be the power set of an n-element set A. Then a(n) = the number of pairs of elements {x,y} of P(A) for which either 0) x and y are disjoint and for which either x is a subset of y or y is a subset of x, or 1) x and y are disjoint and for which x is not a subset of y and y is not a subset of x, or 2) x and y are intersecting but for which x is not a subset of y and y is not a subset of x, or 3) x = y.
; Submitted by Jon Maiga
; 1,3,8,24,86,348,1478,6324,26846,112668,467798,1925124,7867406,31980588,129475718,522603924,2104600766,8461122108,33972973238,136278002724,546271650926
mov $1,3
pow $1,$0
mov $2,2
pow $2,$0
add $2,3
bin $2,2
sub $2,$1
mov $0,$2
sub $0,4
|
bits 32
section .text
align 4
dd 0x1BADB002
dd 0x00
dd - (0x1BADB002+0x00)
global start
extern init ; this function is gonna be located in our c code(kernel.c)
extern advertise ; yum
start:
cli ;clears the interrupts
call init ;send processor to continue execution from the kamin funtion in c code
call advertise
hlt ; halt the cpu(pause it from executing from this address
|
; #########################################################################
.386
.model flat, stdcall
option casemap :none ; case sensitive
; #########################################################################
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\shell32.inc
include \masm32\include\masm32.inc
include \masm32\include\comdlg32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\shell32.lib
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\comdlg32.lib
includelib \masm32\lib\user32.lib
include \masm32\include\user32.inc
; #########################################################################
.const
MAXSIZE equ 260 ; Max buffer size
.data
szAction db 'install', 0 ; Action
szFilename db 'tks_infl.ini', 0 ; Name of INI file
szAppName db 'Setup', 0 ; Section Name
szKeyName db 'INF', 0 ; Key name
szOpen db 'Open', 0 ; Open Dialog Title
szFilter db 'INF Files',0,'*.inf',0,0
hFile dd 0 ; File Handle
hInst dd 0 ; Program Instance
ofn OPENFILENAME <> ; OFN Structure
.data?
szBuffer db MAXSIZE dup (?) ; Name of INF file
szAppPath db MAXSIZE dup (?) ; Application Path
.code
start:
;=====================
; Get program instance
;=====================
invoke GetModuleHandle, NULL
mov hInst, eax
;=====================
; Get our command line
;=====================
;* Advanced INF Installer keeps
;* saying it can not find the file.
invoke ArgCl, 1, addr szBuffer
;=========================
; Check if our file exists
;=========================
invoke CreateFile, addr szBuffer, GENERIC_READ, FILE_SHARE_READ, NULL,\
OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, NULL
mov hFile, eax
.if eax == INVALID_HANDLE_VALUE
invoke CloseHandle, hFile
;=======================================
; Combine application path with INI file
;=======================================
mov byte ptr[szBuffer],0
invoke GetAppPath, addr szAppPath
invoke lstrcat, addr szBuffer, addr szAppPath
invoke lstrcat, addr szBuffer, addr szFilename
;==============
; Read INI file
;==============
invoke GetPrivateProfileString, addr szAppName, addr szKeyName, addr szFilename,
addr szBuffer, MAXSIZE, addr szBuffer
;=========================
; Check if our file exists
;=========================
invoke CreateFile, addr szBuffer, GENERIC_READ, FILE_SHARE_READ, NULL,\
OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, NULL
mov hFile, eax
.if eax == INVALID_HANDLE_VALUE
invoke CloseHandle, hFile
;===================================================
; Check if the user wants to run a diffrent INF file
;===================================================
mov byte ptr[szBuffer],0
mov ofn.lStructSize, sizeof ofn
push hInst
pop ofn.hWndOwner
push hInst
pop ofn.hInstance
mov ofn.lpstrFilter, offset szFilter
mov ofn.lpstrFile, offset szBuffer
mov ofn.nMaxFile, MAXSIZE
mov ofn.Flags, OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or\
OFN_LONGNAMES or OFN_EXPLORER or OFN_HIDEREADONLY
mov ofn.lpstrTitle, offset szOpen
invoke GetOpenFileName, addr ofn
;=================
; No file selected
;=================
.if eax == FALSE
jmp exit
.endif
.endif
.endif
;==========================
; Run our Installation File
;==========================
invoke ShellExecuteA, 0, addr szAction, addr szBuffer, 0, 0, 0
;=================
; Exit our program
;=================
exit:
invoke ExitProcess, 0
end start
|
/**
* Copyright 2011-2013 - Reliable Bits Software by Blommers IT. All Rights Reserved.
* Author Rick Blommers
*/
#include "util.h"
#include <QString>
#include "edbee/debug.h"
namespace edbee {
/// Converst all tabs to sapces of the given string, using the current tab/indent settings
/// It converts "\t" to spaces.
///
/// @param str the string where to convert the tabs to space
/// @param tabSize the size of a single tab. This needs to be at least 1
/// @return A string with all tabs converted to spaces
QString Util::convertTabsToSpaces(const QString& str, int tabSize )
{
Q_ASSERT(tabSize > 0);
QString result;
result.reserve( str.length() );
// append all characters to the result
for( int i=0,cnt=str.size(); i<cnt; ++i ) {
QChar c = str.at(i);
// when a tab character is used it is converted to the correct column
if( c == '\t' ) {
int amount = tabSize - result.length() % tabSize;
result.append( QStringLiteral(" ").repeated(amount) );
} else {
result.append(c);
}
}
return result;
}
/// This method returns all tab-column offsets of the given string
/// @param str the string to convert
/// @param tabSize the tab size to use for conversion
/// @return a vector with the character-offset in the given string that contains the given tab-column
QList<int> Util::tabColumnOffsets(const QString& str, int tabSize)
{
// build the resut (column 0 is always available)
QList<int> offsets;
offsets.push_back( 0);
int column = 0;
// iterate over all characters
for( int offset=0,cnt=str.size(); offset<cnt; ++offset ) {
QChar c = str.at(offset);
// when a tab character is found, we need to jump to the next column
if( c == '\t' ) {
int amount = tabSize - column % tabSize;
column += amount;
} else {
++column;
}
// when we've reached another tab-column, we add the column
if( column % tabSize == 0 ) {
offsets.push_back( offset+1 );
}
}
return offsets;
}
} // edbee
|
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include <base58.h>
CMasternodeConfig masternodeConfig;
void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex)
{
CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
entries.push_back(cme);
}
bool CMasternodeConfig::read(std::string& strErr)
{
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
if (!streamConfig.good()) {
FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
if (configFile != NULL) {
std::string strHeader = "# Masternode config file\n"
"# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
"# Example: mn1 127.0.0.2:18721 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
fclose(configFile);
}
return true; // Nothing to read, so just return
}
for (std::string line; std::getline(streamConfig, line); linenumber++) {
if (line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment) {
if (comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
iss.str(line);
iss.clear();
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
strErr = _("Could not parse masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
}
int port = 0;
std::string hostname = "";
SplitHostPort(ip, port, hostname);
if(port == 0 || hostname == "") {
strErr = _("Failed to parse host:port string") + "\n"+
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
if (Params().NetworkID() == CBaseChainParams::MAIN) {
if (port != 18721) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(must be 18721 for mainnet)");
streamConfig.close();
return false;
}
} else if (port == 18721) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(18721 could be used only on mainnet)");
streamConfig.close();
return false;
}
add(alias, ip, privKey, txHash, outputIndex);
}
streamConfig.close();
return true;
}
bool CMasternodeConfig::CMasternodeEntry::castOutputIndex(int &n)
{
try {
n = std::stoi(outputIndex);
} catch (const std::exception e) {
LogPrintf("%s: %s on getOutputIndex\n", __func__, e.what());
return false;
}
return true;
}
|
; A095669: Seventh column (m=6) of (1,4)-Pascal triangle A095666.
; 4,25,91,252,588,1218,2310,4092,6864,11011,17017,25480,37128,52836,73644,100776,135660,179949,235543,304612,389620,493350,618930,769860,950040,1163799,1415925,1711696,2056912,2457928,2921688,3455760,4068372
mov $1,$0
add $0,5
bin $0,$1
add $1,24
mul $0,$1
div $0,6
|
; A056159: a(n)=floor[10^(n-1)/n].
; 1,5,33,250,2000,16666,142857,1250000,11111111,100000000,909090909,8333333333,76923076923,714285714285,6666666666666,62500000000000,588235294117647,5555555555555555
mov $1,10
mov $3,1
add $3,$0
mov $2,$0
pow $1,$2
div $1,$3
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>fcntl64(vararg_0, vararg_1, vararg_2, vararg_3, vararg_4) -> str
Invokes the syscall fcntl64.
See 'man 2 fcntl64' for more information.
Arguments:
vararg(int): vararg
Returns:
long
</%docstring>
<%page args="vararg_0=None, vararg_1=None, vararg_2=None, vararg_3=None, vararg_4=None"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['vararg_0', 'vararg_1', 'vararg_2', 'vararg_3', 'vararg_4']
argument_values = [vararg_0, vararg_1, vararg_2, vararg_3, vararg_4]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_fcntl64']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* fcntl64(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
Name: zel_sut1.asm
Type: file
Size: 67193
Last-Modified: '2016-05-13T04:23:03Z'
SHA-1: D0F3ADD00907228A447F06487BA2D5A5EAD5930A
Description: null
|
0x00002920 nop; //----------------
0x00002938 nop; //----------------
0x00002950 move.l 0x2220,A0 ; //0,
0x00002968 jsr ix
0x00002980 move.l 0x2220,A0 ; //0,
0x00002998 move.l 0x2250,A1 ; //0,
0x000029b0 move.L (A0),(A1)
0x000029c8 xor.q D0,D0
0x000029e0 move.l 0x2140,A0 ; //640,
0x000029f8 move.w (A0),D0
0x00002a10 move.l 0x2250,A0 ; //0,
0x00002a28 move.L (A0),D1
0x00002a40 extL.Q D1
0x00002a58 mul.Q D0,D1
0x00002a70 move.l 0x2250,A0 ; //0,
0x00002a88 move.Q D1,(A0)
0x00002aa0 move.l 0x2260,A0 ; //0,
0x00002ab8 jsr iw
0x00002ad0 move.l 0x2260,A0 ; //0,
0x00002ae8 move.L (A0),D0
0x00002b00 extL.Q D0
0x00002b18 move.l 0x2250,A0 ; //0,
0x00002b30 move.Q (A0),D1
0x00002b48 div.Q D0,D1
0x00002b60 move.l 0x2250,A0 ; //0,
0x00002b78 move.Q D1,(A0)
0x00002b90 nop; //----------------
0x00002ba8 move.l 0x21a0,A0 ; //960,
0x00002bc0 move.l 0x22f0,A1 ; //0,
0x00002bd8 move.w (A0),(A1)
0x00002bf0 move.l 0x2300,A0 ; //0,
0x00002c08 jsr iy
0x00002c20 move.l 0x2300,A0 ; //0,
0x00002c38 move.L (A0),D0
0x00002c50 extL.Q D0
0x00002c68 xor.q D1,D1
0x00002c80 move.l 0x22f0,A0 ; //0,
0x00002c98 move.w (A0),D1
0x00002cb0 mul.Q D0,D1
0x00002cc8 move.l 0x22f0,A0 ; //0,
0x00002ce0 move.Q D1,(A0)
0x00002cf8 move.l 0x2310,A0 ; //0,
0x00002d10 jsr ih
0x00002d28 move.l 0x2310,A0 ; //0,
0x00002d40 move.L (A0),D0
0x00002d58 extL.Q D0
0x00002d70 move.l 0x22f0,A0 ; //0,
0x00002d88 move.Q (A0),D1
0x00002da0 div.Q D0,D1
0x00002db8 move.l 0x22f0,A0 ; //0,
0x00002dd0 move.Q D1,(A0)
0x00002de8 nop; //----------------
0x00002e00 move.l 0x23e0,A0 ; //0,
0x00002e18 jsr ia
0x00002e30 move.l 0x23e0,A0 ; //0,
0x00002e48 move.l 0x2410,A1 ; //0,
0x00002e60 move.L (A0),(A1)
0x00002e78 xor.q D0,D0
0x00002e90 move.l 0x23c0,A0 ; //1,
0x00002ea8 move.b (A0),D0
0x00002ec0 move.l 0x2410,A0 ; //0,
0x00002ed8 move.L (A0),D1
0x00002ef0 sub.L D0,D1
0x00002f08 move.l 0x2410,A0 ; //0,
0x00002f20 move.L D1,(A0)
0x00002f38 nop; //----------------
0x00002f50 move.l 0x2410,A0 ; //0,
0x00002f68 move.l 0x2480,A1 ; //0,
0x00002f80 move.L (A0),(A1)
0x00002f98 xor.q D0,D0
0x00002fb0 move.l 0x2440,A0 ; //1000,
0x00002fc8 move.w (A0),D0
0x00002fe0 move.l 0x2480,A0 ; //0,
0x00002ff8 move.L (A0),D1
0x00003010 extL.Q D1
0x00003028 mul.Q D0,D1
0x00003040 move.l 0x2480,A0 ; //0,
0x00003058 move.Q D1,(A0)
0x00003070 move.l 0x2510,A0 ; //0,
0x00003088 jsr in
0x000030a0 move.l 0x2510,A0 ; //0,
0x000030b8 move.l 0x2540,A1 ; //0,
0x000030d0 move.L (A0),(A1)
0x000030e8 xor.q D0,D0
0x00003100 move.l 0x24f0,A0 ; //3,
0x00003118 move.b (A0),D0
0x00003130 move.l 0x2540,A0 ; //0,
0x00003148 move.L (A0),D1
0x00003160 sub.L D0,D1
0x00003178 move.l 0x2540,A0 ; //0,
0x00003190 move.L D1,(A0)
0x000031a8 nop; //----------------
0x000031c0 move.l 0x2540,A0 ; //0,
0x000031d8 move.l 0x25b0,A1 ; //0,
0x000031f0 move.L (A0),(A1)
0x00003208 xor.q D0,D0
0x00003220 move.l 0x2570,A0 ; //10000,
0x00003238 move.w (A0),D0
0x00003250 move.l 0x25b0,A0 ; //0,
0x00003268 move.L (A0),D1
0x00003280 extL.Q D1
0x00003298 mul.Q D0,D1
0x000032b0 move.l 0x25b0,A0 ; //0,
0x000032c8 move.Q D1,(A0)
0x000032e0 move.l 0x25c0,A0 ; //0,
0x000032f8 jsr mlb
0x00003310 move.l 0x25c0,A0 ; //0,
0x00003328 move.l 0x25f0,A1 ; //0,
0x00003340 move.L (A0),(A1)
0x00003358 move.l 0x2480,A0 ; //0,
0x00003370 move.Q (A0),D0
0x00003388 move.l 0x25f0,A0 ; //0,
0x000033a0 move.L (A0),D1
0x000033b8 extL.Q D1
0x000033d0 add.Q D0,D1
0x000033e8 move.l 0x25f0,A0 ; //0,
0x00003400 move.Q D1,(A0)
0x00003418 move.l 0x25b0,A0 ; //0,
0x00003430 move.Q (A0),D0
0x00003448 move.l 0x25f0,A0 ; //0,
0x00003460 move.Q (A0),D1
0x00003478 add.Q D0,D1
0x00003490 move.l 0x25f0,A0 ; //0,
0x000034a8 move.Q D1,(A0)
0x000034c0 nop; //----------------
0x000034d8 nop; //----------------
0x000034f0 nop; //----------------
0x00003508 nop; //----------------
0x00003520 nop; //----------------
0x00003538 move.q A7,D7
0x00003550 move.l 0x2750,-(A7)
0x00003568 move.l 0x21c0,-(A7)
0x00003580 move.l 0x2270,-(A7)
0x00003598 move.l 0x2600,-(A7)
0x000035b0 move.l 0x27a0,-(A7)
0x000035c8 move.l 0x27e0,A0 ; //-1,
0x000035e0 jsr print
0x000035f8 move.q D7,A7
0x00003610 nop; //----------------
0x00003628 nop; //----------------
0x00003640 nop; //----------------
0x00003658 nop; //----------------
0x00003670 nop; //----------------
0x00003688 nop; //---------------- |
IDEAL
ASSUME CS:SEG2, DS:SEG2, ES:SEG2, SS:SEG2
SEGMENT SEG2 PUBLIC
EXTRN _XBYTE: BYTE, _XWORD: WORD, _XCODE: PROC
; r/m8 displacement
mov dh, [_XBYTE]
mov dh, [SI+_XBYTE]
; r/m16 displacement
mov dx, [_XWORD]
mov dx, [SI+_XWORD]
; moffs8 displacement
mov al, [_XBYTE]
; moffs16 displacement
mov ax, [_XWORD]
; imm16
mov ax, OFFSET _XBYTE
mov ax, OFFSET _XWORD
; JMP r/m16
jmp [DI+_XWORD]
call [DI+_XWORD]
; JMP rel16
jmp _XCODE
call _XCODE
ENDS
END
|
db "COTTONWEED@" ; species name
db "It can be carried"
next "away on even the"
next "gentlest breeze."
page "It may even float"
next "all the way to the"
next "next town.@"
|
; A173737: (10^n+44)/9 for n>0.
; Submitted by Jamie Morken(m1)
; 6,16,116,1116,11116,111116,1111116,11111116,111111116,1111111116,11111111116,111111111116,1111111111116,11111111111116,111111111111116,1111111111111116,11111111111111116,111111111111111116,1111111111111111116,11111111111111111116,111111111111111111116,1111111111111111111116,11111111111111111111116,111111111111111111111116,1111111111111111111111116,11111111111111111111111116,111111111111111111111111116,1111111111111111111111111116,11111111111111111111111111116,111111111111111111111111111116
seq $0,42 ; Unary representation of natural numbers.
div $0,5
mul $0,5
add $0,6
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r15
push %r8
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x18989, %r8
nop
and %rsi, %rsi
mov $0x6162636465666768, %r15
movq %r15, (%r8)
nop
nop
add %rbx, %rbx
lea addresses_D_ht+0xf293, %rbp
nop
nop
nop
nop
nop
and %rcx, %rcx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm4
vmovups %ymm4, (%rbp)
nop
nop
nop
nop
inc %r8
lea addresses_A_ht+0x1701d, %rsi
lea addresses_UC_ht+0x9c89, %rdi
nop
nop
nop
inc %r12
mov $20, %rcx
rep movsq
nop
sub %rbp, %rbp
lea addresses_UC_ht+0x1ca89, %rsi
lea addresses_normal_ht+0x4509, %rdi
add %rbp, %rbp
mov $23, %rcx
rep movsq
nop
nop
nop
nop
and $62782, %rbx
lea addresses_UC_ht+0x11089, %rbx
nop
nop
nop
nop
nop
xor %r15, %r15
movw $0x6162, (%rbx)
nop
nop
nop
nop
and %r8, %r8
lea addresses_A_ht+0x1ea2d, %rsi
lea addresses_normal_ht+0x3d89, %rdi
xor $45494, %r12
mov $48, %rcx
rep movsb
nop
nop
nop
nop
and %rbx, %rbx
lea addresses_UC_ht+0x2089, %rsi
lea addresses_D_ht+0xb1a9, %rdi
nop
nop
nop
nop
inc %r15
mov $5, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp %rdi, %rdi
lea addresses_UC_ht+0x7b89, %rbp
nop
nop
cmp %r8, %r8
movb (%rbp), %r15b
nop
nop
nop
nop
sub %r15, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WC+0x15089, %rdx
nop
sub $25869, %rsi
movl $0x51525354, (%rdx)
nop
nop
inc %rsi
// Faulty Load
lea addresses_D+0xd089, %rax
nop
cmp %rsi, %rsi
mov (%rax), %r13w
lea oracles, %rdx
and $0xff, %r13
shlq $12, %r13
mov (%rdx,%r13,1), %r13
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 7}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
# This seems to work, but I didn't check the distributions, or anything.
#@ tests the rand instrcuction
rand r1
rand r2
rand r3
rand r4
rand r5
rand r6
rand r7
rand r8
rand r9
rand r10
stop
|
[BotW_VSync_V208]
moduleMatches = 0x6267BFD0
.origin = codecave
setSwapInterval:
li r11, $keepVsync
cmpwi r11, 1
bne setSwapIntervalTo0
lis r11, fpsLimit@ha
lfs f12, fpsLimit@l(r11)
lis r11, const_30@ha
lfs f10, const_30@l(r11)
fcmpu cr0, f10, f12
beq setSwapIntervalTo2
# lis r11, const_60@ha
# lfs f10, const_60@l(r11)
# fcmpu cr0, f10, f12
# beq setSwapIntervalTo1
; Disable vsync for everything else
b setSwapIntervalTo0
setSwapIntervalTo0: ; Disable vsync
mflr r11
li r3, 0
bl import.gx2.GX2SetSwapInterval
mtlr r11
b _convertTicksToFrametime
setSwapIntervalTo1: ; Double Buffered 30FPS
mflr r11
li r3, 1
bl import.gx2.GX2SetSwapInterval
mtlr r11
b _convertTicksToFrametime
setSwapIntervalTo2: ; Double Buffered 30FPS
mflr r11
li r3, 2
bl import.gx2.GX2SetSwapInterval
mtlr r11
b _convertTicksToFrametime
waitForVsyncAddr:
.ptr 0x031FACD4
conditionalVsyncWait:
stwu r1, -0x20(r1)
li r12, $keepVsync
cmpwi r12, 1
beqlr
lis r12, waitForVsyncAddr@ha
lwz r12, waitForVsyncAddr@l(r12)
mtlr r12
blr
0x031FACCC = bla conditionalVsyncWait
conditionalSwapStatus:
li r6, $keepVsync
cmpwi r6, 1
beq continueSwapStatus
cmpw r12, r12
blr
continueSwapStatus:
cmplw r12, r0
blr
0x031FACF0 = bla conditionalSwapStatus
# Disable vsync entirely if not running at 30FPS
# 0x031FACD0 = .uint (($keepVsync == 1) * 0x4914DAB9) + (($keepVsync == 0) * 0x60000000)
# 0x031FACF4 = .uint (($keepVsync == 1) * 0x4180FFDC) + (($keepVsync == 0) * 0x60000000) |
; A137694: Numbers k such that 6k^2-2k = 3n^2-n for some integer n>0.
; 5,5577,6435661,7426747025,8570459630997,9890302987423321,11413401077026881245,13171054952586033533217,15199386001883205670450981,17540078275118266757666898665,20241235130100477955141930608237,23358367800057676441967030255006641,26955536200031428513551997772347055285,31106665416468468446962563462258246792057,35897064935068412556366284683448244450978301,41425181828403531621578245562135811838182167105,47804623932912740422888739012420043413017769860677
add $0,1
mul $0,4
sub $0,2
mov $1,3
mov $2,3
lpb $0
sub $0,1
add $2,$1
add $1,$2
add $1,$2
add $2,$1
lpe
sub $1,87
div $1,18
add $1,5
mov $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: print drivers
FILE: cursorSetCursorTab72ASCII.asm
AUTHOR: Dave Durran, 14 March 1990
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 3/14/90 Initial revision
Dave 3/92 moved from epson9 to printcom
DESCRIPTION:
The cursor position is kept in 2 words: integer <printer units> in Y
and integer 72nds in X
$Id: cursorSetCursorTab72ASCII.asm,v 1.1 97/04/18 11:49:44 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintSetCursor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS:
sets the new cursor position in the PSTATE and moves the printhead
to the new position.
The resolution for positioning the printhead is based on the current
character pitch, as the routine uses tabs to position the printhead
in the X direction.
The printhead can be moved in either direction in X, but only down the
page (increasing Y).
NOTE: this routine differs from that in cursorSetCursorTab72.asm only
in that the tab stop position is sent as a three digit ASCII number.
CALLED BY:
EXTERNAL
PASS:
bp - Segment of PSTATE
cx.si - WWFixed new X position in points
dx.ax - WWFixed new Y position in points
PState MUST have a font initialized for this to work.
RETURN:
carry - set if some communications problem
DESTROYED:
PSEUDO CODE/STRATEGY:
1 if desired position is below the current one, do y positioning
2 save current style word, and set to no styles
3 do X positioning
4 recover and set the previous styles
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 03/90 Initial version
Dave 03/92 changed to do Y first, and generalize pitch
support.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SET_CURSOR_MODIFIES_FONT = 1
PrintSetCursor proc far
uses si,es
.enter
mov es,bp ;get PSTATE segment.
call PrintClearStyles
jc exit
;save the X position words.
push cx ;integer
push si ;fraction
;Service the Y position.
call PrConvertToDriverCoordinates
sub dx,es:[PS_cursorPos].P_y ;see if the position desired is below
clc ; make sure carry is clear for exiting
; when there are no errors. "jle" does
; not look at the carry bit
jle serviceXPosition ;dont update position if neg or zero.
mov es:[PS_cursorPos].P_x,0ffffh ;cram a large value....
call PrLineFeed ;adjust the position in PSTATE and
;the printhead position.
;Service the X position.
serviceXPosition:
;recover the X position words.
pop cx ;pop fraction into cx
pop dx ;and integer into dx
;now in the correct reg for WWFixed.
jc exit ;pass errors from PrLineFeed out.
;before doing any X movement, make sure the position is to the
;right of the last set cursor position.
cmp es:[PS_cursorPos].P_x,dx ;save the new X Position.
je exit ;do nothing before exiting.
jb storeNewXPosition
push cx
mov cl,C_CR ;send a carriage return.
call PrintStreamWriteByte
pop cx
jc exit
storeNewXPosition:
mov es:[PS_cursorPos].P_x,dx ;save the new X Position.
;we'll use 10pitch to get as much standardization
;as possible from most printers.
;dx.cx must be the new X position.
mov ax,9102 ;x .1388888 for 10 pitch.
clr bx
call GrMulWWFixed ;dx.cx = # of chars to tab.
shl cx,1 ;do any necessary rounding.
adc dx,0 ;dl is assumed to have the correct
;tab character position at this point.
push dx ;get the character position.
mov bl,TP_10_PITCH
mov cx,FID_DTC_URW_ROMAN
mov dx,12
call PrintSetFont
pop ax ;get the character position.
jc exit
mov si, offset pr_codes_SetTab
call SendCodeOut
jc exit
mov cx,3 ;send three digits.
call HexToAsciiStreamWrite
jc exit
mov si, offset pr_codes_DoTab ;finish tab table, and execute
call SendCodeOut ;the tab.
exit:
.leave
ret
PrintSetCursor endp
|
; A008728: Molien series for 3-dimensional group [2,n ] = *22n.
; 1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,24,26,28,30,33,36,39,42,45,48,51,54,57,60,64,68,72,76,80,84,88,92,96,100,105,110,115,120,125,130,135,140,145,150,156,162,168,174,180,186,192,198,204,210,217,224,231,238,245,252,259,266,273,280,288,296,304,312,320,328,336,344,352,360,369,378,387,396,405,414,423,432,441,450,460,470,480,490,500,510,520,530,540,550,561,572,583,594,605,616,627,638,649,660,672,684,696,708,720,732,744,756,768,780,793,806,819,832,845,858,871,884,897,910,924,938,952,966,980,994,1008,1022,1036,1050,1065,1080,1095,1110,1125,1140,1155,1170,1185,1200,1216,1232,1248,1264,1280,1296,1312,1328,1344,1360,1377,1394,1411,1428,1445,1462,1479,1496,1513,1530,1548,1566,1584,1602,1620,1638,1656,1674,1692,1710,1729,1748,1767,1786,1805,1824,1843,1862,1881,1900,1920,1940,1960,1980,2000,2020,2040,2060,2080,2100,2121,2142,2163,2184,2205,2226,2247,2268,2289,2310,2332,2354,2376,2398,2420,2442,2464,2486,2508,2530,2553,2576,2599,2622,2645,2668,2691,2714,2737,2760,2784,2808,2832,2856,2880,2904,2928,2952,2976,3000,3025,3050,3075,3100,3125,3150,3175,3200,3225,3250
add $0,1
lpb $0,1
add $1,$0
trn $0,10
lpe
|
; A282154: Coefficients in expansion of Eisenstein series -q*(d/dq)(q*(d/dq)E_2).
; 0,24,288,864,2688,3600,10368,9408,23040,25272,43200,34848,96768,56784,112896,129600,190464,124848,303264,173280,403200,338688,418176,304704,829440,465000,681408,699840,1053696,605520,1555200,738048,1548288,1254528,1498176,1411200,2830464,1248528,2079360,2044224,3456000,1694448,4064256,1952544,3902976,3790800,3656448,2544768,6856704,3284568,5580000,4494528,6359808,3640464,8398080,5227200,9031680,6238080,7266240,5012640,14515200,5536848,8856576,9906624,12484608,8517600,15054336,7326048,13982976
mov $2,$0
mul $2,$0
trn $0,1
seq $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n).
mul $0,$2
mul $0,24
|
;
; Copyright (c) 2020 Phillip Stevens
;
; This Source Code Form is subject to the terms of the Mozilla Public
; License, v. 2.0. If a copy of the MPL was not distributed with this
; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;
; feilipu, August 2020
;
;-------------------------------------------------------------------------
; asm_am9511_1_pushl - am9511 APU push long
;-------------------------------------------------------------------------
;
; Load long into Am9511 APU stack
;
;-------------------------------------------------------------------------
SECTION code_fp_am9511
IFDEF __CLASSIC
INCLUDE "../../_DEVELOPMENT/target/am9511/config_am9511_private.inc"
ELSE
INCLUDE "target/am9511/config_am9511_private.inc"
ENDIF
PUBLIC asm_am9511_1_pushl_hl
PUBLIC asm_am9511_1_pushl_fastcall
.am9511_1_pushl_hl_wait
ex (sp),hl
ex (sp),hl
.asm_am9511_1_pushl_hl
; float primitive
; push a long into Am9511 stack.
;
; enter : stack = ret1, ret0
; : hl = pointer to long
;
; exit : stack = long, ret1
;
; uses : af, bc, hl
in a,(__IO_APU1_STATUS) ; read the APU status register
rlca ; busy? __IO_APU_STATUS_BUSY
jr C,am9511_1_pushl_hl_wait
ld bc,__IO_APU1_DATA ; the address of the APU data port in bc
outi ; load LSW into APU
inc b
outi
inc b
outi ; load MSW into APU
inc b
outi
ret
.am9511_1_pushl_fastcall_wait
ex (sp),hl
ex (sp),hl
.asm_am9511_1_pushl_fastcall
; float primitive
; push a long into Am9511 stack.
;
; enter : stack = ret1, ret0
; : dehl = long
;
; exit : stack = ret1
;
; uses : af, bc, de, hl
in a,(__IO_APU1_STATUS) ; read the APU status register
rlca ; busy? __IO_APU_STATUS_BUSY
jr C,am9511_1_pushl_fastcall_wait
ld bc,__IO_APU1_DATA ; the address of the APU data port in bc
out (c),l ; load LSW into APU
out (c),h
out (c),e ; load MSW into APU
out (c),d
ret
|
; ########################################################################
MergeFile proc hEdit:DWORD
LOCAL poz :DWORD
LOCAL hFile :DWORD
LOCAL hMem :DWORD
LOCAL ln :DWORD
LOCAL br :DWORD
LOCAL Cr :CHARRANGE
mov szFileName[0],0
invoke GetFileName,hWnd,ADDR szTitleM,ADDR szFilterM
cmp szFileName[0],0 ;<< zero if cancel pressed in dlgbox
je @F
invoke CreateFile,ADDR szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
mov hFile, eax
invoke GetFileSize,hFile,NULL
mov ln, eax
stralloc ln
mov hMem, eax
invoke ReadFile,hFile,hMem,ln,ADDR br,NULL
invoke SendMessage,hEdit,EM_REPLACESEL,0,hMem
strfree hMem
@@:
ret
MergeFile endp
; #########################################################################
|
;
; ZX 81 specific routines
; by Stefano Bodrato, Oct 2007
;
; Copy a string to a BASIC variable
;
; int __CALLEE__ zx_setstr_callee(char variable, char *value);
;
;
; $Id: zx_setstr_callee.asm,v 1.4 2015/08/11 07:16:36 stefano Exp $
;
PUBLIC zx_setstr_callee
PUBLIC ASMDISP_ZX_SETSTR_CALLEE
EXTERN asctozx81
zx_setstr_callee:
pop bc
pop hl
pop de
push bc
; enter : hl = char *value
; e = char variable
.asmentry
ld a,e
and 31
add 69
ld (morevar+1),a
ld (pointer+1),hl
ld hl,($4010) ; VARS
loop:
ld a,(hl)
cp 128
jr nz,morevar
jr store ; variable not found
morevar:
cp 0
jr nz,nextvar
IF FORlambda
call $1A13 ; get next variable start
call $0177 ; reclaim space (delete)
ELSE
call $09F2 ; get next variable start
call $0A60 ; reclaim space (delete)
ENDIF
store:
ld bc,0
pointer:
ld de,0 ; point to the string
push de
lenloop:
inc bc ; string length counter
inc de
ld a,(de)
and a
jr nz,lenloop
push hl
push bc
inc bc
inc bc
inc bc
IF FORlambda
call $1CB5
ELSE
call $099E ; MAKE-ROOM
ENDIF
pop bc
pop hl
ld a,(morevar+1)
ld (hl),a
inc hl
ld (hl),c
inc hl
ld (hl),b
inc hl
pop de
ex de,hl
;ldir
;-----------------------------
.outloop
call asctozx81
ld (de),a
inc hl
inc de
dec bc
ld a,b
or c
jr nz,outloop
;------------------------------
ret
nextvar:
IF FORlambda
call $1A13 ; get next variable start
ELSE
call $09F2 ;get next variable start
ENDIF
ex de,hl
jr loop
DEFC ASMDISP_ZX_SETSTR_CALLEE = # asmentry - zx_setstr_callee
|
#pragma once
#include "pixel_neon_base.hpp"
namespace pxl {
//----------------------------------------------------------------------
// vmul_n_type
//----------------------------------------------------------------------
int16x4_t vmul_n_s16(int16x4_t N, int16_t M);
int32x2_t vmul_n_s32(int32x2_t N, int32_t M);
uint16x4_t vmul_n_u16(uint16x4_t N, uint16_t M);
uint32x2_t vmul_n_u32(uint32x2_t N, uint32_t M);
float32x2_t vmul_n_f32(float32x2_t N, float32_t M);
#if __aarch64__
float64x1_t vmul_n_f64(float64x1_t N, float64_t M);
#endif // __aarch64__
//----------------------------------------------------------------------
// vmulq_n_type
//----------------------------------------------------------------------
int16x8_t vmulq_n_s16(int16x8_t N, int16_t M);
int32x4_t vmulq_n_s32(int32x4_t N, int32_t M);
uint16x8_t vmulq_n_u16(uint16x8_t N, uint16_t M);
uint32x4_t vmulq_n_u32(uint32x4_t N, uint32_t M);
float32x4_t vmulq_n_f32(float32x4_t N, float32_t M);
#if __aarch64__
float64x2_t vmulq_n_f64(float64x2_t N, float64_t M);
#endif // __aarch64__
} // namespace pxl |
// Copyright 2018 Julius Roob <julius@juliusroob.de>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <list>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <regex>
#include <map>
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
namespace scad {
std::map<std::string, std::pair<std::map<std::string, int>, std::map<std::string, int>>> const unit_type_buffers {
{"cu",
{ { /* Input */ {"in0", 0}, {"in1", 1}, {"in2", 2} },
{ /* Output */ } }
},
{"lsu",
{ { /* Input */ {"in0", 0}, {"in1", 1}, {"opc", 2} },
{ /* Output */ {"out", 0} } }
},
{"memory_stream_in",
{ { /* Input */ {"in0", 0} },
{ /* Output */ } }
},
{"memory_stream_out",
{ { /* Input */ },
{ /* Output */ {"out", 0} } }
},
{"rob",
{ { /* Input */ {"in0", 0} },
{ /* Output */ {"out", 0} } }
},
{"pu",
{ { /* Input */ {"in0", 0}, {"in1", 1}, {"opc", 2} },
{ /* Output */ {"out", 0} } }
},
};
} // namespace scad
|
RECODE EQU 9AH
ROCODE EQU 98H
RWDATA EQU 92H
RODATA EQU 90H
TASKGATE286 EQU 81h
LDTGATE EQU 82h
TASKGATE286B EQU 83h
CALLGATE286 EQU 84h
TASKGATE EQU 85h
INTRGATE286 EQU 86h
TRAPGATE286 EQU 87h
TSSSEG EQU 89h
TSSSEGB EQU 8bh
CALLGATE EQU 8ch
INTRGATE EQU 8eh
TRAPGATE EQU 8fh
GDL_4G_32B equ 0cfh
GDL_1M_32B equ 04fh
GDL_64K_32B equ 040h
GDL_64K_16B equ 0
DPL0 EQU 0
DPL1 EQU 20H
DPL2 EQU 40H
DPL3 EQU 60H
RPL0 EQU 0
RPL1 EQU 1
RPL2 EQU 2
RPL3 EQU 3
DESCRIPTOR struc
_segLimit dw 0
_baseLow dw 0
_baseMid db 0
_attr db 0
_GDL db 0
_baseHigh db 0
DESCRIPTOR ends
GATEDESCRIPTOR struc
_offsetLow dw 0
_selector dw 0
_paramCnt db 0
_attr db 0
_offsetHigh dw 0
GATEDESCRIPTOR ends
JUMP16 macro seg,off
DB 0eah
dw off
dw seg
endm
CALL16 macro seg,off
DB 09ah
dw off
dw seg
endm
JUMP32 macro seg,off
DB 0eah
dd off
dw seg
endm
CALL32 macro seg,off
DB 09ah
dd off
dw seg
endm
SETDESCBASE MACRO desc, seg
mov eax, seg
shl eax, 4
mov desc._baseLow, ax
shr eax,16
mov desc._baseMid, al
mov desc._baseHigh, ah
ENDM
SETDESCADDR MACRO desc, seg,off
mov eax, seg
shl eax, 4
add eax,off
mov desc._baseLow, ax
shr eax,16
mov desc._baseMid, al
mov desc._baseHigh, ah
ENDM
SETGATEADDR MACRO gate,seg,off,selector
mov eax, seg
shl eax, 4
add eax,off
mov gate + GATEDESCRIPTOR._offsetLow,ax
shr eax,16
mov gate + GATEDESCRIPTOR._offsetHigh,ax
mov gate + GATEDESCRIPTOR._selector,selector
ENDM
comment *
JUMP32 MACRO selector,offsetv
DB 0eaH
DW offsetv ;32位偏移
DW 0
DW selector
ENDM
CALL32 MACRO selector,offsetv
db 09ah
dw offsetv
dw 0
dw selector
endm
JUMP16 MACRO selector,offsetv
db 0eah
dw offsetv
dw selector
endm
call16 MACRO selector,offsetv
db 9ah
dw offsetv
dw selector
endm
* |
/* Copyright (c) 2017 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
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 ROCCOUNTERS_HPP_
#define ROCCOUNTERS_HPP_
#include "top.hpp"
#include "device/device.hpp"
#include "device/rocm/rocdevice.hpp"
#include "hsa_ven_amd_aqlprofile.h"
namespace roc {
class VirtualGPU;
class PerfCounterProfile;
//! Performance counter implementation on GPU
class PerfCounter : public device::PerfCounter {
public:
enum {
ROC_UNSUPPORTED = 0,
ROC_GFX8,
ROC_GFX9,
ROC_GFX10
};
//! The performance counter info
struct Info : public amd::EmbeddedObject {
uint blockIndex_; //!< Index of the block to configure
uint counterIndex_; //!< Index of the hardware counter
uint eventIndex_; //!< Event you wish to count with the counter
};
//! Constructor for the ROC PerfCounter object
PerfCounter(const Device& device, //!< A ROC device object
uint32_t blockIndex, //!< HW block index
uint32_t counterIndex, //!< Counter index (Counter register) within the block
uint32_t eventIndex); //!< Event index (Counter selection) for profiling
//! Destructor for the ROCM PerfCounter object
virtual ~PerfCounter();
//! Returns the specific information about the counter
uint64_t getInfo(uint64_t infoType //!< The type of returned information
) const;
//! Returns the GPU device, associated with the current object
const Device& dev() const { return roc_device_; }
//! Returns the gfx version
const uint32_t gfxVersion() const { return gfxVersion_; }
//! Returns the profile reference
PerfCounterProfile* profileRef() const { return profileRef_; }
//! Update the profile associated with the counter
void setProfile(PerfCounterProfile* profileRef);
private:
//! Disable default copy constructor
PerfCounter(const PerfCounter&);
//! Disable default operator=
PerfCounter& operator=(const PerfCounter&);
//! Returns the ROC performance counter descriptor
const Info* info() const { return &info_; }
const Device& roc_device_; //!< The backend device
Info info_; //!< The info structure for perfcounter
hsa_ven_amd_aqlprofile_event_t event_; //!< event information
PerfCounterProfile* profileRef_; //!< perf counter profile object
uint32_t gfxVersion_; //!< The IP version of the device
};
//! Performance counter profile
class PerfCounterProfile : public amd::ReferenceCountedObject {
public:
//! Default constructor
PerfCounterProfile(const Device& device)
: api_({0}),
roc_device_(device) {
memset(&profile_, 0, sizeof(profile_));
profile_.agent = roc_device_.getBackendDevice();
profile_.type = HSA_VEN_AMD_AQLPROFILE_EVENT_TYPE_PMC;
memset(&prePacket_, 0, sizeof(hsa_ext_amd_aql_pm4_packet_t));
memset(&postPacket_, 0, sizeof(hsa_ext_amd_aql_pm4_packet_t));
memset(&completionSignal_, 0, sizeof(hsa_signal_t));
};
//! Destructor for the PerfCounter profile object
virtual ~PerfCounterProfile();
//! Get the API tables
bool Create() {
hsa_agent_t agent = roc_device_.getBackendDevice();
bool system_support, agent_support;
hsa_system_extension_supported(HSA_EXTENSION_AMD_AQLPROFILE, 1, 0, &system_support);
hsa_agent_extension_supported(HSA_EXTENSION_AMD_AQLPROFILE, agent, 1, 0, &agent_support);
if (!system_support || !agent_support) {
return false;
}
if (hsa_system_get_major_extension_table(HSA_EXTENSION_AMD_AQLPROFILE,
hsa_ven_amd_aqlprofile_VERSION_MAJOR, sizeof(hsa_ven_amd_aqlprofile_pfn_t),
&api_) != HSA_STATUS_SUCCESS) {
return false;
}
return true;
};
//! Returns the performance counter vector
std::vector<PerfCounter*> perfCounters() { return perfCounters_; };
//! Add the event of performance counter object to the profile context object
void addEvent(hsa_ven_amd_aqlprofile_event_t event) { events_.push_back(event); };
//! Create the start packet for performance counter
hsa_ext_amd_aql_pm4_packet_t* createStartPacket();
//! Create the stop packet for performance counter
hsa_ext_amd_aql_pm4_packet_t* createStopPacket();
//! Create the profile context object
bool initialize(); //!< HSA profile context object
//! Return the extension API table
const hsa_ven_amd_aqlprofile_1_00_pfn_t* api() const { return &api_; }
//! Return the profile context object
const hsa_ven_amd_aqlprofile_profile_t* profile() const { return &profile_; }
//! Return the start AQL packet
hsa_ext_amd_aql_pm4_packet_t* prePacket() { return &prePacket_; }
//! Return the stop AQL packet
hsa_ext_amd_aql_pm4_packet_t* postPacket() { return &postPacket_; }
private:
//! Disable copy constructor
PerfCounterProfile(const PerfCounterProfile&);
//! Disable operator=
PerfCounterProfile& operator=(const PerfCounterProfile&);
hsa_ven_amd_aqlprofile_1_00_pfn_t api_; //!< The extension API table
const Device& roc_device_; //!< The backend device
std::vector<PerfCounter*> perfCounters_; //!< Perf counters associate with the profile
std::vector<hsa_ven_amd_aqlprofile_event_t> events_; //!< Events information
hsa_ven_amd_aqlprofile_profile_t profile_; //!< HSA profile context object
hsa_ext_amd_aql_pm4_packet_t prePacket_; //!< aql packet for starting perf counter
hsa_ext_amd_aql_pm4_packet_t postPacket_; //!< aql packet for stoping the perf counter
hsa_signal_t completionSignal_; //!< signal of completion
};
} // namespace roc
#endif // ROCCOUNTERS_HPP_
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r14
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1162a, %r9
nop
nop
cmp $22424, %r13
movw $0x6162, (%r9)
nop
nop
nop
nop
nop
and $14487, %rbx
lea addresses_normal_ht+0x15f9c, %r14
nop
sub $25187, %rax
movups (%r14), %xmm2
vpextrq $0, %xmm2, %r11
nop
nop
nop
sub $31390, %rax
lea addresses_WC_ht+0x1ab74, %r11
clflush (%r11)
nop
nop
nop
nop
dec %r10
movw $0x6162, (%r11)
cmp $18612, %r13
lea addresses_normal_ht+0x54a, %rsi
lea addresses_WT_ht+0xd2a, %rdi
nop
nop
nop
nop
nop
sub %r14, %r14
mov $72, %rcx
rep movsl
nop
nop
nop
nop
nop
and $45071, %rcx
lea addresses_normal_ht+0x1326a, %r10
clflush (%r10)
nop
nop
nop
nop
nop
add %r11, %r11
mov $0x6162636465666768, %rsi
movq %rsi, %xmm1
and $0xffffffffffffffc0, %r10
movntdq %xmm1, (%r10)
nop
nop
cmp %r11, %r11
lea addresses_WT_ht+0x1724a, %rsi
nop
xor $9630, %rbx
mov (%rsi), %r13d
nop
nop
nop
sub $53238, %rdi
lea addresses_A_ht+0x1cd4a, %rax
nop
nop
nop
nop
nop
and $53019, %r10
movw $0x6162, (%rax)
and %rbx, %rbx
lea addresses_A_ht+0xbd4a, %rsi
lea addresses_WT_ht+0xb64a, %rdi
nop
nop
nop
nop
nop
sub $6961, %r14
mov $13, %rcx
rep movsl
nop
nop
nop
nop
xor $6877, %rcx
lea addresses_D_ht+0xdbca, %r11
xor %rdi, %rdi
mov (%r11), %r13d
nop
add $64452, %r11
lea addresses_A_ht+0xe4ba, %rax
nop
nop
nop
nop
nop
sub $26019, %r14
movw $0x6162, (%rax)
nop
nop
sub $61165, %rbx
lea addresses_UC_ht+0x9eea, %rsi
lea addresses_A_ht+0x6471, %rdi
clflush (%rdi)
nop
nop
nop
nop
and $41249, %rbx
mov $104, %rcx
rep movsl
nop
nop
nop
add %rcx, %rcx
lea addresses_normal_ht+0x1084a, %r9
nop
nop
and %r14, %r14
mov $0x6162636465666768, %r13
movq %r13, (%r9)
nop
nop
add %rdi, %rdi
lea addresses_WC_ht+0x1414a, %rbx
nop
nop
nop
nop
xor %rdi, %rdi
movups (%rbx), %xmm1
vpextrq $0, %xmm1, %r13
nop
nop
nop
nop
xor $7281, %r14
lea addresses_WC_ht+0x1744a, %rdi
clflush (%rdi)
nop
nop
nop
nop
and $28668, %rcx
mov $0x6162636465666768, %rax
movq %rax, %xmm3
movups %xmm3, (%rdi)
nop
nop
xor %r14, %r14
lea addresses_WT_ht+0x9d4a, %rsi
lea addresses_WT_ht+0x264, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
and $58324, %rbx
mov $107, %rcx
rep movsl
nop
and %rsi, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r14
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r8
push %rbp
push %rbx
push %rdi
// Store
lea addresses_WC+0xbd4a, %r14
inc %r8
movw $0x5152, (%r14)
nop
nop
cmp %rbx, %rbx
// Faulty Load
lea addresses_normal+0x6d4a, %rbx
nop
nop
nop
nop
nop
and %rbp, %rbp
mov (%rbx), %r14d
lea oracles, %r11
and $0xff, %r14
shlq $12, %r14
mov (%r11,%r14,1), %r14
pop %rdi
pop %rbx
pop %rbp
pop %r8
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WC', 'congruent': 9}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT_ht', 'congruent': 0}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 1}}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 4}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT_ht', 'congruent': 8}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A_ht', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 8, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D_ht', 'congruent': 3}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A_ht', 'congruent': 4}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal_ht', 'congruent': 8}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC_ht', 'congruent': 10}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC_ht', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WT_ht'}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
; A127986: a(n) = n! + 2^n - 1.
; 1,2,5,13,39,151,783,5167,40575,363391,3629823,39918847,479005695,6227028991,87178307583,1307674400767,20922789953535,355687428227071,6402373705990143
mov $2,2
pow $2,$0
mov $3,$0
fac $3
add $3,$2
sub $3,2
mov $1,$3
add $1,1
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD+Patents license found in the
* LICENSE file in the root directory of this source tree.
*/
// Copyright 2004-present Facebook. All Rights Reserved
// -*- c++ -*-
#include "MetaIndexes.h"
#include <pthread.h>
#include <cstdio>
#include "FaissAssert.h"
#include "Heap.h"
#include "AuxIndexStructures.h"
namespace faiss {
/*****************************************************
* IndexIDMap implementation
*******************************************************/
IndexIDMap::IndexIDMap (Index *index):
index (index),
own_fields (false)
{
FAISS_THROW_IF_NOT_MSG (index->ntotal == 0, "index must be empty on input");
is_trained = index->is_trained;
metric_type = index->metric_type;
verbose = index->verbose;
d = index->d;
}
void IndexIDMap::add (idx_t, const float *)
{
FAISS_THROW_MSG ("add does not make sense with IndexIDMap, "
"use add_with_ids");
}
void IndexIDMap::train (idx_t n, const float *x)
{
index->train (n, x);
is_trained = index->is_trained;
}
void IndexIDMap::reset ()
{
index->reset ();
id_map.clear();
ntotal = 0;
}
void IndexIDMap::add_with_ids (idx_t n, const float * x, const long *xids)
{
index->add (n, x);
for (idx_t i = 0; i < n; i++)
id_map.push_back (xids[i]);
ntotal = index->ntotal;
}
void IndexIDMap::search (idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
index->search (n, x, k, distances, labels);
idx_t *li = labels;
for (idx_t i = 0; i < n * k; i++) {
li[i] = li[i] < 0 ? li[i] : id_map[li[i]];
}
}
void IndexIDMap::range_search (idx_t n, const float *x, float radius,
RangeSearchResult *result) const
{
index->range_search(n, x, radius, result);
for (idx_t i = 0; i < result->lims[result->nq]; i++) {
result->labels[i] = result->labels[i] < 0 ?
result->labels[i] : id_map[result->labels[i]];
}
}
namespace {
struct IDTranslatedSelector: IDSelector {
const std::vector <long> & id_map;
const IDSelector & sel;
IDTranslatedSelector (const std::vector <long> & id_map,
const IDSelector & sel):
id_map (id_map), sel (sel)
{}
bool is_member(idx_t id) const override {
return sel.is_member(id_map[id]);
}
};
}
long IndexIDMap::remove_ids (const IDSelector & sel)
{
// remove in sub-index first
IDTranslatedSelector sel2 (id_map, sel);
long nremove = index->remove_ids (sel2);
long j = 0;
for (idx_t i = 0; i < ntotal; i++) {
if (sel.is_member (id_map[i])) {
// remove
} else {
id_map[j] = id_map[i];
j++;
}
}
FAISS_ASSERT (j == index->ntotal);
ntotal = j;
id_map.resize(ntotal);
return nremove;
}
IndexIDMap::~IndexIDMap ()
{
if (own_fields) delete index;
}
/*****************************************************
* IndexIDMap2 implementation
*******************************************************/
IndexIDMap2::IndexIDMap2 (Index *index): IndexIDMap (index)
{}
void IndexIDMap2::add_with_ids(idx_t n, const float* x, const long* xids)
{
size_t prev_ntotal = ntotal;
IndexIDMap::add_with_ids (n, x, xids);
for (size_t i = prev_ntotal; i < ntotal; i++) {
rev_map [id_map [i]] = i;
}
}
void IndexIDMap2::construct_rev_map ()
{
rev_map.clear ();
for (size_t i = 0; i < ntotal; i++) {
rev_map [id_map [i]] = i;
}
}
long IndexIDMap2::remove_ids(const IDSelector& sel)
{
// This is quite inefficient
long nremove = IndexIDMap::remove_ids (sel);
construct_rev_map ();
return nremove;
}
void IndexIDMap2::reconstruct (idx_t key, float * recons) const
{
try {
index->reconstruct (rev_map.at (key), recons);
} catch (const std::out_of_range& e) {
FAISS_THROW_FMT ("key %ld not found", key);
}
}
/*****************************************************
* IndexShards implementation
*******************************************************/
// subroutines
namespace {
typedef Index::idx_t idx_t;
template<class Job>
struct Thread {
Job job;
pthread_t thread;
Thread () {}
explicit Thread (const Job & job): job(job) {}
void start () {
pthread_create (&thread, nullptr, run, this);
}
void wait () {
pthread_join (thread, nullptr);
}
static void * run (void *arg) {
static_cast<Thread*> (arg)->job.run();
return nullptr;
}
};
/// callback + thread management to train 1 shard
struct TrainJob {
IndexShards *index; // the relevant index
int no; // shard number
idx_t n; // train points
const float *x;
void run ()
{
if (index->verbose)
printf ("begin train shard %d on %ld points\n", no, n);
index->shard_indexes [no]->train(n, x);
if (index->verbose)
printf ("end train shard %d\n", no);
}
};
struct AddJob {
IndexShards *index; // the relevant index
int no; // shard number
idx_t n;
const float *x;
const idx_t *ids;
void run ()
{
if (index->verbose)
printf ("begin add shard %d on %ld points\n", no, n);
if (ids)
index->shard_indexes[no]->add_with_ids (n, x, ids);
else
index->shard_indexes[no]->add (n, x);
if (index->verbose)
printf ("end add shard %d on %ld points\n", no, n);
}
};
/// callback + thread management to query in 1 shard
struct QueryJob {
const IndexShards *index; // the relevant index
int no; // shard number
// query params
idx_t n;
const float *x;
idx_t k;
float *distances;
idx_t *labels;
void run ()
{
if (index->verbose)
printf ("begin query shard %d on %ld points\n", no, n);
index->shard_indexes [no]->search (n, x, k,
distances, labels);
if (index->verbose)
printf ("end query shard %d\n", no);
}
};
// add translation to all valid labels
void translate_labels (long n, idx_t *labels, long translation)
{
if (translation == 0) return;
for (long i = 0; i < n; i++) {
if(labels[i] < 0) return;
labels[i] += translation;
}
}
/** merge result tables from several shards.
* @param all_distances size nshard * n * k
* @param all_labels idem
* @param translartions label translations to apply, size nshard
*/
template <class C>
void merge_tables (long n, long k, long nshard,
float *distances, idx_t *labels,
const float *all_distances,
idx_t *all_labels,
const long *translations)
{
if(k == 0) {
return;
}
long stride = n * k;
#pragma omp parallel
{
std::vector<int> buf (2 * nshard);
int * pointer = buf.data();
int * shard_ids = pointer + nshard;
std::vector<float> buf2 (nshard);
float * heap_vals = buf2.data();
#pragma omp for
for (long i = 0; i < n; i++) {
// the heap maps values to the shard where they are
// produced.
const float *D_in = all_distances + i * k;
const idx_t *I_in = all_labels + i * k;
int heap_size = 0;
for (long s = 0; s < nshard; s++) {
pointer[s] = 0;
if (I_in[stride * s] >= 0)
heap_push<C> (++heap_size, heap_vals, shard_ids,
D_in[stride * s], s);
}
float *D = distances + i * k;
idx_t *I = labels + i * k;
for (int j = 0; j < k; j++) {
if (heap_size == 0) {
I[j] = -1;
D[j] = C::neutral();
} else {
// pop best element
int s = shard_ids[0];
int & p = pointer[s];
D[j] = heap_vals[0];
I[j] = I_in[stride * s + p] + translations[s];
heap_pop<C> (heap_size--, heap_vals, shard_ids);
p++;
if (p < k && I_in[stride * s + p] >= 0)
heap_push<C> (++heap_size, heap_vals, shard_ids,
D_in[stride * s + p], s);
}
}
}
}
}
};
IndexShards::IndexShards (idx_t d, bool threaded, bool successive_ids):
Index (d), own_fields (false),
threaded (threaded), successive_ids (successive_ids)
{
}
void IndexShards::add_shard (Index *idx)
{
shard_indexes.push_back (idx);
sync_with_shard_indexes ();
}
void IndexShards::sync_with_shard_indexes ()
{
if (shard_indexes.empty()) return;
Index * index0 = shard_indexes[0];
d = index0->d;
metric_type = index0->metric_type;
is_trained = index0->is_trained;
ntotal = index0->ntotal;
for (int i = 1; i < shard_indexes.size(); i++) {
Index * index = shard_indexes[i];
FAISS_THROW_IF_NOT (metric_type == index->metric_type);
FAISS_THROW_IF_NOT (d == index->d);
ntotal += index->ntotal;
}
}
void IndexShards::train (idx_t n, const float *x)
{
// pre-alloc because we don't want reallocs
std::vector<Thread<TrainJob > > tss (shard_indexes.size());
int nt = 0;
for (int i = 0; i < shard_indexes.size(); i++) {
if(!shard_indexes[i]->is_trained) {
TrainJob ts = {this, i, n, x};
if (threaded) {
tss[nt] = Thread<TrainJob> (ts);
tss[nt++].start();
} else {
ts.run();
}
}
}
for (int i = 0; i < nt; i++) {
tss[i].wait();
}
sync_with_shard_indexes ();
}
void IndexShards::add (idx_t n, const float *x)
{
add_with_ids (n, x, nullptr);
}
void IndexShards::add_with_ids (idx_t n, const float * x, const long *xids)
{
FAISS_THROW_IF_NOT_MSG(!(successive_ids && xids),
"It makes no sense to pass in ids and "
"request them to be shifted");
if (successive_ids) {
FAISS_THROW_IF_NOT_MSG(!xids,
"It makes no sense to pass in ids and "
"request them to be shifted");
FAISS_THROW_IF_NOT_MSG(ntotal == 0,
"when adding to IndexShards with sucessive_ids, "
"only add() in a single pass is supported");
}
long nshard = shard_indexes.size();
const long *ids = xids;
ScopeDeleter<long> del;
if (!ids && !successive_ids) {
long *aids = new long[n];
for (long i = 0; i < n; i++)
aids[i] = ntotal + i;
ids = aids;
del.set (ids);
}
std::vector<Thread<AddJob > > asa (shard_indexes.size());
int nt = 0;
for (int i = 0; i < nshard; i++) {
long i0 = i * n / nshard;
long i1 = (i + 1) * n / nshard;
AddJob as = {this, i,
i1 - i0, x + i0 * d,
ids ? ids + i0 : nullptr};
if (threaded) {
asa[nt] = Thread<AddJob>(as);
asa[nt++].start();
} else {
as.run();
}
}
for (int i = 0; i < nt; i++) {
asa[i].wait();
}
ntotal += n;
}
void IndexShards::reset ()
{
for (int i = 0; i < shard_indexes.size(); i++) {
shard_indexes[i]->reset ();
}
sync_with_shard_indexes ();
}
void IndexShards::search (
idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
long nshard = shard_indexes.size();
float *all_distances = new float [nshard * k * n];
idx_t *all_labels = new idx_t [nshard * k * n];
ScopeDeleter<float> del (all_distances);
ScopeDeleter<idx_t> del2 (all_labels);
#if 1
// pre-alloc because we don't want reallocs
std::vector<Thread<QueryJob> > qss (nshard);
for (int i = 0; i < nshard; i++) {
QueryJob qs = {
this, i, n, x, k,
all_distances + i * k * n,
all_labels + i * k * n
};
if (threaded) {
qss[i] = Thread<QueryJob> (qs);
qss[i].start();
} else {
qs.run();
}
}
if (threaded) {
for (int i = 0; i < qss.size(); i++) {
qss[i].wait();
}
}
#else
// pre-alloc because we don't want reallocs
std::vector<QueryJob> qss (nshard);
for (int i = 0; i < nshard; i++) {
QueryJob qs = {
this, i, n, x, k,
all_distances + i * k * n,
all_labels + i * k * n
};
if (threaded) {
qss[i] = qs;
} else {
qs.run();
}
}
if (threaded) {
#pragma omp parallel for
for (int i = 0; i < qss.size(); i++) {
qss[i].run();
}
}
#endif
std::vector<long> translations (nshard, 0);
if (successive_ids) {
translations[0] = 0;
for (int s = 0; s + 1 < nshard; s++)
translations [s + 1] = translations [s] +
shard_indexes [s]->ntotal;
}
if (metric_type == METRIC_L2) {
merge_tables< CMin<float, int> > (
n, k, nshard, distances, labels,
all_distances, all_labels, translations.data ());
} else {
merge_tables< CMax<float, int> > (
n, k, nshard, distances, labels,
all_distances, all_labels, translations.data ());
}
}
IndexShards::~IndexShards ()
{
if (own_fields) {
for (int s = 0; s < shard_indexes.size(); s++)
delete shard_indexes [s];
}
}
/*****************************************************
* IndexSplitVectors implementation
*******************************************************/
IndexSplitVectors::IndexSplitVectors (idx_t d, bool threaded):
Index (d), own_fields (false),
threaded (threaded), sum_d (0)
{
}
void IndexSplitVectors::add_sub_index (Index *index)
{
sub_indexes.push_back (index);
sync_with_sub_indexes ();
}
void IndexSplitVectors::sync_with_sub_indexes ()
{
if (sub_indexes.empty()) return;
Index * index0 = sub_indexes[0];
sum_d = index0->d;
metric_type = index0->metric_type;
is_trained = index0->is_trained;
ntotal = index0->ntotal;
for (int i = 1; i < sub_indexes.size(); i++) {
Index * index = sub_indexes[i];
FAISS_THROW_IF_NOT (metric_type == index->metric_type);
FAISS_THROW_IF_NOT (ntotal == index->ntotal);
sum_d += index->d;
}
}
void IndexSplitVectors::add(idx_t /*n*/, const float* /*x*/) {
FAISS_THROW_MSG("not implemented");
}
namespace {
/// callback + thread management to query in 1 shard
struct SplitQueryJob {
const IndexSplitVectors *index; // the relevant index
int no; // shard number
// query params
idx_t n;
const float *x;
idx_t k;
float *distances;
idx_t *labels;
void run ()
{
if (index->verbose)
printf ("begin query shard %d on %ld points\n", no, n);
const Index * sub_index = index->sub_indexes[no];
long sub_d = sub_index->d, d = index->d;
idx_t ofs = 0;
for (int i = 0; i < no; i++) ofs += index->sub_indexes[i]->d;
float *sub_x = new float [sub_d * n];
ScopeDeleter<float> del (sub_x);
for (idx_t i = 0; i < n; i++)
memcpy (sub_x + i * sub_d, x + ofs + i * d, sub_d * sizeof (sub_x));
sub_index->search (n, sub_x, k, distances, labels);
if (index->verbose)
printf ("end query shard %d\n", no);
}
};
}
void IndexSplitVectors::search (
idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
FAISS_THROW_IF_NOT_MSG (k == 1,
"search implemented only for k=1");
FAISS_THROW_IF_NOT_MSG (sum_d == d,
"not enough indexes compared to # dimensions");
long nshard = sub_indexes.size();
float *all_distances = new float [nshard * k * n];
idx_t *all_labels = new idx_t [nshard * k * n];
ScopeDeleter<float> del (all_distances);
ScopeDeleter<idx_t> del2 (all_labels);
// pre-alloc because we don't want reallocs
std::vector<Thread<SplitQueryJob> > qss (nshard);
for (int i = 0; i < nshard; i++) {
SplitQueryJob qs = {
this, i, n, x, k,
i == 0 ? distances : all_distances + i * k * n,
i == 0 ? labels : all_labels + i * k * n
};
if (threaded) {
qss[i] = Thread<SplitQueryJob> (qs);
qss[i].start();
} else {
qs.run();
}
}
if (threaded) {
for (int i = 0; i < qss.size(); i++) {
qss[i].wait();
}
}
long factor = 1;
for (int i = 0; i < nshard; i++) {
if (i > 0) { // results of 0 are already in the table
const float *distances_i = all_distances + i * k * n;
const idx_t *labels_i = all_labels + i * k * n;
for (long j = 0; j < n; j++) {
if (labels[j] >= 0 && labels_i[j] >= 0) {
labels[j] += labels_i[j] * factor;
distances[j] += distances_i[j];
} else {
labels[j] = -1;
distances[j] = 0.0 / 0.0;
}
}
}
factor *= sub_indexes[i]->ntotal;
}
}
void IndexSplitVectors::train(idx_t /*n*/, const float* /*x*/) {
FAISS_THROW_MSG("not implemented");
}
void IndexSplitVectors::reset ()
{
FAISS_THROW_MSG ("not implemented");
}
IndexSplitVectors::~IndexSplitVectors ()
{
if (own_fields) {
for (int s = 0; s < sub_indexes.size(); s++)
delete sub_indexes [s];
}
}
}; // namespace faiss
|
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The BitcoinNode Core developers
#include "cachemultimap.h"
#include "test/test_bitcoinnode.h"
#include <algorithm>
#include <iostream>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(cachemultimap_tests, BasicTestingSetup)
void DumpMap(const CacheMultiMap<int,int>& map)
{
const CacheMultiMap<int,int>::list_t& listItems = map.GetItemList();
for(CacheMultiMap<int,int>::list_cit it = listItems.begin(); it != listItems.end(); ++it) {
const CacheItem<int,int>& item = *it;
std::cout << item.key << " : " << item.value << std::endl;
}
}
bool Compare(const CacheMultiMap<int,int>& map1, const CacheMultiMap<int,int>& map2 )
{
if(map1.GetMaxSize() != map2.GetMaxSize()) {
std::cout << "Compare returning false: max size mismatch" << std::endl;
return false;
}
if(map1.GetSize() != map2.GetSize()) {
std::cout << "Compare returning false: size mismatch" << std::endl;
return false;
}
const CacheMultiMap<int,int>::list_t& items1 = map1.GetItemList();
const CacheMultiMap<int,int>::list_t& items2 = map2.GetItemList();
CacheMultiMap<int,int>::list_cit it2 = items2.begin();
for(CacheMultiMap<int,int>::list_cit it1 = items1.begin(); it1 != items1.end(); ++it1) {
const CacheItem<int,int>& item1 = *it1;
const CacheItem<int,int>& item2 = *it2;
if(item1.key != item2.key) {
return false;
}
if(item1.value != item2.value) {
return false;
}
++it2;
}
return true;
}
bool CheckExpected(const CacheMultiMap<int,int>& map, int* expected, CacheMultiMap<int,int>::size_type nSize)
{
if(map.GetSize() != nSize) {
return false;
}
for(CacheMultiMap<int,int>::size_type i = 0; i < nSize; ++i) {
int nVal = 0;
int eVal = expected[i];
if(!map.Get(eVal, nVal)) {
return false;
}
if(nVal != eVal) {
return false;
}
}
return true;
}
BOOST_AUTO_TEST_CASE(cachemultimap_test)
{
// create a CacheMultiMap limited to 10 items
CacheMultiMap<int,int> mapTest1(10);
// check that the max size is 10
BOOST_CHECK(mapTest1.GetMaxSize() == 10);
// check that the size is 0
BOOST_CHECK(mapTest1.GetSize() == 0);
// insert (-1, -1)
mapTest1.Insert(-1, -1);
// make sure that the size is updated
BOOST_CHECK(mapTest1.GetSize() == 1);
// make sure the map contains the key
BOOST_CHECK(mapTest1.HasKey(-1) == true);
// add 10 items
for(int i = 0; i < 10; ++i) {
mapTest1.Insert(i, i);
}
// check that the size is 10
BOOST_CHECK(mapTest1.GetSize() == 10);
// check that the map contains the expected items
for(int i = 0; i < 10; ++i) {
int nVal = 0;
BOOST_CHECK(mapTest1.Get(i, nVal) == true);
BOOST_CHECK(nVal == i);
}
// check that the map no longer contains the first item
BOOST_CHECK(mapTest1.HasKey(-1) == false);
// erase an item
mapTest1.Erase(5);
// check the size
BOOST_CHECK(mapTest1.GetSize() == 9);
// check that the map no longer contains the item
BOOST_CHECK(mapTest1.HasKey(5) == false);
// check that the map contains the expected items
int expected[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 };
BOOST_CHECK(CheckExpected(mapTest1, expected, 9 ) == true);
// add multiple items for the same key
mapTest1.Insert(5, 2);
mapTest1.Insert(5, 1);
mapTest1.Insert(5, 4);
// check the size
BOOST_CHECK(mapTest1.GetSize() == 10);
// check that 2 keys have been removed
BOOST_CHECK(mapTest1.HasKey(0) == false);
BOOST_CHECK(mapTest1.HasKey(1) == false);
BOOST_CHECK(mapTest1.HasKey(2) == true);
// check multiple values
std::vector<int> vecVals;
BOOST_CHECK(mapTest1.GetAll(5, vecVals) == true);
BOOST_CHECK(vecVals.size() == 3);
BOOST_CHECK(vecVals[0] == 1);
BOOST_CHECK(vecVals[1] == 2);
BOOST_CHECK(vecVals[2] == 4);
// std::cout << "mapTest1 dump:" << std::endl;
// DumpMap(mapTest1);
// test serialization
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << mapTest1;
CacheMultiMap<int,int> mapTest2;
ss >> mapTest2;
// std::cout << "mapTest2 dump:" << std::endl;
// DumpMap(mapTest2);
// check multiple values
std::vector<int> vecVals2;
BOOST_CHECK(mapTest2.GetAll(5, vecVals2) == true);
BOOST_CHECK(vecVals2.size() == 3);
BOOST_CHECK(vecVals2[0] == 1);
BOOST_CHECK(vecVals2[1] == 2);
BOOST_CHECK(vecVals2[2] == 4);
BOOST_CHECK(Compare(mapTest1, mapTest2));
// test copy constructor
CacheMultiMap<int,int> mapTest3(mapTest1);
BOOST_CHECK(Compare(mapTest1, mapTest3));
// test assignment operator
CacheMultiMap<int,int> mapTest4;
mapTest4 = mapTest1;
BOOST_CHECK(Compare(mapTest1, mapTest4));
}
BOOST_AUTO_TEST_SUITE_END()
|
; uint __CALLEE__ zx_attr_callee(uchar row, uchar col)
; aralbrec 06.2007
SECTION code_clib
PUBLIC zx_attr_callee
PUBLIC _zx_attr_callee
PUBLIC asm_zx_attr
EXTERN asm_zx_cyx2aaddr
.zx_attr_callee
._zx_attr_callee
pop hl
pop de
ex (sp),hl
ld h,l
ld l,e
.asm_zx_attr
; h = char Y 0..23
; l = char X 0..31
call asm_zx_cyx2aaddr
ld l,(hl)
ld h,0
ret
|
; A010694: Period 2: repeat (2,4).
; 2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2
gcd $0,2
mov $1,4
div $1,$0
|
/**********************************************************************
Audacity: A Digital Audio Editor
Grid.cpp
Leland Lucius
*******************************************************************//**
\class Grid
\brief Supplies an accessible grid based on wxGrid.
*//*******************************************************************/
#include "Grid.h"
#include <wx/setup.h> // for wxUSE_* macros
#include <wx/defs.h>
#include <wx/choice.h>
#include <wx/clipbrd.h>
#include <wx/dc.h>
#include <wx/grid.h>
#include <wx/intl.h>
#include <wx/settings.h>
#include <wx/toplevel.h>
#include "../SelectedRegion.h"
#if wxUSE_ACCESSIBILITY
#include "WindowAccessible.h"
/**********************************************************************//**
\class GridAx
\brief wxAccessible object providing grid information for Grid.
**************************************************************************/
class GridAx final : public WindowAccessible
{
public:
GridAx(Grid *grid);
void SetCurrentCell(int row, int col);
void TableUpdated();
bool GetRowCol(int childId, int & row, int & col);
// Retrieves the address of an IDispatch interface for the specified child.
// All objects must support this property.
wxAccStatus GetChild(int childId, wxAccessible **child) override;
// Gets the number of children.
wxAccStatus GetChildCount(int *childCount) override;
// Gets the default action for this object (0) or > 0 (the action for a child).
// Return wxACC_OK even if there is no action. actionName is the action, or the empty
// string if there is no action.
// The retrieved string describes the action that is performed on an object,
// not what the object does as a result. For example, a toolbar button that prints
// a document has a default action of "Press" rather than "Prints the current document."
wxAccStatus GetDefaultAction(int childId, wxString *actionName) override;
// Returns the description for this object or a child.
wxAccStatus GetDescription(int childId, wxString *description) override;
// Gets the window with the keyboard focus.
// If childId is 0 and child is NULL, no object in
// this subhierarchy has the focus.
// If this object has the focus, child should be 'this'.
wxAccStatus GetFocus(int *childId, wxAccessible **child) override;
// Returns help text for this object or a child, similar to tooltip text.
wxAccStatus GetHelpText(int childId, wxString *helpText) override;
// Returns the keyboard shortcut for this object or child.
// Return e.g. ALT+K
wxAccStatus GetKeyboardShortcut(int childId, wxString *shortcut) override;
// Returns the rectangle for this object (id = 0) or a child element (id > 0).
// rect is in screen coordinates.
wxAccStatus GetLocation(wxRect & rect, int elementId) override;
// Gets the name of the specified object.
wxAccStatus GetName(int childId, wxString *name) override;
// Gets the parent, or NULL.
wxAccStatus GetParent(wxAccessible **parent) override;
// Returns a role constant.
wxAccStatus GetRole(int childId, wxAccRole *role) override;
// Gets a variant representing the selected children
// of this object.
// Acceptable values:
// - a null variant (IsNull() returns TRUE)
// - a list variant (GetType() == wxT("list"))
// - an integer representing the selected child element,
// or 0 if this object is selected (GetType() == wxT("long"))
// - a "void*" pointer to a wxAccessible child object
wxAccStatus GetSelections(wxVariant *selections) override;
// Returns a state constant.
wxAccStatus GetState(int childId, long* state) override;
// Returns a localized string representing the value for the object
// or child.
wxAccStatus GetValue(int childId, wxString* strValue) override;
#if defined(__WXMAC__)
// Selects the object or child.
wxAccStatus Select(int childId, wxAccSelectionFlags selectFlags) override;
#endif
Grid *mGrid;
int mLastId;
};
#endif
NumericEditor::NumericEditor
(NumericConverter::Type type, const NumericFormatSymbol &format, double rate)
{
mType = type;
mFormat = format;
mRate = rate;
mOld = 0.0;
}
NumericEditor::~NumericEditor()
{
}
void NumericEditor::Create(wxWindow *parent, wxWindowID id, wxEvtHandler *handler)
{
wxASSERT(parent); // to justify safenew
auto control = safenew NumericTextCtrl(
parent, wxID_ANY,
mType,
mFormat,
mOld,
mRate,
NumericTextCtrl::Options{}
.AutoPos(true)
.InvalidValue(mType == NumericTextCtrl::FREQUENCY,
SelectedRegion::UndefinedFrequency)
);
m_control = control;
wxGridCellEditor::Create(parent, id, handler);
}
void NumericEditor::SetSize(const wxRect &rect)
{
wxSize size = m_control->GetSize();
// Always center...looks bad otherwise
int x = rect.x + ((rect.width / 2) - (size.x / 2)) + 1;
int y = rect.y + ((rect.height / 2) - (size.y / 2)) + 1;
m_control->Move(x, y);
}
void NumericEditor::BeginEdit(int row, int col, wxGrid *grid)
{
wxGridTableBase *table = grid->GetTable();
mOldString = table->GetValue(row, col);
mOldString.ToDouble(&mOld);
auto control = GetNumericTextControl();
control->SetValue(mOld);
control->EnableMenu();
control->SetFocus();
}
bool NumericEditor::EndEdit(int WXUNUSED(row), int WXUNUSED(col), const wxGrid *WXUNUSED(grid), const wxString &WXUNUSED(oldval), wxString *newval)
{
double newtime = GetNumericTextControl()->GetValue();
bool changed = newtime != mOld;
if (changed) {
mValueAsString = wxString::Format(wxT("%g"), newtime);
*newval = mValueAsString;
}
return changed;
}
void NumericEditor::ApplyEdit(int row, int col, wxGrid *grid)
{
grid->GetTable()->SetValue(row, col, mValueAsString);
}
void NumericEditor::Reset()
{
GetNumericTextControl()->SetValue(mOld);
}
bool NumericEditor::IsAcceptedKey(wxKeyEvent &event)
{
if (wxGridCellEditor::IsAcceptedKey(event)) {
if (event.GetKeyCode() == WXK_RETURN) {
return true;
}
}
return false;
}
// Clone is required by wxwidgets; implemented via copy constructor
wxGridCellEditor *NumericEditor::Clone() const
{
return safenew NumericEditor{ mType, mFormat, mRate };
}
wxString NumericEditor::GetValue() const
{
return wxString::Format(wxT("%g"), GetNumericTextControl()->GetValue());
}
NumericFormatSymbol NumericEditor::GetFormat() const
{
return mFormat;
}
double NumericEditor::GetRate() const
{
return mRate;
}
void NumericEditor::SetFormat(const NumericFormatSymbol &format)
{
mFormat = format;
}
void NumericEditor::SetRate(double rate)
{
mRate = rate;
}
NumericRenderer::~NumericRenderer()
{
}
void NumericRenderer::Draw(wxGrid &grid,
wxGridCellAttr &attr,
wxDC &dc,
const wxRect &rect,
int row,
int col,
bool isSelected)
{
wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);
wxGridTableBase *table = grid.GetTable();
NumericEditor *ne =
static_cast<NumericEditor *>(grid.GetCellEditor(row, col));
wxString tstr;
if (ne) {
double value;
table->GetValue(row, col).ToDouble(&value);
NumericTextCtrl tt(&grid, wxID_ANY,
mType,
ne->GetFormat(),
value,
ne->GetRate(),
NumericTextCtrl::Options{}.AutoPos(true),
wxPoint(10000, 10000)); // create offscreen
tstr = tt.GetString();
ne->DecRef();
}
dc.SetBackgroundMode(wxTRANSPARENT);
if (grid.IsEnabled())
{
if (isSelected)
{
dc.SetTextBackground(grid.GetSelectionBackground());
dc.SetTextForeground(grid.GetSelectionForeground());
}
else
{
dc.SetTextBackground(attr.GetBackgroundColour());
dc.SetTextForeground(attr.GetTextColour());
}
}
else
{
dc.SetTextBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
dc.SetTextForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT));
}
dc.SetFont(attr.GetFont());
int hAlign, vAlign;
attr.GetAlignment(&hAlign, &vAlign);
grid.DrawTextRectangle(dc, tstr, rect, hAlign, vAlign);
}
wxSize NumericRenderer::GetBestSize(wxGrid &grid,
wxGridCellAttr & WXUNUSED(attr),
wxDC & WXUNUSED(dc),
int row,
int col)
{
wxGridTableBase *table = grid.GetTable();
NumericEditor *ne =
static_cast<NumericEditor *>(grid.GetCellEditor(row, col));
wxSize sz;
if (ne) {
double value;
table->GetValue(row, col).ToDouble(&value);
NumericTextCtrl tt(&grid, wxID_ANY,
mType,
ne->GetFormat(),
value,
ne->GetRate(),
NumericTextCtrl::Options{}.AutoPos(true),
wxPoint(10000, 10000)); // create offscreen
sz = tt.GetSize();
ne->DecRef();
}
return sz;
}
// Clone is required by wxwidgets; implemented via copy constructor
wxGridCellRenderer *NumericRenderer::Clone() const
{
return safenew NumericRenderer{ mType };
}
ChoiceEditor::ChoiceEditor(size_t count, const wxString choices[])
{
if (count) {
mChoices.reserve(count);
for (size_t n = 0; n < count; n++) {
mChoices.push_back(choices[n]);
}
}
}
ChoiceEditor::ChoiceEditor(const wxArrayString &choices)
{
mChoices = choices;
}
ChoiceEditor::~ChoiceEditor()
{
if (m_control)
mHandler.DisconnectEvent(m_control);
}
// Clone is required by wxwidgets; implemented via copy constructor
wxGridCellEditor *ChoiceEditor::Clone() const
{
return safenew ChoiceEditor(mChoices);
}
void ChoiceEditor::Create(wxWindow* parent, wxWindowID id, wxEvtHandler* evtHandler)
{
m_control = safenew wxChoice(parent,
id,
wxDefaultPosition,
wxDefaultSize,
mChoices);
wxGridCellEditor::Create(parent, id, evtHandler);
mHandler.ConnectEvent(m_control);
}
void ChoiceEditor::SetSize(const wxRect &rect)
{
wxSize size = m_control->GetSize();
// Always center...looks bad otherwise
int x = rect.x + ((rect.width / 2) - (size.x / 2)) + 1;
int y = rect.y + ((rect.height / 2) - (size.y / 2)) + 1;
m_control->Move(x, y);
}
void ChoiceEditor::BeginEdit(int row, int col, wxGrid* grid)
{
if (!m_control)
return;
mOld = grid->GetTable()->GetValue(row, col);
Choice()->Clear();
Choice()->Append(mChoices);
Choice()->SetSelection( make_iterator_range( mChoices ).index( mOld ) );
Choice()->SetFocus();
}
bool ChoiceEditor::EndEdit(int row, int col, wxGrid *grid)
{
wxString newvalue;
bool changed = EndEdit(row, col, grid, mOld, &newvalue);
if (changed) {
ApplyEdit(row, col, grid);
}
return changed;
}
bool ChoiceEditor::EndEdit(int WXUNUSED(row), int WXUNUSED(col),
const wxGrid* WXUNUSED(grid),
const wxString &WXUNUSED(oldval), wxString *newval)
{
int sel = Choice()->GetSelection();
// This can happen if the wxChoice control is displayed and the list of choices get changed
if ((sel < 0) || (sel >= (int)(mChoices.size())))
{
return false;
}
wxString val = mChoices[sel];
bool changed = val != mOld;
if (changed)
{
mValueAsString = val;
*newval = val;
}
return changed;
}
void ChoiceEditor::ApplyEdit(int row, int col, wxGrid *grid)
{
grid->GetTable()->SetValue(row, col, mValueAsString);
}
void ChoiceEditor::Reset()
{
Choice()->SetSelection( make_iterator_range( mChoices ).index( mOld ) );
}
void ChoiceEditor::SetChoices(const wxArrayString &choices)
{
mChoices = choices;
}
wxString ChoiceEditor::GetValue() const
{
return mChoices[Choice()->GetSelection()];
}
///
///
///
BEGIN_EVENT_TABLE(Grid, wxGrid)
EVT_SET_FOCUS(Grid::OnSetFocus)
EVT_KEY_DOWN(Grid::OnKeyDown)
EVT_GRID_SELECT_CELL(Grid::OnSelectCell)
EVT_GRID_EDITOR_SHOWN(Grid::OnEditorShown)
END_EVENT_TABLE()
Grid::Grid(wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
: wxGrid(parent, id, pos, size, style | wxWANTS_CHARS, name)
{
#if wxUSE_ACCESSIBILITY
GetGridWindow()->SetAccessible(mAx = safenew GridAx(this));
#endif
// RegisterDataType takes ownership of renderer and editor
RegisterDataType(GRID_VALUE_TIME,
safenew NumericRenderer{ NumericConverter::TIME },
safenew NumericEditor
{ NumericTextCtrl::TIME,
NumericConverter::SecondsFormat(), 44100.0 });
RegisterDataType(GRID_VALUE_FREQUENCY,
safenew NumericRenderer{ NumericConverter::FREQUENCY },
safenew NumericEditor
{ NumericTextCtrl::FREQUENCY,
NumericConverter::HertzFormat(), 44100.0 });
RegisterDataType(GRID_VALUE_CHOICE,
safenew wxGridCellStringRenderer,
safenew ChoiceEditor);
// Bug #2803:
// Ensure selection doesn't show up.
SetSelectionForeground(GetDefaultCellTextColour());
SetSelectionBackground(GetDefaultCellBackgroundColour());
}
Grid::~Grid()
{
#if wxUSE_ACCESSIBILITY
int cnt = mChildren.size();
while (cnt--) {
// PRL: I found this loop destroying right-to-left.
// Is the sequence of destruction important?
mChildren.pop_back();
}
#endif
}
void Grid::OnSetFocus(wxFocusEvent &event)
{
event.Skip();
#if wxUSE_ACCESSIBILITY
mAx->SetCurrentCell(GetGridCursorRow(), GetGridCursorCol());
#endif
}
void Grid::OnSelectCell(wxGridEvent &event)
{
event.Skip();
MakeCellVisible(event.GetRow(), event.GetCol());
#if wxUSE_ACCESSIBILITY
mAx->SetCurrentCell(event.GetRow(), event.GetCol());
#endif
}
void Grid::OnEditorShown(wxGridEvent &event)
{
event.Skip();
// Bug #2803 (comment 7):
// Select row whenever an editor is displayed
SelectRow(GetGridCursorRow());
}
void Grid::OnKeyDown(wxKeyEvent &event)
{
auto keyCode = event.GetKeyCode();
int crow = GetGridCursorRow();
int ccol = GetGridCursorCol();
if (event.CmdDown() && crow != wxGridNoCellCoords.GetRow() && ccol != wxGridNoCellCoords.GetCol())
{
wxClipboardLocker cb;
switch (keyCode)
{
case 'C': // Copy
{
wxTextDataObject *data = safenew wxTextDataObject(GetCellValue(crow, ccol));
wxClipboard::Get()->SetData(data);
return;
}
break;
case 'X': // Cut
{
wxTextDataObject *data = safenew wxTextDataObject(GetCellValue(crow, ccol));
wxClipboard::Get()->SetData(data);
SetCellValue(crow, ccol, "" );
return;
}
break;
case 'V': // Paste
{
if (wxClipboard::Get()->IsSupported(wxDF_UNICODETEXT))
{
wxTextDataObject data;
if (wxClipboard::Get()->GetData(data))
{
SetCellValue(crow, ccol, data.GetText());
return;
}
}
}
break;
}
}
switch (keyCode)
{
case WXK_LEFT:
case WXK_RIGHT:
{
int rows = GetNumberRows();
int cols = GetNumberCols();
const bool has_cells = rows > 0 && cols > 0;
if (has_cells) {
int crow = GetGridCursorRow();
int ccol = GetGridCursorCol();
const bool has_no_selection = crow == wxGridNoCellCoords.GetRow() || ccol == wxGridNoCellCoords.GetCol();
if (has_no_selection) {
SetGridCursor(0, 0);
}
else if (event.GetKeyCode() == WXK_LEFT) {
if (crow == 0 && ccol == 0) {
// do nothing
}
else if (ccol == 0) {
SetGridCursor(crow - 1, cols - 1);
}
else {
SetGridCursor(crow, ccol - 1);
}
}
else {
if (crow == rows - 1 && ccol == cols - 1) {
// do nothing
}
else if (ccol == cols - 1) {
SetGridCursor(crow + 1, 0);
}
else {
SetGridCursor(crow, ccol + 1);
}
}
}
#if wxUSE_ACCESSIBILITY
// Make sure the NEW cell is made available to the screen reader
mAx->SetCurrentCell(GetGridCursorRow(), GetGridCursorCol());
#endif
}
break;
case WXK_TAB:
{
if (event.ControlDown()) {
int flags = wxNavigationKeyEvent::FromTab |
( event.ShiftDown() ?
wxNavigationKeyEvent::IsBackward :
wxNavigationKeyEvent::IsForward );
Navigate(flags);
return;
}
int rows = GetNumberRows();
int cols = GetNumberCols();
int crow = GetGridCursorRow();
int ccol = GetGridCursorCol();
const auto is_empty = rows <= 0 || cols <= 0;
const auto has_no_selection = crow == wxGridNoCellCoords.GetRow() || ccol == wxGridNoCellCoords.GetCol();
if (event.ShiftDown()) {
if (is_empty) {
Navigate(wxNavigationKeyEvent::FromTab | wxNavigationKeyEvent::IsBackward);
return;
}
if (crow == 0 && ccol == 0) {
Navigate(wxNavigationKeyEvent::FromTab | wxNavigationKeyEvent::IsBackward);
return;
}
if (has_no_selection) {
SetGridCursor(rows -1, cols - 1);
}
else if (ccol == 0) {
SetGridCursor(crow - 1, cols - 1);
}
else {
SetGridCursor(crow, ccol - 1);
}
}
else {
if (is_empty) {
Navigate(wxNavigationKeyEvent::FromTab | wxNavigationKeyEvent::IsForward);
return;
}
if (crow == rows - 1 && ccol == cols - 1) {
Navigate(wxNavigationKeyEvent::FromTab | wxNavigationKeyEvent::IsForward);
return;
}
if (has_no_selection) {
SetGridCursor(0, 0);
}
else if (ccol == cols - 1) {
SetGridCursor(crow + 1, 0);
}
else {
SetGridCursor(crow, ccol + 1);
}
}
MakeCellVisible(GetGridCursorRow(), GetGridCursorCol());
#if wxUSE_ACCESSIBILITY
// Make sure the NEW cell is made available to the screen reader
mAx->SetCurrentCell(GetGridCursorRow(), GetGridCursorCol());
#endif
}
break;
case WXK_RETURN:
case WXK_NUMPAD_ENTER:
{
if (!IsCellEditControlShown()) {
wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
wxWindow *def = tlw->GetDefaultItem();
if (def && def->IsEnabled()) {
wxCommandEvent cevent(wxEVT_COMMAND_BUTTON_CLICKED,
def->GetId());
GetParent()->GetEventHandler()->ProcessEvent(cevent);
}
}
else {
wxGrid::OnKeyDown(event);
// This looks strange, but what it does is selects the cell when
// enter is pressed after editing. Without it, Jaws and Window-Eyes
// do not speak the NEW cell contents (the one below the edited one).
SetGridCursor(GetGridCursorRow(), GetGridCursorCol());
}
break;
}
default:
wxGrid::OnKeyDown(event);
break;
}
}
#if wxUSE_ACCESSIBILITY
void Grid::ClearGrid()
{
wxGrid::ClearGrid();
mAx->TableUpdated();
return;
}
bool Grid::InsertRows(int pos, int numRows, bool updateLabels)
{
bool res = wxGrid::InsertRows(pos, numRows, updateLabels);
mAx->TableUpdated();
return res;
}
bool Grid::AppendRows(int numRows, bool updateLabels)
{
bool res = wxGrid::AppendRows(numRows, updateLabels);
mAx->TableUpdated();
return res;
}
bool Grid::DeleteRows(int pos, int numRows, bool updateLabels)
{
bool res = wxGrid::DeleteRows(pos, numRows, updateLabels);
mAx->TableUpdated();
return res;
}
bool Grid::InsertCols(int pos, int numCols, bool updateLabels)
{
bool res = wxGrid::InsertCols(pos, numCols, updateLabels);
mAx->TableUpdated();
return res;
}
bool Grid::AppendCols(int numCols, bool updateLabels)
{
bool res = wxGrid::AppendCols(numCols, updateLabels);
mAx->TableUpdated();
return res;
}
bool Grid::DeleteCols(int pos, int numCols, bool updateLabels)
{
bool res = wxGrid::DeleteCols(pos, numCols, updateLabels);
mAx->TableUpdated();
return res;
}
GridAx::GridAx(Grid *grid)
: WindowAccessible(grid->GetGridWindow())
{
mGrid = grid;
mLastId = -1;
}
void GridAx::TableUpdated()
{
NotifyEvent(wxACC_EVENT_OBJECT_REORDER,
mGrid->GetGridWindow(),
wxOBJID_CLIENT,
0);
}
void GridAx::SetCurrentCell(int row, int col)
{
int id = (((row * mGrid->GetNumberCols()) + col) + 1);
if (mLastId != -1) {
NotifyEvent(wxACC_EVENT_OBJECT_SELECTIONREMOVE,
mGrid->GetGridWindow(),
wxOBJID_CLIENT,
mLastId);
}
if (mGrid == wxWindow::FindFocus()) {
NotifyEvent(wxACC_EVENT_OBJECT_FOCUS,
mGrid->GetGridWindow(),
wxOBJID_CLIENT,
id);
}
NotifyEvent(wxACC_EVENT_OBJECT_SELECTION,
mGrid->GetGridWindow(),
wxOBJID_CLIENT,
id);
mLastId = id;
}
bool GridAx::GetRowCol(int childId, int & row, int & col)
{
if (childId == wxACC_SELF) {
return false;
}
int cols = mGrid->GetNumberCols();
int id = childId - 1;
row = id / cols;
col = id % cols;
return true;
}
// Retrieves the address of an IDispatch interface for the specified child.
// All objects must support this property.
wxAccStatus GridAx::GetChild(int childId, wxAccessible** child)
{
if (childId == wxACC_SELF) {
*child = this;
}
else {
*child = NULL;
}
return wxACC_OK;
}
// Gets the number of children.
wxAccStatus GridAx::GetChildCount(int *childCount)
{
*childCount = mGrid->GetNumberRows() * mGrid->GetNumberCols();
return wxACC_OK;
}
// Gets the default action for this object (0) or > 0 (the action for a child).
// Return wxACC_OK even if there is no action. actionName is the action, or the empty
// string if there is no action.
// The retrieved string describes the action that is performed on an object,
// not what the object does as a result. For example, a toolbar button that prints
// a document has a default action of "Press" rather than "Prints the current document."
wxAccStatus GridAx::GetDefaultAction(int WXUNUSED(childId), wxString *actionName)
{
actionName->clear();
return wxACC_OK;
}
// Returns the description for this object or a child.
wxAccStatus GridAx::GetDescription(int WXUNUSED(childId), wxString *description)
{
description->clear();
return wxACC_OK;
}
// Returns help text for this object or a child, similar to tooltip text.
wxAccStatus GridAx::GetHelpText(int WXUNUSED(childId), wxString *helpText)
{
helpText->clear();
return wxACC_OK;
}
// Returns the keyboard shortcut for this object or child.
// Return e.g. ALT+K
wxAccStatus GridAx::GetKeyboardShortcut(int WXUNUSED(childId), wxString *shortcut)
{
shortcut->clear();
return wxACC_OK;
}
// Returns the rectangle for this object (id = 0) or a child element (id > 0).
// rect is in screen coordinates.
wxAccStatus GridAx::GetLocation(wxRect & rect, int elementId)
{
wxRect r;
int row;
int col;
if (GetRowCol(elementId, row, col)) {
rect = mGrid->CellToRect(row, col);
rect.SetPosition(mGrid->CalcScrolledPosition(rect.GetPosition()));
rect.SetPosition(mGrid->GetGridWindow()->ClientToScreen(rect.GetPosition()));
}
else {
rect = mGrid->GetRect();
rect.SetPosition(mGrid->GetParent()->ClientToScreen(rect.GetPosition()));
}
return wxACC_OK;
}
// Gets the name of the specified object.
wxAccStatus GridAx::GetName(int childId, wxString *name)
{
int row;
int col;
if (GetRowCol(childId, row, col)) {
wxString n = mGrid->GetColLabelValue(col);
wxString v = mGrid->GetCellValue(row, col);
if (v.empty()) {
v = _("Empty");
}
// Hack to provide a more intelligible response
NumericEditor *dt =
static_cast<NumericEditor *>(mGrid->GetDefaultEditorForType(GRID_VALUE_TIME));
NumericEditor *df =
static_cast<NumericEditor *>(mGrid->GetDefaultEditorForType(GRID_VALUE_FREQUENCY));
NumericEditor *c =
static_cast<NumericEditor *>(mGrid->GetCellEditor(row, col));
if (c && dt && df && ( c == dt || c == df)) {
double value;
v.ToDouble(&value);
NumericConverter converter(c == dt ? NumericConverter::TIME : NumericConverter::FREQUENCY,
c->GetFormat(),
value,
c->GetRate() );
v = converter.GetString();
}
if (c)
c->DecRef();
if (dt)
dt->DecRef();
if (df)
df->DecRef();
*name = n + wxT(" ") + v;
}
return wxACC_OK;
}
wxAccStatus GridAx::GetParent(wxAccessible ** WXUNUSED(parent))
{
return wxACC_NOT_IMPLEMENTED;
}
// Returns a role constant.
wxAccStatus GridAx::GetRole(int childId, wxAccRole *role)
{
if (childId == wxACC_SELF) {
#if defined(__WXMSW__)
*role = wxROLE_SYSTEM_TABLE;
#endif
#if defined(__WXMAC__)
*role = wxROLE_SYSTEM_GROUPING;
#endif
}
else {
*role = wxROLE_SYSTEM_TEXT;
}
return wxACC_OK;
}
// Gets a variant representing the selected children
// of this object.
// Acceptable values:
// - a null variant (IsNull() returns TRUE)
// - a list variant (GetType() == wxT("list"))
// - an integer representing the selected child element,
// or 0 if this object is selected (GetType() == wxT("long"))
// - a "void*" pointer to a wxAccessible child object
wxAccStatus GridAx::GetSelections(wxVariant * WXUNUSED(selections))
{
return wxACC_NOT_IMPLEMENTED;
}
// Returns a state constant.
wxAccStatus GridAx::GetState(int childId, long *state)
{
int flag = wxACC_STATE_SYSTEM_FOCUSABLE |
wxACC_STATE_SYSTEM_SELECTABLE;
int col;
int row;
if (!GetRowCol(childId, row, col)) {
*state = 0;
return wxACC_FAIL;
}
#if defined(__WXMSW__)
flag |= wxACC_STATE_SYSTEM_FOCUSED |
wxACC_STATE_SYSTEM_SELECTED;
if (mGrid->IsReadOnly(row, col)) {
// It would be more logical to also include the state
// wxACC_STATE_SYSTEM_FOCUSABLE, but this causes Window-Eyes to
// no longer read the cell as disabled
flag = wxACC_STATE_SYSTEM_UNAVAILABLE | wxACC_STATE_SYSTEM_FOCUSED;
}
#endif
#if defined(__WXMAC__)
if (mGrid->IsInSelection(row, col)) {
flag |= wxACC_STATE_SYSTEM_SELECTED;
}
if (mGrid->GetGridCursorRow() == row && mGrid->GetGridCursorCol() == col) {
flag |= wxACC_STATE_SYSTEM_FOCUSED;
}
if (mGrid->IsReadOnly(row, col)) {
flag |= wxACC_STATE_SYSTEM_UNAVAILABLE;
}
#endif
*state = flag;
return wxACC_OK;
}
// Returns a localized string representing the value for the object
// or child.
#if defined(__WXMAC__)
wxAccStatus GridAx::GetValue(int childId, wxString *strValue)
#else
wxAccStatus GridAx::GetValue(int WXUNUSED(childId), wxString *strValue)
#endif
{
strValue->clear();
#if defined(__WXMSW__)
return wxACC_OK;
#endif
#if defined(__WXMAC__)
return GetName(childId, strValue);
#endif
}
#if defined(__WXMAC__)
// Selects the object or child.
wxAccStatus GridAx::Select(int childId, wxAccSelectionFlags selectFlags)
{
int row;
int col;
if (GetRowCol(childId, row, col)) {
if (selectFlags & wxACC_SEL_TAKESELECTION) {
mGrid->SetGridCursor(row, col);
}
mGrid->SelectBlock(row, col, row, col, selectFlags & wxACC_SEL_ADDSELECTION);
}
return wxACC_OK;
}
#endif
// Gets the window with the keyboard focus.
// If childId is 0 and child is NULL, no object in
// this subhierarchy has the focus.
// If this object has the focus, child should be 'this'.
wxAccStatus GridAx::GetFocus(int * childId, wxAccessible **child)
{
if (mGrid == wxWindow::FindFocus()) {
if (mGrid->GetNumberRows() * mGrid->GetNumberCols() == 0) {
*child = this;
}
else {
*childId = mGrid->GetGridCursorRow()*mGrid->GetNumberCols() +
mGrid->GetGridCursorCol() + 1;
}
}
return wxACC_OK;
}
#endif // wxUSE_ACCESSIBILITY
|
; A002296: Number of dissections of a polygon: binomial(7n,n)/(6n+1).
; 1,1,7,70,819,10472,141778,1997688,28989675,430321633,6503352856,99726673130,1547847846090,24269405074740,383846168712104,6116574500860880,98106248306858715,1582638261961640247,25661404527790252375,417980115131315136400,6836064539925118356600,112217382010337651183136,1848287308595474361079710,30535549185811381791388400,505890729677853961180935930,8402797840829663573766318582,139900837415397852310273466892,2334364695212889956723772319654,39030153183991985838807403452040
sub $1,$0
mul $0,6
sub $1,1
bin $1,$0
add $0,1
div $1,$0
mov $0,$1
|
; A021410: Decimal expansion of 1/406.
; Submitted by Jamie Morken(m2)
; 0,0,2,4,6,3,0,5,4,1,8,7,1,9,2,1,1,8,2,2,6,6,0,0,9,8,5,2,2,1,6,7,4,8,7,6,8,4,7,2,9,0,6,4,0,3,9,4,0,8,8,6,6,9,9,5,0,7,3,8,9,1,6,2,5,6,1,5,7,6,3,5,4,6,7,9,8,0,2,9,5,5,6,6,5,0,2,4,6,3,0,5,4,1,8,7,1,9,2
seq $0,83811 ; Numbers n such that 2n+1 is the digit reversal of n+1.
div $0,1624
mod $0,10
|
;//###########################################################################
;//
;// FILE: F2837xD_DBGIER.asm
;//
;// TITLE: Set the DBGIER register
;//
;// DESCRIPTION:
;//
;// Function to set the DBGIER register (for realtime emulation).
;// Function Prototype: void SetDBGIER(Uint16)
;// Usage: SetDBGIER(value);
;// Input Parameters: Uint16 value = value to put in DBGIER register.
;// Return Value: none
;//
;//###########################################################################
;// $TI Release: F2837xD Support Library v190 $
;// $Release Date: Mon Feb 1 16:51:57 CST 2016 $
;// $Copyright: Copyright (C) 2013-2016 Texas Instruments Incorporated -
;// http://www.ti.com/ ALL RIGHTS RESERVED $
;//###########################################################################
.global _SetDBGIER
.text
_SetDBGIER:
MOV *SP++,AL
POP DBGIER
LRETR
|
pong game, v1.2 written by Hrvoje Cavrak, 02/2019
szm=sza sma-szf
define swap
rcl 9s / Swap AC and IO registers macro
rcl 9s
terminate
define point A, B / Draw a point at (x+A, y+B)
law B
add y
sal 8s
swap
law A
add x
sal 8s
dpy-i +300
terminate
/ Ball consists of 8 points
define circle
point 0, 1 / 50 us between successive calls, it's ok to
point 0, 3 / use without waiting on completion pulse
point 4, 1
point 4, 3
point 1, 0
point 1, 3
point 1, 4
point 3, 4
terminate
define paddle X, Y / Draws paddles
lac pdlwidth
cma
dac p1cnt
pdloop,
lac Y
add pdlwidth
add p1cnt
sal 8s
swap
lac X
dpy-i+300
law 6
add p1cnt
dac p1cnt
isp p1cnt
jmp pdloop+R
terminate
define line C, D / Central line which acts as the "net"
law 0
sub maxdown
sub maxdown
dac p1cnt
ploop2,
lac p1cnt
add maxdown
sal 9s
swap
law D
dpy-i
law 70
add p1cnt
dac p1cnt
isp p1cnt
jmp ploop2+R
terminate
0/ opr
opr
opr
opr
jmp init / Jump to the init routine
400/
init,
dzm p1score
dzm p2score
dzm x
dzm y
dzm pdl1y
dzm pdl2y
jsp prec
jmp loop
500/
loop, / Main loop start
lac timer / If the timer is negative, proceed to increment it and skip over
sma / the part where ball and paddles are drawn (between games)
jmp lpskip
idx timer / Increment the wait timer and don't draw ball and paddles
jmp wait
lpskip,
circle / Draw the ball
lac x
add dx / Add the x delta to the ball position
dac x / Store the x back to memory
jsp checkx / Jump to subroutine which checks permitted x position
lac y
add dy / Add the y delta to the ball position
dac y / Store the y back to memory
jsp checky / Jump to subroutine which checks permitted y position
jsp rnd / Update the random number generator
wait,
jsp move / Invoke the paddle moving routine
paddle left, pdl1y / Invoke the paddle drawing routine
paddle right, pdl2y
jsp co1 / Draw score using compiled code, left player
jsp co2 / right player
line 0, 0 / Draw the net
jmp loop
rnd, dap rret / Spacewar's random generator
lac random
rar 1s
xor (355670
add (355670
dac random / It's also altered by user input, so it's user + prng
rret, jmp .
define noc X / Number outline compiler
lac X
dac i cptr
idx cptr
terminate
cx, 000000 / Initial X position
cy1, 000360 / Initial Y position
prec, dap pc1r
law co1 1
dac cptr
lac (n1dots
add p1score
dac \index
law 200
dac cx
jsp jit / Render digit for player 1
noc (jmp cr1
/ -------------- Player 2 --------------
law co2 1
dac cptr
lac (n2dots
add p2score
dac \index
law 201
dac cx
jsp jit
noc (jmp cr2
pc1r, jmp .
jit, dap jret / compiler routine, generates time-sensitive display
/ writing code so digits can be displayed and still game without flicker
lac i \index
cma / Complement it, so we can use spi to skip on 0
swap / Move it to IO register
lac cx / Load initial X position
dac crow / Store it in X position pointer
lac cy1 / Load initial Y position
dac ccol / Store it in Y position pointer
jlp,
rir 1s / Rotate IO left
spi / Skip if bit is 1
jsp nodot
lac (law / Generate code to generate dots
add ccol
dac i cptr
idx cptr
noc (sal 9s
noc (rcr 9s
noc (rcr 9s
lac (law
add crow
dac i cptr
idx cptr
noc (nop / Timing budget between DPYs
noc (nop / law (5us), shift (5us), rotate (5us)
noc (nop / rotate (5us), law (5us), shift (5us), opr (5us)
noc (nop / = 35 us, we need 50 us so insert 4 more nops just to be safe
/ completion pulse not needed
noc (sal 8s
lac cx
and (1
sza
jmp sd1 / NOC macro is 3 instructions, jump over it if cma not needed
noc (cma / If negative, complement accumulator in compiled code
sd1, noc (dpy -i +300
nodot,
law 10 / Load X step
add crow / Add to current X position
dac crow / Store back into memory
lac cx
add (30
sas crow / If we reached the end of row
jmp nd2skp / Skip the next statements
lac cx / Reset X position to start of row
dac crow
lac ccol / Move down to next row
sub (4
dac ccol
nd2skp,
lac cy1 / Load bottom row
sub (24
sas ccol / Skip if current row equals bottom row
jmp jlp / Repeat loop
jret, jmp .
define testkey K, N / Tests if key K was pressed and skips to N if it is not
lac controls
and K
sza
jmp N
terminate
define padmove Y, A / Initiates moving of the pads
lac Y
dac pdly
jsp A
lac pdly
dac Y
terminate
move,
dap mvret / Moves the paddles
cli / Load current controller button state
iot 11
dio controls
move1,
testkey rghtup, move2 / Right UP
padmove pdl2y, mvup
move2,
testkey leftup, move3 / Left UP
padmove pdl1y, mvup
move3, / Right DOWN
testkey rghtdown, move4
padmove pdl2y, mvdown
move4, / Left DOWN
testkey leftdown, mvret
padmove pdl1y, mvdown
mvret, jmp .
define flip A / Inverts the bits of memory location A
lac A
cma
dac A
terminate
mvup, dap upret / Move pad UP
lac pdly
sub limitup / Check if pad at top edge
sma
jmp upret / Do nothing if it is
lac pdly
add padoff
dac pdly
add random / Use pad coordinates as user provided randomness
dac random
upret, jmp .
mvdown, dap downret / Move pad DOWN
lac pdly
add limitdown / Check if pad at bottom edge
spa
jmp downret / Do nothing if it is
lac pdly
sub padoff
dac pdly
add random / Use pad coordinates as user provided randomness
dac random
downret, jmp .
delay, dap dlyret / Delay routine
lac dlytime
dac dlycnt
dlyloop,
isp dlycnt
jmp dlyloop
dlyret, jmp .
gmovr, / Game over routine
lac (777000 / Long pause after game is over
dac timer
jmp init / Init won't re-set the timer so the game will pause for a while
srvover, / Serve was lost
lac dx
dac whowon / Store who won last serve
sma / If dx was positive, the ball was going right and player 2 (right) lost
idx p1score
lac whowon
spa / Else, player 1 (left) lost
idx p2score
jsp prec / Call compiler to recompute the routines for drawing digits
lac (777650 / Short pause between ball launches
dac timer
lac p1score / Did player 1 win the game?
sub (12
sma
jmp gmovr / If so, go to game over
lac p2score / Did player 2 win the game?
sub (12
sma
jmp gmovr / If true, jump to game over
jmp restart / Nobody won yet, jump to serve another ball
restart,
jsp delay / Wait a bit before serving
idx iter / Count the number of restarts
lac random / Load the current randomness value
and dymask / Limit it to the interval we need it to be
add (1 / Don't want it to be 0
dac dy / Set initial launch vector to this value
lac random
and ymask
sub maxdown
dac y / Do the same for launch position
law 2 / Set initial launch vector
lio whowon
spi / Skip complementing depending on who won last round
cma / Therefore, the ball will be launched towards the loser
dac dx / of the previous round
law 600 / Set X coordinate of ball to serve
cma
spi / If serve was won by player 1, complement so it's left of the net
cma
dac x
jmp ckret
hitpaddle, dap ckret / Check for colision with paddle
lac y
sub pdly
add (1
spa / must be true: y - pdl1y > 0
jmp srvover / return if not
sub pdlwidth
sub (2 / tweak borders so edges are not registered as a miss
sma / must be true: y - pdlwidth - pdl1y < 0
jmp srvover / return if not
flip dx
idx dirchng / Count number of paddle hits, increase speed subsequently
lac dx
spa
jmp skipfast / Consider increasing dx only if positive
law 3 / if 3 - dirchng < 0 (every 3 hits from right paddle), increase speed
sub dirchng
spa
idx dx
spa
dzm dirchng / Reset dirchng counter back to zero, everything starts from scratch
skipfast,
lac pdly / get distance from center of paddle
add pdlhalf
sub y
spa
cma / take abs() of accumulator
sar 4s / shift 3 bits right (divide by 8)
add (1 / To prevent x-only movement, add 1 so it should never be zero
/ Here, accumulator holds the absolute offset from the paddle center divided by 8
lio dy / Load dy to IO not to destroy ACC contents
spi / If dy is positive, subtract
cma
dac dy / Set new y bounce angle
ckret, jmp .
checkx,
dap cxret
lac pdl1y / Load position of right paddle
dac pdly
lac x
add maxleft / AC = x + maxright, if x < -500, swap dx
spa
jsp hitpaddle
lac pdl2y / Load position of left paddle
dac pdly
lac x
sub maxright / AC = x - maxleft, if x > 500, swap dx
sma
jsp hitpaddle
cxret, jmp .
checky,
dap cyret
lac y
add maxdown / AC = y + maxdown, if y < -500, swap dy
spa
jmp cnext
flip dy
cnext,
lac y
sub maxdown / AC = y - maxdown, if y > 500, swap dy
sma
jmp cyret
flip dy
cyret, jmp .
////////////////////////////////////////////////////////////////////////////////////////////////
x, 000500 / Current ball coordinates
y, 000000
dx, 777775 / Movement vector
dy, 000003
iter, 000000 / Number of restarts
cptr, 000000 / Current LUT compiler pointer
crow, 000000 / Current row X position
ccol, 000000 / Current row Y position
padoff, 000004 / Paddle offset
random, 000001 / Randomness pool, changes via PRNG + user input
pdly, 000000 / Paddle vertical position
pdl1y, 000000 / Paddle 1 vertical position
pdl2y, 000000 / Paddle 2 vertical position
p1cnt, 000000
controls, 000000 / Current state of input buttons
left, 400400
right, 374000
pdlwidth, 000150 / Width of a paddle
pdlhalf, 000064 / Half width
maxright, 000764 / Limit the X coordinate in right direction
maxleft, 000774 / Limit X coordinate left
maxdown, 000764 / Limit Y coordinate down
dymask, 000003 / Anded with dymask, take only the last 2 bits
ymask, 000777 / Anded with ymask, take only the last 9 bits
limitup, 000562 / Top limit for the PAD position
limitdown, 000760 / Bottom limit for the PAD position
leftdown, 000001 / Key bitmasks, left down
leftup, 000002 / left up
rghtdown, 040000 / Right down
rghtup, 100000 / Right up
dlytime, 770000 / Time to wait before launching the ball
dlycnt, 000000 / Delay counter register
dirchng, 000000 / Counts direction changes, used for increasing ball speed
p1score, 000000 / Player 1's score
p2score, 000000 / Player 2's score
whowon, 000000 / Which player won last serve (>0 = right, <0 = left)
timer, 777700 / Used to wait a while after game over
/ n1dots and n2dots are horizontally flipped
n1dots, 075557 / 0
011111 / 1
074717 / 2
071717 / 3
011755 / 4
071747 / 5
075744 / 6
011117 / 7
075757 / 8
011757 / 9
n2dots, 075557 / 0
011111 / 1
071747 / 2
074747 / 3
044755 / 4
074717 / 5
075711 / 6
044447 / 7
075757 / 8
044757 / 9
5670/
co1, dap cr1
jmp cr1
. 300/ / Reserve space for number compilation, player 1
cr1, jmp .
co2, dap cr2
jmp cr2
. 300/ / Reserve space for number compilation, player 2
cr2, jmp .
constants
variables
start 400
|
#define __STDC_FORMAT_MACROS
#include <torch/csrc/python_headers.h>
#include <structmember.h>
#include <vector>
#include <stack>
#include <tuple>
#include <torch/csrc/cuda/THCP.h>
#include <torch/csrc/cuda/override_macros.h>
#include <torch/csrc/copy_utils.h>
#include <torch/csrc/DynamicTypes.h>
#include <torch/csrc/utils/tensor_numpy.h>
//generic_include THC torch/csrc/generic/Tensor.cpp
#include <torch/csrc/cuda/undef_macros.h>
#include <torch/csrc/cuda/restore_macros.h>
|
.MODEL SMALL
.STACK 100h
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
|
#include "IntroWindow.h"
#ifdef CONSPIRACY_LINUX
#include <stdlib.h>
Display *dpy;
Window root;
XVisualInfo *vi;
Colormap cmap;
XSetWindowAttributes swa;
Window win;
GLXContext glc;
XWindowAttributes gwa;
XEvent xev;
HDC hDC=NULL;
#else
HDC hDC=NULL;
HGLRC hRC=NULL;
HWND hWnd=NULL;
HINSTANCE hInstance;
#endif
bool keys[256];
bool active=TRUE;
bool done = false;
bool mode3d = true;
#ifdef CONSPIRACY_LINUX
#else
MSG msg;
#endif
int xres,yres;
GLvoid KillGLWindow(GLvoid)
{
#ifdef CONSPIRACY_LINUX
XCloseDisplay(dpy);
#else
ChangeDisplaySettings(NULL,0);
ShowCursor(TRUE);
#endif
}
BOOL Intro_CreateWindow(const char* title, int width, int height, int bits, bool fullscreenflag, HICON icon, bool aontop)
{
xres=width;
yres=height;
#ifdef CONSPIRACY_LINUX
dpy = XOpenDisplay(NULL);
if(dpy == NULL) {
printf("\n\tcannot connect to X server\n\n");
exit(0);
}
root = DefaultRootWindow(dpy);
GLint att[] = {
GLX_RGBA,
GLX_DOUBLEBUFFER,
GLX_DEPTH_SIZE, 24,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
None };
vi = glXChooseVisual(dpy, 0, att);
if(vi == NULL) {
printf("\n\tno appropriate visual found\n\n");
exit(0);
}
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
swa.colormap = cmap;
swa.event_mask = KeyPressMask;
win = XCreateWindow(dpy, root, 0, 0, xres, yres, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa);
XMapWindow(dpy, win);
XStoreName(dpy, win, title);
glc = glXCreateContext(dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(dpy, win, glc);
#else
GLuint PixelFormat;
WNDCLASS wc;
DWORD dwExStyle;
DWORD dwStyle;
RECT WindowRect;
WindowRect.left=(long)0;
WindowRect.right=(long)width;
WindowRect.top=(long)0;
WindowRect.bottom=(long)height;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = icon;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "OpenGL";
RegisterClass(&wc);
if (fullscreenflag)
{
DEVMODE dmScreenSettings;
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
dmScreenSettings.dmSize=sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = width;
dmScreenSettings.dmPelsHeight = height;
dmScreenSettings.dmBitsPerPel = bits;
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
dwExStyle=WS_EX_APPWINDOW;
dwStyle=WS_POPUP;
ShowCursor(FALSE);
}
else
{
dwExStyle=WS_EX_APPWINDOW + WS_EX_WINDOWEDGE;
dwStyle=WS_OVERLAPPED+ WS_CAPTION+ WS_SYSMENU+WS_MINIMIZEBOX;
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
hWnd=CreateWindowEx( dwExStyle,
"OpenGL",
title,
dwStyle |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,
CW_USEDEFAULT, CW_USEDEFAULT,
WindowRect.right-WindowRect.left,
WindowRect.bottom-WindowRect.top,
NULL,
NULL,
hInstance,
NULL);
static PIXELFORMATDESCRIPTOR pfd=
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
bits,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
32,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
hDC=GetDC(hWnd);
PixelFormat=ChoosePixelFormat(hDC,&pfd);
SetPixelFormat(hDC,PixelFormat,&pfd);
hRC=wglCreateContext(hDC);
wglMakeCurrent(hDC,hRC);
ShowWindow(hWnd,SW_SHOW);
SetForegroundWindow(hWnd);
SetFocus(hWnd);
if (aontop) {
SetWindowPos(hWnd,HWND_TOPMOST,
(GetSystemMetrics(SM_CXSCREEN)-width)/2,
(GetSystemMetrics(SM_CYSCREEN)-height)/2,
0, 0, SWP_NOSIZE);
//WriteDebug("Always on top.\n");
}
#endif
glEnable(GL_DEPTH_TEST);
//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return TRUE;
}
#ifdef CONSPIRACY_LINUX
void handleXevents() {
while (XCheckWindowEvent(dpy, win, KeyPressMask, &xev)) {
if (xev.xkey.keycode == 9) {
keys[27] = true;
}
}
}
void SwapBuffers(HDC hdc) {
glXSwapBuffers(dpy, win);
}
#else
LRESULT CALLBACK WndProc( HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
switch (uMsg)
{
case WM_ACTIVATE:
{
active=(!HIWORD(wParam));
return 0;
}
case WM_SYSCOMMAND:
{
switch (wParam)
{
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
}
break;
}
case WM_CLOSE:
{
done = true;
return 0;
}
case WM_KEYDOWN:
{
keys[wParam] = true;
return 0;
}
}
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
#endif
void switchto2d()
{
glLoadIdentity();
glViewport(0, 0, xres, yres);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, 800, 600,0.0);
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r8
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x10437, %r8
nop
nop
nop
nop
nop
cmp $59340, %rdx
movups (%r8), %xmm4
vpextrq $0, %xmm4, %r11
nop
nop
nop
and $31387, %r8
lea addresses_normal_ht+0x5637, %r13
nop
nop
nop
nop
xor %r9, %r9
mov $0x6162636465666768, %r14
movq %r14, %xmm4
vmovups %ymm4, (%r13)
cmp $23974, %r9
lea addresses_UC_ht+0x308f, %rsi
lea addresses_A_ht+0x1b5ab, %rdi
nop
nop
nop
nop
nop
add %r11, %r11
mov $77, %rcx
rep movsw
nop
nop
nop
and %r8, %r8
lea addresses_normal_ht+0x3b6f, %rdi
nop
nop
inc %r11
movw $0x6162, (%rdi)
nop
nop
nop
inc %rcx
lea addresses_WC_ht+0xb9b7, %rsi
lea addresses_UC_ht+0x7637, %rdi
nop
sub %r13, %r13
mov $98, %rcx
rep movsw
nop
nop
nop
and $3642, %rdx
lea addresses_UC_ht+0x89b7, %r8
nop
nop
nop
nop
sub $26145, %rsi
movb (%r8), %r13b
nop
nop
nop
nop
xor %r11, %r11
lea addresses_normal_ht+0x17a37, %r8
nop
nop
add $38169, %rsi
movb $0x61, (%r8)
nop
nop
nop
xor $60037, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r8
push %rax
push %rbp
push %rbx
// Store
lea addresses_normal+0x16d8f, %r11
nop
nop
and %rbp, %rbp
mov $0x5152535455565758, %r8
movq %r8, %xmm1
vmovups %ymm1, (%r11)
nop
nop
nop
nop
nop
cmp %r13, %r13
// Store
lea addresses_RW+0x2757, %r8
nop
nop
nop
inc %rax
mov $0x5152535455565758, %r10
movq %r10, %xmm0
movaps %xmm0, (%r8)
add $21822, %rax
// Store
lea addresses_WT+0x5737, %r13
nop
nop
nop
nop
add $51692, %rbx
movl $0x51525354, (%r13)
nop
nop
xor %rbx, %rbx
// Faulty Load
lea addresses_RW+0x19e37, %rbp
sub $8459, %rax
mov (%rbp), %r8w
lea oracles, %rax
and $0xff, %r8
shlq $12, %r8
mov (%rax,%r8,1), %r8
pop %rbx
pop %rbp
pop %rax
pop %r8
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': True, 'size': 16, 'NT': False, 'same': False, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': True, 'size': 4, 'NT': False, 'same': False, 'congruent': 8}}
[Faulty Load]
{'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 11}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 2}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 1, 'NT': False, 'same': False, 'congruent': 10}}
{'32': 1517}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
#include <alg/sobel.hpp>
#include <cmn/image.hpp>
#include <cmn/image_utils.hpp>
#include <cmn/log.hpp>
#include <cmn/point.hpp>
#include <math.h>
#include <string.h>
//for tests
#include <adapter/image.hpp>
#include <adapter/filesystem.hpp>
#include <alg/paint.hpp>
#include <alg/seg_object.hpp>
//#include <alg/diagram.hpp>
namespace alg
{
#if 0
static int const mask[3][3]
{
{-3, 0, 3},
{-10, 0, 10},
{-3, 0, 3},
};
#endif
struct rgb_mask_t
{
static int const constexpr maskr[3][3] =
{
{-3*76, 0, 3*76},
{-10*76, 0, 10*76},
{-3*76, 0, 3*76},
};
static int const constexpr maskg[3][3] =
{
{-3*150, 0, 3*150},
{-10*150, 0, 10*150},
{-3*150, 0, 3*150},
};
static int const constexpr maskb[3][3] =
{
{-3*29, 0, 3*29},
{-10*29, 0, 10*29},
{-3*29, 0, 3*29},
};
};
struct hsv_mask_t
{
static int const constexpr maskr[3][3] =
{
{-3*20, 0, 3*20},
{-10*20, 0, 10*20},
{-3*20, 0, 3*20},
};
static int const constexpr maskg[3][3] =
{
{-3*110, 0, 3*110},
{-10*110, 0, 10*110},
{-3*110, 0, 3*110},
};
static int const constexpr maskb[3][3] =
{
{-3*110, 0, 3*110},
{-10*110, 0, 10*110},
{-3*110, 0, 3*110},
};
};
struct lab_mask_t
{
static float const constexpr mask[3][3] =
{
{-3, 0, 3},
{-10, 0, 10},
{-3, 0, 3},
};
};
//reason: http://stackoverflow.com/questions/8016780/undefined-reference-to-static-constexpr-char
constexpr const int rgb_mask_t::maskr[3][3];
constexpr const int rgb_mask_t::maskg[3][3];
constexpr const int rgb_mask_t::maskb[3][3];
constexpr const int hsv_mask_t::maskr[3][3];
constexpr const int hsv_mask_t::maskg[3][3];
constexpr const int hsv_mask_t::maskb[3][3];
constexpr const float lab_mask_t::mask[3][3];
template< typename M > //M stands for Mask, see above
static void
sobel_template( cmn::image_pt * img_edge, sobel_stat_t * stat, cmn::image_pt const img_src )
{
int max_gradi = 0;
int * const diagram = stat->diagram;
memset( diagram, 0, 256*sizeof(int) );
int const width = img_src->header.width;
int const height = img_src->header.height;
if( width < 3 || height < 3 )
return;
cmn::image_pt img_dstp = cmn::image_create( width, height, cmn::pitch_default, cmn::format_g );
cmn::image_t * img_dst = img_dstp.get();
int const lastx = width - 1;
int const lasty = height - 1;
cmn::color4b_t const * row[3];
row[1] = img_src->row<cmn::color4b_t>(0);
row[2] = img_src->row<cmn::color4b_t>(1);
for( int y = 1; y < lasty; ++y )
{
row[0] = row[1];
row[1] = row[2];
row[2] = img_src->row<cmn::color4b_t>(y+1);
uint8_t * row_dst = img_dst->row<uint8_t>(y);
for( int x = 1; x < lastx; ++x )
{
//compiler optimization heaven...
int const x0 = x-1;
int const x2 = x+1;
typedef cmn::color4b_t c_t;
c_t const row00 = row[0][x0];
c_t const row01 = row[0][x];
c_t const row02 = row[0][x2];
c_t const row10 = row[1][x0];
c_t const row12 = row[1][x2];
c_t const row20 = row[2][x0];
c_t const row21 = row[2][x];
c_t const row22 = row[2][x2];
int const gx00r = M::maskr[0][0]*row00.r; int const gx00g = M::maskg[0][0]*row00.g; int const gx00b = M::maskb[0][0]*row00.b;
int const gx02r = M::maskr[0][2]*row02.r; int const gx02g = M::maskg[0][2]*row02.g; int const gx02b = M::maskb[0][2]*row02.b;
int const gx10r = M::maskr[1][0]*row10.r; int const gx10g = M::maskg[1][0]*row10.g; int const gx10b = M::maskb[1][0]*row10.b;
int const gx12r = M::maskr[1][2]*row12.r; int const gx12g = M::maskg[1][2]*row12.g; int const gx12b = M::maskb[1][2]*row12.b;
int const gx20r = M::maskr[2][0]*row20.r; int const gx20g = M::maskg[2][0]*row20.g; int const gx20b = M::maskb[2][0]*row20.b;
int const gx22r = M::maskr[2][2]*row22.r; int const gx22g = M::maskg[2][2]*row22.g; int const gx22b = M::maskb[2][2]*row22.b;
int const gy00r = M::maskr[0][0]*row00.r; int const gy00g = M::maskg[0][0]*row00.g; int const gy00b = M::maskb[0][0]*row00.b;
int const gy01r = M::maskr[1][0]*row01.r; int const gy01g = M::maskg[1][0]*row01.g; int const gy01b = M::maskb[1][0]*row01.b;
int const gy02r = M::maskr[2][0]*row02.r; int const gy02g = M::maskg[2][0]*row02.g; int const gy02b = M::maskb[2][0]*row02.b;
int const gy20r = M::maskr[0][2]*row20.r; int const gy20g = M::maskg[0][2]*row20.g; int const gy20b = M::maskb[0][2]*row20.b;
int const gy21r = M::maskr[1][2]*row21.r; int const gy21g = M::maskg[1][2]*row21.g; int const gy21b = M::maskb[1][2]*row21.b;
int const gy22r = M::maskr[2][2]*row22.r; int const gy22g = M::maskg[2][2]*row22.g; int const gy22b = M::maskb[2][2]*row22.b;
int const sumx0r = gx00r + gx02r; int const sumx0g = gx00g + gx02g; int const sumx0b = gx00b + gx02b;
int const sumx1r = gx10r + gx12r; int const sumx1g = gx10g + gx12g; int const sumx1b = gx10b + gx12b;
int const sumx2r = gx20r + gx22r; int const sumx2g = gx20g + gx22g; int const sumx2b = gx20b + gx22b;
int const sumy0r = gy00r + gy01r; int const sumy0g = gy00g + gy01g; int const sumy0b = gy00b + gy01b;
int const sumy1r = gy02r + gy20r; int const sumy1g = gy02g + gy20g; int const sumy1b = gy02b + gy20b;
int const sumy2r = gy21r + gy22r; int const sumy2g = gy21g + gy22g; int const sumy2b = gy21b + gy22b;
int const sumxr = sumx0r + sumx1r + sumx2r; int const sumxg = sumx0g + sumx1g + sumx2g; int const sumxb = sumx0b + sumx1b + sumx2b;
int const sumyr = sumy0r + sumy1r + sumy2r; int const sumyg = sumy0g + sumy1g + sumy2g; int const sumyb = sumy0b + sumy1b + sumy2b;
//Normalize: YUV (8bits) + 4Bits for Scharr
int const gradxr = sumxr >> (4+8); int const gradxg = sumxg >> (4+8); int const gradxb = sumxb >> (4+8);
int const gradyr = sumyr >> (4+8); int const gradyg = sumyg >> (4+8); int const gradyb = sumyb >> (4+8);
//now calculate distance... invent something, definitely will be the slowest point
int const grad = (int)sqrt(gradxr*gradxr + gradyr*gradyr + gradxg*gradxg + gradyg*gradyg + gradxb*gradxb + gradyb*gradyb);
row_dst[x] = (uint8_t)grad;
++diagram[ (uint8_t)grad ];
if( grad > max_gradi )
max_gradi = grad;
}
}
{
uint8_t * row_dst0 = img_dst->row<uint8_t>(lasty-1);
uint8_t * row_dst1 = img_dst->row<uint8_t>(lasty);
for( int x = 0; x <= lastx; ++x )
row_dst1[x] = row_dst0[x];
row_dst0 = img_dst->row<uint8_t>(0);
row_dst1 = img_dst->row<uint8_t>(1);
for( int x = 0; x <= lastx; ++x )
row_dst0[x] = row_dst1[x];
//vertical access:
int const prelastx = lastx - 1;
for( int y = 1; y < lasty; ++y )
{
row_dst0 = img_dst->row<uint8_t>(y);
row_dst0[0] = row_dst0[1];
row_dst0[lastx] = row_dst0[prelastx];
}
}
*img_edge = img_dstp;
stat->max_grad = max_gradi;
}
template<typename M> //M here - lab mask...
void sobel_lab(cmn::image_pt * img_edge, sobel_stat_t * stat, cmn::image_pt const img_src)
{
int max_gradi = 0;
int * const diagram = stat->diagram;
memset( diagram, 0, 256*sizeof(int) );
int const width = img_src->header.width;
int const height = img_src->header.height;
if( width < 3 || height < 3 )
return;
cmn::image_pt img_dstp = cmn::image_create( width, height, cmn::pitch_default, cmn::format_g );
cmn::image_t * img_dst = img_dstp.get();
int const lastx = width - 1;
int const lasty = height - 1;
cmn::color3f_t const * row[3];
row[1] = img_src->row<cmn::color3f_t>(0);
row[2] = img_src->row<cmn::color3f_t>(1);
for( int y = 1; y < lasty; ++y )
{
row[0] = row[1];
row[1] = row[2];
row[2] = img_src->row<cmn::color3f_t>(y+1);
uint8_t * row_dst = img_dst->row<uint8_t>(y);
for( int x = 1; x < lastx; ++x )
{
//compiler optimization heaven...
int const x0 = x-1;
int const x2 = x+1;
typedef cmn::color3f_t c_t;
c_t const row00 = row[0][x0];
c_t const row01 = row[0][x];
c_t const row02 = row[0][x2];
c_t const row10 = row[1][x0];
c_t const row12 = row[1][x2];
c_t const row20 = row[2][x0];
c_t const row21 = row[2][x];
c_t const row22 = row[2][x2];
float const gx00r = M::mask[0][0]*row00.r; float const gx00g = M::mask[0][0]*row00.g; float const gx00b = M::mask[0][0]*row00.b;
float const gx02r = M::mask[0][2]*row02.r; float const gx02g = M::mask[0][2]*row02.g; float const gx02b = M::mask[0][2]*row02.b;
float const gx10r = M::mask[1][0]*row10.r; float const gx10g = M::mask[1][0]*row10.g; float const gx10b = M::mask[1][0]*row10.b;
float const gx12r = M::mask[1][2]*row12.r; float const gx12g = M::mask[1][2]*row12.g; float const gx12b = M::mask[1][2]*row12.b;
float const gx20r = M::mask[2][0]*row20.r; float const gx20g = M::mask[2][0]*row20.g; float const gx20b = M::mask[2][0]*row20.b;
float const gx22r = M::mask[2][2]*row22.r; float const gx22g = M::mask[2][2]*row22.g; float const gx22b = M::mask[2][2]*row22.b;
float const gy00r = M::mask[0][0]*row00.r; float const gy00g = M::mask[0][0]*row00.g; float const gy00b = M::mask[0][0]*row00.b;
float const gy01r = M::mask[1][0]*row01.r; float const gy01g = M::mask[1][0]*row01.g; float const gy01b = M::mask[1][0]*row01.b;
float const gy02r = M::mask[2][0]*row02.r; float const gy02g = M::mask[2][0]*row02.g; float const gy02b = M::mask[2][0]*row02.b;
float const gy20r = M::mask[0][2]*row20.r; float const gy20g = M::mask[0][2]*row20.g; float const gy20b = M::mask[0][2]*row20.b;
float const gy21r = M::mask[1][2]*row21.r; float const gy21g = M::mask[1][2]*row21.g; float const gy21b = M::mask[1][2]*row21.b;
float const gy22r = M::mask[2][2]*row22.r; float const gy22g = M::mask[2][2]*row22.g; float const gy22b = M::mask[2][2]*row22.b;
float const sumx0r = gx00r + gx02r; float const sumx0g = gx00g + gx02g; float const sumx0b = gx00b + gx02b;
float const sumx1r = gx10r + gx12r; float const sumx1g = gx10g + gx12g; float const sumx1b = gx10b + gx12b;
float const sumx2r = gx20r + gx22r; float const sumx2g = gx20g + gx22g; float const sumx2b = gx20b + gx22b;
float const sumy0r = gy00r + gy01r; float const sumy0g = gy00g + gy01g; float const sumy0b = gy00b + gy01b;
float const sumy1r = gy02r + gy20r; float const sumy1g = gy02g + gy20g; float const sumy1b = gy02b + gy20b;
float const sumy2r = gy21r + gy22r; float const sumy2g = gy21g + gy22g; float const sumy2b = gy21b + gy22b;
float const sumxr = sumx0r + sumx1r + sumx2r; float const sumxg = sumx0g + sumx1g + sumx2g; float const sumxb = sumx0b + sumx1b + sumx2b;
float const sumyr = sumy0r + sumy1r + sumy2r; float const sumyg = sumy0g + sumy1g + sumy2g; float const sumyb = sumy0b + sumy1b + sumy2b;
//normalize
//16 should be here instead of 8, but practically I see that max Lab distance I have on images is about 100,
//so I think scale x2 is fully ok
float const gradxr = sumxr / 8.f; float const gradxg = sumxg / 8.f; float const gradxb = sumxb / 8.f;
float const gradyr = sumyr / 8.f; float const gradyg = sumyg / 8.f; float const gradyb = sumyb / 8.f;
//now calculate distance... invent something, definitely will be the slowest point
int grad = (int)sqrt(gradxr*gradxr + gradyr*gradyr + gradxg*gradxg + gradyg*gradyg + gradxb*gradxb + gradyb*gradyb);
if( grad > max_gradi )
max_gradi = grad;
if( grad > 255.f ) grad = 255.f; //clamping
row_dst[x] = (uint8_t)grad;
++diagram[ (uint8_t)grad ];
}
}
{
uint8_t * row_dst0 = img_dst->row<uint8_t>(lasty-1);
uint8_t * row_dst1 = img_dst->row<uint8_t>(lasty);
for( int x = 0; x <= lastx; ++x )
row_dst1[x] = row_dst0[x];
row_dst0 = img_dst->row<uint8_t>(0);
row_dst1 = img_dst->row<uint8_t>(1);
for( int x = 0; x <= lastx; ++x )
row_dst0[x] = row_dst1[x];
//vertical access:
int const prelastx = lastx - 1;
for( int y = 1; y < lasty; ++y )
{
row_dst0 = img_dst->row<uint8_t>(y);
row_dst0[0] = row_dst0[1];
row_dst0[lastx] = row_dst0[prelastx];
}
}
*img_edge = img_dstp;
stat->max_grad = max_gradi;
}
void sobel( cmn::image_pt * img_edge, sobel_stat_t * stat, cmn::image_pt const img_src )
{
switch( img_src->header.format )
{
case cmn::format_rgba:
sobel_template<rgb_mask_t>( img_edge, stat, img_src );
break;
case cmn::format_hsva:
sobel_template<hsv_mask_t>( img_edge, stat, img_src );
break;
case cmn::format_lab_f32:
sobel_lab<lab_mask_t>( img_edge, stat, img_src );
break;
default:
cmn::log_and_throw("alg/sobel.cpp:sobel - format %d is not supported", img_src->header.format );
}
}
#if 0 //works but results are not better than with sobel 3x3
static int mask_f = 1;
//I tried severel different masks... anyway it doesn't become better :(
//sum 30
static int const maskg[5][5] =
{
{2, 1, 0, -1, -2},
{4, 2, 0, -2, -4},
{8, 4, 0, -4, -8},
{4, 2, 0, -2, -4},
{2, 1, 0, -1, -2},
};
static void sobel5( cmn::image_pt * img_edge, sobel_stat_t * stat, cmn::image_pt const img_src )
{
int max_gradi = 0;
int * const diagram = stat->diagram;
memset( diagram, 0, 256*sizeof(int) );
int const width = img_src->header.width;
int const height = img_src->header.height;
if( width < 5 || height < 5 )
return;
cmn::image_pt img_dstp = cmn::image_create( width, height, cmn::pitch_default, cmn::format_g );
cmn::image_t * img_dst = img_dstp.get();
int const lastx = width - 2;
int const lasty = height - 2;
cmn::color4b_t const * row[5];
row[1] = img_src->row<cmn::color4b_t>(0);
row[2] = img_src->row<cmn::color4b_t>(1);
row[3] = img_src->row<cmn::color4b_t>(2);
row[4] = img_src->row<cmn::color4b_t>(3);
for( int y = 2; y < lasty; ++y )
{
//shifting...
row[0] = row[1];
row[1] = row[2];
row[2] = row[3];
row[3] = row[4];
row[4] = img_src->row<cmn::color4b_t>(y+2);
uint8_t * row_dst = img_dst->row<uint8_t>(y);
for( int x = 2; x < lastx; ++x )
{
int sumx = 0, sumy = 0;
for( int8_t my = 0; my < 5; ++my )
{
for( int8_t mx = 0; mx < 5; ++mx )
{
sumx += row[my][x + mx-2].g*maskg[my][mx];
sumy += row[my][x + mx-2].g*maskg[mx][my];
}
}
int grad = (int)(sqrt( sumx*sumx + sumy*sumy ));
grad = grad / 30;
row_dst[x] = grad;
if( grad > max_gradi )
max_gradi = grad;
}
}
stat->max_grad = max_gradi;
*img_edge = img_dstp;
}
#endif
static void sobel_test_do_rest( cmn::image_pt const & img, std::string const & name_base )
{
std::string dir_dst = adapter::fs_prefs_dir();
cmn::image_pt img_sobel;
sobel_stat_t stat;
sobel(&img_sobel, &stat, img);
cmn::image_pt img_sobel_color = cmn::image_rgba_from_g8(img_sobel);
printf("%s: max_grad: %d\n", name_base.c_str(), stat.max_grad);
if( stat.max_grad > 255 ) stat.max_grad = 255;
adapter::image_save_to_png( img_sobel_color, (dir_dst + name_base +"_sobel.png").c_str() );
//alg::diagram_make_integral( stat.diagram, stat.max_grad );
//uint8_t cutting_point = alg::diagram_find_cutting_point( stat.diagram, stat.max_grad );
cmn::image_pt img_colored_g16 = alg::image_paint_with_hint( img_sobel, img, 0.07f );
//cmn::image_pt img_colored_g16 = alg::image_paint_with_hint2( img_sobel, img, 0.04f );
cmn::image_pt img_colored_rgba = alg::seg_color(img_colored_g16);
adapter::image_save_to_png( img_colored_rgba, (dir_dst + name_base +"_sobel_colored.png").c_str() );
}
void sobel_test()
{
std::string dir_src = adapter::fs_resource_dir() + "pictures/faces_png/";
std::string dir_dst = adapter::fs_prefs_dir();
std::string dir_objects = dir_dst + "objects/";
adapter::fs_make_dir( dir_objects );
std::vector<adapter::fs_file_info_t> files;
//adapter::fs_dir_contents( &files, dir_src );
adapter::fs_file_info_t fi1;
fi1.name = "post-1178333-1266493347.png";
files.push_back(fi1);
for( size_t i = 0; i < files.size(); ++i )
{
adapter::fs_file_info_t const & fi = files[i];
cmn::image_pt img = adapter::image_create_from_png( (dir_src + fi.name).c_str() );
cmn::image_pt img_lab = cmn::image_lab_from_rgba( img );
std::string base_name = "objects/" + adapter::fs_name_ext( fi.name ).first;
//sobel_test_do_rest(img, base_name);
sobel_test_do_rest(img_lab, base_name+"_lab");
}
}
} |
; A248621: Floor of sums of the squares of the non-integer cube roots of n, as partitioned by the integer roots: floor[sum(j from n^3+1 to (n+1)^3-1, j^(2/3))].
; 0,16,120,456,1240,2760,5376,9520,15696,24480,36520,52536,73320,99736,132720,173280,222496,281520,351576,433960,530040,641256,769120,915216,1081200,1268800,1479816,1716120,1979656,2272440,2596560,2954176,3347520,3778896,4250680,4765320,5325336,5933320,6591936,7303920,8072080,8899296,9788520,10742776,11765160,12858840,14027056,15273120,16600416,18012400,19512600,21104616,22792120,24578856,26468640,28465360,30572976,32795520,35137096,37601880,40194120,42918136,45778320,48779136,51925120,55220880,58671096,62280520,66053976,69996360,74112640,78407856,82887120,87555616,92418600,97481400,102749416,108228120,113923056,119839840,125984160,132361776,138978520,145840296,152953080,160322920,167955936,175858320,184036336,192496320,201244680,210287896,219632520,229285176,239252560,249541440,260158656,271111120,282405816,294049800,306050200,318414216,331149120,344262256,357761040,371652960,385945576,400646520,415763496,431304280,447276720,463688736,480548320,497863536,515642520,533893480,552624696,571844520,591561376,611783760,632520240,653779456,675570120,697901016,720781000,744219000,768224016,792805120,817971456,843732240,870096760,897074376,924674520,952906696,981780480,1011305520,1041491536,1072348320,1103885736,1136113720,1169042280,1202681496,1237041520,1272132576,1307964960,1344549040,1381895256,1420014120,1458916216,1498612200,1539112800,1580428816,1622571120,1665550656,1709378440,1754065560,1799623176,1846062520,1893394896,1941631680,1990784320,2040864336,2091883320,2143852936,2196784920,2250691080,2305583296,2361473520,2418373776,2476296160,2535252840,2595256056,2656318120,2718451416,2781668400,2845981600,2911403616,2977947120,3045624856,3114449640,3184434360,3255591976,3327935520,3401478096,3476232880,3552213120,3629432136,3707903320,3787640136,3868656120,3950964880,4034580096,4119515520,4205784976,4293402360,4382381640,4472736856,4564482120,4657631616,4752199600,4848200400,4945648416,5044558120,5144944056,5246820840,5350203160,5455105776,5561543520,5669531296,5779084080,5890216920,6002944936,6117283320,6233247336,6350852320,6470113680,6591046896,6713667520,6837991176,6964033560,7091810440,7221337656,7352631120,7485706816,7620580800,7757269200,7895788216,8036154120,8178383256,8322492040,8468496960,8616414576,8766261520,8918054496,9071810280,9227545720,9385277736,9545023320,9706799536,9870623520,10036512480,10204483696,10374554520,10546742376,10721064760,10897539240,11076183456,11257015120,11440052016,11625312000
add $0,1
bin $0,2
mov $1,$0
mov $2,3
mul $2,$0
mul $0,$2
add $1,$0
div $1,2
mul $1,8
|
PokemonTower6F_Object:
db $1 ; border block
def_warps
warp 18, 9, 1, POKEMON_TOWER_5F
warp 9, 16, 0, POKEMON_TOWER_7F
def_signs
def_objects
object SPRITE_CHANNELER, 12, 10, STAY, RIGHT, 1, OPP_CHANNELER, 19
object SPRITE_CHANNELER, 9, 5, STAY, DOWN, 2, OPP_CHANNELER, 20
object SPRITE_CHANNELER, 16, 5, STAY, LEFT, 3, OPP_CHANNELER, 21
object SPRITE_POKE_BALL, 6, 8, STAY, NONE, 4, RARE_CANDY
object SPRITE_POKE_BALL, 14, 14, STAY, NONE, 5, X_ACCURACY
def_warps_to POKEMON_TOWER_6F
|
; Glidix kernel
;
; Copyright (c) 2014-2017, Madd Games.
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; * Redistributions of source code must retain the above copyright notice, this
; list of conditions and the following disclaimer.
;
; * Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
section .text
bits 64
extern sysNumber
extern sysTable
extern sysEpilog
extern sysInvalid
global _syscall_entry
_syscall_entry:
; the fourth argument, that is normally in RCX, is passed in R10 in this context
; as RCX contains the return address
swapgs ; GS.base = currentThread
mov [gs:0x208], rbx
mov [gs:0x210], rsp
mov [gs:0x218], rbp
mov [gs:0x220], r12
mov [gs:0x228], r13
mov [gs:0x230], r14
mov [gs:0x238], r15
mov [gs:0x240], rcx ; return RIP
mov [gs:0x248], dword 0 ; errno
mov rsp, [gs:512] ; get syscall stack pointer
push qword [gs:0x210] ; push user stack pointer
swapgs
; preserve other stuff
push rcx ; return RIP
push rbp ; RBP (to create a stack frame)
mov rbp, rsp
push r11 ; return RFLAGS
push r9 ; R9 needs to be preserved for resettable system calls
push r9 ; push again to align stack
; segments and enabling interrupts
mov cx, 0x10
mov ds, cx
mov es, cx
xor cx, cx
mov ss, cx
sti
; fourth argument back into RCX
mov rcx, r10
; make sure the system call number is within bounds
mov r10, sysNumber
mov r10, [r10]
cmp rax, r10
jae .invalid
; find the system call pointer (it is never NULL; unused slots map to
; sysInvalid now!)
mov r10, sysTable
call [r10+8*rax]
; we must always perform the epilog
mov rdi, rax
call sysEpilog
; restore
pop r9 ; was pushed for stack alignment
pop r9
pop r11
pop rbp
pop rcx
cli
pop rsp
mov dx, 0x23
mov ds, dx
mov es, dx
o64 sysret
.invalid:
call sysInvalid
section .data
syscall_name db 'syscall.asm', 0
|
tsx
lda STACK_BASE+{c1},x
sta {m1}
lda STACK_BASE+{c1}+1,x
sta {m1}+1
lda STACK_BASE+{c1}+2,x
sta {m1}+2
lda STACK_BASE+{c1}+3,x
sta {m1}+3 |
;print something without BIOS interrupts
[bits 32]
;0xb8000 + 2 * (row * 80 + col)
;2 bytes, first char, second attribute
WHITE_ON_BLACK equ 0x0f
BEGIN_32:
pusha
mov ebx, 0xb8000
mov al, [TEST_DATA]
mov ah, WHITE_ON_BLACK
mov [ebx], ax
popa
ret
TEST_DATA: db 'X'
|
UnknownDungeon1_h:
db CAVERN ; tileset
db UNKNOWN_DUNGEON_1_HEIGHT, UNKNOWN_DUNGEON_1_WIDTH ; dimensions (y, x)
dw UnknownDungeon1Blocks, UnknownDungeon1TextPointers, UnknownDungeon1Script ; blocks, texts, scripts
db $00 ; connections
dw UnknownDungeon1Object ; objects
|
; A213714: Inverse function for injection A005187.
; 0,1,0,2,3,0,0,4,5,0,6,7,0,0,0,8,9,0,10,11,0,0,12,13,0,14,15,0,0,0,0,16,17,0,18,19,0,0,20,21,0,22,23,0,0,0,24,25,0,26,27,0,0,28,29,0,30,31,0,0,0,0,0,32,33,0,34,35,0,0,36,37,0,38,39,0,0,0,40,41,0,42,43,0,0,44,45,0,46,47,0,0,0,0,48,49,0,50,51,0
seq $0,213724 ; Largest natural number x such that x=n+A000120(x), or zero if no such number exists.
div $0,2
|
;
; System Call for REX6000
;
; $Id: syscall6.asm,v 1.4 2002/04/17 21:30:25 dom Exp $
;
XLIB syscall6
.syscall6
ld ix,2
add ix,sp
ld l,(ix+0) ;par 6
ld h,(ix+1)
ld ($c00c),hl
ld l,(ix+2) ;par 5
ld h,(ix+3)
ld ($c00a),hl
ld l,(ix+4) ;par 4
ld h,(ix+5)
ld ($c008),hl
ld l,(ix+6) ;par 3
ld h,(ix+7)
ld ($c006),hl
ld l,(ix+8) ;par 2
ld h,(ix+9)
ld ($c004),hl
ld l,(ix+10) ;par 1
ld h,(ix+11)
ld ($c002),hl
ld l,(ix+12) ;call
ld h,(ix+13)
ld ($c000),hl
rst $10
ld hl,($c00e)
ret
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
// Load
lea addresses_WT+0xae47, %r15
nop
nop
sub %r13, %r13
vmovups (%r15), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %r8
nop
nop
nop
dec %r8
// REPMOV
lea addresses_WC+0x129f3, %rsi
lea addresses_normal+0x38a7, %rdi
nop
inc %r9
mov $9, %rcx
rep movsl
nop
nop
nop
nop
inc %r9
// Faulty Load
lea addresses_normal+0x13647, %rbx
sub %r15, %r15
mov (%rbx), %r8d
lea oracles, %r15
and $0xff, %r8
shlq $12, %r8
mov (%r15,%r8,1), %r8
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_WT', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal', 'congruent': 4, 'same': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
#include <iostream>
#include "CondFormats/Calibration/interface/BlobComplex.h"
void BlobComplexData::fill(unsigned int &serial)
{
a = ++serial;
b = ++serial;
for(unsigned int i = 0; i < 10; i++)
values.push_back(++serial);
}
void BlobComplexData::print() const
{
std::cout << " a = " << a << std::endl;
std::cout << " b = " << b << std::endl;
for(std::vector<unsigned int>::const_iterator iter = values.begin();
iter != values.end(); iter++)
std::cout << " value[" << (iter - values.begin()) << "] = "
<< *iter << std::endl;
}
bool BlobComplexData::operator == (const BlobComplexData &rhs) const
{
if (a != rhs.a) return false;
if (b != rhs.b) return false;
if (values.size() != rhs.values.size()) return false;
std::vector<unsigned int>::const_iterator iter1 = values.begin();
std::vector<unsigned int>::const_iterator iter2 = rhs.values.begin();
while(iter1 != values.end())
if (*iter1++ != *iter2++) return false;
return true;
}
void BlobComplexContent::fill(unsigned int &serial)
{
data1.first.fill(serial);
data1.second = ++serial;
data2.first.fill(serial);
data2.second = ++serial;
data3.first.fill(serial);
data3.second = ++serial;
}
static void printBlobComplexContentData(const BlobComplexContent::Data &data)
{
std::cout << " first = " << std::endl;
data.first.print();
std::cout << " second = " << data.second << std::endl;
}
void BlobComplexContent::print() const
{
std::cout << " data1 = " << std::endl;
printBlobComplexContentData(data1);
std::cout << " data2 = " << std::endl;
printBlobComplexContentData(data2);
std::cout << " data3 = " << std::endl;
printBlobComplexContentData(data3);
}
bool BlobComplexContent::operator == (const BlobComplexContent &rhs) const
{
if (data1.first != rhs.data1.first ||
data1.second != rhs.data1.second) return false;
if (data2.first != rhs.data2.first ||
data2.second != rhs.data2.second) return false;
if (data3.first != rhs.data3.first ||
data3.second != rhs.data3.second) return false;
return true;
}
void BlobComplexObjects::fill(unsigned int &serial)
{
a = ++serial;
b = ++serial;
for(unsigned int i = 0; i < 3; i++) {
content.push_back(BlobComplexContent());
content.back().fill(serial);
}
}
void BlobComplexObjects::print() const
{
std::cout << " a = " << a << std::endl;
std::cout << " b = " << b << std::endl;
for(std::vector<BlobComplexContent>::const_iterator iter = content.begin();
iter != content.end(); iter++) {
std::cout << " content[" << (iter - content.begin()) << "] =" << std::endl;
iter->print();
}
}
bool BlobComplexObjects::operator == (const BlobComplexObjects &rhs) const
{
if (a != rhs.a) return false;
if (b != rhs.b) return false;
if (content.size() != rhs.content.size()) return false;
std::vector<BlobComplexContent>::const_iterator iter1 = content.begin();
std::vector<BlobComplexContent>::const_iterator iter2 = rhs.content.begin();
while(iter1 != content.end())
if (*iter1++ != *iter2++) return false;
return true;
}
void BlobComplex::fill(unsigned int &serial)
{
for(unsigned int i = 0; i < 3; i++) {
objects.push_back(BlobComplexObjects());
objects.back().fill(serial);
}
}
void BlobComplex::print() const
{
for(std::vector<BlobComplexObjects>::const_iterator iter = objects.begin();
iter != objects.end(); iter++) {
std::cout << "objects[" << (iter - objects.begin()) << "] =" << std::endl;
iter->print();
}
}
bool BlobComplex::operator == (const BlobComplex &rhs) const
{
if (objects.size() != rhs.objects.size()) return false;
std::vector<BlobComplexObjects>::const_iterator iter1 = objects.begin();
std::vector<BlobComplexObjects>::const_iterator iter2 = rhs.objects.begin();
while(iter1 != objects.end())
if (*iter1++ != *iter2++) return false;
return true;
}
|
//
// OpenSSLTestSuite.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "NetSSLTestSuite.h"
#include "HTTPSClientTestSuite.h"
#include "TCPServerTestSuite.h"
#include "HTTPSServerTestSuite.h"
#include "WebSocketTestSuite.h"
CppUnit::Test* NetSSLTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("OpenSSLTestSuite");
pSuite->addTest(HTTPSClientTestSuite::suite());
pSuite->addTest(TCPServerTestSuite::suite());
pSuite->addTest(HTTPSServerTestSuite::suite());
pSuite->addTest(WebSocketTestSuite::suite());
return pSuite;
}
|
.model small
.stack 100h
.186
.386
.data
arr1 dw 20 dup(?) ; массив чисел
result db ' $' ; формат вывода
nl dw 0Ah, 0Dh, '$' ; новая строка
.code
;==============================================================================
; Процедура преобразования числа в форматированную строку
;==============================================================================
toasc proc
; Сохраняем значения регистров
pusha
; Выделяем цифры из числа и помещаем в стек
xor cx, cx
mov bx, 10
xor dx, dx
_lbl2: div bx
push dx
xor dx, dx
inc cx
cmp ax, 00h
jne _lbl2
; Преобразуем цифры числа в ascii код
; и помещаем в результат
mov bx, cx
mov si, 5
sub si, cx
_lbl3: pop dx
push ax
add dl, 48
cmp dl, 39h
jle _lbl4
add dl, 07
_lbl4: mov result[si], dl
inc si
pop ax
loop _lbl3
; Заполняем пробелами незначащие символы
mov cx, 5
sub cx, bx
mov si, 0
_null: mov result[si], ' '
inc si
loop _null
; Восстанавливаем значения регистров
popa
ret
toasc endp
;==============================================================================
; НАЧАЛО ПРОГРАММЫ
;==============================================================================
start: mov ax, @data
mov ds, ax
; Формирование массива
mov cx, 10
mov bx, 3
mov si, 0
_fill_arr1: mov arr1[si], bx
xor ax, ax
mov ax, arr1[si]
mul ax
mov arr1[si+20], ax
add bl, 3
add si, 2
loop _fill_arr1
mov ah, 09h
mov dx, offset nl
int 21h
mov cx, 20
mov si, 0
_loop1: mov ax, arr1[si]
call toasc
mov ah, 09h
cmp cx, 10
je _nl
mov dx, offset result
jmp _print
_nl: mov dx, offset nl
int 21h
mov dx, offset result
_print: int 21h
add si, 2
loop _loop1
mov ah, 09h
mov dx, offset nl
int 21h
mov ax, 4c00h
int 21h
end start
|
/*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_X3_ANY_CHAR_APRIL_16_2006_1051AM)
#define BOOST_SPIRIT_X3_ANY_CHAR_APRIL_16_2006_1051AM
#include <boost/type_traits/extent.hpp>
#include <boost/spirit/home/x3/char/literal_char.hpp>
#include <boost/spirit/home/x3/char/char_set.hpp>
namespace boost { namespace spirit { namespace x3
{
template <typename Encoding>
struct any_char : char_parser<any_char<Encoding>>
{
typedef typename Encoding::char_type char_type;
typedef Encoding encoding;
typedef char_type attribute_type;
static bool const has_attribute = true;
template <typename Char, typename Context>
bool test(Char ch_, Context const&) const
{
return ((sizeof(Char) <= sizeof(char_type)) || encoding::ischar(ch_));
}
template <typename Char>
literal_char<Encoding> operator()(Char ch) const
{
return { ch };
}
template <typename Char>
literal_char<Encoding> operator()(const Char (&ch)[2]) const
{
return { ch[0] };
}
template <typename Char, std::size_t N>
char_set<Encoding> operator()(const Char (&ch)[N]) const
{
return { ch };
}
template <typename Char>
char_range<Encoding> operator()(Char from, Char to) const
{
return { from, to };
}
template <typename Char>
char_range<Encoding> operator()(Char (&from)[2], Char (&to)[2]) const
{
return { static_cast<char_type>(from[0]), static_cast<char_type>(to[0]) };
}
template <typename Char>
char_set<Encoding> operator()(std::basic_string<Char> const& s) const
{
return { s };
}
};
}}}
#endif
|
; A164304: a(n) = 4*a(n-1) - 2*a(n-2) for n > 1; a(0) = 3, a(1) = 14.
; 3,14,50,172,588,2008,6856,23408,79920,272864,931616,3180736,10859712,37077376,126590080,432205568,1475642112,5038157312,17201345024,58729065472,200513571840,684596156416,2337357481984,7980237615104,27246235496448,93024466755584,317605396029440,1084372650606592,3702279810367488
mov $1,3
mov $2,4
lpb $0
sub $0,1
add $1,$2
add $2,$1
mul $1,2
lpe
|
;
; Copyright (c) 2020 Phillip Stevens
;
; This Source Code Form is subject to the terms of the Mozilla Public
; License, v. 2.0. If a copy of the MPL was not distributed with this
; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;
; feilipu, 2020 May
;
;-------------------------------------------------------------------------
; asm_f16_fabs - z80 half floating point absolute value
;-------------------------------------------------------------------------
;
; unpacked format: exponent in d, sign in e[7], mantissa in hl
; return normalized result also in unpacked format
;
; return half float in hl
;
;-------------------------------------------------------------------------
SECTION code_fp_math16
PUBLIC asm_f24_fabs
PUBLIC asm_f16_fabs
.asm_f24_fabs
res 7,e
ret
.asm_f16_fabs
res 7,h
ret
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <tuple>
// template <class... Types> class tuple;
// template<class... TTypes, class... UTypes>
// bool
// operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u);
#include <tuple>
#include <string>
#include <cassert>
int main()
{
{
typedef std::tuple<> T1;
typedef std::tuple<> T2;
const T1 t1;
const T2 t2;
assert(t1 == t2);
assert(!(t1 != t2));
}
{
typedef std::tuple<int> T1;
typedef std::tuple<double> T2;
const T1 t1(1);
const T2 t2(1.1);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<int> T1;
typedef std::tuple<double> T2;
const T1 t1(1);
const T2 t2(1);
assert(t1 == t2);
assert(!(t1 != t2));
}
{
typedef std::tuple<int, double> T1;
typedef std::tuple<double, char> T2;
const T1 t1(1, 2);
const T2 t2(1, char(2));
assert(t1 == t2);
assert(!(t1 != t2));
}
{
typedef std::tuple<int, double> T1;
typedef std::tuple<double, char> T2;
const T1 t1(1, 2);
const T2 t2(1, char(3));
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<int, double> T1;
typedef std::tuple<double, char> T2;
const T1 t1(1, 2);
const T2 t2(1.1, char(2));
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<int, double> T1;
typedef std::tuple<double, char> T2;
const T1 t1(1, 2);
const T2 t2(1.1, char(3));
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1, 2, 3);
assert(t1 == t2);
assert(!(t1 != t2));
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1.1, 2, 3);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1, 3, 3);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1, 2, 4);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1, 3, 2);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1.1, 2, 2);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1.1, 3, 3);
assert(!(t1 == t2));
assert(t1 != t2);
}
{
typedef std::tuple<char, int, double> T1;
typedef std::tuple<double, char, int> T2;
const T1 t1(1, 2, 3);
const T2 t2(1.1, 3, 2);
assert(!(t1 == t2));
assert(t1 != t2);
}
}
|
;*****************************************************************
;* This stationery serves as the framework for a *
;* user application (single file, absolute assembly application) *
;* For a more comprehensive program that *
;* demonstrates the more advanced functionality of this *
;* processor, please see the demonstration applications *
;* located in the examples subdirectory of the *
;* Freescale CodeWarrior for the HC12 Program directory *
;*****************************************************************
; export symbols
ABSENTRY Entry ; for absolute assembly: mark this as application entry point
INCLUDE 'mc9s12dp512.inc'
ROMStart EQU $8000 ; absolute address to place my code/constant data
; code section
ORG ROMStart
Entry:
SUM EQU $4210 ;RAM loc 210H for SUM
LDAA #$25 ;A = 25H
ADDA #$34 ;add 34H to A (A=59H)
ADDA #$11 ;add 11H to A (A=6AH)
ADDA #18 ;A = A + 12H = 7CH
ADDA #%00011100 ;A = A + 1CH = 98H
STAA SUM ;save the SUM in loc 210H
HERE JMP HERE ;infinity loop
END
;**************************************************************
;* Interrupt Vectors *
;**************************************************************
ORG $FFFE
DC.W Entry ; Reset Vector
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r14
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0xa3d2, %rsi
lea addresses_UC_ht+0x19ada, %rdi
xor %r14, %r14
mov $3, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp %r13, %r13
lea addresses_D_ht+0x1d44e, %r10
nop
sub $51101, %rcx
mov $0x6162636465666768, %r13
movq %r13, %xmm6
movups %xmm6, (%r10)
nop
nop
nop
nop
sub %r14, %r14
lea addresses_A_ht+0x1472, %rcx
nop
nop
nop
xor $61848, %rdi
mov $0x6162636465666768, %r14
movq %r14, %xmm3
vmovups %ymm3, (%rcx)
nop
nop
sub %r14, %r14
lea addresses_D_ht+0x85d2, %r14
nop
nop
nop
and $32211, %rsi
mov (%r14), %ecx
nop
sub $5343, %rsi
lea addresses_WC_ht+0x1e572, %rsi
clflush (%rsi)
and $22533, %r13
and $0xffffffffffffffc0, %rsi
movntdqa (%rsi), %xmm7
vpextrq $0, %xmm7, %rdi
nop
nop
nop
add $45757, %rdi
lea addresses_UC_ht+0x7ad2, %rsi
lea addresses_A_ht+0x53d0, %rdi
nop
nop
nop
nop
sub %r13, %r13
mov $33, %rcx
rep movsw
nop
nop
nop
nop
nop
inc %rdi
pop %rsi
pop %rdi
pop %rcx
pop %r14
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r14
push %r9
push %rcx
push %rsi
// Store
lea addresses_RW+0x900e, %r12
clflush (%r12)
cmp $16794, %r11
mov $0x5152535455565758, %r14
movq %r14, %xmm1
vmovups %ymm1, (%r12)
nop
nop
nop
add %r14, %r14
// Store
lea addresses_normal+0x10b82, %rsi
nop
nop
nop
nop
inc %r10
movw $0x5152, (%rsi)
nop
nop
nop
nop
nop
add $38144, %rsi
// Store
lea addresses_A+0x1ca8b, %r10
nop
nop
xor %r12, %r12
mov $0x5152535455565758, %r11
movq %r11, (%r10)
nop
nop
nop
nop
nop
dec %rsi
// Faulty Load
lea addresses_normal+0x85d2, %r14
nop
nop
nop
cmp %rcx, %rcx
movb (%r14), %r10b
lea oracles, %rcx
and $0xff, %r10
shlq $12, %r10
mov (%rcx,%r10,1), %r10
pop %rsi
pop %rcx
pop %r9
pop %r14
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_RW', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal', 'congruent': 4}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 8, 'type': 'addresses_A', 'congruent': 0}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 5}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D_ht', 'congruent': 7}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC_ht', 'congruent': 3}}
{'dst': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 8, 'type': 'addresses_UC_ht'}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
;
; VGA ROM font, modified to ZX code page
;
; Extracted from: https://www.min.at/prinz/o/software/pixelfont/
;
SECTION rodata_font
SECTION rodata_font_8x8
PUBLIC _zx7_font_8x8_vga_rom
PUBLIC _zx7_font_8x8_vga_rom_end
_zx7_font_8x8_vga_rom:
BINARY "font_8x8_vga_rom.bin.zx7"
_zx7_font_8x8_vga_rom_end:
|
copyright zengfr site:http://github.com/zengfr/romhack
001590 lea ($20,A0), A0
00249A move.l -(A6), (A4)+ [123p+ 6C, enemy+6C]
00249C rts [123p+ 6E, 123p+ 70, enemy+6E, enemy+70]
0024B6 move.l -(A6), (A4)+ [123p+ 6C, enemy+6C]
0024B8 rts [123p+ 6E, 123p+ 70, enemy+6E, enemy+70]
0024E8 move.l -(A6), (A4)+ [123p+ 6C, enemy+6C]
0024EA tst.b ($30,A0) [123p+ 6E, 123p+ 70, enemy+6E, enemy+70]
00250A move.l -(A6), (A4)+ [123p+ 6C, enemy+6C]
00250C tst.b ($30,A0) [123p+ 6E, 123p+ 70, enemy+6E, enemy+70]
0086C0 beq $86a4 [123p+ 6E, enemy+6E]
0089DA beq $89ae [enemy+6E]
00906A beq $8e58 [enemy+6E]
0094EE beq $9430 [enemy+6E]
00976A beq $9430 [enemy+6E]
009934 beq $998c [enemy+6E]
009BD8 beq $9430 [enemy+6E]
012282 move.l (A2)+, (A3)+ [enemy+68, enemy+6A]
012284 move.l (A2)+, (A3)+ [enemy+6C, enemy+6E]
01A75E dbra D4, $1a75c
copyright zengfr site:http://github.com/zengfr/romhack
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0xf279, %rsi
lea addresses_A_ht+0x289a, %rdi
sub %r14, %r14
mov $114, %rcx
rep movsb
nop
nop
nop
nop
and $50616, %r12
lea addresses_WC_ht+0x15df9, %rsi
lea addresses_WC_ht+0x1372b, %rdi
xor %r9, %r9
mov $48, %rcx
rep movsl
nop
nop
nop
nop
cmp %r12, %r12
lea addresses_A_ht+0x16279, %rdi
nop
nop
add $25128, %rdx
mov $0x6162636465666768, %rcx
movq %rcx, (%rdi)
and %rdx, %rdx
lea addresses_WC_ht+0x7479, %rsi
lea addresses_normal_ht+0x1e679, %rdi
nop
xor %rax, %rax
mov $124, %rcx
rep movsw
nop
nop
nop
add %r12, %r12
lea addresses_UC_ht+0x28bf, %rsi
lea addresses_WC_ht+0xcd1b, %rdi
nop
nop
nop
nop
inc %rdx
mov $43, %rcx
rep movsb
nop
nop
nop
nop
and %rcx, %rcx
lea addresses_WC_ht+0x1592d, %rsi
lea addresses_WT_ht+0xf015, %rdi
nop
nop
add %r14, %r14
mov $11, %rcx
rep movsl
cmp %rdx, %rdx
lea addresses_UC_ht+0x3f79, %rsi
lea addresses_D_ht+0xc415, %rdi
nop
nop
sub %r14, %r14
mov $71, %rcx
rep movsb
nop
nop
nop
sub %rax, %rax
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r9
push %rdi
push %rdx
// Faulty Load
lea addresses_normal+0x7a79, %r11
nop
nop
nop
nop
nop
add %r14, %r14
mov (%r11), %edi
lea oracles, %rdx
and $0xff, %rdi
shlq $12, %rdi
mov (%rdx,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %r9
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}}
{'src': {'same': False, 'congruent': 7, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8}}
{'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}}
{'src': {'same': True, 'congruent': 1, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}}
{'src': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}}
{'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_D_ht'}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dali/operators/expressions/arithmetic_meta.h"
#include "dali/operators/expressions/expression_impl_cpu.h"
#include "dali/operators/expressions/expression_factory_instances/expression_impl_factory.h"
namespace dali {
IMPLEMENT_OP_FACTORY_CPU_BINARY(geq);
} // namespace dali
|
; A142285: Primes congruent to 36 mod 43.
; Submitted by Simon Strandgaard
; 79,251,337,509,853,1283,1627,2143,2659,2917,3089,3347,3433,3691,3863,4637,4723,5153,5669,5927,6271,6529,6701,6959,7561,9109,9281,9539,9883,10141,10313,10399,10657,11087,11173,11689,12119,12377,12721,12893,12979,13151,14011,14699,14957,15473,15559,15731,15817,16333,16763,17021,17107,17623,17881,18311,18397,18913,19429,19687,20117,20719,21149,21407,21493,21751,22697,22783,23041,23557,24847,25621,25793,26309,27427,27943,28201,28631,29147,29663,29921,30781,31039,31469,31727,32587,33533,33619,33791
mov $1,39
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,2
mov $3,$1
mul $3,2
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,43
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
sub $0,83
mul $0,2
add $0,81
|
<%
from pwnlib.shellcraft.aarch64.linux import syscall
%>
<%page args="file, buf"/>
<%docstring>
Invokes the syscall lstat. See 'man 2 lstat' for more information.
Arguments:
file(char): file
buf(stat): buf
</%docstring>
${syscall('SYS_lstat', file, buf)}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1717b, %r13
nop
nop
xor %rbx, %rbx
movb (%r13), %al
nop
nop
nop
add $22156, %rbx
lea addresses_A_ht+0x1aa53, %rsi
lea addresses_normal_ht+0x1abab, %rdi
clflush (%rsi)
nop
xor $38482, %r9
mov $57, %rcx
rep movsl
nop
nop
nop
and $29734, %rax
lea addresses_D_ht+0x27bd, %rsi
lea addresses_WT_ht+0x1d2bb, %rdi
clflush (%rsi)
nop
nop
nop
xor $43902, %r15
mov $70, %rcx
rep movsq
nop
nop
nop
cmp %r13, %r13
lea addresses_WT_ht+0x7307, %rbx
nop
nop
nop
inc %r15
movb (%rbx), %r13b
nop
nop
nop
nop
nop
add $33465, %r13
lea addresses_WC_ht+0x1edfb, %r15
nop
nop
nop
nop
add %rsi, %rsi
mov $0x6162636465666768, %rbx
movq %rbx, (%r15)
nop
xor $49725, %rbx
lea addresses_A_ht+0x1db7b, %r15
nop
nop
nop
cmp $12035, %rdi
movw $0x6162, (%r15)
nop
nop
nop
cmp %rdi, %rdi
lea addresses_WC_ht+0x11bbd, %rsi
lea addresses_A_ht+0x677b, %rdi
clflush (%rsi)
nop
nop
nop
nop
add $30366, %r15
mov $50, %rcx
rep movsw
add $31226, %r13
lea addresses_WC_ht+0x2b7b, %rax
nop
nop
nop
nop
xor $55097, %r15
and $0xffffffffffffffc0, %rax
movntdqa (%rax), %xmm7
vpextrq $0, %xmm7, %r9
nop
nop
nop
add $29629, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_normal+0x184fb, %rbx
nop
nop
nop
add $15975, %rcx
mov $0x5152535455565758, %rdx
movq %rdx, %xmm0
movups %xmm0, (%rbx)
nop
nop
nop
nop
nop
cmp %rdx, %rdx
// Store
lea addresses_WC+0x1b21b, %rsi
nop
nop
nop
nop
add %rax, %rax
movw $0x5152, (%rsi)
nop
nop
nop
nop
nop
cmp $29797, %rsi
// Store
lea addresses_PSE+0x4b7b, %rsi
nop
nop
nop
nop
nop
cmp $48233, %rbx
movl $0x51525354, (%rsi)
nop
nop
nop
nop
sub %r9, %r9
// Store
lea addresses_US+0xfc1b, %rdi
nop
nop
nop
sub $51148, %rbx
mov $0x5152535455565758, %rsi
movq %rsi, %xmm4
vmovups %ymm4, (%rdi)
nop
nop
nop
nop
nop
and $42589, %rbx
// Faulty Load
lea addresses_normal+0x1fb7b, %rsi
nop
dec %rcx
mov (%rsi), %rdx
lea oracles, %rcx
and $0xff, %rdx
shlq $12, %rdx
mov (%rcx,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': True, 'same': False, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_normal', 'AVXalign': False, 'size': 16}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WC', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_US', 'AVXalign': False, 'size': 32}}
[Faulty Load]
{'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'same': True, 'congruent': 8, 'type': 'addresses_WT_ht', 'AVXalign': True, 'size': 1}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_normal_ht'}}
{'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2}}
{'src': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_A_ht'}}
{'src': {'NT': True, 'same': False, 'congruent': 10, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
; A107970: a(n) = (n+1)*(n+2)^3*(n+3)*(2n+3)*(2n+5)/360.
; Submitted by Jamie Morken(s4)
; 1,21,168,825,3003,8918,22848,52326,109725,214291,394680,692055,1163799,1887900,2968064,4539612,6776217,9897537,14177800,19955397,27643539,37742034,50850240,67681250,89077365,116026911,149682456,191380483
mul $0,2
add $0,6
mov $1,$0
bin $0,5
sub $1,2
pow $1,2
mov $2,$1
mul $2,$0
mov $0,$2
div $0,96
|
#include "Precompiled.h"
const Matrix3x3 Matrix3x3::Identity(Vector3(1.f, 0.f, 0.f), Vector3(0.f, 1.f, 0.f), Vector3(0.f, 0.f, 1.f));
std::vector<std::string> Matrix3x3::ToStrings() const
{
std::vector<std::string> result;
Matrix3x3 trMatrix = this->Tranpose();
for (BYTE i = 0; i < Rank; ++i)
{
char row[64];
std::snprintf(row, sizeof(row), "| %.3f , %.3f , %.3f |", trMatrix.Cols[i].X, trMatrix.Cols[i].Y, trMatrix.Cols[i].Z);
result.emplace_back(row);
}
return result;
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Titanium developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "consensus/tx_verify.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "validation.h"
#include "net.h"
#include "policy/feerate.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/transaction.h"
#include "script/standard.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "masternode/masternode-payments.h"
#include "masternode/masternode-sync.h"
#include "validationinterface.h"
#include "evo/specialtx.h"
#include "evo/cbtx.h"
#include "evo/simplifiedmns.h"
#include "evo/deterministicmns.h"
#include "llmq/quorums_blockprocessor.h"
#include "llmq/quorums_chainlocks.h"
#include <algorithm>
#include <queue>
#include <utility>
//////////////////////////////////////////////////////////////////////////////
//
// TtmMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest fee rate of a transaction combined with all
// its ancestors.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
return nNewTime - nOldTime;
}
BlockAssembler::Options::Options() {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
}
BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
{
blockMinFeeRate = options.blockMinFeeRate;
// Limit size to between 1K and MaxBlockSize()-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MaxBlockSize(fDIP0001ActiveAtTip) - 1000), (unsigned int)options.nBlockMaxSize));
}
static BlockAssembler::Options DefaultOptions(const CChainParams& params)
{
// Block resource limits
BlockAssembler::Options options;
options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
if (gArgs.IsArgSet("-blockmaxsize")) {
options.nBlockMaxSize = gArgs.GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
}
if (gArgs.IsArgSet("-blockmintxfee")) {
CAmount n = 0;
ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
return options;
}
BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockSize = 1000;
nBlockSigOps = 100;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
bool fDIP0003Active_context = nHeight >= chainparams.GetConsensus().DIP0003Height;
bool fDIP0008Active_context = VersionBitsState(chainActive.Tip(), chainparams.GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus(), chainparams.BIP9CheckMasternodesUpgraded());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
if (fDIP0003Active_context) {
for (auto& p : chainparams.GetConsensus().llmqs) {
CTransactionRef qcTx;
if (llmq::quorumBlockProcessor->GetMinableCommitmentTx(p.first, nHeight, qcTx)) {
pblock->vtx.emplace_back(qcTx);
pblocktemplate->vTxFees.emplace_back(0);
pblocktemplate->vTxSigOps.emplace_back(0);
nBlockSize += qcTx->GetTotalSize();
++nBlockTx;
}
}
}
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated);
int64_t nTime1 = GetTimeMicros();
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
// NOTE: unlike in bitcoin, we need to pass PREVIOUS block height here
CAmount blockReward = nFees + GetBlockSubsidy(pindexPrev->nBits, pindexPrev->nHeight, Params().GetConsensus());
// Compute regular coinbase transaction.
coinbaseTx.vout[0].nValue = blockReward;
if (!fDIP0003Active_context) {
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
} else {
coinbaseTx.vin[0].scriptSig = CScript() << OP_RETURN;
coinbaseTx.nVersion = 3;
coinbaseTx.nType = TRANSACTION_COINBASE;
CCbTx cbTx;
if (fDIP0008Active_context) {
cbTx.nVersion = 2;
} else {
cbTx.nVersion = 1;
}
cbTx.nHeight = nHeight;
CValidationState state;
if (!CalcCbTxMerkleRootMNList(*pblock, pindexPrev, cbTx.merkleRootMNList, state)) {
throw std::runtime_error(strprintf("%s: CalcCbTxMerkleRootMNList failed: %s", __func__, FormatStateMessage(state)));
}
if (fDIP0008Active_context) {
if (!CalcCbTxMerkleRootQuorums(*pblock, pindexPrev, cbTx.merkleRootQuorums, state)) {
throw std::runtime_error(strprintf("%s: CalcCbTxMerkleRootQuorums failed: %s", __func__, FormatStateMessage(state)));
}
}
SetTxPayload(coinbaseTx, cbTx);
}
// Update coinbase transaction with additional info about masternode and governance payments,
// get some info back to pass to getblocktemplate
FillBlockPayments(coinbaseTx, nHeight, blockReward, pblocktemplate->voutMasternodePayments, pblocktemplate->voutSuperblockPayments);
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vTxFees[0] = -nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
pblock->nNonce = 0;
pblocktemplate->nPrevBits = pindexPrev->nBits;
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*pblock->vtx[0]);
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
int64_t nTime2 = GetTimeMicros();
LogPrint(BCLog::BENCHMARK, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
return std::move(pblocktemplate);
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, unsigned int packageSigOps)
{
if (nBlockSize + packageSize >= nBlockMaxSize)
return false;
if (nBlockSigOps + packageSigOps >= MaxBlockSigOps(fDIP0001ActiveAtTip))
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - safe TXs in regard to ChainLocks
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
for (const CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!llmq::chainLocksHandler->IsTxSafeForMining(it->GetTx().GetHash())) {
return false;
}
}
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOps.push_back(iter->GetSigOpCount());
nBlockSize += iter->GetTxSize();
++nBlockTx;
nBlockSigOps += iter->GetSigOpCount();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
for (const CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCountWithAncestors -= it->GetSigOpCount();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
return nDescendantsUpdated;
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
// Limit the number of attempts to add transactions to the block when it is
// close to full; this is just a simple heuristic to finish quickly if the
// mempool has a lot of entries.
const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
int64_t nConsecutiveFailed = 0;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
unsigned int packageSigOps = iter->GetSigOpCountWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOps = modit->nSigOpCountWithAncestors;
}
if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOps)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
++nConsecutiveFailed;
if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockSize > nBlockMaxSize - 1000) {
// Give up if we're close to full and haven't succeeded in a while
break;
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final and safe
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// This transaction will make it in; reset the failed counter.
nConsecutiveFailed = 0;
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
++nPackagesSelected;
// Update transactions that depend on each of these
nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
|
; void p_forward_list_alt_push_back(p_forward_list_alt_t *list, void *item)
SECTION code_clib
SECTION code_adt_p_forward_list_alt
PUBLIC p_forward_list_alt_push_back_callee
EXTERN asm_p_forward_list_alt_push_back
p_forward_list_alt_push_back_callee:
pop af
pop de
pop bc
push af
jp asm_p_forward_list_alt_push_back
|
/*
**
** Copyright (C) 2018 Softbank Robotics Europe
*/
#pragma once
#include <thread>
#include <random>
#include <chrono>
#include <qi/anyobject.hpp>
struct RemotePerformanceService
{
using nanosecs = std::int64_t;
void setObject(qi::AnyObject obj)
{
objects.push_back(obj);
}
void setObjectList(std::vector<qi::AnyObject> objs)
{
objects = std::move(objs);
}
// Returns nanoseconds taken for each call the object's function.
std::vector<nanosecs> measureCallDuration(const std::string& functionToCall)
{
return measureOperationDuration([&](qi::AnyObject& o){
auto ft = o.async<void>(functionToCall);
handleCallResult(ft, __func__);
});
}
// Returns nanoseconds taken to call the object's function.
std::vector<nanosecs> measureCallDurationArgument(const std::string& functionToCall, qi::AnyValue arg)
{
return measureOperationDuration([&](qi::AnyObject& o) {
auto ft = o.async<void>(functionToCall, arg);
handleCallResult(ft, __func__);
});
}
// Returns nanoseconds taken to get an object's property value.
std::vector<nanosecs> measureGetPropertyDuration(const std::string& propertyName)
{
return measureOperationDuration([&](qi::AnyObject& o) {
auto ft = o.property<qi::AnyValue>(propertyName).async();
handleCallResult(ft, __func__);
});
}
// Returns nanoseconds taken to set an object's property value.
std::vector<nanosecs> measureSetPropertyDuration(const std::string& propertyName)
{
return measureOperationDuration([&](qi::AnyObject& o) {
auto connectFt = o.connect(propertyName, [propertyName](int value){
qiLogInfo("RemotePerformanceService") << "Property '" << propertyName << "' set to '" << value << "'";
}).async();
auto disconnectOnScopeExit = ka::scoped([&]{
auto linkId = connectFt.value();
o.disconnect(linkId);
});
handleCallResult(connectFt, std::string{__func__} + ".Property::connect()");
auto ft = o.setProperty(propertyName, qi::AnyValue::from(99)).async();
handleCallResult(ft, __func__);
});
}
void clear()
{
objects.clear();
}
void setMeasureCount(int count)
{
measureCount = count;
}
private:
std::vector<qi::AnyObject> objects;
int measureCount = 4; // arbitrary default
int totalCallCount = 0;
std::default_random_engine randomEngine{ std::random_device{}() };
qi::AnyObject randomObject()
{
if(objects.empty())
return {};
std::uniform_int_distribution<size_t> distribution(0, objects.size() -1);
const auto randomIdx = distribution(randomEngine);
return objects[randomIdx];
}
// Returns nanoseconds taken to do the operation
// Requires: Procedure< _ (qi::AnyObject)> Operation
template<class Operation>
std::vector<nanosecs> measureOperationDuration(Operation&& operation)
{
using namespace std::chrono;
if (objects.empty())
throw std::runtime_error("No stored object to call");
std::vector<nanosecs> results;
for (int i = 0; i < measureCount; ++i)
{
qi::AnyObject o = randomObject();
++totalCallCount;
qiLogInfo("RemotePerformanceService") << "Test Operation START: call num "
<< totalCallCount << "/measure " << i
<< " on " << " UID{" << o.uid() << "}";
const auto startTime = high_resolution_clock::now();
operation(o);
const auto endTime = high_resolution_clock::now();
const auto recordedDuration = endTime - startTime;
const auto recordedNanosecs = static_cast<nanosecs>(nanoseconds{recordedDuration}.count());
qiLogInfo("RemotePerformanceService") << "Test Operation STOP: call num "
<< totalCallCount << "/measure " << i
<< " on " << " UID{" << o.uid() << "}: "
<< duration_cast<milliseconds>(recordedDuration).count() << " ms ("
<< recordedNanosecs << " ns)"
;
results.emplace_back(recordedNanosecs);
}
return results;
}
template<class T>
void handleCallResult(const qi::Future<T>& ft, std::string source)
{
const auto timeout = qi::Seconds{ 20 };
auto state = ft.wait(timeout);
switch (state)
{
case qi::FutureState_FinishedWithError:
{
qiLogWarning("RemotePerformanceService") << source << ": Measured call returned an error: " << ft.error();
return;
}
case qi::FutureState_Canceled:
{
qiLogWarning("RemotePerformanceService") << source << ": Measured call was canceled";
return;
}
case qi::FutureState_Running:
{
auto newState = ft.wait(timeout);
if (newState == qi::FutureState_Running)
{
std::stringstream stream;
stream << source << ": Measured call did not finish after timeout ("
<< boost::chrono::duration_cast<qi::MilliSeconds>(timeout).count() << " ms)";
qiLogError("RemotePerformanceService") << stream.str();
throw std::runtime_error(stream.str());
}
return handleCallResult(ft, source);
}
case qi::FutureState_FinishedWithValue:
{
qiLogInfo("RemotePerformanceService") << source << ": Measured call finished successfully.";
return;
}
default:
std::stringstream stream;
stream << source << ": Unhandled future state";
qiLogError("RemotePerformanceService") << stream.str();
throw std::runtime_error(stream.str());
}
}
};
QI_REGISTER_OBJECT(RemotePerformanceService, setObject, setObjectList,
measureCallDuration, measureGetPropertyDuration, measureSetPropertyDuration, measureCallDurationArgument,
clear, setMeasureCount)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.