问:
Program is losing an increment and two ``printf``s
In the method below, we set volatile int success = 0 and then enter a

while(!success) loop.

The loop increments tries, then enters a transaction, from within which we make a call to java sun.misc.Unsafe.putLong and we keep looping until the transaction succeeds.

so long as the debug flag __TRX_DEBUG__ is set, it will print the number of tries before returning.

Since that number is consistently zero, I have since added some "Hello" printfs.

The output of the program is

Hello0?!

putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with 0 tries

And I quite simply don't understand why.

```<code>/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V
*/
jmethodID midPutLong = NULL;
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ(
    JNIEnv *env,
    jclass _obsolete,
    jobject unsafe,
    jclass unsafe_class,
    jobject base,
    jlong off,
    jlong value
){
    if(midPutLong == NULL){
        midPutLong = (*env)->GetMethodID(env,unsafe_class,"putLong","(Ljava/lang/Object;JJ)V");
        #ifdef __TRX_ASSERT__
        assert(midPutLong != NULL);
        #endif
    }

    volatile int tries = 0;
    volatile int success = 0;
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
        printf("Hello0?!\n");
        __asm__ __volatile__ (
            "incl %0\n"
            "xbegin 1f" /*1f: local label 1, look forward to find first*/
                :"+rm"(tries)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putInt(base,off,value);
        printf("Hello1?!\n");
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);
        printf("Hello2?!\n");

        __asm__ __volatile__ (
            "xend\n\t"
            "incl %0\n" /*increment success ==> break out of loop*/
            "jmp 2f\n" /*jump to end of loop*/
            "1:\n" /*local label 1 (jumped to when transaction is aborted)*/
            "2:" /*local label 2 (jumped to after a successfully completed transaction)*/
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with %d tries\n",tries);
    #endif
}
</code>```

The interesting thing is that further up the file, I have a different method,

```<code>/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Ljava/lang/Object;Ljava/lang/String;J)V
*/
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J(JNIEnv* env, jclass _obsolete, jobject target, jstring fieldname, jlong value){
    jclass targetClass = (*env)->GetObjectClass(env,target);

    const char *str_fname = (*env)->GetStringUTFChars(env,fieldname,NULL);
    jfieldID fidFLD = (*env)->GetFieldID(env, targetClass, str_fname, "J");

    volatile int tries = 0;
    volatile int success = 0;
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
        __asm__ __volatile__ (
            "incl %0\n"
            "xbegin 1f" /*1f: local label 1, look forward to find first*/
                :"+rm"(tries)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);

        __asm__ __volatile__ (
            "xend\n\t"
            "incl %0\n" /*increment success ==> break out of loop*/
            "jmp 2f\n" /*jump to end of loop*/
            "1:\n" /*local label 1 (jumped to when transaction is aborted)*/
            "2:" /*local label 2 (jumped to after a successfully completed transaction)*/
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with %d tries\n",tries);
    #endif
}
</code>```

which does essentially the same (except it's using a different method to change the data), but which consistently outputs

putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with 1 tries

Each method gets called exactly once per run (from Java):

```<code>    //requires base class acquisition and field index lookup
    Transactionally.putLong(base$x, "x",3L);
    assert(data.x == 3);

    //requires callback to java which then invokes intrinsics
    Transactionally.putLong(Transactionally.unsafe, Transactionally.unsafe_class, base$x, off$x, 4L);
    assert(data.x == 4);
</code>```

and that the program is running without throwing an assertion error is just adding to my confusion.

Because if assert(data.x == 4) does no throw an error, then

```<code>(*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);
</code>```

in the first C method must have succeeded.
Yet it succeeded without executing the increment to tries before it started the transaction, nor did it execute the two printfs I inserted around it.

UPDATE
Adding the printfs to the second method will also not print them. So I guess being in a transaction suppresses IO and the behaviour is different only for the tries counter.

Why is this happening and how do I stop it?

UPDATE

Removed the hello printfs and wasn't sure how to create the asm code directly, so I instead disassembled the resulting .so file.

Zooming in on the parts that matter,

this is from the working method:

```<code>    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
867:    eb 41                   jmp    8aa <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xda>
        __asm__ __volatile__ (
869:    8b 45 e4                mov    -0x1c(%rbp),%eax
86c:    8b 55 e0                mov    -0x20(%rbp),%edx
86f:    ff c2                   inc    %edx
871:    c7 f8 30 00 00 00       xbeginq 8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
877:    89 55 e0                mov    %edx,-0x20(%rbp)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);

        [...]

8aa:    8b 45 e4                mov    -0x1c(%rbp),%eax
8ad:    85 c0                   test   %eax,%eax
8af:    74 b8                   je     869 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0x99>
</code>```

And this is from the faulty method:

```<code>   while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
968:    eb 5b                   jmp    9c5 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xfb>
        __asm__ __volatile__ (
96a:    8b 45 fc                mov    -0x4(%rbp),%eax
96d:    8b 55 f8                mov    -0x8(%rbp),%edx
970:    ff c2                   inc    %edx
972:    c7 f8 4a 00 00 00       xbeginq 9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
978:    89 55 f8                mov    %edx,-0x8(%rbp)
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putLong(base,off,value);
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);

        [...]

9c5:    8b 45 fc                mov    -0x4(%rbp),%eax
9c8:    85 c0                   test   %eax,%eax
9ca:    74 9e                   je     96a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xa0>
</code>```

I still don't see any relevant difference that would explain the behaviour.

Full Objdump

```<code>lib/libRTM_transact.so:     file format elf64-x86-64

Disassembly of section .init:

0000000000000670 <_init>:
670:    48 83 ec 08             sub    $0x8,%rsp
674:    48 8b 05 5d 09 20 00    mov    0x20095d(%rip),%rax        # 200fd8 <__gmon_start__>
67b:    48 85 c0                test   %rax,%rax
67e:    74 02                   je     682 <_init+0x12>
680:    ff d0                   callq  *%rax
682:    48 83 c4 08             add    $0x8,%rsp
686:    c3                      retq

Disassembly of section .plt:

0000000000000690 <.plt>:
690:    ff 35 72 09 20 00       pushq  0x200972(%rip)        # 201008 <_GLOBAL_OFFSET_TABLE_+0x8>
696:    ff 25 74 09 20 00       jmpq   *0x200974(%rip)        # 201010 <_GLOBAL_OFFSET_TABLE_+0x10>
69c:    0f 1f 40 00             nopl   0x0(%rax)

00000000000006a0 <printf@plt>:
6a0:    ff 25 72 09 20 00       jmpq   *0x200972(%rip)        # 201018 <printf@GLIBC_2.2.5>
6a6:    68 00 00 00 00          pushq  $0x0
6ab:    e9 e0 ff ff ff          jmpq   690 <.plt>

00000000000006b0 <__assert_fail@plt>:
6b0:    ff 25 6a 09 20 00       jmpq   *0x20096a(%rip)        # 201020 <__assert_fail@GLIBC_2.2.5>
6b6:    68 01 00 00 00          pushq  $0x1
6bb:    e9 d0 ff ff ff          jmpq   690 <.plt>

Disassembly of section .plt.got:

00000000000006c0 <.plt.got>:
6c0:    ff 25 32 09 20 00       jmpq   *0x200932(%rip)        # 200ff8 <__cxa_finalize@GLIBC_2.2.5>
6c6:    66 90                   xchg   %ax,%ax

Disassembly of section .text:

00000000000006d0 <deregister_tm_clones>:
6d0:    48 8d 3d 59 09 20 00    lea    0x200959(%rip),%rdi        # 201030 <_edata>
6d7:    48 8d 05 59 09 20 00    lea    0x200959(%rip),%rax        # 201037 <_edata+0x7>
6de:    55                      push   %rbp
6df:    48 29 f8                sub    %rdi,%rax
6e2:    48 89 e5                mov    %rsp,%rbp
6e5:    48 83 f8 0e             cmp    $0xe,%rax
6e9:    76 15                   jbe    700 <deregister_tm_clones+0x30>
6eb:    48 8b 05 de 08 20 00    mov    0x2008de(%rip),%rax        # 200fd0 <_ITM_deregisterTMCloneTable>
6f2:    48 85 c0                test   %rax,%rax
6f5:    74 09                   je     700 <deregister_tm_clones+0x30>
6f7:    5d                      pop    %rbp
6f8:    ff e0                   jmpq   *%rax
6fa:    66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)
700:    5d                      pop    %rbp
701:    c3                      retq
702:    0f 1f 40 00             nopl   0x0(%rax)
706:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
70d:    00 00 00

0000000000000710 <register_tm_clones>:
710:    48 8d 3d 19 09 20 00    lea    0x200919(%rip),%rdi        # 201030 <_edata>
717:    48 8d 35 12 09 20 00    lea    0x200912(%rip),%rsi        # 201030 <_edata>
71e:    55                      push   %rbp
71f:    48 29 fe                sub    %rdi,%rsi
722:    48 89 e5                mov    %rsp,%rbp
725:    48 c1 fe 03             sar    $0x3,%rsi
729:    48 89 f0                mov    %rsi,%rax
72c:    48 c1 e8 3f             shr    $0x3f,%rax
730:    48 01 c6                add    %rax,%rsi
733:    48 d1 fe                sar    %rsi
736:    74 18                   je     750 <register_tm_clones+0x40>
738:    48 8b 05 b1 08 20 00    mov    0x2008b1(%rip),%rax        # 200ff0 <_ITM_registerTMCloneTable>
73f:    48 85 c0                test   %rax,%rax
742:    74 0c                   je     750 <register_tm_clones+0x40>
744:    5d                      pop    %rbp
745:    ff e0                   jmpq   *%rax
747:    66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
74e:    00 00
750:    5d                      pop    %rbp
751:    c3                      retq
752:    0f 1f 40 00             nopl   0x0(%rax)
756:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
75d:    00 00 00

0000000000000760 <__do_global_dtors_aux>:
760:    80 3d c9 08 20 00 00    cmpb   $0x0,0x2008c9(%rip)        # 201030 <_edata>
767:    75 27                   jne    790 <__do_global_dtors_aux+0x30>
769:    48 83 3d 87 08 20 00    cmpq   $0x0,0x200887(%rip)        # 200ff8 <__cxa_finalize@GLIBC_2.2.5>
770:    00
771:    55                      push   %rbp
772:    48 89 e5                mov    %rsp,%rbp
775:    74 0c                   je     783 <__do_global_dtors_aux+0x23>
777:    48 8b 3d aa 08 20 00    mov    0x2008aa(%rip),%rdi        # 201028 <__dso_handle>
77e:    e8 3d ff ff ff          callq  6c0 <.plt.got>
783:    e8 48 ff ff ff          callq  6d0 <deregister_tm_clones>
788:    5d                      pop    %rbp
789:    c6 05 a0 08 20 00 01    movb   $0x1,0x2008a0(%rip)        # 201030 <_edata>
790:    f3 c3                   repz retq
792:    0f 1f 40 00             nopl   0x0(%rax)
796:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
79d:    00 00 00

00000000000007a0 <frame_dummy>:
7a0:    48 8d 3d 61 06 20 00    lea    0x200661(%rip),%rdi        # 200e08 <__JCR_END__>
7a7:    48 83 3f 00             cmpq   $0x0,(%rdi)
7ab:    75 0b                   jne    7b8 <frame_dummy+0x18>
7ad:    e9 5e ff ff ff          jmpq   710 <register_tm_clones>
7b2:    66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)
7b8:    48 8b 05 29 08 20 00    mov    0x200829(%rip),%rax        # 200fe8 <_Jv_RegisterClasses>
7bf:    48 85 c0                test   %rax,%rax
7c2:    74 e9                   je     7ad <frame_dummy+0xd>
7c4:    55                      push   %rbp
7c5:    48 89 e5                mov    %rsp,%rbp
7c8:    ff d0                   callq  *%rax
7ca:    5d                      pop    %rbp
7cb:    e9 40 ff ff ff          jmpq   710 <register_tm_clones>

00000000000007d0 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J>:
/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Ljava/lang/Object;Ljava/lang/String;J)V
*/
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J(JNIEnv* env, jclass _obsolete, jobject target, jstring fieldname, jlong value){
7d0:    55                      push   %rbp
7d1:    48 89 e5                mov    %rsp,%rbp
7d4:    48 83 ec 50             sub    $0x50,%rsp
7d8:    48 89 7d d8             mov    %rdi,-0x28(%rbp)
7dc:    48 89 75 d0             mov    %rsi,-0x30(%rbp)
7e0:    48 89 55 c8             mov    %rdx,-0x38(%rbp)
7e4:    48 89 4d c0             mov    %rcx,-0x40(%rbp)
7e8:    4c 89 45 b8             mov    %r8,-0x48(%rbp)
    jclass targetClass = (*env)->GetObjectClass(env,target);
7ec:    48 8b 45 d8             mov    -0x28(%rbp),%rax
7f0:    48 8b 00                mov    (%rax),%rax
7f3:    48 8b 80 f8 00 00 00    mov    0xf8(%rax),%rax
7fa:    48 8b 4d c8             mov    -0x38(%rbp),%rcx
7fe:    48 8b 55 d8             mov    -0x28(%rbp),%rdx
802:    48 89 ce                mov    %rcx,%rsi
805:    48 89 d7                mov    %rdx,%rdi
808:    ff d0                   callq  *%rax
80a:    48 89 45 e8             mov    %rax,-0x18(%rbp)

    const char *str_fname = (*env)->GetStringUTFChars(env,fieldname,NULL);
80e:    48 8b 45 d8             mov    -0x28(%rbp),%rax
812:    48 8b 00                mov    (%rax),%rax
815:    48 8b 80 48 05 00 00    mov    0x548(%rax),%rax
81c:    48 8b 75 c0             mov    -0x40(%rbp),%rsi
820:    48 8b 4d d8             mov    -0x28(%rbp),%rcx
824:    ba 00 00 00 00          mov    $0x0,%edx
829:    48 89 cf                mov    %rcx,%rdi
82c:    ff d0                   callq  *%rax
82e:    48 89 45 f0             mov    %rax,-0x10(%rbp)
    jfieldID fidFLD = (*env)->GetFieldID(env, targetClass, str_fname, "J");
832:    48 8b 45 d8             mov    -0x28(%rbp),%rax
836:    48 8b 00                mov    (%rax),%rax
839:    48 8b 80 f0 02 00 00    mov    0x2f0(%rax),%rax
840:    48 8b 55 f0             mov    -0x10(%rbp),%rdx
844:    48 8b 75 e8             mov    -0x18(%rbp),%rsi
848:    48 8b 7d d8             mov    -0x28(%rbp),%rdi
84c:    48 8d 0d ad 01 00 00    lea    0x1ad(%rip),%rcx        # a00 <_fini+0x18>
853:    ff d0                   callq  *%rax
855:    48 89 45 f8             mov    %rax,-0x8(%rbp)

    volatile int tries = 0;
859:    c7 45 e0 00 00 00 00    movl   $0x0,-0x20(%rbp)
    volatile int success = 0;
860:    c7 45 e4 00 00 00 00    movl   $0x0,-0x1c(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
867:    eb 41                   jmp    8aa <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xda>
        __asm__ __volatile__ (
869:    8b 45 e4                mov    -0x1c(%rbp),%eax
86c:    8b 55 e0                mov    -0x20(%rbp),%edx
86f:    ff c2                   inc    %edx
871:    c7 f8 30 00 00 00       xbeginq 8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
877:    89 55 e0                mov    %edx,-0x20(%rbp)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);
87a:    48 8b 45 d8             mov    -0x28(%rbp),%rax
87e:    48 8b 00                mov    (%rax),%rax
881:    48 8b 80 70 03 00 00    mov    0x370(%rax),%rax
888:    48 8b 4d b8             mov    -0x48(%rbp),%rcx
88c:    48 8b 55 f8             mov    -0x8(%rbp),%rdx
890:    48 8b 75 e8             mov    -0x18(%rbp),%rsi
894:    48 8b 7d d8             mov    -0x28(%rbp),%rdi
898:    ff d0                   callq  *%rax

        __asm__ __volatile__ (
89a:    8b 45 e0                mov    -0x20(%rbp),%eax
89d:    8b 55 e4                mov    -0x1c(%rbp),%edx
8a0:    0f 01 d5                xend
8a3:    ff c2                   inc    %edx
8a5:    eb 00                   jmp    8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
8a7:    89 55 e4                mov    %edx,-0x1c(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
8aa:    8b 45 e4                mov    -0x1c(%rbp),%eax
8ad:    85 c0                   test   %eax,%eax
8af:    74 b8                   je     869 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0x99>
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with %d tries\n",tries);
8b1:    8b 45 e0                mov    -0x20(%rbp),%eax
8b4:    89 c6                   mov    %eax,%esi
8b6:    48 8d 3d 4b 01 00 00    lea    0x14b(%rip),%rdi        # a08 <_fini+0x20>
8bd:    b8 00 00 00 00          mov    $0x0,%eax
8c2:    e8 d9 fd ff ff          callq  6a0 <printf@plt>
    #endif
}
8c7:    90                      nop
8c8:    c9                      leaveq
8c9:    c3                      retq

00000000000008ca <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ>:
    jobject unsafe,
    jclass unsafe_class,
    jobject base,
    jlong off,
    jlong value
){
8ca:    55                      push   %rbp
8cb:    48 89 e5                mov    %rsp,%rbp
8ce:    48 83 ec 40             sub    $0x40,%rsp
8d2:    48 89 7d e8             mov    %rdi,-0x18(%rbp)
8d6:    48 89 75 e0             mov    %rsi,-0x20(%rbp)
8da:    48 89 55 d8             mov    %rdx,-0x28(%rbp)
8de:    48 89 4d d0             mov    %rcx,-0x30(%rbp)
8e2:    4c 89 45 c8             mov    %r8,-0x38(%rbp)
8e6:    4c 89 4d c0             mov    %r9,-0x40(%rbp)
    if(midPutLong == NULL){
8ea:    48 8b 05 ef 06 20 00    mov    0x2006ef(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
8f1:    48 8b 00                mov    (%rax),%rax
8f4:    48 85 c0                test   %rax,%rax
8f7:    75 61                   jne    95a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0x90>
        midPutLong = (*env)->GetMethodID(env,unsafe_class,"putLong","(Ljava/lang/Object;JJ)V");
8f9:    48 8b 45 e8             mov    -0x18(%rbp),%rax
8fd:    48 8b 00                mov    (%rax),%rax
900:    48 8b 80 08 01 00 00    mov    0x108(%rax),%rax
907:    48 8b 75 d0             mov    -0x30(%rbp),%rsi
90b:    48 8b 7d e8             mov    -0x18(%rbp),%rdi
90f:    48 8d 0d 33 01 00 00    lea    0x133(%rip),%rcx        # a49 <_fini+0x61>
916:    48 8d 15 44 01 00 00    lea    0x144(%rip),%rdx        # a61 <_fini+0x79>
91d:    ff d0                   callq  *%rax
91f:    48 89 c2                mov    %rax,%rdx
922:    48 8b 05 b7 06 20 00    mov    0x2006b7(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
929:    48 89 10                mov    %rdx,(%rax)
        #ifdef __TRX_ASSERT__
        assert(midPutLong != NULL);
92c:    48 8b 05 ad 06 20 00    mov    0x2006ad(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
933:    48 8b 00                mov    (%rax),%rax
936:    48 85 c0                test   %rax,%rax
939:    75 1f                   jne    95a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0x90>
93b:    48 8d 0d be 01 00 00    lea    0x1be(%rip),%rcx        # b00 <__PRETTY_FUNCTION__.3410>
942:    ba 43 00 00 00          mov    $0x43,%edx
947:    48 8d 35 1b 01 00 00    lea    0x11b(%rip),%rsi        # a69 <_fini+0x81>
94e:    48 8d 3d 2d 01 00 00    lea    0x12d(%rip),%rdi        # a82 <_fini+0x9a>
955:    e8 56 fd ff ff          callq  6b0 <__assert_fail@plt>
        #endif
    }

    volatile int tries = 0;
95a:    c7 45 f8 00 00 00 00    movl   $0x0,-0x8(%rbp)
    volatile int success = 0;
961:    c7 45 fc 00 00 00 00    movl   $0x0,-0x4(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
968:    eb 5b                   jmp    9c5 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xfb>
        __asm__ __volatile__ (
96a:    8b 45 fc                mov    -0x4(%rbp),%eax
96d:    8b 55 f8                mov    -0x8(%rbp),%edx
970:    ff c2                   inc    %edx
972:    c7 f8 4a 00 00 00       xbeginq 9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
978:    89 55 f8                mov    %edx,-0x8(%rbp)
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putInt(base,off,value);
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);
97b:    48 8b 45 e8             mov    -0x18(%rbp),%rax
97f:    48 8b 00                mov    (%rax),%rax
982:    4c 8b 90 e8 01 00 00    mov    0x1e8(%rax),%r10
989:    48 8b 05 50 06 20 00    mov    0x200650(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
990:    48 8b 10                mov    (%rax),%rdx
993:    48 8b 7d c0             mov    -0x40(%rbp),%rdi
997:    48 8b 4d c8             mov    -0x38(%rbp),%rcx
99b:    48 8b 75 d8             mov    -0x28(%rbp),%rsi
99f:    48 8b 45 e8             mov    -0x18(%rbp),%rax
9a3:    4c 8b 4d 10             mov    0x10(%rbp),%r9
9a7:    49 89 f8                mov    %rdi,%r8
9aa:    48 89 c7                mov    %rax,%rdi
9ad:    b8 00 00 00 00          mov    $0x0,%eax
9b2:    41 ff d2                callq  *%r10

        __asm__ __volatile__ (
9b5:    8b 45 f8                mov    -0x8(%rbp),%eax
9b8:    8b 55 fc                mov    -0x4(%rbp),%edx
9bb:    0f 01 d5                xend
9be:    ff c2                   inc    %edx
9c0:    eb 00                   jmp    9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
9c2:    89 55 fc                mov    %edx,-0x4(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
9c5:    8b 45 fc                mov    -0x4(%rbp),%eax
9c8:    85 c0                   test   %eax,%eax
9ca:    74 9e                   je     96a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xa0>
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with %d tries\n",tries);
9cc:    8b 45 f8                mov    -0x8(%rbp),%eax
9cf:    89 c6                   mov    %eax,%esi
9d1:    48 8d 3d c0 00 00 00    lea    0xc0(%rip),%rdi        # a98 <_fini+0xb0>
9d8:    b8 00 00 00 00          mov    $0x0,%eax
9dd:    e8 be fc ff ff          callq  6a0 <printf@plt>
    #endif
}
9e2:    90                      nop
9e3:    c9                      leaveq
9e4:    c3                      retq

Disassembly of section .fini:

00000000000009e8 <_fini>:
9e8:    48 83 ec 08             sub    $0x8,%rsp
9ec:    48 83 c4 08             add    $0x8,%rsp
9f0:    c3                      retq
</code>```

答:
No I/O can be performed can be performed in a transaction so the printf calls will likely abort the transaction. Then control passes to the 1: label, this is undefined behaviour as jumps between asm statements are not allowed, and eax is modified without being listed in the clobber or output lists.

The target of xbegin needs to be in the same asm statement or be a C label referenced using the asm goto extension. Or better use the intrinsics and avoid inline assembly.

Body:
In the method below, we set volatile int success = 0 and then enter a

while(!success) loop.

The loop increments tries, then enters a transaction, from within which we make a call to java sun.misc.Unsafe.putLong and we keep looping until the transaction succeeds.

so long as the debug flag __TRX_DEBUG__ is set, it will print the number of tries before returning.

Since that number is consistently zero, I have since added some "Hello" printfs.

The output of the program is

Hello0?!

putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with 0 tries

And I quite simply don't understand why.

/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V
*/
jmethodID midPutLong = NULL;
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ(
    JNIEnv *env,
    jclass _obsolete,
    jobject unsafe,
    jclass unsafe_class,
    jobject base,
    jlong off,
    jlong value
){
    if(midPutLong == NULL){
        midPutLong = (*env)->GetMethodID(env,unsafe_class,"putLong","(Ljava/lang/Object;JJ)V");
        #ifdef __TRX_ASSERT__
        assert(midPutLong != NULL);
        #endif
    }

    volatile int tries = 0;
    volatile int success = 0;
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
        printf("Hello0?!\n");
        __asm__ __volatile__ (
            "incl %0\n"
            "xbegin 1f" /*1f: local label 1, look forward to find first*/
                :"+rm"(tries)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putInt(base,off,value);
        printf("Hello1?!\n");
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);
        printf("Hello2?!\n");

        __asm__ __volatile__ (
            "xend\n\t"
            "incl %0\n" /*increment success ==> break out of loop*/
            "jmp 2f\n" /*jump to end of loop*/
            "1:\n" /*local label 1 (jumped to when transaction is aborted)*/
            "2:" /*local label 2 (jumped to after a successfully completed transaction)*/
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with %d tries\n",tries);
    #endif
}

The interesting thing is that further up the file, I have a different method,

/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Ljava/lang/Object;Ljava/lang/String;J)V
*/
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J(JNIEnv* env, jclass _obsolete, jobject target, jstring fieldname, jlong value){
    jclass targetClass = (*env)->GetObjectClass(env,target);

    const char *str_fname = (*env)->GetStringUTFChars(env,fieldname,NULL);
    jfieldID fidFLD = (*env)->GetFieldID(env, targetClass, str_fname, "J");

    volatile int tries = 0;
    volatile int success = 0;
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
        __asm__ __volatile__ (
            "incl %0\n"
            "xbegin 1f" /*1f: local label 1, look forward to find first*/
                :"+rm"(tries)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);

        __asm__ __volatile__ (
            "xend\n\t"
            "incl %0\n" /*increment success ==> break out of loop*/
            "jmp 2f\n" /*jump to end of loop*/
            "1:\n" /*local label 1 (jumped to when transaction is aborted)*/
            "2:" /*local label 2 (jumped to after a successfully completed transaction)*/
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with %d tries\n",tries);
    #endif
}

which does essentially the same (except it's using a different method to change the data), but which consistently outputs

putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with 1 tries

Each method gets called exactly once per run (from Java):

    //requires base class acquisition and field index lookup
    Transactionally.putLong(base$x, "x",3L);
    assert(data.x == 3);

    //requires callback to java which then invokes intrinsics
    Transactionally.putLong(Transactionally.unsafe, Transactionally.unsafe_class, base$x, off$x, 4L);
    assert(data.x == 4);

and that the program is running without throwing an assertion error is just adding to my confusion.

Because if assert(data.x == 4) does no throw an error, then

(*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);

in the first C method must have succeeded.
Yet it succeeded without executing the increment to tries before it started the transaction, nor did it execute the two printfs I inserted around it.

UPDATE
Adding the printfs to the second method will also not print them. So I guess being in a transaction suppresses IO and the behaviour is different only for the tries counter.

Why is this happening and how do I stop it?

UPDATE

Removed the hello printfs and wasn't sure how to create the asm code directly, so I instead disassembled the resulting .so file.

Zooming in on the parts that matter,

this is from the working method:

    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
867:    eb 41                   jmp    8aa <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xda>
        __asm__ __volatile__ (
869:    8b 45 e4                mov    -0x1c(%rbp),%eax
86c:    8b 55 e0                mov    -0x20(%rbp),%edx
86f:    ff c2                   inc    %edx
871:    c7 f8 30 00 00 00       xbeginq 8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
877:    89 55 e0                mov    %edx,-0x20(%rbp)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);

        [...]

8aa:    8b 45 e4                mov    -0x1c(%rbp),%eax
8ad:    85 c0                   test   %eax,%eax
8af:    74 b8                   je     869 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0x99>

And this is from the faulty method:

   while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
968:    eb 5b                   jmp    9c5 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xfb>
        __asm__ __volatile__ (
96a:    8b 45 fc                mov    -0x4(%rbp),%eax
96d:    8b 55 f8                mov    -0x8(%rbp),%edx
970:    ff c2                   inc    %edx
972:    c7 f8 4a 00 00 00       xbeginq 9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
978:    89 55 f8                mov    %edx,-0x8(%rbp)
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putLong(base,off,value);
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);

        [...]

9c5:    8b 45 fc                mov    -0x4(%rbp),%eax
9c8:    85 c0                   test   %eax,%eax
9ca:    74 9e                   je     96a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xa0>

I still don't see any relevant difference that would explain the behaviour.

Full Objdump

lib/libRTM_transact.so:     file format elf64-x86-64

Disassembly of section .init:

0000000000000670 <_init>:
670:    48 83 ec 08             sub    $0x8,%rsp
674:    48 8b 05 5d 09 20 00    mov    0x20095d(%rip),%rax        # 200fd8 <__gmon_start__>
67b:    48 85 c0                test   %rax,%rax
67e:    74 02                   je     682 <_init+0x12>
680:    ff d0                   callq  *%rax
682:    48 83 c4 08             add    $0x8,%rsp
686:    c3                      retq

Disassembly of section .plt:

0000000000000690 <.plt>:
690:    ff 35 72 09 20 00       pushq  0x200972(%rip)        # 201008 <_GLOBAL_OFFSET_TABLE_+0x8>
696:    ff 25 74 09 20 00       jmpq   *0x200974(%rip)        # 201010 <_GLOBAL_OFFSET_TABLE_+0x10>
69c:    0f 1f 40 00             nopl   0x0(%rax)

00000000000006a0 <printf@plt>:
6a0:    ff 25 72 09 20 00       jmpq   *0x200972(%rip)        # 201018 <printf@GLIBC_2.2.5>
6a6:    68 00 00 00 00          pushq  $0x0
6ab:    e9 e0 ff ff ff          jmpq   690 <.plt>

00000000000006b0 <__assert_fail@plt>:
6b0:    ff 25 6a 09 20 00       jmpq   *0x20096a(%rip)        # 201020 <__assert_fail@GLIBC_2.2.5>
6b6:    68 01 00 00 00          pushq  $0x1
6bb:    e9 d0 ff ff ff          jmpq   690 <.plt>

Disassembly of section .plt.got:

00000000000006c0 <.plt.got>:
6c0:    ff 25 32 09 20 00       jmpq   *0x200932(%rip)        # 200ff8 <__cxa_finalize@GLIBC_2.2.5>
6c6:    66 90                   xchg   %ax,%ax

Disassembly of section .text:

00000000000006d0 <deregister_tm_clones>:
6d0:    48 8d 3d 59 09 20 00    lea    0x200959(%rip),%rdi        # 201030 <_edata>
6d7:    48 8d 05 59 09 20 00    lea    0x200959(%rip),%rax        # 201037 <_edata+0x7>
6de:    55                      push   %rbp
6df:    48 29 f8                sub    %rdi,%rax
6e2:    48 89 e5                mov    %rsp,%rbp
6e5:    48 83 f8 0e             cmp    $0xe,%rax
6e9:    76 15                   jbe    700 <deregister_tm_clones+0x30>
6eb:    48 8b 05 de 08 20 00    mov    0x2008de(%rip),%rax        # 200fd0 <_ITM_deregisterTMCloneTable>
6f2:    48 85 c0                test   %rax,%rax
6f5:    74 09                   je     700 <deregister_tm_clones+0x30>
6f7:    5d                      pop    %rbp
6f8:    ff e0                   jmpq   *%rax
6fa:    66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)
700:    5d                      pop    %rbp
701:    c3                      retq
702:    0f 1f 40 00             nopl   0x0(%rax)
706:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
70d:    00 00 00

0000000000000710 <register_tm_clones>:
710:    48 8d 3d 19 09 20 00    lea    0x200919(%rip),%rdi        # 201030 <_edata>
717:    48 8d 35 12 09 20 00    lea    0x200912(%rip),%rsi        # 201030 <_edata>
71e:    55                      push   %rbp
71f:    48 29 fe                sub    %rdi,%rsi
722:    48 89 e5                mov    %rsp,%rbp
725:    48 c1 fe 03             sar    $0x3,%rsi
729:    48 89 f0                mov    %rsi,%rax
72c:    48 c1 e8 3f             shr    $0x3f,%rax
730:    48 01 c6                add    %rax,%rsi
733:    48 d1 fe                sar    %rsi
736:    74 18                   je     750 <register_tm_clones+0x40>
738:    48 8b 05 b1 08 20 00    mov    0x2008b1(%rip),%rax        # 200ff0 <_ITM_registerTMCloneTable>
73f:    48 85 c0                test   %rax,%rax
742:    74 0c                   je     750 <register_tm_clones+0x40>
744:    5d                      pop    %rbp
745:    ff e0                   jmpq   *%rax
747:    66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)
74e:    00 00
750:    5d                      pop    %rbp
751:    c3                      retq
752:    0f 1f 40 00             nopl   0x0(%rax)
756:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
75d:    00 00 00

0000000000000760 <__do_global_dtors_aux>:
760:    80 3d c9 08 20 00 00    cmpb   $0x0,0x2008c9(%rip)        # 201030 <_edata>
767:    75 27                   jne    790 <__do_global_dtors_aux+0x30>
769:    48 83 3d 87 08 20 00    cmpq   $0x0,0x200887(%rip)        # 200ff8 <__cxa_finalize@GLIBC_2.2.5>
770:    00
771:    55                      push   %rbp
772:    48 89 e5                mov    %rsp,%rbp
775:    74 0c                   je     783 <__do_global_dtors_aux+0x23>
777:    48 8b 3d aa 08 20 00    mov    0x2008aa(%rip),%rdi        # 201028 <__dso_handle>
77e:    e8 3d ff ff ff          callq  6c0 <.plt.got>
783:    e8 48 ff ff ff          callq  6d0 <deregister_tm_clones>
788:    5d                      pop    %rbp
789:    c6 05 a0 08 20 00 01    movb   $0x1,0x2008a0(%rip)        # 201030 <_edata>
790:    f3 c3                   repz retq
792:    0f 1f 40 00             nopl   0x0(%rax)
796:    66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
79d:    00 00 00

00000000000007a0 <frame_dummy>:
7a0:    48 8d 3d 61 06 20 00    lea    0x200661(%rip),%rdi        # 200e08 <__JCR_END__>
7a7:    48 83 3f 00             cmpq   $0x0,(%rdi)
7ab:    75 0b                   jne    7b8 <frame_dummy+0x18>
7ad:    e9 5e ff ff ff          jmpq   710 <register_tm_clones>
7b2:    66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)
7b8:    48 8b 05 29 08 20 00    mov    0x200829(%rip),%rax        # 200fe8 <_Jv_RegisterClasses>
7bf:    48 85 c0                test   %rax,%rax
7c2:    74 e9                   je     7ad <frame_dummy+0xd>
7c4:    55                      push   %rbp
7c5:    48 89 e5                mov    %rsp,%rbp
7c8:    ff d0                   callq  *%rax
7ca:    5d                      pop    %rbp
7cb:    e9 40 ff ff ff          jmpq   710 <register_tm_clones>

00000000000007d0 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J>:
/*
* Class:     jnirtm_Transactionally
* Method:    putLong
* Signature: (Ljava/lang/Object;Ljava/lang/String;J)V
*/
JNIEXPORT void JNICALL Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J(JNIEnv* env, jclass _obsolete, jobject target, jstring fieldname, jlong value){
7d0:    55                      push   %rbp
7d1:    48 89 e5                mov    %rsp,%rbp
7d4:    48 83 ec 50             sub    $0x50,%rsp
7d8:    48 89 7d d8             mov    %rdi,-0x28(%rbp)
7dc:    48 89 75 d0             mov    %rsi,-0x30(%rbp)
7e0:    48 89 55 c8             mov    %rdx,-0x38(%rbp)
7e4:    48 89 4d c0             mov    %rcx,-0x40(%rbp)
7e8:    4c 89 45 b8             mov    %r8,-0x48(%rbp)
    jclass targetClass = (*env)->GetObjectClass(env,target);
7ec:    48 8b 45 d8             mov    -0x28(%rbp),%rax
7f0:    48 8b 00                mov    (%rax),%rax
7f3:    48 8b 80 f8 00 00 00    mov    0xf8(%rax),%rax
7fa:    48 8b 4d c8             mov    -0x38(%rbp),%rcx
7fe:    48 8b 55 d8             mov    -0x28(%rbp),%rdx
802:    48 89 ce                mov    %rcx,%rsi
805:    48 89 d7                mov    %rdx,%rdi
808:    ff d0                   callq  *%rax
80a:    48 89 45 e8             mov    %rax,-0x18(%rbp)

    const char *str_fname = (*env)->GetStringUTFChars(env,fieldname,NULL);
80e:    48 8b 45 d8             mov    -0x28(%rbp),%rax
812:    48 8b 00                mov    (%rax),%rax
815:    48 8b 80 48 05 00 00    mov    0x548(%rax),%rax
81c:    48 8b 75 c0             mov    -0x40(%rbp),%rsi
820:    48 8b 4d d8             mov    -0x28(%rbp),%rcx
824:    ba 00 00 00 00          mov    $0x0,%edx
829:    48 89 cf                mov    %rcx,%rdi
82c:    ff d0                   callq  *%rax
82e:    48 89 45 f0             mov    %rax,-0x10(%rbp)
    jfieldID fidFLD = (*env)->GetFieldID(env, targetClass, str_fname, "J");
832:    48 8b 45 d8             mov    -0x28(%rbp),%rax
836:    48 8b 00                mov    (%rax),%rax
839:    48 8b 80 f0 02 00 00    mov    0x2f0(%rax),%rax
840:    48 8b 55 f0             mov    -0x10(%rbp),%rdx
844:    48 8b 75 e8             mov    -0x18(%rbp),%rsi
848:    48 8b 7d d8             mov    -0x28(%rbp),%rdi
84c:    48 8d 0d ad 01 00 00    lea    0x1ad(%rip),%rcx        # a00 <_fini+0x18>
853:    ff d0                   callq  *%rax
855:    48 89 45 f8             mov    %rax,-0x8(%rbp)

    volatile int tries = 0;
859:    c7 45 e0 00 00 00 00    movl   $0x0,-0x20(%rbp)
    volatile int success = 0;
860:    c7 45 e4 00 00 00 00    movl   $0x0,-0x1c(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
867:    eb 41                   jmp    8aa <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xda>
        __asm__ __volatile__ (
869:    8b 45 e4                mov    -0x1c(%rbp),%eax
86c:    8b 55 e0                mov    -0x20(%rbp),%edx
86f:    ff c2                   inc    %edx
871:    c7 f8 30 00 00 00       xbeginq 8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
877:    89 55 e0                mov    %edx,-0x20(%rbp)
                :"rm"(success)/*artificial dependency to prevent re-ordering*/
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        (*env)->SetLongField(env,targetClass,fidFLD,value);
87a:    48 8b 45 d8             mov    -0x28(%rbp),%rax
87e:    48 8b 00                mov    (%rax),%rax
881:    48 8b 80 70 03 00 00    mov    0x370(%rax),%rax
888:    48 8b 4d b8             mov    -0x48(%rbp),%rcx
88c:    48 8b 55 f8             mov    -0x8(%rbp),%rdx
890:    48 8b 75 e8             mov    -0x18(%rbp),%rsi
894:    48 8b 7d d8             mov    -0x28(%rbp),%rdi
898:    ff d0                   callq  *%rax

        __asm__ __volatile__ (
89a:    8b 45 e0                mov    -0x20(%rbp),%eax
89d:    8b 55 e4                mov    -0x1c(%rbp),%edx
8a0:    0f 01 d5                xend
8a3:    ff c2                   inc    %edx
8a5:    eb 00                   jmp    8a7 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0xd7>
8a7:    89 55 e4                mov    %edx,-0x1c(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
8aa:    8b 45 e4                mov    -0x1c(%rbp),%eax
8ad:    85 c0                   test   %eax,%eax
8af:    74 b8                   je     869 <Java_jnirtm_Transactionally_putLong__Ljava_lang_Object_2Ljava_lang_String_2J+0x99>
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Ljava/lang/Object;Ljava/lang/String;J)V with %d tries\n",tries);
8b1:    8b 45 e0                mov    -0x20(%rbp),%eax
8b4:    89 c6                   mov    %eax,%esi
8b6:    48 8d 3d 4b 01 00 00    lea    0x14b(%rip),%rdi        # a08 <_fini+0x20>
8bd:    b8 00 00 00 00          mov    $0x0,%eax
8c2:    e8 d9 fd ff ff          callq  6a0 <printf@plt>
    #endif
}
8c7:    90                      nop
8c8:    c9                      leaveq
8c9:    c3                      retq

00000000000008ca <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ>:
    jobject unsafe,
    jclass unsafe_class,
    jobject base,
    jlong off,
    jlong value
){
8ca:    55                      push   %rbp
8cb:    48 89 e5                mov    %rsp,%rbp
8ce:    48 83 ec 40             sub    $0x40,%rsp
8d2:    48 89 7d e8             mov    %rdi,-0x18(%rbp)
8d6:    48 89 75 e0             mov    %rsi,-0x20(%rbp)
8da:    48 89 55 d8             mov    %rdx,-0x28(%rbp)
8de:    48 89 4d d0             mov    %rcx,-0x30(%rbp)
8e2:    4c 89 45 c8             mov    %r8,-0x38(%rbp)
8e6:    4c 89 4d c0             mov    %r9,-0x40(%rbp)
    if(midPutLong == NULL){
8ea:    48 8b 05 ef 06 20 00    mov    0x2006ef(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
8f1:    48 8b 00                mov    (%rax),%rax
8f4:    48 85 c0                test   %rax,%rax
8f7:    75 61                   jne    95a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0x90>
        midPutLong = (*env)->GetMethodID(env,unsafe_class,"putLong","(Ljava/lang/Object;JJ)V");
8f9:    48 8b 45 e8             mov    -0x18(%rbp),%rax
8fd:    48 8b 00                mov    (%rax),%rax
900:    48 8b 80 08 01 00 00    mov    0x108(%rax),%rax
907:    48 8b 75 d0             mov    -0x30(%rbp),%rsi
90b:    48 8b 7d e8             mov    -0x18(%rbp),%rdi
90f:    48 8d 0d 33 01 00 00    lea    0x133(%rip),%rcx        # a49 <_fini+0x61>
916:    48 8d 15 44 01 00 00    lea    0x144(%rip),%rdx        # a61 <_fini+0x79>
91d:    ff d0                   callq  *%rax
91f:    48 89 c2                mov    %rax,%rdx
922:    48 8b 05 b7 06 20 00    mov    0x2006b7(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
929:    48 89 10                mov    %rdx,(%rax)
        #ifdef __TRX_ASSERT__
        assert(midPutLong != NULL);
92c:    48 8b 05 ad 06 20 00    mov    0x2006ad(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
933:    48 8b 00                mov    (%rax),%rax
936:    48 85 c0                test   %rax,%rax
939:    75 1f                   jne    95a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0x90>
93b:    48 8d 0d be 01 00 00    lea    0x1be(%rip),%rcx        # b00 <__PRETTY_FUNCTION__.3410>
942:    ba 43 00 00 00          mov    $0x43,%edx
947:    48 8d 35 1b 01 00 00    lea    0x11b(%rip),%rsi        # a69 <_fini+0x81>
94e:    48 8d 3d 2d 01 00 00    lea    0x12d(%rip),%rdi        # a82 <_fini+0x9a>
955:    e8 56 fd ff ff          callq  6b0 <__assert_fail@plt>
        #endif
    }

    volatile int tries = 0;
95a:    c7 45 f8 00 00 00 00    movl   $0x0,-0x8(%rbp)
    volatile int success = 0;
961:    c7 45 fc 00 00 00 00    movl   $0x0,-0x4(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
968:    eb 5b                   jmp    9c5 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xfb>
        __asm__ __volatile__ (
96a:    8b 45 fc                mov    -0x4(%rbp),%eax
96d:    8b 55 f8                mov    -0x8(%rbp),%edx
970:    ff c2                   inc    %edx
972:    c7 f8 4a 00 00 00       xbeginq 9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
978:    89 55 f8                mov    %edx,-0x8(%rbp)
        );

        /*do we need more artificial dependencies, here, to avoid re-ordering?*/

        //unsafe.putInt(base,off,value);
        (*env)-> CallVoidMethod(env,unsafe,midPutLong,base,off,value);
97b:    48 8b 45 e8             mov    -0x18(%rbp),%rax
97f:    48 8b 00                mov    (%rax),%rax
982:    4c 8b 90 e8 01 00 00    mov    0x1e8(%rax),%r10
989:    48 8b 05 50 06 20 00    mov    0x200650(%rip),%rax        # 200fe0 <midPutLong@@Base-0x58>
990:    48 8b 10                mov    (%rax),%rdx
993:    48 8b 7d c0             mov    -0x40(%rbp),%rdi
997:    48 8b 4d c8             mov    -0x38(%rbp),%rcx
99b:    48 8b 75 d8             mov    -0x28(%rbp),%rsi
99f:    48 8b 45 e8             mov    -0x18(%rbp),%rax
9a3:    4c 8b 4d 10             mov    0x10(%rbp),%r9
9a7:    49 89 f8                mov    %rdi,%r8
9aa:    48 89 c7                mov    %rax,%rdi
9ad:    b8 00 00 00 00          mov    $0x0,%eax
9b2:    41 ff d2                callq  *%r10

        __asm__ __volatile__ (
9b5:    8b 45 f8                mov    -0x8(%rbp),%eax
9b8:    8b 55 fc                mov    -0x4(%rbp),%edx
9bb:    0f 01 d5                xend
9be:    ff c2                   inc    %edx
9c0:    eb 00                   jmp    9c2 <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xf8>
9c2:    89 55 fc                mov    %edx,-0x4(%rbp)
    while(!success){/*TODO: maybe switch to a different strategy when tries grows too large?*/
9c5:    8b 45 fc                mov    -0x4(%rbp),%eax
9c8:    85 c0                   test   %eax,%eax
9ca:    74 9e                   je     96a <Java_jnirtm_Transactionally_putLong__Lsun_misc_Unsafe_2Ljava_lang_Class_2Ljava_lang_Object_2JJ+0xa0>
            :"+rm"(success)
            :"rm"(tries) /*artificial dependency*/
        );
    }
    #ifdef __TRX_DEBUG__
        printf("putLong: (Lsun/misc/Unsafe;Ljava/lang/Class;Ljava/lang/Object;JJ)V with %d tries\n",tries);
9cc:    8b 45 f8                mov    -0x8(%rbp),%eax
9cf:    89 c6                   mov    %eax,%esi
9d1:    48 8d 3d c0 00 00 00    lea    0xc0(%rip),%rdi        # a98 <_fini+0xb0>
9d8:    b8 00 00 00 00          mov    $0x0,%eax
9dd:    e8 be fc ff ff          callq  6a0 <printf@plt>
    #endif
}
9e2:    90                      nop
9e3:    c9                      leaveq
9e4:    c3                      retq

Disassembly of section .fini:

00000000000009e8 <_fini>:
9e8:    48 83 ec 08             sub    $0x8,%rsp
9ec:    48 83 c4 08             add    $0x8,%rsp
9f0:    c3                      retq


来源: stackexchange

问:
sudo ipython - how to launch ipython with sudo power
I have ipyhon installed in my CentOS6. When I launch ipython without sudo, it works fine. However, one of my python code is writing a new text file. When I do

```<code>%run writeText.py
PremissionError: [Errno 13] Permission denied: 'log.txt'
</code>```

I tried to start ipython with sudo but it did not allow me

```<code>sudo ipython
sudo: unable to execute /usr/bin/ipython: No such file or directory
</code>```

which I have double checked ipython is in that directory

答:
To run sudo command in ipython, I found out I do not necessary need to run ipython with "sudo". Instead, I run ipython and use the magic word "!" to run linux command with sudo access:</p>

```<code>%ipython
%!sudo lspci
%!sudo ...some command
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have ipyhon installed in my CentOS6. When I launch ipython without sudo, it works fine. However, one of my python code is writing a new text file. When I do

%run writeText.py
PremissionError: [Errno 13] Permission denied: 'log.txt'

I tried to start ipython with sudo but it did not allow me

sudo ipython
sudo: unable to execute /usr/bin/ipython: No such file or directory

which I have double checked ipython is in that directory

Body:
To run sudo command in ipython, I found out I do not necessary need to run ipython with "sudo". Instead, I run ipython and use the magic word "!" to run linux command with sudo access:

%ipython
%!sudo lspci
%!sudo ...some command


问:
Getting TS session ID that user is using from LUID
I am connecting to an XP computer on a domain using remote desktop (no user is or was connected since last restart), and I can see that the applications I am using (like explorer.exe) belongs to TS session ID 0.

In the same time I am getting information using the function LsaGetLogonSessionData() in a Windows service I am running, and according to the information I get from that function, my TS session ID is 2 (for example) and NOT 0.

How can I tell in my Windows service that my login is using explorer.exe at TS session 0 if the function tells me that it is on TS session 2 ?!

I must admit that these Windows session got me REALLY confused!

I'll try to rephrase the question:
How do I know on which TS session ID a LUID is using ?

答: May be due to logon session vs RDP session mismatch.  Try ProcessIdToSessionId  instead.  </p>

ContentLicense: CC BY-SA 2.5


问:
Signal for Entire Row Selection in QTableWidget
Is there a signal for when an entire row in the QTableWidget has been selected by pressing the  buttons that are stacked on the left? I would like that to enable some functionality, but am not sure how?

Thank you in advance!

答:
This is what worked for me:

```<code>connect(tableWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), ...)
</code>```

I got the idea from here.

Body:
This is what worked for me:

connect(tableWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), ...)

I got the idea from here.


问:
You do not have permission to call showSidebar / showModalDialog
I created a spreadsheet in Google Sheets several months ago and use the Google Analytics add-on. It has always worked fine until today, now if I try to create a new report, I see this error message:

You do not have permission to call showSidebar.

Run Reports shows:

You do not have permission to call showModalDialog

Schedule a report shows:

You do not have permission to call showModalDialog

I am but a humble AdWords consultant who knows just enough coding to break things. However, in this case, I haven't changed anything. All I did was try to run a report.

Any help would be greatly appreciated.

答:
It appears either my (or all of our) alert(s) were heard or someone in the GA group noticed a coding error.

I opened the sheet today, did a CTRL F5 (loads the page as if it were the very first time, for those of you who were not aware of this keyboard shortcut, it eliminates the need to go into settings and clear cache and/or cookies), ran my report and all worked as previously.

ContentLicense: CC BY-SA 4.0


问:
Intel python and intel environment in anaconda difference?
I am using Windows and I followed these steps to get the intel environment for my anaconda 3.

I realized that Intel Python can be obtained without anaconda by directly downloading it from the Intel website.
 (Intel python Download option screenshot)

So What is the difference in Intel python in both the cases?

答:
Anaconda is the leading Open Data Science platform powered by Python. Anaconda includes an open source core. Python distribution and over 700 packages. The Anaconda installer includes 150+ packages, and the balance of the packages are easily installed via the conda install package name command.

The Intel Distribution for Python Powered by Anaconda is focused on tools and techniques to accelerate the performance of Python and the widely used numerical computing packages, especially for the latest Intel processors.
Both distributions work on Intel KNL, the recently released Intel Xeon Phi.
To ensure compatibility, the Intel Distribution for Python Powered by Anaconda shares build recipes with Anaconda and uses conda for packaging. The Intel packages for accelerating Python performance are available on AnacondaCloud.

The Anaconda Distribution includes many more packages to provide a more complete ecosystem and focuses on supporting a wide user base that includes the latest as well as older hardware and operating systems. The Anaconda
Distribution installers include over 150 packages and give users access to over 400 Python packages and over 200 R packages hosted on repo.continuum.io and installable with conda. The full list of packages available packages for the Anaconda Distribution is available on the Continuum website.

The Intel Distribution accelerates performance of certain numerical data science Python packages such as Numpy, Scipy, Scikit-learn, Tensorflow for cpu etc., with Intel® Performance Libraries, including Intel®
Math Kernel Library (Intel® MKL), Intel® Threading Building Blocks (Intel® TBB), Intel® Data Analytics Acceleration
Library (Intel® DAAL), and Intel® MPI. The packages have been optimized to take advantage of parallelism through
the use of threading, multiple nodes, and vectorization.


问:
Scenekit ConcavePolyhedron body shape on SCNTorus - strange effects on physics
I'm working on a simple ring toss game where SCNToruses are pushed towards a vertical rod.  I'd like them to collide with eachother, be affected by forces and gravity fields and also be able to fall around the rod.

When using ConvexHull, the boundary on the torus looks good but the inner area is part of the collider so the torus will not go around a rod.  Otherwise the physics forces look good.

When using a ConcavePolyhedron, the boundary on the torus has a hole in the center and allows the torus to go around the rod.  The problem is that when I use concave polyhedron, the rest of the physics stuff does not work so well.  Rings do not collide with eachother and when a force is applied at an offset, let's say (.5, .5, .5), the torus does not rotate, it stays as it was created.

Is there any way to achieve both of these affects so that I can model a ring toss game using basic physics?

答:
I believe that the issue here is that the concavePolyhedron SCNPhysicsShape.ShapeType must be a static physics body which means that it cannot react to forces:

https://developer.apple.com/documentation/scenekit/scnphysicsshape.shapetype/1508890-concavepolyhedron

This shape type may only be used for static physics bodies (that is, those whose type property is static)

I know that this shapetype is very inefficient anyway so I'm going to go with surrounding the torus with small cylindrical nodes.


问:
Why does fgetpos() return a negative offset?
When I am using fgetpos(fp,&pos), the call is setting pos to a negative value where pos is of type fpos_t. Can some one explain why this is happening?

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define TRUE 1
#define FALSE 0

#define MAX_TAG_LEN 50

char filename[1000] = "d:\\ire\\a.xml";

//extract each tag from the xml file
int getTag(char * tag, FILE *fp)
{
    //skip until a beginning of a next
    while(!feof(fp))
        if((char)fgetc(fp) == '<')break;

    if(!feof(fp)){
        char temp[MAX_TAG_LEN]={0};
        char *ptr;
        int len;
        fpos_t b;
        fgetpos(fp,&b);   // here the b is containing -ve values.....???
        fread(temp,sizeof(char),MAX_TAG_LEN - 1,fp);
        temp[MAX_TAG_LEN-1] = 0;
        ptr = strchr(temp,'>');  //search of ending tag bracket
        len = ptr - temp + 1;
        sprintf(tag,"<%.*s",len,temp); //copy the tag
        printf("%s",tag); //print the tag
        b += len;         //reset the position of file pointer to just after the tag character.
        fsetpos(fp,&b);

        return TRUE;
    }
    else{
        return FALSE;
    }
}

int main()
{
    int ch;
    char tag[100]={0};
    FILE *fp = fopen(filename,"r");

    while(getTag(tag,fp)){
    }

    fclose(fp);

    return 0;
}
</code>```

where a.xml is a very basic xml file

```<code><file>
  <page>
    <title>AccessibleComputing</title>
    <id>10</id>
    <redirect />
    <revision>
      <id>133452289</id>
      <timestamp>2007-05-25T17:12:12Z</timestamp>
      <contributor>
        <username>Gurch</username>
        <id>241822</id>
      </contributor>
      <minor />
      <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Rory096|Rory096]]</comment>
      <text xml:space="preserve">#REDIRECT [[Computer accessibility]] {{R from CamelCase}}</text>
    </revision>
  </page>

  </file>
</code>```

The code is working for some xml files but for the above xml file it is stoping after printing the first  tag.

答:
According to the cplusplus.com description of fpos_t:

fpos_t objects are usually created by a call to fgetpos, which returns a reference to an object of this type.  The content of a fpos_t is not meant to be read directly, but only to use its reference as an argument in a call to fsetpos.

I think that means that in theory the value of an fpos_t could be arbitrarily positive or negative, so long as the implementation treats it correctly.  For example, fpos_t could be some offset from the end of the file rather than the beginning, in which case negative values make sense.  It also could be some weird bit-packed representation that would use each bit, including the sign bit, to encode some other information about the file position.

Body:
When I am using fgetpos(fp,&pos), the call is setting pos to a negative value where pos is of type fpos_t. Can some one explain why this is happening?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define TRUE 1
#define FALSE 0

#define MAX_TAG_LEN 50

char filename[1000] = "d:\\ire\\a.xml";

//extract each tag from the xml file
int getTag(char * tag, FILE *fp)
{
    //skip until a beginning of a next
    while(!feof(fp))
        if((char)fgetc(fp) == '<')break;

    if(!feof(fp)){
        char temp[MAX_TAG_LEN]={0};
        char *ptr;
        int len;
        fpos_t b;
        fgetpos(fp,&b);   // here the b is containing -ve values.....???
        fread(temp,sizeof(char),MAX_TAG_LEN - 1,fp);
        temp[MAX_TAG_LEN-1] = 0;
        ptr = strchr(temp,'>');  //search of ending tag bracket
        len = ptr - temp + 1;
        sprintf(tag,"<%.*s",len,temp); //copy the tag
        printf("%s",tag); //print the tag
        b += len;         //reset the position of file pointer to just after the tag character.
        fsetpos(fp,&b);

        return TRUE;
    }
    else{
        return FALSE;
    }
}

int main()
{
    int ch;
    char tag[100]={0};
    FILE *fp = fopen(filename,"r");

    while(getTag(tag,fp)){
    }

    fclose(fp);

    return 0;
}

where a.xml is a very basic xml file

<file>
  <page>
    <title>AccessibleComputing</title>
    <id>10</id>
    <redirect />
    <revision>
      <id>133452289</id>
      <timestamp>2007-05-25T17:12:12Z</timestamp>
      <contributor>
        <username>Gurch</username>
        <id>241822</id>
      </contributor>
      <minor />
      <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Rory096|Rory096]]</comment>
      <text xml:space="preserve">#REDIRECT [[Computer accessibility]] {{R from CamelCase}}</text>
    </revision>
  </page>

  </file>

The code is working for some xml files but for the above xml file it is stoping after printing the first  tag.


问:
Problems using Firebase in Library Module: Uknown property 'LibraryVariants'
I'm trying to add Firebase to my project, but my project is a little special. Firebase will be used in a library module of my project, so it will not be on my app module.

I'm following the manual process of adding firebase from the guidelines, but always I get this error:

Uknown property 'LibraryVariants' for object of type com.android.build.gradle.LibraryExtension

I'm adding this on my project gradle file:

```<code>    buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.1.0'
  }
}
</code>```

And this on my library module gradle file:

```<code>    ...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
</code>```

The error appears when trying to synch my project. I tryed also with the last gradle plugin. Also I tryed adding the plugin in my app module with same result. I'm using Android Studio 3.0.

What is producing this error? Maybe Firebase is not compatible with library modules?

PS: I'm compiling with SDK level 23:

```<code>android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '24.0.2'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 20
    }
</code>```

Note: I know that there are questions answered in Stack Overflow about LibraryVariants, but those questions do not apply to my case.

答:
The google-services plugin is not intended to be used on a library module.  It's only for app modules.

This page says in step 1:

Open the build.gradle file inside your application module directory.

Note: Android Studio projects contain a top-level build.gradle file
  and a build.gradle file for each module. Be sure to edit the file for
  your application module. See Building Your Project with Gradle for
  more information about Gradle.

This page says:

This step requires that the apply plugin:
  'com.google.gms.google-services' line be at the bottom of your
  app/build.gradle

And also:

The google-services.json file is generally placed in the app/
  directory (at the root of the Android Studio app module).

Body:
I'm trying to add Firebase to my project, but my project is a little special. Firebase will be used in a library module of my project, so it will not be on my app module.

I'm following the manual process of adding firebase from the guidelines, but always I get this error:

Uknown property 'LibraryVariants' for object of type com.android.build.gradle.LibraryExtension

I'm adding this on my project gradle file:

    buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.1.0'
  }
}

And this on my library module gradle file:

    ...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

The error appears when trying to synch my project. I tryed also with the last gradle plugin. Also I tryed adding the plugin in my app module with same result. I'm using Android Studio 3.0.

What is producing this error? Maybe Firebase is not compatible with library modules?

PS: I'm compiling with SDK level 23:

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '24.0.2'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 20
    }

Note: I know that there are questions answered in Stack Overflow about LibraryVariants, but those questions do not apply to my case.


问:
Why can't I open my registry Key
First time asking a question so hope I'm doing it right...

I'm trying to write a small program to change the reg key for the home page of internet explorer but each time I run it I'm getting the error that the key location open was unsuccessful. Any ideas why? (Tried running in admin)

```<code>//this string array will be the value for the new home page (w/ null termination)
char newHomePage[] = "https://www.youtube.com/watch?v=gwJ_LgYYvpU \0";
HKEY homePageKey = NULL; //handle for the key once opened

//Open reg key we wish to change, if this fails then abort

//reg key for home page
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Microsoft\\Internet Explorer\\Main", 0, KEY_SET_VALUE, &homePageKey) == ERROR_SUCCESS)
{
    printf("Key location open successful \n");
    if (RegSetValueExW(homePageKey, L"Start Page", 0, REG_SZ, (LPBYTE)&newHomePage, sizeof(char)) == ERROR_SUCCESS)
    {
        printf("Key changed in registry \n");
    }
    else
    {
        printf("Key not changed in registry \n");
        printf("Error %u ", (unsigned int)GetLastError());
    }
    RegCloseKey(homePageKey);
}
else
{
    printf("Error: %u \n", (unsigned int)GetLastError());
    printf("Key location open UNsuccessful \n");
    system("pause");
    RegCloseKey(homePageKey);
    return 0;
}

return 0;
</code>```

答:
There are several problems with your code:

Do NOT include a leading slash when specifying a subkey to RegCreateKeyEx() or RegOpenKeyEx().

You are passing your URL as an ANSI string to a function that expects a Unicode string. And you are specifying the wrong data size.

You are getting error codes from GetLastError(), but the Registry API doesn't use SetLastError() to report errors.  Error codes are returned in function return values instead.

Try this instead:

```<code>//this string array will be the value for the new home page (w/ null termination)
const wchar_t newHomePage[] = L"https://www.youtube.com/watch?v=gwJ_LgYYvpU\0";
HKEY homePageKey = NULL; //handle for the key once opened

//Open reg key we wish to change, if this fails then abort
//reg key for home page
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Internet Explorer\\Main", 0, KEY_SET_VALUE, &homePageKey);
if (lResult == ERROR_SUCCESS)
{
    printf("Key location open successful \n");
    lResult = RegSetValueExW(homePageKey, L"Start Page", 0, REG_SZ, (LPBYTE)newHomePage, sizeof(newHomePage)); // or (lstrlenW(newHomePage)+1)*sizeof(wchar_t)
    if (lResult == ERROR_SUCCESS)
    {
        printf("Key changed in registry \n");
    }
    else
    {
        printf("Key not changed in registry \n");
        printf("Error %ld \n", lResult);
    }
    RegCloseKey(homePageKey);
}
else
{
    printf("Key location open UNsuccessful \n");
    printf("Error: %ld \n", lResult);
}
system("pause");
return 0;
</code>```

Title: Why can't I open my registry Key

Body:
First time asking a question so hope I'm doing it right...

I'm trying to write a small program to change the reg key for the home page of internet explorer but each time I run it I'm getting the error that the key location open was unsuccessful. Any ideas why? (Tried running in admin)

//this string array will be the value for the new home page (w/ null termination)
char newHomePage[] = "https://www.youtube.com/watch?v=gwJ_LgYYvpU \0";
HKEY homePageKey = NULL; //handle for the key once opened

//Open reg key we wish to change, if this fails then abort

//reg key for home page
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Microsoft\\Internet Explorer\\Main", 0, KEY_SET_VALUE, &homePageKey) == ERROR_SUCCESS)
{
    printf("Key location open successful \n");
    if (RegSetValueExW(homePageKey, L"Start Page", 0, REG_SZ, (LPBYTE)&newHomePage, sizeof(char)) == ERROR_SUCCESS)
    {
        printf("Key changed in registry \n");
    }
    else
    {
        printf("Key not changed in registry \n");
        printf("Error %u ", (unsigned int)GetLastError());
    }
    RegCloseKey(homePageKey);
}
else
{
    printf("Error: %u \n", (unsigned int)GetLastError());
    printf("Key location open UNsuccessful \n");
    system("pause");
    RegCloseKey(homePageKey);
    return 0;
}

return 0;

Body:
There are several problems with your code:

Do NOT include a leading slash when specifying a subkey to RegCreateKeyEx() or RegOpenKeyEx().

You are passing your URL as an ANSI string to a function that expects a Unicode string. And you are specifying the wrong data size.

You are getting error codes from GetLastError(), but the Registry API doesn't use SetLastError() to report errors.  Error codes are returned in function return values instead.

Try this instead:

//this string array will be the value for the new home page (w/ null termination)
const wchar_t newHomePage[] = L"https://www.youtube.com/watch?v=gwJ_LgYYvpU\0";
HKEY homePageKey = NULL; //handle for the key once opened

//Open reg key we wish to change, if this fails then abort
//reg key for home page
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Internet Explorer\\Main", 0, KEY_SET_VALUE, &homePageKey);
if (lResult == ERROR_SUCCESS)
{
    printf("Key location open successful \n");
    lResult = RegSetValueExW(homePageKey, L"Start Page", 0, REG_SZ, (LPBYTE)newHomePage, sizeof(newHomePage)); // or (lstrlenW(newHomePage)+1)*sizeof(wchar_t)
    if (lResult == ERROR_SUCCESS)
    {
        printf("Key changed in registry \n");
    }
    else
    {
        printf("Key not changed in registry \n");
        printf("Error %ld \n", lResult);
    }
    RegCloseKey(homePageKey);
}
else
{
    printf("Key location open UNsuccessful \n");
    printf("Error: %ld \n", lResult);
}
system("pause");
return 0;


问:
How to consume credential based webservice (asmx) in Asp.net Core web application?
I am facing issue while adding asmx service in .NetCore Console application. I am using WCF Connected Service extension as add web reference is not available. So,I followed the same steps which was suggested in following link
https://blogs.msdn.microsoft.com/webdev/2016/06/26/wcf-connected-service-for-net-core-1-0-0-and-asp-net-core-1-0-0-is-now-available/

After completing all step it provided auto-generated reference class which contains all method as async method. My asmx service required username and password authentication for each method and we pass credential as first parameter of any method.

for example, using web reference my method looks like GetData(Credential credential) but here auto generated class shows this method like
GetDataAsync() so I used the below mention code to pass the credentials before calling my web service method

client.ClientCredentials.UserName.UserName = "myusername";
client.ClientCredentials.UserName.Password = "mypassword";

It's giving me Not Authorized error, after putting the breakpoints I found that credential was not getting at asmx service.

Please suggest some solution.

答:
Previous Approach I Took:

I ran into a similar issue. I have an MVC Core web application (targeting .NET Framework 4.6.1) and was not able to add a Web Reference the way I used to be able to within previous (non-Core) applications. I was not able to get Connected Services to add a reference to an asmx and allow for the passing of credentials.

To work around this, I created an additional project (a class project also targeting .NET Framework 4.6.1). From there I was able to add a Web Reference the way one could in the past. Within this project I created a class with a publicly accessible method that calls the asmx service.

Then, within my MVC Core project, I set a reference to this additional project and am able to call the public method on the other project.

Latest and Best Approach I Have Found:

I fully updated VS 2017 as well as going to this site to get the latest WCF Connected Services extension (https://marketplace.visualstudio.com/items?itemName=WCFCORETEAM.VisualStudioWCFConnectedService).

The AuthorizationSoapHeader was easy to access and set.

```<code>MySoapClient.EndpointConfiguration endpoint = new MySoapClient.EndpointConfiguration();
MySoapClient myService = new MySoapClient(endpoint, myURL);
AuthorizationSoapHeader MyAuthHeader = new AuthorizationSoapHeader();

MyAuthHeader.AppName = FDSServiceAppName;
MyAuthHeader.AppID = Guid.Parse(MyAppID);

Entry[] entries = MyService.GetUsers().Result;
</code>```

Body:
Previous Approach I Took:

I ran into a similar issue. I have an MVC Core web application (targeting .NET Framework 4.6.1) and was not able to add a Web Reference the way I used to be able to within previous (non-Core) applications. I was not able to get Connected Services to add a reference to an asmx and allow for the passing of credentials.

To work around this, I created an additional project (a class project also targeting .NET Framework 4.6.1). From there I was able to add a Web Reference the way one could in the past. Within this project I created a class with a publicly accessible method that calls the asmx service.

Then, within my MVC Core project, I set a reference to this additional project and am able to call the public method on the other project.

Latest and Best Approach I Have Found:

I fully updated VS 2017 as well as going to this site to get the latest WCF Connected Services extension (https://marketplace.visualstudio.com/items?itemName=WCFCORETEAM.VisualStudioWCFConnectedService).

The AuthorizationSoapHeader was easy to access and set.

MySoapClient.EndpointConfiguration endpoint = new MySoapClient.EndpointConfiguration();
MySoapClient myService = new MySoapClient(endpoint, myURL);
AuthorizationSoapHeader MyAuthHeader = new AuthorizationSoapHeader();

MyAuthHeader.AppName = FDSServiceAppName;
MyAuthHeader.AppID = Guid.Parse(MyAppID);

Entry[] entries = MyService.GetUsers().Result;


问:
Mining All Tweets and Retweets from A Specified User's Timeline Using Tweepy
I'm trying to mine every single tweet on the WomensMarch's Twitter timeline.

I've been trying to use Tweepy and Python 3.x, but I can't seem to mine more than 3219 tweets back. Is there any way to mine /every/ tweet that a specified user on Twitter has ever retweeted or tweeted since the creation of their account?

Here's the code I'm currently using:

```<code>import pandas as pd
import tweepy
from tweepy import OAuthHandler
import time

consumer_key = "--"
consumer_secret = "--"
access_token = "--"
access_secret = "--"

authHandler = OAuthHandler(consumer_key, consumer_secret)
authHandler.set_access_token(access_token, access_secret)
twitterAPI = tweepy.API(authHandler, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

womensMarchTwitter = twitterAPI.get_user('womensmarch')
minedTwitterDataFrom_womensMarchTwitter = pd.DataFrame(columns=["Tweet Text", "Tweet Created On"])

def MineTimelineData(idToMine):
    cursor = tweepy.Cursor(twitterAPI.user_timeline, id=idToMine)
    while(tweepy.Cursor(twitterAPI.user_timeline).items() != None):
        try:
            for page in cursor.pages():
                for tweet in page:
                    yield tweet
        except tweepy.RateLimitError:
            print("Rate limit reached! Waiting 15 minutes...")
            time.sleep(60 * 15) #wait 15 minutes (900 seconds)

minedData = MineTimelineData(womensMarchTwitter.id)

numberOfTweetsMined = 0
for tweet in minedData:
    print(tweet.text)
    print("Posted on: ", tweet.created_at)
    minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Text"] = tweet.text
    minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Created On"] = tweet.created_at
    numberOfTweetsMined = numberOfTweetsMined + 1

minedTwitterDataFrom_womensMarchTwitter.to_csv(r"PATH")
print(numberOfTweetsMined)
print("\n \n \n Finished Mining Tweets!")
</code>```

答:
According to the Twitter API docs the most records you can return at once using user_timeline is going to be 3,200.

From the docs:

This method can only return up to 3,200 of a user’s most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource.

I'm honestly not sure how you got those extra 19 tweets, but this is definitely part of the spec.

Body:
I'm trying to mine every single tweet on the WomensMarch's Twitter timeline.

I've been trying to use Tweepy and Python 3.x, but I can't seem to mine more than 3219 tweets back. Is there any way to mine /every/ tweet that a specified user on Twitter has ever retweeted or tweeted since the creation of their account?

Here's the code I'm currently using:

import pandas as pd
import tweepy
from tweepy import OAuthHandler
import time

consumer_key = "--"
consumer_secret = "--"
access_token = "--"
access_secret = "--"

authHandler = OAuthHandler(consumer_key, consumer_secret)
authHandler.set_access_token(access_token, access_secret)
twitterAPI = tweepy.API(authHandler, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

womensMarchTwitter = twitterAPI.get_user('womensmarch')
minedTwitterDataFrom_womensMarchTwitter = pd.DataFrame(columns=["Tweet Text", "Tweet Created On"])

def MineTimelineData(idToMine):
    cursor = tweepy.Cursor(twitterAPI.user_timeline, id=idToMine)
    while(tweepy.Cursor(twitterAPI.user_timeline).items() != None):
        try:
            for page in cursor.pages():
                for tweet in page:
                    yield tweet
        except tweepy.RateLimitError:
            print("Rate limit reached! Waiting 15 minutes...")
            time.sleep(60 * 15) #wait 15 minutes (900 seconds)

minedData = MineTimelineData(womensMarchTwitter.id)

numberOfTweetsMined = 0
for tweet in minedData:
    print(tweet.text)
    print("Posted on: ", tweet.created_at)
    minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Text"] = tweet.text
    minedTwitterDataFrom_womensMarchTwitter.loc[numberOfTweetsMined, "Tweet Created On"] = tweet.created_at
    numberOfTweetsMined = numberOfTweetsMined + 1

minedTwitterDataFrom_womensMarchTwitter.to_csv(r"PATH")
print(numberOfTweetsMined)
print("\n \n \n Finished Mining Tweets!")


问:
Oracle SQL count group by day distinct in day and days before
I need help with this: I have this table:

```<code>DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020
</code>```

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

```<code>DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)
</code>```

Thanks for your help

```<code>Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547
</code>```

答:
```<code>select a.day_number, count(a.WO) as WO_count
from (
SELECT * FROM data d
WHERE d.day_number = (
SELECT MIN(day_number) FROM data d2
WHERE d.WO = d2.WO

)
) as a
group by a.day_number
</code>```

Body:
I need help with this: I have this table:

DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020

I need to group by day distinct WO, but not only in the day I'm grouping, also distinct in the days before, to obtain this:

DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)

Thanks for your help

Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547


问:
How to sum two cells into one and delete the formula after that?
I have this very niche problem. For instance Lets say the value in the cell A1 is 5 and A2 is 10, what I want to do is add A1 to A2 i.e A2 is now 15 and then when I delete the value in A1 the sum should remain in A2. I cannot use the paste special option to copy just the values because i want to retain the formula for later use i.e when I again input a value to A1 lets say 3 then the sum in A2 should be 18. Any help???
VBA code that triggers this sort of action will be helpful
Thanks In advance.</p>

答:
You just set the Value:</p>

```<code>Range("A3").Value = Range("A1").Value + Range("A2").Value
</code>```

Body:
You just set the Value:

Range("A3").Value = Range("A1").Value + Range("A2").Value


问:
Loops in RMarkdown from two tables - outputs don't match
I am trying to automate reports in RMarkdown where I have two tables with different information in, but a site in common.  I have written loops so that I can produce a summary report for each site, one for each table, but I can't get one of the tables to work.  The first table always produces the same information, but the second is correct for each unique site.

I got so far using this post: R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop? but I can't get the two loops to print the same site in the same document:

R script:

```<code>set.seed(100)
Site<-c("A","B","C","D","E")
Species<-c("a","b","c","d","e")
Count<-rnorm(40,20,20)
df1<-data.frame(Site,Species,Count)
df1

Habitat<-c("v","w","x","y","z")
Size<-rnorm(40,20,20)
df2<-data.frame(Site,Habitat,Size)
df2

library(tidyverse)
library(rmarkdown)

Habitats<-df2 %>%
  group_by(Site, Habitat) %>%
  summarise(Total_Size=sum(Size))
Habitats
report1<-filter(Habitats,Site=='A')
report1

Species<-df1 %>%
  group_by(Site,Species) %>%
  summarise(Total_Count=sum(Count))
Species

#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}
</code>```

template.rmd:

```<code>```{r, echo=FALSE}
#Report Analysis
Habs<-filter(subgroup1)
Habs
```

```{r, echo=FALSE}
Spp<-filter(subgroup2)
Spp
```
</code>```

How do I do this please?  And if I wanted to use 3, 4 or 5 tables all with data relating to the same sites, would your solution also work?

答:
In your template.rmd you are calling subgroup2

{r, echo=FALSE}
Spp<-filter(subgroup2)
Spp

but it is not created untill you enter the second loop.

```<code>#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}
</code>```

so when you run

```<code>#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}
</code>```

It does not exist yet. Perhaps something along those lines would help ?

```<code>for(Site in unique(c(Species$Site,Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}
</code>```

Body:
I am trying to automate reports in RMarkdown where I have two tables with different information in, but a site in common.  I have written loops so that I can produce a summary report for each site, one for each table, but I can't get one of the tables to work.  The first table always produces the same information, but the second is correct for each unique site.

I got so far using this post: R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop? but I can't get the two loops to print the same site in the same document:

R script:

set.seed(100)
Site<-c("A","B","C","D","E")
Species<-c("a","b","c","d","e")
Count<-rnorm(40,20,20)
df1<-data.frame(Site,Species,Count)
df1

Habitat<-c("v","w","x","y","z")
Size<-rnorm(40,20,20)
df2<-data.frame(Site,Habitat,Size)
df2

library(tidyverse)
library(rmarkdown)

Habitats<-df2 %>%
  group_by(Site, Habitat) %>%
  summarise(Total_Size=sum(Size))
Habitats
report1<-filter(Habitats,Site=='A')
report1

Species<-df1 %>%
  group_by(Site,Species) %>%
  summarise(Total_Count=sum(Count))
Species

#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

template.rmd:

```{r, echo=FALSE}
#Report Analysis
Habs<-filter(subgroup1)
Habs
```

```{r, echo=FALSE}
Spp<-filter(subgroup2)
Spp
```

How do I do this please?  And if I wanted to use 3, 4 or 5 tables all with data relating to the same sites, would your solution also work?

Body:
In your template.rmd you are calling subgroup2

{r, echo=FALSE}
Spp<-filter(subgroup2)
Spp

but it is not created untill you enter the second loop.

#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

so when you run

#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

It does not exist yet. Perhaps something along those lines would help ?

for(Site in unique(c(Species$Site,Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}


问:
What differences are there between running monotouch in simulator vs. on device?
Is there any documentation on the difference between the monotouch runtime used in (iPad) Simulator vs. running on an actual device?

I've recently had to change some code that resulted in ExecutionEngineException (seemingly unrelated to the one mentioned here) when running on the device, but not in the simulator.

Is JIT enabled in the simulator (I know it is not on the device) or why is there this difference?

(Question also posted to Monotouch forums here)

答: The iOS simulator is a simulator and not an emulator.  This means that when running on the simulator you have access to a full x86 JIT, where as on the device you can only do ARM full-aot.  There are a number of other subtle differences as well (certain frameworks / features are not available on the simulator).</p>


问:
Is it possible to give a sub-module the same name as a top-level class?
Background:

ruby thinks I'm referencing a top-level constant even when I specify the full namespace

How do I refer to a submodule's "full path" in ruby?

Here's the problem, distilled down to a minimal example:

```<code># bar.rb
class Bar
end

# foo/bar.rb
module Foo::Bar
end

# foo.rb
class Foo
  include Foo::Bar
end

# runner.rb
require 'bar'
require 'foo'
</code>```

```
➔ ruby runner.rb
./foo.rb:2: warning: toplevel constant Bar referenced by Foo::Bar
./foo.rb:2:in `include': wrong argument type Class (expected Module) (TypeError)
    from ./foo.rb:2
    from runner.rb:2:in `require'
    from runner.rb:2
```

答:
Here's another fun example:

```<code>module SomeName
  class Client
  end
end

module Integrations::SomeName::Importer
  def perform
    ...
    client = ::SomeName::Client.new(...)
    ...
  end
end
</code>```

That produces:

block in load_missing_constant': uninitialized constant Integrations::SomeName::Importer::SomeName (NameError)

Ruby (2.3.4) just goes to the first occurrence of "SomeName" it can find, not to the top-level.

A way to get around it is to either use better nesting of modules/classes(!!), or to use Kernel.const_get('SomeName')

Body:
Background:

ruby thinks I'm referencing a top-level constant even when I specify the full namespace

How do I refer to a submodule's "full path" in ruby?

Here's the problem, distilled down to a minimal example:

# bar.rb
class Bar
end

# foo/bar.rb
module Foo::Bar
end

# foo.rb
class Foo
  include Foo::Bar
end

# runner.rb
require 'bar'
require 'foo'

➔ ruby runner.rb
./foo.rb:2: warning: toplevel constant Bar referenced by Foo::Bar
./foo.rb:2:in `include': wrong argument type Class (expected Module) (TypeError)
    from ./foo.rb:2
    from runner.rb:2:in `require'
    from runner.rb:2

Body:
Here's another fun example:

module SomeName
  class Client
  end
end

module Integrations::SomeName::Importer
  def perform
    ...
    client = ::SomeName::Client.new(...)
    ...
  end
end

That produces:

block in load_missing_constant': uninitialized constant Integrations::SomeName::Importer::SomeName (NameError)

Ruby (2.3.4) just goes to the first occurrence of "SomeName" it can find, not to the top-level.

A way to get around it is to either use better nesting of modules/classes(!!), or to use Kernel.const_get('SomeName')


问:
How to average several readings in python?
A sensor generates an reading every one second for five seconds. I was trying to use the function np.mean to calculate the average of five sensor readings (i.e., sensor1_t1 to sensor1_t5), however it doesn't work.

Can you please help me on this?

Thanks.

```<code>sensor1_t1 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t2 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t3 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t4 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t5 = BridgeValue(0) * 274.0 - 2.1
sleep(1)

# my code - not working
#avg_sensor1 = np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5)
</code>```

答:
This would be more easily done using Numpy arrays throughout.  Something like:</p>

```<code>import numpy as np

N = 5
sensor1 = np.zeros((N,), dtype=float)

for i in range(N):
    sensor1[i] = BridgeValue(0) * 274.0 - 2.1
    sleep(1)

average = np.mean(sensor1)
</code>```

Body:
A sensor generates an reading every one second for five seconds. I was trying to use the function np.mean to calculate the average of five sensor readings (i.e., sensor1_t1 to sensor1_t5), however it doesn't work.

Can you please help me on this?

Thanks.

sensor1_t1 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t2 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t3 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t4 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t5 = BridgeValue(0) * 274.0 - 2.1
sleep(1)

# my code - not working
#avg_sensor1 = np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5)

Body:
This would be more easily done using Numpy arrays throughout.  Something like:

import numpy as np

N = 5
sensor1 = np.zeros((N,), dtype=float)

for i in range(N):
    sensor1[i] = BridgeValue(0) * 274.0 - 2.1
    sleep(1)

average = np.mean(sensor1)


问:
How to send push notifications to web application and browser?
I have a database in which I insert and send data using java.So I want to send push notifications using java to my web application and getting them in javascript.

I also want to send push notification to my browser.Is there an easy way to do these two things? I have been trying for days but I have not found a well explained tutorial that I can understand.

Thank you in advance.

答:
In short, no. There isn't a necessarily "easy" way to do it. Most browsers handle push notifications differently, and as far as sending push notifications to your web application, you should look up RESTful implementation, and once you have that set up, whenever data is passed to the web application, you will be able to capture it and send/receive any notification you'd like.

I would suggest looking into Firebase, as they have a pretty good implementation for push notifications.


问:
Need help with text box input
It's actually a grid column but it functions just like a textbox. I need it to be able to accept numbers only, but it has to be able to accept numbers with leading 0's. What would I use as a mask to get this result? If I do any kind of numeric mask then it will cut off the leading 0's, eg 002456841. If I don't use a numeric mask, then characters will be accepted which is unacceptable.

Am I not thinking outside of the box enough with this? I was also thinking like maybe instead of a mask using a loop or something to make sure it's only numbers and erase/pop up a message if it's not...but I just don't know, I would rather just have the box so it only accepts numbers but any number.

答:
If you're working in asp.net webforms (you didn't say which platform/language), then you can use the MS Ajax filteredTextBox extender, which lets you specify what can be entered.  It connects to an asp.net TextBox and when a not allowed character key is pressed, nothing happens.

I'd suggest a bit more information in your questions if you want specific answers.  Especially what platform/language your working in.  C# is rather broad, and isn't mentioned in your question or title, just as a tag.

Title: Need help with text box input


问:
SQL Divide Multiply Execution Order
```<code>select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2
</code>```

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

答:
The reason is that SQL server is going to not lose decimal precision.  Arithmetic operators work left to right, and in the first equation the initial operation does not create an actual decimal component (117378300.0), while the second generates a number with six decimal digits (0.1295810).  So, in the subsequent operation, SQL Server will maintain 0 and 6 decimal places, respectively, so as not to 'lose data'.  You can actually see the difference writing the initial result to a table and observing the data types that are generated:

```<code>select 3900.0 * 30097 val
into tbl_a

select 3900.0 / 30097  val
into tbl_b

select table_name, column_name, numeric_precision, numeric_scale
from information_schema.columns
where  table_name in ( 'tbl_a', 'tbl_b')
</code>```

generates:

```<code>table_name  column_name numeric_precision   numeric_scale
tbl_a   val 11  1
tbl_b   val 11  7 <-- decimal component
</code>```

Title: SQL Divide Multiply Execution Order

Body:
select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

Body:
The reason is that SQL server is going to not lose decimal precision.  Arithmetic operators work left to right, and in the first equation the initial operation does not create an actual decimal component (117378300.0), while the second generates a number with six decimal digits (0.1295810).  So, in the subsequent operation, SQL Server will maintain 0 and 6 decimal places, respectively, so as not to 'lose data'.  You can actually see the difference writing the initial result to a table and observing the data types that are generated:

select 3900.0 * 30097 val
into tbl_a

select 3900.0 / 30097  val
into tbl_b

select table_name, column_name, numeric_precision, numeric_scale
from information_schema.columns
where  table_name in ( 'tbl_a', 'tbl_b')

generates:

table_name  column_name numeric_precision   numeric_scale
tbl_a   val 11  1
tbl_b   val 11  7 <-- decimal component