text:
Q: need trick with object creator This is my code:
public interface InterfaceA<J>{
    // …
}

public interface InterfaceB extends InterfaceA<String> {
    // …
}

public interface InterfaceC extends InterfaceA<Long>{
    // …
}

public class Creator<J, I extends InterfaceA<J>> {}

public abstract class Base<J, J1> implements InterfaceA<J> {
    protected Creator<J, J1> creator;

    protected Base() {
        creator=ObjectCreator.createCreator();
    }
}

public class Extension1 extends Base<Integer> implements InterfaceB {
    // …
}

public class Extension2 extends Base<Double> implements InterfaceC {
    // …
}

I want Extension1 to have Creator<Integer, InterfaceB> and Extension2 to have Creator<Double, interfaceC>. See the pattern? Creator<T1, T2> where T1 is the type of immediate parent and T2 is the interface implemented by said class. Is there any way to do this? can anybody tell the code of ObjectCreator.createCreator()?
Right now my code looks like this:
public class ObjectCreator {
    public static <J, I extends InterfaceA<J>> Creator<J, I> createCreator() {
        return new Creator();
    }
}

I got errors all over my code. I'm really confused. What am I missing here?

A: There's a whole bunch of stuff you missed, a compiling version would look something like this:
package scratch;

interface InterfaceA<J> {
    // …
}

interface InterfaceB extends InterfaceA<String> {
    // …
}

interface InterfaceC extends InterfaceA<Long> {
    // …
}

class Creator<J, I extends InterfaceA<J>> {
}

abstract class Base<J, I extends InterfaceA<J>> {
    protected Creator<J, I> creator;

    protected Base(Class<J> jClass, Class<I> iClass) {
        creator = ObjectCreator.createCreator(jClass, iClass);
    }
}

class Extension1 extends Base<String, InterfaceB> implements InterfaceB {
    protected Extension1() {
        super(String.class, InterfaceB.class);
    }
}

class Extension2 extends Base<Long, InterfaceC> implements InterfaceC {
    protected Extension2() {
        super(Long.class, InterfaceC.class);
    }
}

class ObjectCreator {
    public static <J, I extends InterfaceA<J>> Creator<J, I>
    createCreator(Class<J> jClass, Class<I> iClass) {
        return new Creator();
    }
}

In no particular order of importance:

*

*When you have a class with a signature like createCreator() has, you need to pass Class objects as type tokens to it. The Java compiler can't infer the types based on the type of the variable you're assigning the return value to. Besides, you want them there anyway because of type erasure, otherwise you couldn't specialise the Creator based on the given types.

*

*If you have Base<J, I> with two type parameters, extending classes should use both of those type parameters.

*Your extension class signatures were odd. You can't have class Extension1 extends Base<Integer, InterfaceA<String>>, because you can't have a Creator<Integer, InterfaceA<String>>. Using explicit type tokens in createCreator() would have forced you to propagate this constraint everywhere it needs to be and made the error less mysterious. You can't really make Base independent of the constraint between the J and I type parameters.


text:
Q: Make "find in path" appear for PHPStorm I linked a external folder to my PHPStorm project. In PHPStorm 6 I could right click the folder and do a file search.
In PHPStorm this feature is gone. Can I get it again?

redpajama_set_name: RedPajamaStackExchange


text:
Q: centralizer of permutations in Symmetric group I would greatly appreciate it if you kindly give me some advice.
Let $a$ and $b$ be two distinct permutations in $\text{Sym}(n)$. When $C_{S_n}(a)=C_{S_n}(b)$?
I guess either $a$ and $b$ be in the same conjugacy class with the cyclic type $(x)(y)(z\;w)a_0$ where $(z\;w)$ is a transposition and $a_0$ is a product of cycles of size at least three,
or $a=(x)(y)a_1$ and $b=(x\;y)b_1$ where $a_1$ and $b_1$ are conjugate. Moreover, $a_1$ and $b_1$ are the product of cycles of size at least three.
Thanks in advance for your consideration.

A: This seems tricky to get right, so let me have a go. I hope someone will correct any inaccuracies!
For a permutation $g$ on a finite set $\Omega$ and $k \ge 0$, let $\Omega_k(g)$ denote the subset of $\Omega$ consisting of the support of all cycles of $g$ of length $k$. So, for fixed $g$, the $\Omega_k(g)$ partition $\Omega$.
For example. if $g = (3,4)(5,6)(7,8)(9,10,11,12,13)(14,15,16,17,18)(19,20,21,22,23,24)$ with $\Omega = \{1, \ldots,24\}$, then $\Omega_k(g) = \{1,2\}$, $\{3,4,5,6,7,8\}$, $\{9,10,11,12,13,14,15,16,17,18\}$, $\{19,20,21,22,23,24\}$, for $k=1,2,5,6$, respectively, and all other $\Omega_k(g)$ are empty.
Then, for $a,b \in S := {\rm Sym}(\Omega)$, we have $C_S(a) = C_S(b)$ if and only if the following two conditions hold:
(i) $\Omega_k(a)=\Omega_k(b)$ for all $k \ge 3$, and either this holds also for $k=1,2$, or $\Omega_1(a) = \Omega_2(b)$ with $|\Omega_1(a)|=2$ and/or  $\Omega_2(a) = \Omega_1(b)$ with $|\Omega_2(a)|=2$.
(ii) For all $ k \ge 0$, the restrictions of $a$ and $b$ to $\Omega_k(a)$ are powers of each other, except when $k=1$ or 2 in the exceptional cases of Condition (i).


text:
Q: How to display last 12 months of data in proper order in SQL I want the count of last 12 months records group by MM-YYYY.
select to_char((SCHEDULED_START_DT), 'MM-YYYY') , count(*)
    from XYZ where  SCHEDULED_START_DT > TRUNC (ADD_MONTHS (SYSDATE, -11), 'MM')
    group by to_char((SCHEDULED_START_DT), 'MM-YYYY')

This is the output of the above query.

But i want the output to be in the following order
10-2016
11-2016
12-2016
01-2017
02-2017
03-2017
04-2017
05-2017
06-2017
07-2017
08-2017
09-2017

What is the best way to do this ?

A: A simple method is to order by any one date from each period.  The min() or max() will do for ordering purposes:
select to_char(SCHEDULED_START_DT, 'MM-YYYY'), count(*)
from XYZ
where SCHEDULED_START_DT > TRUNC(ADD_MONTHS(SYSDATE, -11), 'MM')
group by to_char(SCHEDULED_START_DT, 'MM-YYYY')
order by min(SCHEDULED_START_DT);

A: The simplest way is to group by a date (rather than a string) and then sort by it:
select to_char(trunc(SCHEDULED_START_DT,'MM'), 'MM-YYYY') , count(*)
from XYZ where SCHEDULED_START_DT > TRUNC (ADD_MONTHS (SYSDATE, -11), 'MM')
group by trunc(SCHEDULED_START_DT,'MM')
order by trunc(SCHEDULED_START_DT,'MM')

A: select to_char(SCHEDULED_START_DT, 'MM-YYYY'), count(*)
from XYZ
where SCHEDULED_START_DT > TRUNC(ADD_MONTHS(SYSDATE, -11), 'MM')
group by to_char(SCHEDULED_START_DT, 'MM-YYYY')
order by SCHEDULED_START_DT DESC;
Should do it!


text:
Q: ARM program example with Keil Uvision startup file Sorry, I am newbie, I am just starting to explore assembly with ARM.
I am trying to run example from the book
        AREA Prog1, CODE, READONLY
        ENTRY
        MOV r0, #0x11 ; load initial value
        LSL r1, r0, #1 ; shift 1 bit left
        LSL r2, r1, #1 ; shift 1 bit left
stop    B stop ; stop program
        END

But as far as I know program should have RESET area vector set in order to start execution.
So I added Startup.s file into my project
;/*****************************************************************************/
;/* STARTUP.S: Startup file for Philips LPC2000                               */
;/*****************************************************************************/
;/* <<< Use Configuration Wizard in Context Menu >>>                          */
;/*****************************************************************************/
;/* This file is part of the uVision/ARM development tools.                   */
;/* Copyright (c) 2005-2007 Keil Software. All rights reserved.               */
;/* This software may only be used under the terms of a valid, current,       */
;/* end user licence from KEIL for a compatible version of KEIL software      */
;/* development tools. Nothing else gives you the right to use this software. */
;/*****************************************************************************/

;/*
; *  The STARTUP.S code is executed after CPU Reset. This file may be
; *  translated with the following SET symbols. In uVision these SET
; *  symbols are entered under Options - ASM - Define.
; *
; *  REMAP: when set the startup code initializes the register MEMMAP
; *  which overwrites the settings of the CPU configuration pins. The
; *  startup and interrupt vectors are remapped from:
; *     0x00000000  default setting (not remapped)
; *     0x80000000  when EXTMEM_MODE is used
; *     0x40000000  when RAM_MODE is used
; *
; *  EXTMEM_MODE: when set the device is configured for code execution
; *  from external memory starting at address 0x80000000.
; *
; *  RAM_MODE: when set the device is configured for code execution
; *  from on-chip RAM starting at address 0x40000000.
; *
; *  EXTERNAL_MODE: when set the PIN2SEL values are written that enable
; *  the external BUS at startup.
; */

; Standard definitions of Mode bits and Interrupt (I & F) flags in PSRs

Mode_USR        EQU     0x10
Mode_FIQ        EQU     0x11
Mode_IRQ        EQU     0x12
Mode_SVC        EQU     0x13
Mode_ABT        EQU     0x17
Mode_UND        EQU     0x1B
Mode_SYS        EQU     0x1F

I_Bit           EQU     0x80            ; when I bit is set, IRQ is disabled
F_Bit           EQU     0x40            ; when F bit is set, FIQ is disabled

;// <h> Stack Configuration (Stack Sizes in Bytes)
;//   <o0> Undefined Mode      <0x0-0xFFFFFFFF:8>
;//   <o1> Supervisor Mode     <0x0-0xFFFFFFFF:8>
;//   <o2> Abort Mode          <0x0-0xFFFFFFFF:8>
;//   <o3> Fast Interrupt Mode <0x0-0xFFFFFFFF:8>
;//   <o4> Interrupt Mode      <0x0-0xFFFFFFFF:8>
;//   <o5> User/System Mode    <0x0-0xFFFFFFFF:8>
;// </h>

UND_Stack_Size  EQU     0x00000000
SVC_Stack_Size  EQU     0x00000008
ABT_Stack_Size  EQU     0x00000000
FIQ_Stack_Size  EQU     0x00000000
IRQ_Stack_Size  EQU     0x00000080
USR_Stack_Size  EQU     0x00000400

ISR_Stack_Size  EQU     (UND_Stack_Size + SVC_Stack_Size + ABT_Stack_Size + \
                         FIQ_Stack_Size + IRQ_Stack_Size)

                AREA    STACK, NOINIT, READWRITE, ALIGN=3

Stack_Mem       SPACE   USR_Stack_Size
__initial_sp    SPACE   ISR_Stack_Size

Stack_Top

;// <h> Heap Configuration
;//   <o>  Heap Size (in Bytes) <0x0-0xFFFFFFFF>
;// </h>

Heap_Size       EQU     0x00000000

                AREA    HEAP, NOINIT, READWRITE, ALIGN=3
__heap_base
Heap_Mem        SPACE   Heap_Size
__heap_limit

; VPBDIV definitions
VPBDIV          EQU     0xE01FC100      ; VPBDIV Address

;// <e> VPBDIV Setup
;// <i> Peripheral Bus Clock Rate
;//   <o1.0..1>   VPBDIV: VPB Clock
;//               <0=> VPB Clock = CPU Clock / 4
;//               <1=> VPB Clock = CPU Clock
;//               <2=> VPB Clock = CPU Clock / 2
;//   <o1.4..5>   XCLKDIV: XCLK Pin
;//               <0=> XCLK Pin = CPU Clock / 4
;//               <1=> XCLK Pin = CPU Clock
;//               <2=> XCLK Pin = CPU Clock / 2
;// </e>
VPBDIV_SETUP    EQU     0
VPBDIV_Val      EQU     0x00000000

; Phase Locked Loop (PLL) definitions
PLL_BASE        EQU     0xE01FC080      ; PLL Base Address
PLLCON_OFS      EQU     0x00            ; PLL Control Offset
PLLCFG_OFS      EQU     0x04            ; PLL Configuration Offset
PLLSTAT_OFS     EQU     0x08            ; PLL Status Offset
PLLFEED_OFS     EQU     0x0C            ; PLL Feed Offset
PLLCON_PLLE     EQU     (1<<0)          ; PLL Enable
PLLCON_PLLC     EQU     (1<<1)          ; PLL Connect
PLLCFG_MSEL     EQU     (0x1F<<0)       ; PLL Multiplier
PLLCFG_PSEL     EQU     (0x03<<5)       ; PLL Divider
PLLSTAT_PLOCK   EQU     (1<<10)         ; PLL Lock Status

;// <e> PLL Setup
;//   <o1.0..4>   MSEL: PLL Multiplier Selection
;//               <1-32><#-1>
;//               <i> M Value
;//   <o1.5..6>   PSEL: PLL Divider Selection
;//               <0=> 1   <1=> 2   <2=> 4   <3=> 8
;//               <i> P Value
;// </e>
PLL_SETUP       EQU     1
PLLCFG_Val      EQU     0x00000024

; Memory Accelerator Module (MAM) definitions
MAM_BASE        EQU     0xE01FC000      ; MAM Base Address
MAMCR_OFS       EQU     0x00            ; MAM Control Offset
MAMTIM_OFS      EQU     0x04            ; MAM Timing Offset

;// <e> MAM Setup
;//   <o1.0..1>   MAM Control
;//               <0=> Disabled
;//               <1=> Partially Enabled
;//               <2=> Fully Enabled
;//               <i> Mode
;//   <o2.0..2>   MAM Timing
;//               <0=> Reserved  <1=> 1   <2=> 2   <3=> 3
;//               <4=> 4         <5=> 5   <6=> 6   <7=> 7
;//               <i> Fetch Cycles
;// </e>
MAM_SETUP       EQU     1
MAMCR_Val       EQU     0x00000002
MAMTIM_Val      EQU     0x00000004

; External Memory Controller (EMC) definitions
EMC_BASE        EQU     0xFFE00000      ; EMC Base Address
BCFG0_OFS       EQU     0x00            ; BCFG0 Offset
BCFG1_OFS       EQU     0x04            ; BCFG1 Offset
BCFG2_OFS       EQU     0x08            ; BCFG2 Offset
BCFG3_OFS       EQU     0x0C            ; BCFG3 Offset

;// <e> External Memory Controller (EMC)
EMC_SETUP       EQU     0

;//   <e> Bank Configuration 0 (BCFG0)
;//     <o1.0..3>   IDCY: Idle Cycles <0-15>
;//     <o1.5..9>   WST1: Wait States 1 <0-31>
;//     <o1.11..15> WST2: Wait States 2 <0-31>
;//     <o1.10>     RBLE: Read Byte Lane Enable
;//     <o1.26>     WP: Write Protect
;//     <o1.27>     BM: Burst ROM
;//     <o1.28..29> MW: Memory Width  <0=>  8-bit  <1=> 16-bit
;//                                   <2=> 32-bit  <3=> Reserved
;//   </e>
BCFG0_SETUP EQU         0
BCFG0_Val   EQU         0x0000FBEF

;//   <e> Bank Configuration 1 (BCFG1)
;//     <o1.0..3>   IDCY: Idle Cycles <0-15>
;//     <o1.5..9>   WST1: Wait States 1 <0-31>
;//     <o1.11..15> WST2: Wait States 2 <0-31>
;//     <o1.10>     RBLE: Read Byte Lane Enable
;//     <o1.26>     WP: Write Protect
;//     <o1.27>     BM: Burst ROM
;//     <o1.28..29> MW: Memory Width  <0=>  8-bit  <1=> 16-bit
;//                                   <2=> 32-bit  <3=> Reserved
;//   </e>
BCFG1_SETUP EQU         0
BCFG1_Val   EQU         0x0000FBEF

;//   <e> Bank Configuration 2 (BCFG2)
;//     <o1.0..3>   IDCY: Idle Cycles <0-15>
;//     <o1.5..9>   WST1: Wait States 1 <0-31>
;//     <o1.11..15> WST2: Wait States 2 <0-31>
;//     <o1.10>     RBLE: Read Byte Lane Enable
;//     <o1.26>     WP: Write Protect
;//     <o1.27>     BM: Burst ROM
;//     <o1.28..29> MW: Memory Width  <0=>  8-bit  <1=> 16-bit
;//                                   <2=> 32-bit  <3=> Reserved
;//   </e>
BCFG2_SETUP EQU         0
BCFG2_Val   EQU         0x0000FBEF

;//   <e> Bank Configuration 3 (BCFG3)
;//     <o1.0..3>   IDCY: Idle Cycles <0-15>
;//     <o1.5..9>   WST1: Wait States 1 <0-31>
;//     <o1.11..15> WST2: Wait States 2 <0-31>
;//     <o1.10>     RBLE: Read Byte Lane Enable
;//     <o1.26>     WP: Write Protect
;//     <o1.27>     BM: Burst ROM
;//     <o1.28..29> MW: Memory Width  <0=>  8-bit  <1=> 16-bit
;//                                   <2=> 32-bit  <3=> Reserved
;//   </e>
BCFG3_SETUP EQU         0
BCFG3_Val   EQU         0x0000FBEF

;// </e> End of EMC

; External Memory Pins definitions
PINSEL2         EQU     0xE002C014      ; PINSEL2 Address
PINSEL2_Val     EQU     0x0E6149E4      ; CS0..3, OE, WE, BLS0..3,
                                        ; D0..31, A2..23, JTAG Pins

                PRESERVE8

; Area Definition and Entry Point
;  Startup Code must be linked first at Address at which it expects to run.

                AREA    RESET, CODE, READONLY
                ARM

; Exception Vectors
;  Mapped to Address 0.
;  Absolute addressing mode must be used.
;  Dummy Handlers are implemented as infinite loops which can be modified.

Vectors         LDR     PC, Reset_Addr
                LDR     PC, Undef_Addr
                LDR     PC, SWI_Addr
                LDR     PC, PAbt_Addr
                LDR     PC, DAbt_Addr
                NOP                            ; Reserved Vector
;               LDR     PC, IRQ_Addr
                LDR     PC, [PC, #-0x0FF0]     ; Vector from VicVectAddr
                LDR     PC, FIQ_Addr

Reset_Addr      DCD     Reset_Handler
Undef_Addr      DCD     Undef_Handler
SWI_Addr        DCD     SWI_Handler
PAbt_Addr       DCD     PAbt_Handler
DAbt_Addr       DCD     DAbt_Handler
                DCD     0                      ; Reserved Address
IRQ_Addr        DCD     IRQ_Handler
FIQ_Addr        DCD     FIQ_Handler

Undef_Handler   B       Undef_Handler
SWI_Handler     B       SWI_Handler
PAbt_Handler    B       PAbt_Handler
DAbt_Handler    B       DAbt_Handler
IRQ_Handler     B       IRQ_Handler
FIQ_Handler     B       FIQ_Handler

; Reset Handler

                EXPORT  Reset_Handler
Reset_Handler

; Setup External Memory Pins
                IF      :DEF:EXTERNAL_MODE
                LDR     R0, =PINSEL2
                LDR     R1, =PINSEL2_Val
                STR     R1, [R0]
                ENDIF

; Setup External Memory Controller
                IF      EMC_SETUP <> 0
                LDR     R0, =EMC_BASE

                IF      BCFG0_SETUP <> 0
                LDR     R1, =BCFG0_Val
                STR     R1, [R0, #BCFG0_OFS]
                ENDIF

                IF      BCFG1_SETUP <> 0
                LDR     R1, =BCFG1_Val
                STR     R1, [R0, #BCFG1_OFS]
                ENDIF

                IF      BCFG2_SETUP <> 0
                LDR     R1, =BCFG2_Val
                STR     R1, [R0, #BCFG2_OFS]
                ENDIF

                IF      BCFG3_SETUP <> 0
                LDR     R1, =BCFG3_Val
                STR     R1, [R0, #BCFG3_OFS]
                ENDIF

                ENDIF   ; EMC_SETUP

; Setup VPBDIV
                IF      VPBDIV_SETUP <> 0
                LDR     R0, =VPBDIV
                LDR     R1, =VPBDIV_Val
                STR     R1, [R0]
                ENDIF

; Setup PLL
                IF      PLL_SETUP <> 0
                LDR     R0, =PLL_BASE
                MOV     R1, #0xAA
                MOV     R2, #0x55

;  Configure and Enable PLL
                MOV     R3, #PLLCFG_Val
                STR     R3, [R0, #PLLCFG_OFS]
                MOV     R3, #PLLCON_PLLE
                STR     R3, [R0, #PLLCON_OFS]
                STR     R1, [R0, #PLLFEED_OFS]
                STR     R2, [R0, #PLLFEED_OFS]

;  Wait until PLL Locked
PLL_Loop        LDR     R3, [R0, #PLLSTAT_OFS]
                ANDS    R3, R3, #PLLSTAT_PLOCK
                BEQ     PLL_Loop

;  Switch to PLL Clock
                MOV     R3, #(PLLCON_PLLE:OR:PLLCON_PLLC)
                STR     R3, [R0, #PLLCON_OFS]
                STR     R1, [R0, #PLLFEED_OFS]
                STR     R2, [R0, #PLLFEED_OFS]
                ENDIF   ; PLL_SETUP

; Setup MAM
                IF      MAM_SETUP <> 0
                LDR     R0, =MAM_BASE
                MOV     R1, #MAMTIM_Val
                STR     R1, [R0, #MAMTIM_OFS]
                MOV     R1, #MAMCR_Val
                STR     R1, [R0, #MAMCR_OFS]
                ENDIF   ; MAM_SETUP

; Memory Mapping (when Interrupt Vectors are in RAM)
MEMMAP          EQU     0xE01FC040      ; Memory Mapping Control
                IF      :DEF:REMAP
                LDR     R0, =MEMMAP
                IF      :DEF:EXTMEM_MODE
                MOV     R1, #3
                ELIF    :DEF:RAM_MODE
                MOV     R1, #2
                ELSE
                MOV     R1, #1
                ENDIF
                STR     R1, [R0]
                ENDIF

; Initialise Interrupt System
;  ...

; Setup Stack for each mode

                LDR     R0, =Stack_Top

;  Enter Undefined Instruction Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_UND:OR:I_Bit:OR:F_Bit
                MOV     SP, R0
                SUB     R0, R0, #UND_Stack_Size

;  Enter Abort Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_ABT:OR:I_Bit:OR:F_Bit
                MOV     SP, R0
                SUB     R0, R0, #ABT_Stack_Size

;  Enter FIQ Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_FIQ:OR:I_Bit:OR:F_Bit
                MOV     SP, R0
                SUB     R0, R0, #FIQ_Stack_Size

;  Enter IRQ Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_IRQ:OR:I_Bit:OR:F_Bit
                MOV     SP, R0
                SUB     R0, R0, #IRQ_Stack_Size

;  Enter Supervisor Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_SVC:OR:I_Bit:OR:F_Bit
                MOV     SP, R0
                SUB     R0, R0, #SVC_Stack_Size

;  Enter User Mode and set its Stack Pointer
                MSR     CPSR_c, #Mode_USR
                IF      :DEF:__MICROLIB

                EXPORT __initial_sp

                ELSE

                MOV     SP, R0
                SUB     SL, SP, #USR_Stack_Size

                ENDIF

; Enter the C code

                IMPORT  __main
                LDR     R0, =__main
                BX      R0

                IF      :DEF:__MICROLIB

                EXPORT  __heap_base
                EXPORT  __heap_limit

                ELSE
; User Initial Stack & Heap
                AREA    |.text|, CODE, READONLY

                IMPORT  __use_two_region_memory
                EXPORT  __user_initial_stackheap
__user_initial_stackheap

                LDR     R0, =  Heap_Mem
                LDR     R1, =(Stack_Mem + USR_Stack_Size)
                LDR     R2, = (Heap_Mem +      Heap_Size)
                LDR     R3, = Stack_Mem
                BX      LR
                ENDIF

                END

Unfortunately I am just starting to learn assembly, so I have no idea what this code does, but more important how to fix the problem.
Here problematic line
; Enter the C code

                IMPORT  __main
                LDR     R0, =__main
                BX      R0

                IF      :DEF:__MICROLIB

                EXPORT  __heap_base
                EXPORT  __heap_limit

                ELSE

As I can guess here main function is being called, but as far as I am writing assembly program, it throws me an error that I have no section main.
What is the correct way to start execution of my custom code from this startup.
I know that I can name my area RESET and it will goes here, but I want to do this in right way.
Thank you.
UPDATE
This code works just fine
        AREA Factorial, CODE, READONLY
        EXPORT __main
        ENTRY
__main
        MOV r0, #10 ; load initial value
        MOV r1, #1 ; if n=0 than 1 is result
loop    CMP r0, #0 ; if n=0
        MULGT r1, r0, r1
        SUBGT r0, r0, #1
        BGT loop
stop    B stop ; stop program
        END

Thank you
But only one warning
.\Objects\SortingAlgorithm.sct(8): warning: L6314W: No section matches pattern *(InRoot$$Sections).

A: Actually all that code is used to initialize the processor (set a stack for your push/pop operations, set vector for exceptions, clocks...) and initialize the "C" runtime (prepare a heap, initialize the variables for the runtime etc), but in general you can forget about these things. Please note that
Nevertheless, all the programs in "C" starts with a function called "main" or really "_main", so that piece of code is looking for a symbol called on that way.
If you get your example code and declare a public label called "_main", you should be able to execute your code when your target (your board) boots!
So, something like that should make it work:
   AREA Prog1, CODE, READONLY
EXPORT  __main
;        ENTRY  <= You do not need to declare an entry point
__main
    MOV r0, #0x11 ; load initial value
    LSL r1, r0, #1 ; shift 1 bit left
    LSL r2, r1, #1 ; shift 1 bit left
stop    B stop ; stop program
    END

Please note that I did not test that code! But as an starting point you can start with this.
Regards

A: That is not an important issue, nevertheless if you do not like to see it, just rename your section as follows:
AREA InRoot$$Sections, CODE, READONLY
;    AREA InRoot, CODE, READONLY <= Maybe that is the syntax
EXPORT  __main
ENTRY
 __main
     MOV r0, #0x11 ; load initial value
     LSL r1, r0, #1 ; shift 1 bit left
     LSL r2, r1, #1 ; shift 1 bit left
 stop    B stop ; stop program
     END

(Once again, I did not test that, it may be that the section have to be called just "InRoot")
Hope it helps!


text:
Q: How to use dispatch_queue_set_specific() and dispatch_get_specific() I'm having a hard time finding good examples on how to use these functions.
static void * kQueue1Key = "key1";
static void * kQueue2Key = "key2";

dispatch_queue_t queue1 = dispatch_queue_create("com.company.queue1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("com.company.queue2", DISPATCH_QUEUE_SERIAL);

dispatch_queue_set_specific(queue1, kQueue1Key, (void *)kQueue1Key, NULL);
dispatch_queue_set_specific(queue2, kQueue2Key, (void *)kQueue2Key, NULL);

dispatch_sync(queue1, ^{
    if(dispatch_get_specific(kQueue1Key))
    {
        NSLog(@"I'm expecting this line to run (A)");

        dispatch_sync(queue2, ^{

            NSLog(@"I'm expecting this line to run (B)");

            if(dispatch_get_specific(kQueue2Key))
            {
                if(dispatch_get_specific(kQueue1Key))
                {
                    NSLog(@"I'm expecting this line to run (C)");
                }
                else
                {
                    [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
                }
            }
            else
            {
                [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (B)"];
            }
        });
    }
    else
    {
        [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (A)"];
    }
});

Result
I'm expecting this line to run (A)
I'm expecting this line to run (B)
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Should not end up here (C)'

Is it expected behavior? If I were to dispatch_sync to queue1 since I'm not on the queue I would deadlock. What am I missing?

A: As mentioned in my comment, recursive locking using dispatch_sync is, in the general case, not possible due to the possibility of non-default queue targeting. For what it's worth, given/assuming default queue targeting, here is one possible approach:
#import <unordered_set>
#import <pthread.h>

static dispatch_once_t recursiveLockWithDispatchQueueTLSKeyOnceToken;
static pthread_key_t recursiveLockWithDispatchQueueTLSKey;
typedef std::unordered_multiset<const void*> RecursiveLockQueueBag;

static void freeRecursiveLockWithDispatchQueueTLSValue(void* tlsValue)
{
    RecursiveLockQueueBag* ms = reinterpret_cast<RecursiveLockQueueBag*>(tlsValue);
    if (ms) delete ms;
}

static inline BOOL queueStackCheck(dispatch_queue_t q, BOOL checkAndPushNotPop) // If yes, check and push if not on. If no, pop.
{
    dispatch_once(&recursiveLockWithDispatchQueueTLSKeyOnceToken, ^{
        pthread_key_create(&recursiveLockWithDispatchQueueTLSKey, freeRecursiveLockWithDispatchQueueTLSValue);
    });

    RecursiveLockQueueBag* ms = reinterpret_cast<RecursiveLockQueueBag*>(pthread_getspecific(recursiveLockWithDispatchQueueTLSKey));
    if (!ms)
    {
        ms = new RecursiveLockQueueBag();
        pthread_setspecific(recursiveLockWithDispatchQueueTLSKey, reinterpret_cast<const void*>(ms));
    }

    const void* const vpq = reinterpret_cast<const void*>((__bridge const void*)q);

    BOOL alreadyOn = NO;

    if (checkAndPushNotPop)
    {
        alreadyOn = (ms->count(vpq) > 0);
        if (!alreadyOn)
        {
            ms->insert(vpq);
        }
    }
    else
    {
        ms->erase(vpq);
    }
    return alreadyOn;
}

void dispatch_recursive_sync(dispatch_queue_t queue, dispatch_block_t block)
{
    if (queueStackCheck(queue, YES))
    {
        block();
    }
    else
    {
        @try
        {
            dispatch_sync(queue, block);
        }
        @finally
        {
            queueStackCheck(queue, NO);
        }
    }
}

@implementation MyAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    dispatch_queue_t a = dispatch_queue_create("a", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t b = dispatch_queue_create("b", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t c = dispatch_queue_create("c", DISPATCH_QUEUE_SERIAL);
    //dispatch_set_target_queue(a, c);

    dispatch_recursive_sync(a, ^{
        dispatch_recursive_sync(b, ^{
            dispatch_recursive_sync(c, ^{
                dispatch_recursive_sync(a, ^{
                    dispatch_recursive_sync(b, ^{
                        dispatch_recursive_sync(c, ^{
                            dispatch_recursive_sync(a, ^{
                                NSLog(@"got there");
                            });
                        });
                    });
                });
            });
        });
    });

}

@end

This is the lowest-overhead implementation I could think of in a few minutes. I used C++ to avoid message sending overhead. It requires that all uses of the queue use this function. This can be useful when there's a private queue protecting internal state of an object (i.e. where the queue is private and therefore guaranteed not to be retargeted, and where you can easily ensure that all consumers of the queue use dispatch_recursive_sync.

A: Oh here, it popped into my head why you're getting what you're getting. Notes in line:
dispatch_sync(queue1, ^{

When you get to this point, the "current queue" is queue1
    if(dispatch_get_specific(kQueue1Key))

You're asking the current queue for the value it has for kQueue1Key, you set that earlier, so it gives it back to you.
    {
        NSLog(@"I'm expecting this line to run (A)");

        dispatch_sync(queue2, ^{

When you get to this point, the "current queue" is now queue2
            NSLog(@"I'm expecting this line to run (B)");

            if(dispatch_get_specific(kQueue2Key))

You're asking the current queue for the value it has for kQueue2Key, you set that earlier, so it gives it back to you.
            {

                if(dispatch_get_specific(kQueue1Key))

You're now asking the current queue for the value it has for kQueue1Key. Since the current queue is queue2 and you never set a value with kQueue1Key on queue2 you get back NULL.
                {
                    NSLog(@"I'm expecting this line to run (C)");
                }
                else
                {
                    [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
                }

The misunderstanding here is that dispatch_get_specific doesn't traverse the stack of nested queues, it traverses the queue targeting lineage. For instance, if you did this instead,
static void * kQueue1Key = (void*)"key1";
static void * kQueue2Key = (void*)"key2";

dispatch_queue_t queue1 = dispatch_queue_create("com.company.queue1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("com.company.queue2", DISPATCH_QUEUE_SERIAL);

dispatch_queue_set_specific(queue1, kQueue1Key, (void *)kQueue1Key, NULL);
dispatch_queue_set_specific(queue2, kQueue2Key, (void *)kQueue2Key, NULL);

// Set Queue2 to target Queue1
dispatch_set_target_queue(queue2, queue1);

dispatch_sync(queue2, ^{

    if(dispatch_get_specific(kQueue1Key))
    {
        NSLog(@"I'm expecting this line to run (A)");
    }
    else
    {
        [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
    }

    if(dispatch_get_specific(kQueue2Key))
    {
        NSLog(@"I'm expecting this line to run (B)");
    }
    else
    {
        [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
    }
});

...the targeting relationship is the one that gets traversed, not the stack relationship. It would be nice if there were something that traversed the stack relationship, but I'm not aware of anything (that you wouldn't have to implement yourself).


text:
Q: Complex impedance of a transformer I consider only an ideal transformer here (no leakage etc.).
Let L1 and L2 be the induction coefficients of the primary and secondary resp., and M be the mutual induction coefficient. Assume that the primary has n1 turns, and the secondary n2 turns.
Finally, assume that the secondary is connected to an (complex) impedance Z. What is the complex impedance of the primary ?
Put in another way, if we see the primary of the transformer whose secondary is wired to Z as a dipole, what is its complex input impedance?
I believe there should be such complex impedance, because all the components are passive and obey common law of induction.
After a lot of research on the web, I found only the following article that would provide approximatively an answer to this question; unfortunately, I found it unclear in many aspects:
Couplage magnétique etc.
Since this question is theoretical, everything I have not specified can be introduced as a parameter, and the question can be reduced if needed.
EDIT: The terms "ideal transformer" are contradictory with the finite values of L1 and L2 given in the question. Indeed, according to several documents, an ideal transformer is one for which L1 and L2 tend to infinity, while the ratio of the wires remains constant.
For such ideal transformers, the answer has been given by user1582568. For non ideal transformers (L1 and L2 have finite values), 3 formulae were derived mathematically in my own answer below: the first one is the general case (but is still theoretical because it neglects the inner resistance of the self, and other type of noises). The second one is for 100% coupling (but finite L1 and L2), and the third one is the ideal transformer already given.

A: The impedance seen at the primary will be Z * (n1 / n2)^2 .

A:
I consider only an ideal transformer here (no leakage etc.).

An ideal transformer with no leakage means unequivocally the coupling is 100%. This means that the impedance of the secondary is "transported" to the primary side by the turns ratio squared.

What is the complex impedance of the primary ?

If the primary has infinite impedance (a true power transformer/converter in the theoretical sense), then the impedance looking into that primary is as stated above but, the primary has a magnetization inductance totally defined in the question as L1: -

Let L1 and L2 be the induction coefficients of the primary and
  secondary resp.

Therefore the input impedance into the "L1" primary is the answer above but in parallel with the inductance L1.
L2 plays no part in the answer because L2 isn't "felt" by L1 when it is open circuit.

A: Well the key words "magnetically coupled equivalent circuit" of Lancovici has lead me to some hints. I found in a document (and this comes in fact from the very definitions) that we have the system
u1 = L1 d i1/dt + j w M d i2/dt
u2 = M d i1/dt + L2 d i2/dt
In the frequency domain, this gives
u1 = j w  L1 i1 + j w M i2
u2 = j w M i1 + j w L2 i2
Now, hoping my derivation is correct, we have
u2 = Z i2 ; substituting this value into the second equation, and eliminating i2 between the two equations, we get
u1 = ( j w L1 + (w^2 M^2)/(Z + j w L2) ) i1, hence the apparent impedance (first formula in the general case).
In the case where the coefficient of coupling k = M/(L1L2)^(1/2) is close (or equal) to 1, then reporting into the above equation leads to
u1 = ( j w L1 Z / (Z + j w L2) ) i1, hence the impedance of the primary in this case (second formula for 100% coupling).
Finally, in the so called case of an "ideal transformer" were L1 and L2 are very large while the ratio L2/L1 = a^2 remains constant (a can be shown to be the ratio of the number of wires in the primary and the secondary), then the previous formula reduces to
u1 = L1/L2 Z i1 = Z/a^2 i1. This coincides with the answer of user1582568 (third formula).


text:
Q: How to convert stringbuilder text and get pdf format file output in asp.net I'm using Visual Studio 2008 and I need to convert some stringbulider text and get pdf format output file on button click event..
Following is sample stringbuilder text.
StringBuilder reqReport = new StringBuilder();
reqReport.Append("
Five copies of your latest Passport size.
");
reqReport.Append("
Your certificates, testimonials etc. (in original with one photocopy)
");
reqReport.Append("
Residence & Identity proof required in Bank account opening process as per RBI guidelines.
");

I tried using itextsharp..
string html = reqReport.ToString();
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(pdfDoc, _xmlr);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Table.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

This creates the pdf file.. But when I try to open the file, it shows the the file is either corrupted or damaged and could not be opened..
Is there any other format to do the function..?
Thanks in advance...


text:
Q: Can't make XPath to work with complex namespaces Let's start with an XML like this one:
<?xml version="1.0" encoding="UTF-8"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2009-11-26T15:21:36Z" uuid="02334fb6-3ae8-4094-9279-29ff59fc5bc8">
    <config xmlns="http://www.xfa.org/schema/xci/2.6/">
        ...
    </config>
    <template xmlns="http://www.xfa.org/schema/xfa-template/2.6/">
        <subform name="movie" w="196.85mm">
            <field name="duration" y="11.7mm" x="2.175mm" w="62mm" h="9mm">
                ...
            </field>
            <field name="imdb" y="11.7mm" x="65.675mm" w="62mm" h="9mm">
                ...
            </field>
            ...
            <subform name="directors" layout="tb" x="2.175mm" y="30.75mm" w="95.25mm">
                ...
                <field name="director" w="91.075mm" h="9mm">
                    ...
                </field>
                ...
            </subform>
            ...
        </subform>
        ...
    </template>
    ...
</xdp:xdp>

(For those who are wondering, it's a simplified version of the XFA document of the PDF used in this iText example.)
Now I want to get all the <field> elements in a NodeList, and XPath would be perfect for the purpose:
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
    public String getNamespaceURI(String p) {
        return "http://www.xfa.org/schema/xfa-template/2.6/";
    }
    public String getPrefix(String arg0) {return null;}
    public Iterator<?> getPrefixes(String arg0) {return null;}
});
NodeList fields = (NodeList)xpath.evaluate("//field", document, XPathConstants.NODESET);

Now that doesn't work, the result is empty. I've tried returning null in getNamespaceURI too; also returning "http://ns.adobe.com/xdp/" if the prefix is "xdp" and null otherwise.
I've also tried getting the <template> element manually and using evaluate from that node, with the above NamespaceContext or with getNamespaceURI returning null...
Nothing seems to work with this over-complicated system, and I don't want to keep on trying without getting a clue of what I'm doing wrong.

A: You should use a prefix in your path e.g. //df:field and then of course make sure that prefix is bound to the namespace URI e.g.
xpath.setNamespaceContext(new NamespaceContext() {
    public String getNamespaceURI(String p) {
      if (p.equals("df")) {
        return "http://www.xfa.org/schema/xfa-template/2.6/";
      }
    }
    public String getPrefix(String arg0) {return null;}
    public Iterator<?> getPrefixes(String arg0) {return null;}
});


text:
Q: Setting up a MC server on Ubuntu Server 19.04 I'm trying to setup a Minecraft server of my own. I've successfully done so before on Windows, but since the new server will be always on and headless (remote access only, no screen or other peripherals attatched), I decided to use Ubuntu instead. Figured it couldn't be too different, but I was wrong.
Google isn't much of a help: every tutorial starts with a list of dependencies to install, and every tutorial has a different list.
On Windows, it was as simple as installing a JRE and downloading and running the server.jar. I don't see why I need a JDK, and why I specifically need a headless JDK. I also don't understand why I would need the Screen package on a displayless server.
Of course, none of the tutorials actually explain WHY I need those dependencies, or what they do. I'm no security expert, but I refuse to install a random list of programs just because a site tells me it will work. Therefore, I'd like to ask what dependencies I NEED to install, and why?
Any other help or tips are also appreciated.
Thanks in advance.

A:
Therefore, I'd like to ask what dependencies I NEED to install, and why?

You only need the JRE (preferably Java 8). This is the openjdk-8-jre-headless package on Ubuntu. You can download the server file on minecraft.net.
Then you run it like this:
$ java -Xmx1024M -Xms1024M -jar server.jar nogui

Where

*

*-Xmx1024M says that the server can use no more than 1024MB.

*-Xms1024M says that the server initially starts with 1024MB.

*server.jar is your Minecraft Server jar that you dowloaded

*nogui specifies that the gui is not opened. This is needed for headless since it can't open if there is no window manager.


text:
Q: How can I store a timestamp in a DBM database? I am implemening simple file-sharing service. Currently I use a file-based database (as it suits my needs).
   # somewhere in my cgi script
   sub first_run
    {
      my $dbh = DBI->connect('dbi:DBM:');
      $dbh = DBI->connect("dbi:DBM:", "", "",{ AutoCommit => 1, RaiseError => 1, f_dir=>$DATABASE_DIR} );
      unless ($dbh)
      {
        print "<br>Cannot connect: $DBI::errstr";
        return undef;
      }
      $dbh->do("CREATE TABLE uploads( user_name TEXT,
        file_name TEXT,
        upload_date TEXT ) ");
      $dbh->disconnect( );
    }

As you can see I propose to store the upload timestamp as a string, since currently I only have to display it (suppose to use localtime() to get timestamp in a human readable format).
But this seems to me somewhat bad. What if later I'll want to show uploads from some period, etc.
What is the common way of storing timestamps in a DBM database without using third-party, CPAN modules? How can I pull them later and show them to the user (in my situation, convert back to string)?

A: Consider that storing UTC time is less ambiguous than storing local time. If you save a time at your computer in London and send me the file in Hong Kong, will I when I load the file in your program see the time you actually saved?
Consider that in storing UTC time you have (at least) two choices: the formatted time string, or a count of numbers of (seconds/milliseconds/whatever) since a particular time ("the epoch"). Presumably either format is isomorphic with the other, as there is a well-defined bi-directional conversion rom one to the other.

A: I would just store the epoch, it's easy to then display it with *localtime* or *strftime*.
 If you really want to be able to browse the content of the DB without having to convert back the epoch, you could store both the numerical value and the *localtime* string (" `1238693517 - Thu Apr  2 19:31:57 2009`"). This makes the data redundant and denormalized, but also makes it easy to inspect, while still being able to process the numerical value. Your call.


text:
Q: How to get indexes of all maximum values in python multidimensional np array I would like to get all indexes of maximum values for each row from ndarray.
For example, i have
arr = np.array([[1, 3, 3], [1, 5, 4]])

And i would like to get indexes of all 3's from first row, and all 5's from second row.
np.where(((arr == arr[0].max()) | (arr == arr[1].max())))

And it returns
(array([0, 0, 1], dtype=int64), array([1, 2, 1], dtype=int64))

I want something like that but more universal for any amount of rows.
Because np.where(arr == arr.argmax()) doesn't work like i want it to work. It only returns indexes of first maxium that it met in each row.

A: @Paul's answer in comments might be the best you can find. Writing it for readers. arr.max(1) find max in each row and arr==arr.max(1,keepdims=True) finds all elements in each row that are equal to corresponding max in that row. Finally nonzero returns indices of those elements:
(arr==arr.max(axis=1,keepdims=True)).nonzero()

output for OP's example:
(array([0, 0, 1]), array([1, 2, 1]))


text:
Q: Fourier Transform one the problems from my book, states the following:
Find the Fourier Transform of:
a) $$\frac{1}{2\pi(a-jt)^2}$$
the solution for it is -> \$\omega e^{-a\omega} \mathrm{u}(\omega)\$
I know there exist a relation such that \$1/(a+jt)^2\$    is F.T of \$te^{-at}  \mathrm{u}(t)\$. what happens to the \$1/2\pi\$ part? I don't understand how they manipulate it such that they are able to use the Fourier Table they have in the book.

A: I haven't been doing math for a long time. Though I think you've already found most of the answer.
I don't remember all the Fourier tables but if what you say is correct, then if you suppose that ω = 2πf you finally have your solution.
\$2πf e^{-2πfa} \mathrm{u}(f)\$ which is \$\omega e^{-\omega a} \mathrm{u}(\omega)\$


text:
Q: "Recycled user" creates C:\Users\TEMP on logon An employee left, and was replaced by another to fill the exact same position. Since this employee used the exact same permissions on the network, had no personal files on the local C:, I just renamed the account on the Primary Domain Controller, deleted the local account on the machine, and deleted the user's local folder (i.e. inside C:\Users)
However, now when I logon with that "recycled" (renamed) user, Windows create C:\Users/TEMP every time.
How do I tell Windows not to do that and create the proper user's directory?

Edit
The user is not member of "Guest" or "Domain Guest".

A: Just deleting the folder is not how you remove a user profile from a Windows PC; so you've corrupted the profile and as such it's loading a temporary profile instead.
For information on how to properly remove a domain-based user profile, and how to clean up a half-deleted profile, see this existing SU question: How do I delete a user profile on a Windows 7 machine that is part of a domain?


text:
Q: compile error: Supertypes of the following classes cannot be resolved I have a gradle project with proto3 generator:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("com.google.protobuf:protobuf-gradle-plugin:0.8.14")
    }
}
...

dependencies {
  ...
  implementation("com.google.protobuf:protobuf-java:$protoBufCoreVersion")
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:$protoBufCoreVersion"
    }
}

Also, I have config for adding generated source code to classpath:
   tasks.register<Jar>("sourcesJar") {
        from(sourceSets.main.get().allSource)
        archiveClassifier.set("sources")
    }

    publishing {
        publications {
            create<MavenPublication>("mavenJava") {
                from(components["java"])
                artifact(tasks["sourcesJar"])
            }
        }
    }

Finally, when all source code generated from protobuf models, I can see it in a classpath and import it in unit tests. But when I'm trying to run build or manually run unit test, next error happened:
Trying to invoke builder manually in unit tests:
@Test
fun test() {
   Device.newBuilder() // compile error
}

Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class my.project.model.request.Device, unresolved supertypes: com.google.protobuf.GeneratedMessageV3
    class my.project.model.request.DeviceOrBuilder, unresolved supertypes: com.google.protobuf.MessageOrBuilder
Adding -Xextended-compiler-checks argument might provide additional information.

Where Device - just a simple model:
message Device {
  string id = 1;
  Type type = 2;
  optional string manufacturer = 3;
  optional string model = 4;
  optional string software = 5;
}

Which generated into next java class:
public final class Device extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:source.request.Device)
    DeviceOrBuilder {
private static final long serialVersionUID = 0L;
...
 @java.lang.Override
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

How can I use generated models in a test?

A: The problem turned out to be a transitive dependency, the thing is that the required module was not exported as a JAR module in the module with tests, because there was no next dependency: implementation("com.google.protobuf:protobuf-java:$protoBufCoreVersion")


text:
Q: Modifying Boyer Moore for multiple pattern search I have used Boyer Moore algorithm according to this site. This implements pattern search in the text for only once and the program exits. Can anyone help me to modify this code in order to find the pattern multiple times with their starting and ending index?
    public class BoyerMoore {
        private final int R;     // the radix
        private int[] right;     // the bad-character skip array
        private String pat;      // or as a string

        // pattern provided as a string
        public BoyerMoore(String pat) {
            this.R = 256;
            this.pat = pat;

            // position of rightmost occurrence of c in the pattern
            right = new int[R];
            for (int c = 0; c < R; c++)
                right[c] = -1;
            for (int j = 0; j < pat.length(); j++)
                right[pat.charAt(j)] = j;
        }

        // return offset of first match; N if no match
        public ArrayList<Integer> search(String txt) {
            int M = pat.length();
            int N = txt.length();
            ArrayList<Integer> newArrayInt = new ArrayList<Integer>();
            int skip;
            for (int i = 0; i <= N - M; i += skip) {
                skip = 0;
                for (int j = M-1; j >= 0; j--) {
                    if (pat.charAt(j) != txt.charAt(i+j)) {
                        skip = Math.max(1, j - right[txt.charAt(i+j)]);
                        break;
                    }
                }
                if (skip == 0)
                    newArrayInt.add(i);    // found
            }
            return newArrayInt;                       // not found
        }

        // test client
        public static void main(String[] args) {
            String pat = "abc";
            String txt = "asdf ghjk klll abc qwerty abc and poaslf abc";

            BoyerMoore boyermoore1 = new BoyerMoore(pat);

            ArrayList<Integer> offset = boyermoore1.search(txt);

            // print results
            System.out.println("Offset: "+ offset);

 }
}

A: I got it. The skip was always 0 when it found the pattern in the text.
public class BoyerMoore {
    private final int R;     // the radix
    private int[] right;     // the bad-character skip array
    private String pat;      // or as a string

    // pattern provided as a string
    public BoyerMoore(String pat) {
        this.R = 256;
        this.pat = pat;

        // position of rightmost occurrence of c in the pattern
        right = new int[R];
        for (int c = 0; c < R; c++)
            right[c] = -1;
        for (int j = 0; j < pat.length(); j++)
            right[pat.charAt(j)] = j;
    }

    // return offset of first match; N if no match
    public ArrayList<Integer> search(String txt) {
        int M = pat.length();
        int N = txt.length();
        ArrayList<Integer> newArrayInt = new ArrayList<Integer>();
        int skip;
        for (int i = 0; i <= N - M; i += skip) {
            skip = 0;
            for (int j = M-1; j >= 0; j--) {
                if (pat.charAt(j) != txt.charAt(i+j)) {
                    skip = Math.max(1, j - right[txt.charAt(i+j)]);
                    break;
                }
            }
            if (skip == 0)
            {
                newArrayInt.add(i);    // found
                skip++;
            }
        }
        return newArrayInt;                       // not found
    }

    // test client
    public static void main(String[] args) {
        String pat = "abc";
        String txt = "asdf ghjk klll abc qwerty abc and poaslf abc";

        BoyerMoore boyermoore1 = new BoyerMoore(pat);

        ArrayList<Integer> offset = boyermoore1.search(txt);

        // print results
        System.out.println("Offset: "+ offset);
    }
}

A: public class Boyer {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner get= new Scanner(System.in);
      String m,n;
      int i,j;
      String T,P;
      T=get.nextLine();
      System.out.println("Text T is"+T);
      P=get.nextLine();
      System.out.println("Pattern P is"+P);
      int n1=T.length();
      int m1=P.length();
      for(i=0;i<=n1-m1;i++){
           j=0;
          while(j<m1 && (T.charAt(i+j)==P.charAt(j))){
               j=j+1;
               if(j==m1)
                   System.out.println("match found at"+i);
          }
      }
    }
}


text:
Q: What are some useful SQL statements / usage patterns that should be known by all developers who may touch the Back end side of the project? What are some useful SQL statements that should be known by all developers who may touch the Back end side of the project?
(Update: just like in algorithm, we know there are sorting problems, shuffling problems, and we know some solutions to them.  This question is aiming at the same thing).
For example, one I can think of are:

Get a list of Classes that are not
  registered by any students.  (Outer
  join and check whether the match is
  NULL, or by Get from Classes table,
  all ClassIDs which are NOT IN (a
  subquery to get all ClassIDs from the
  Registrations table))

Are there some SQL statements that should be under the sleeve of all developers that might touch back end data?

A: Hmm generalizing what types of queries you should be able to write.

*

*First a straight up select with no
joins (and no select *)

*You should know how to combine two
or more tables and get records that
are in all the tables

*You should know how to combine two
or more tables and get records that
are in all the tables but return
only one record from the table with
the many side of the one-to-many
relationship

*You should be able to get the
records in one table but not in an
associated table

*You should be able to Aggregate data
for a report

*You should be able to insert one
record to a table

*You should be able to update one
record in a table

*You should be able to delete one
record in a table

*You should be able to insert a group
of records to a table without a
cursor

*You should be able to update a
 group of records in a table without
 a cursor

*You should be able to delete a
 group of records in a table without
 a cursor

*You should be able to perform
 multiple actions in one transaction
 and handle error trapping

*You should be able to create union
 of records and know when to use
 UNION vice UNION ALL

*You should be able to vary the data
 for one field based on some
 criteria (using CASE)

*You should be able to write an IF
 Statement.

Well that's what springs to mind immedaitely. This is for a beginner SQL developer of course. This includes nothing I would consider advanced.

A: Developers should learn the principles of databases and SQL. Not any specific SQL statements as SQL statements required will change depending on what the database stores and the structure of the database.
Update: Your updated question is interesting. I am thinking SQL statements in general are quite simple. So they are not worth memorising. If they are complex then they are tied to a specific problem and again are not worth memorising.


text:
Q: I can't draw. How can I make polished applications? I'm not a graphic designer. I'm pretty bad at drawing anything. I struggle to build things that look even as nice as "sample" applications bundled with development tools; primarily because I don't have squat in the way of art assets.
What strategies might I take to mitigate this?

A: If you're looking for graphical assets there are a few websites which collect high-quality graphics for free use:

*

*Bootstrap for arguably the best (but definitely the hottest right now) UI web framework

*Glyphicons for an icon set that complements Twitter's Bootstrap UI framework

*Subtle Patterns for, well, subtle background patterns

*FamFamFam's Silk icons which get used in a lot of software all over

*Creative Market for diverse elements

And many more, such as the GNOME art project which includes lots of free graphical assets as well.
Not being the least bit creative, and having no education in design, I always strive on the side of conservativism: use established patterns (i.e. frameworks) and deviate as little as possible from trodden paths. This won't necessarily be very interesting but at least you minimise your chance of failure and UX disaster.
Picasso said that "great artists steal" but in reality it's mostly the talentless hacks, and look where this has led Microsoft and Samsung: to great-selling platforms.

A: You can hire specialists for this sort of thing, but you don't need innate artistic ability to learn some basic techniques.  My undergrad degree actually required a semester of "art for engineers."  Taking a class or two at your local community college could be very beneficial.  You still won't be as good as people specially trained in the field, but you can definitely improve to the point where your programs look more professional.
There are also books geared toward relative amateurs.  One book I found useful for web design is The Principles of Beautiful Web Design by Jason Beaird.  Even if your designs don't improve much, getting a little education can help you better verbalize what's wrong with a design.  Instead of always saying, "I know it looks bad, but I can't figure out why," you'll be able to pinpoint problems like bad kerning or a lack of negative space, and defining the problem is half the battle.

A: What you might be looking for is "UI/UX Design for Developers".  One book related to this topic is User Interface Design for Programmers
If you're not looking for UI/UX design but looking to improve graphic design skills, I would recommend finding a class on how to use Adobe Photoshop or Adobe Illustrator (if not, at least some tutorials on the internet).  By learning a few techniques and looking at other people's work for inspiration, you would be surprised how little artistic creativity you need.
For example, you could learn the Gradient Tool in Photoshop, along with the Rounded Rectangle tool, and you could make something similar to the "Sign up for the newsletter" button on the right (although in this case it's done with pure CSS).

A: I personally do not think you have to be good artistically to create pleasing user interfaces.
What makes a good UI is not up to creativity, but is more related to a couple of well-established guidelines. If you follow these guidelines and practice some you can create great interfaces yourself.
I would suggest doing the following...

*

*Read about what makes a good user interface. (online mostly)

*Research and find some user interfaces that are pleasing to you.

*Compare several good designs and try to pick out things that are similar between them.

*Now look at your own design and see if you have those elements.

*Try to recreate your user interface to be similar to the ones you liked.

I forecast that if you do this exercise for a week or two (and if you ask me, a week or two to learn how to design good interfaces is not such a long time), you will learn most of what makes a good user interface.
Just a couple of things I found that make user interfaces pleasing:

*

*Simplicity

*Consistency (colors, fonts, usage of buttons, links, etc...)

*Spacing

*Less is more (hide as much as you can from the user without diminishing usability)

*Do not use white background and black font. Make sure the contrast is good enough, but usually change your background to a light shade of gray while your font to be dark gray.

Also... do not start with the design. Start with functionality and let the design evolve. Also, experiment! Do not get upset if it does not look perfect after 1-2 'iterations'. It gets better over time. But most importantly, you have to try.

A: My art ability is about 5th grade on a good day:). I employ a graphic designer, either
professionally when at work, or my wife, who has excellent art skills and loves using them.
Note that in my mind Graphics design is not UI/UX design. I either do a majority of UX, or employ a UX expert to retain control of UX, who then works with the GD to make it look pretty. Although I am sure there are good combined UX/GD professionals, I have had very bad experiences with GDs doing stuff that looked pretty, had very bad UX, and was outdated in a couple of months, and won't take that risk until I have worked with the GD for a couple of projects.

A: Let others "do the work for you" in the form of using frameworks, templates and pre-built gui components. For example I can't draw or design are either so for every new web project I do I start off with a css template (from the many free css template sites) for the layout and design and then 'tweak' it from there.
These templates include a complete design that can help you address this gap.
I agree with c_maker in that good usability is good design, although it sounds you are being more specific on the 'arty' designy end.
If you are doing web design and layout work here are some of those css sites:
http://www.freecsstemplates.com/
http://www.templatemo.com/
http://www.free-css.com/
http://www.oswd.org/
http://www.openwebdesign.org/


text:
Q: Error when creating a static field I created a static field c on my class but it generated an error saying illegal start of expression.
Please help me to solve this problem.
public static void main(String[] args) {

    System.out.println("program started.");
    static Controller c; //Where the error is

    try {
        Model m = new Model();
        View v = new View();
        c = new Controller(m,v);
        c.sendDataToView();
        c.showView();
    } catch(Exception ex) {
        System.out.println("error");
    }
}

A: You cannot declare a static field (or any other field, for that matter) inside a method, even if it is a static one.
You can either declare a static field outside the method:
static Controller c;
public static void main(String[] args) {
    System.out.println("program started.");

    try {
       Model m = new Model();
       View v = new View();
       c = new Controller(m,v);
       c.sendDataToView();
       c.showView();
    }catch(Exception ex) {
        System.out.println("error");
    }
}

Or a plain old fashioned local variable:
public static void main(String[] args) {
    System.out.println("program started.");

    Controller c;
    try {
       Model m = new Model();
       View v = new View();
       c = new Controller(m,v);
       c.sendDataToView();
       c.showView();
    }catch(Exception ex) {
        System.out.println("error");
    }
}

A: You can't declare a static field inside a method.
Move it outside :
static Controller c;

public static void main(String[] args)
{
    System.out.println("program started.");
    try {
        Model m = new Model();
        View v = new View();
        c = new Controller(m,v);
        c.sendDataToView();
        c.showView();
    } catch(Exception ex) {
        System.out.println("error");
    }
}


text:
Q: make images change opacity after hovering over separate text with React in the process of learning React and making a small practice website. On one of my pages i've got a CSS Grid with a central grid square that has text in it and surrounding the text are multiple images. In the text i've put spans on certain words to make them different colour and each word has a corresponding Image around it somewhere.

          {/* About Heading Sq */}

                About

                me

                  Born: 1992

                  Graduated Highschool

                  Lived in Europe for a Year

                  Worked As A Waiter

                  Loves Working in The Garden

                  Worked as a Tiler/Landscaper

                  Became a Student at 42: 2020

                  Trainee Software Engineer at SRA: 2022

          {/* highschool */}

          {/* 42 */}

          {/* born */}

          {/* tradie */}

          {/* waiter*/}

          {/* travel */}

          {/* garden */}

This is what my code is currently set out like
What i want to do is make it so that onHovering over one of the span words the corresponding image will change from opacity 0 to 1. I'm very unclear on how to achieve this, if i need to useState or use onHover and using events or what. Some clarity on which way to go would be greatly appreciated.

A: You can use the onMouseEnter and onMouseLeave events to set state to a specific number, name or id, which can then be used to change the opacity of the corresponding image with that number, name or id.
Initiate the state as follows:
const [hoveredImage, setHoveredImage] = useState("")

Then, at each span, create events that trigger a change in state like:
 setHoveredImage("born")} onMouseLeave={() => setHoveredImage("")}>Born

Finally, use the state to change the opacity of the images:
{/* born */}


text:
Q: Is a VeraCrypt partition slower? I just got a new external hard drive. I want to create an encrypted partition on it with VeraCrypt. I did the same thing with a similar drive. I just copied a file over to it and the speed was about 100 MB/s. The other drive's speed, after encryption, was much lower, maybe 10 MB/s. I don't know what the drive's original speed was though.
Does this mean that an encrypted partition is slower than an encryption that's not encrypted, even after mounting it? Does it actually encrypt the newly copied files while it's copying, slowing down the copying operation massively?

A: My tests with a USB 3.1 Gen 2 Type C hard disk (able to write at 10Gib/s, aka a little more than 1GiB/s) is:

*

*Encrypted with TrueCrypt, veraCrypt, DiskCryptor or any other will make read and write to be much more slower, the best i got is arrond 100MiB/s (one tenth of non encrypted), so encryption makes it to be ten times slower.

*Copying a huge big large file (more than 600GiB file) on non encrypted fly, took a little less than 10 minutes), copying a huge amount of really very small files (with write cache on) makes same speed, please note that write such huge amount of really very small files without write cache tooks forever, aka speed goes down to a 1KiB/s (yes kilobyte), all theese tests without encryption.

*With VeraCrypt encryption, speed can not be 1GiB/s, and goes down to arround 100MiB/s, CPU is not enought fast, among it has 64 cores (i will explain it later how to improve it)... but, copying small files makes speed goes down to near 1KiB/s with write cache on... it is VeraCrypt fault... seems that it is not allowing caching the NTFS that is seen by windows, and Windows only can cache writes done to the HDD itself.

Oh, yes i had been very afortunated i could had (for some days only) a mainboard with 4 sockets and 4 microprocessors with 16 cores each, so a total of 64 cores... and RAM, wow! it was 32GiB of ram in 4 sections, each one near to each processor socket with 4 banks each and a 2GiB ram on each bank 4Sections*4Banks/section*2GiB/Bank=32GiB... the fastest PC i had ever touch.
In other words:

*

*Windows have write cache enabled (for the USB device), if not encrypted that cache improves a lot the small files writes.

*VeraCrypt seems to not allow windows to cache writes to the NTFS, because there is no way to Enable/Disable such cache, and small files writes is very, very slow.

I had tested with other Encryption software (very expensive) that emulates a whole SAS controller (yes Serial SCSI) and also emulates a whole HDD connected to it... so on windows you can enable and disable its write cache... with that software writting small files is as fast as writting a big file (if such write cache is enabled on windows).
I am talking about windows write cache, so i will explain how to enable/disable it for people that do not know how:

*

*Open explorer and go to where you can see root folder of partitions mounted, C:, D:, etc.

*Select any of thoose, right click and go to properties.

*Go to Hardware and select the device on the list (here is the problem with VeraCrypt, it does not create a virtual controller).

*Clik on Properties button.

*On the General tab click on the button to change the configuration.

*Now go to tab for directives.

*There you can select to fast extract (write cache off) or to better performance (write cache on).

Remember if write cache is on, do not unplug without windows informing you can safely eject it... after asking for safe remove.
Well, that cache affects only to write operations done on the device, since the device is the physical one, it means for encrypted data written to the HDD, not for un-encrypted data written to the NTFS estructure.
So what happens? Windows writes to the NTFS estructure without write cache, then VeraCrypt do the encryption (yes pipelined) and send the encrypted data to the HDD, then Windows see the device has write cache on so waits a little to write the data... but modifing the NTFS estructure is done without cache... so in practice windows is asking VeraCrypt for encrypting the same structure a lot of times (when small files are written) in a short period of time... so VeraCrypt must encrypt a lot of times something that will be putted on the exact same cluster of the disk.
That causes a huge, very huge, slow down if compared with non-encrypted.
To whom belongs the fault? In part to Windows NTFS that do not cache estructure changes, in part to VeraCrypt for not emulating a device.
Such way of working of VeraCrypt (comes from TruCrypt, etc) causes another rare things, like SmartDefrag not able to see and defragment files on it (Piriform Deflagger can, so can be a bad algorithm on SmartDrefrag)... also BootIce see them as IFS: and not as HD#: or RM#:... some parttition manage apps are not even able to see it, etc.
Another side effect (for Linux people): In practice you can not format as Ext4 a VeraCrypt partition if you try on windows... at least all partition tools i tried that allow to create (i mean format) Ext4 partitions do not see VeraCrypt device (it is very normal as VeraCrypt does not emulate a device).
Among all this... for some BackUps (on Windows) i still use VeraCrypt and NTFS with compression enabled... and i do not enable physical device write cache (has no sence), why i want to cache writes of encrypted data... i want to cache NTFS modifications, not the data sent to the HDD... VeraCrypt uses a good write cache for such, so why double cache... the horrible part is Windows do not cache NTFS changes on RAM, only cache "Clusters" sent to disk.
And if you think putting veraCrypt encrypt engine on a more lower layer (nearest to HDD physical write) would gain something... wrong! the problem is this:

*

*One small file write to NTFS is asked

*Seach for empty entry on Dir occurs (in RAM)

*Write the new entry on Dir occurs (in RAM)

*Windows check device write cache (VeraCrypt does not emulate a device, so can not be consulted, so interpreted as there is no write cache on)

*Since windows think (non-encrypted part) has no write cache, sends DIR clusters to HDD

*VeraCrypt intercepts that and do the encryption (this is unnecesary if same clusters will be re-written in a near future, as occurs when writting a lot of small files on the same folder)

*VeraCrypt send encrypted data to the HDD

*Windows check if device (this time it is the real one, so can be consulted) and see write cache is on (or off)

*If was on, it do not write "encrypted" cluster to physical disk, it waits a little

*Got to step 1 for next file

That is the problem... steps 5 and next steps... they would not be done if NTFS has write cache... but VeraCrypt does not present the option for caching at that level.. to do that it would need to emulate a whole device.
So what happens is that the clusters where the folder list of files is stored is sent to VeraCrypt a lot of times, one per file; instead of sent if only once after all files are set in the directory.
Said with little words: the problem is encrypting a lot of times the same folder listing... think it as encrypting the whole text after you write each letter versus encrypting the whole text after you finish writting it... that makes things to go really slow (when a lot of changes are maded in a short period of time to the same folder, like adding a lot of small files).
Not to mention, this problem also affects file deletion... put more than ten thousand files on a folder on a not encrypted disk (with write cache on), delete them tooks less than a second (if write cache is off it tooks more than one hour), now do the same but having the partition encrypted and write cache on (yes, activated), delete so much files causes ten thousand times to encrypt the folder list of files, it also takes a lot on that same disk (quite near as if not encrypted without write cache).
So, to talk in general: Encryption can make operations go much more slower, not only caused by a slow CPU or high CPU usage by other process, etc. also because a write cache is missing for NTFS estructure changes and that cause encryption multiple times the information that would be stored on the same place.
Hope i could open the eyes of someone about encryption... and hope VeraCrypt (the best in terms of security i have ever seen) would activate a NTFS write cache prior to encryption... it is very easy to do, just difere encryption of any cluster a little and if before end such time comes another write to that cluster, just ignore previous non-encrypted data... so encryption is done only once... in other words... a dynamic buffer prior to encryption.
Bad part for that is ... power lost, abrupt shutdown, etc... will make size of lost info to be a little more big... as if you use a HDD with 1GiB cache without a battery, etc... it is allways the race between speed or ensure write is done... i preffer speed for that, let me explain why...
If copying one millon small files (all in the same folder; windows really hates that, you are advised) tooks only 10 minutes (with write cache on at all levels) versus one week (write cache off at all levels)... do the maths yourself... that data is real life times, obtained by my self on abnormal tests i had done in the past to the NTFS system (FAT32 was a lot faster).
The maths are: what is the risk of needing power for only ten minutes versus for one whole week? what much will i loose? in case cache is on, i can loose 1/600 of the data (more or less); in case the cache is off i can loose only the file it was working on at that moment... but in both cases i will need to do a compare (full compare since file name can be on dir, but content may differ), so i will need near the same time to ensure all is well copied... i preffer to waste 10 minutes, than need one week to compare and see what is miss or different content, etc.
And in general, if loose for you is not an option... just to start you would not be using windows, neither FAT32, NTFS, etc... would be using at least Linux and Ext3/4 (journaling) and a power generator, etc.
So, please VeraCrypt, put that write buffer of NTFS as soon as can be.
Final note: FAT32 is affected by the same concept... it is not only NTFS... it is the way windows asks for directoies changes when files are created or deleted.
Do this test to see how speed goes done... in a lop create ten thousand files of ZERO size... take note of the speed / time the first 100 takes, versus how much time tooks another 100 when in the middle or the end... you really will see one file per minute (in some not so high speed CPUs)... ah! do it on a ramdrive (to ensure HDD does not affect speed).
Now to finish... i could not resist to do the same tests on Linux (over a Ext4 partition that resides on a VeraCrypt volume)... remember on Linux all are devices... so VeraCrypt presents to the kernel a device... so write cache can be on on both levels, Ext4 level and physical cluster writting... and by default Linux have all them allways on.
In Linux it really flies... as supposed to do since write cache is on, on both devices, the one that is normally mounted on /media/veracrypt# and the one that is physical /dev/sd$# (if talking about encryption a physical partition).
But, hey, VeraCrypt does not have a write buffer for Ext4 changes, no, it is Linux the one that has it... also more important... the period of time something is not sent to disk is reset as soon as another write goes to it; some linux have a top limit and send the data to the disk passed that one, but other Linux do not and can not send data to disk for years, in case for example when a cluster is written twice per second, each second of a full year, that cluster on such year could never ever have been writted to physical disk.
So on Linux, is Linux the one that is not sending more than once, the folder list (if changes on it are made in short time, like creating a lot of files on same folder, as when copying, etc), so VeraCrypt will only do the encryption once, after all files are set inside the folder list of files... etc. A lot, lot faster, than encrypting the whole dir list of files after each file is added.
Finish think: Windows hates, Linux love... or not, Linux tends to loose a lot of info is power is lost, much more than Windows... just because it has write chache... what is better? speed? or be secure writes are done? took 10 minutes to copy all, or one week? some preffer one, others preffer other... it is up to you.
But at least, i hope i had clarified why copying a lot of small files can be so slow (in Windows of course) to an Encrypted container (disk, partition, file, etc.) versus to the physical device when not encrypted.

A: Modern CPU are very fast.. Even previous generation of AMD FX-8350 with hardware AES support performs 5Gb/s with VeraCrypt v1.19 AES-256.
Most likely 2nd USB drive cannot perform better. It can be for example USB 2.0 drive.
In any case I recommend to spend some time for tests side-by-side.. You will have much more information.. and maybe you will be able to help somebody else.

A: To further complete what's been said so far:
VeraCrypt seems to have serious performance-wise disadvantages compared to some other solutions (Here and here). The referenced pages are mainly titled "...SSD...", but the contents describe multiple cases of performance degradation with conventional HDDs and more complex configurations (RAID/etc.). The serious cases seem to be due to (a) suboptimal coding  or (b) security-savvy configuration decisions by VeraCrypt's community. The rest of this post is about (b).
IMPORTANT NOTE Some important parameters must be considered, investigated and normalized before comparing different solutions available:

*

*Some of the performance keep seen by other solutions might be due to the fact that they're (almost?) completely offloading the cryptographic operations to the device itself which is very bad esp. after some recent reports. See this and this from Microsoft. The disclosed research has been focused on BitLocker but some other solutions may be doing the same.

*More importantly, as others have pointed out, lower security margins can be the cause for some/most of performance improvement (e.g. fewer default hash iterations, smaller default key length, mode of operation, etc.).


text:
Q: mysql query choosing an incorrect execution plan I have a primary with an dependant subquery as a where condition that is choosing a wrong execution plan, and therefore is running for ever.
Main query:
SELECT  rtr.id AS id156_,
           rtr.procesada AS procesada156_,
           rtr.idTransaccion AS idTransa3_156_
FROM
   ReservasTiempoReal rtr
        INNER JOIN Transacciones t ON t.id=rtr.idTransaccion
        INNER JOIN TransaccionLineas tl ON tl.idTransaccion = rtr.idTransaccion
        INNER JOIN Productos prod ON prod.id=tl.idProducto
        INNER JOIN Proveedores prov ON prov.id=prod.idProveedor
WHERE t.confirmada = 'S'
    AND t.codTipoTransaccion = 'RTRCT'
    AND t.fechaHora >= '2015-01-20 15:30:59'
    AND t.fechaHora <= '2015-01-21 15:30:59'
    AND prov.id=77
       AND (EXISTS ( SELECT rtr2.id
                       FROM ReservasTiempoReal rtr2
                       INNER JOIN Transacciones t2 ON rtr2.idTransaccion = t2.id
                       WHERE t2.confirmada = 'S'
                                AND t2.codTipoTransaccion = 'ECTR'
                                AND t2.idTransaccionOriginal = rtr.idTransaccion));

And its execution plan:

In red is shown the used index using 'codTipoTransaccion' and 'confirmada' columns.
The first query (without the inner one) returns only 10 rows. But the whole transaction table has over 5 millon records. And most of them have the attribute confirmada = 'S'.
If I delete the index 'idxConfirmada' (index by 'confirmada' field) the query takes only 10 seconds to execute and the execution plan is:

Just to add more info, if I execute the dependent inner query only with the records identified in the primary query, it returns only 6 records. The used query was:
SELECT rtr2.id
FROM ReservasTiempoReal rtr2
      INNER JOIN Transacciones t2 ON rtr2.idTransaccion = t2.id
WHERE t2.confirmada = 'S'
      AND t2.codTipoTransaccion = 'ECTR'
      AND t2.idTransaccionOriginal IN (14748319,
14748519,14750327,14751060,14751126,14751351,14751354,14752902,14754752,
14754785)

I don't want to delete the 'idxConfirmada' index, I need the ORM to choose the correct plan. Also, I cannot use hints to ignore the index as the query is coming from hibernate.
How can I make mysql to choose the correct plan (not using idxConfirmada) ?
I am using MYSQL 5.1.51.
Added table details
CREATE TABLE `Transacciones` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `fechaHora` datetime NOT NULL ,
   `nroTicket` varchar(255) NOT NULL ,
   `puntosGenerados` decimal(19,2) DEFAULT NULL,
   `creditoPendiente` decimal(19,2) DEFAULT NULL,
   `debitoPendiente` decimal(19,2) DEFAULT NULL,
   `saldoReal` decimal(19,2) DEFAULT NULL,
   `idTransaccionOriginal` bigint(20) DEFAULT NULL,
   `codTipoTransaccion` varchar(5) DEFAULT NULL,
   `confirmada` varchar(1) NOT NULL,
   `nroLote` varchar(5) DEFAULT NULL,
   `idMonedaImporteFinal` bigint(20) DEFAULT NULL,
   `totalImporteFinal` decimal(19,2) DEFAULT NULL,
   `anulada` varchar(1) DEFAULT NULL,
   `idLote` bigint(20) DEFAULT NULL,
   `online` varchar(1) DEFAULT NULL,
   `manualConPIN` varchar(1) DEFAULT NULL,
   `manualSinPIN` varchar(1) DEFAULT NULL,
   `facturada` varchar(1) DEFAULT NULL,
   PRIMARY KEY (`id`),
   KEY `FK2D546D5D771F9D3A` (`idTransaccionOriginal`),
   KEY `idxAnulada` (`anulada`),
   KEY `idxConfirmada` (`confirmada`),
   KEY `idxCodTipoTransaccion` (`codTipoTransaccion`),
   KEY `idxFechaHora_CodTipoTransaccion` (`fechaHora`,`codTipoTransaccion`),
   KEY `idxNroTicket` (`nroTicket`),
   KEY `idxNroLote` (`nroLote`),
   KEY `idxFechaHora` (`fechaHora`),
   KEY `idxOnline` (`online`),
   KEY `idxFacturada` (`facturada`),
   CONSTRAINT `FK2D546D5D771F9D3A` FOREIGN KEY (`idTransaccionOriginal`) REFERENCES `Transacciones` (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=15359563 DEFAULT CHARSET=latin1

CREATE TABLE `ReservasTiempoReal` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `procesada` varchar(1) NOT NULL,
   `idTransaccion` bigint(20) NOT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `idTransaccion` (`idTransaccion`),
   KEY `FK2375B195C078E769` (`idTransaccion`),
   KEY `idxProcesada` (`procesada`),
   CONSTRAINT `FK2375B195C078E769` FOREIGN KEY (`idTransaccion`) REFERENCES `Transacciones` (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=50805 DEFAULT CHARSET=latin1

A: Use a composite index:
INDEX(confirmada, codTipoTransaccion, idTransaccionOriginal, idTransaccion)

The columns can be in any order, so I recommend shuffling them to meet other need(s) and/or facilitate removing some other index from t2.
If you need to discuss this further, please provide SHOW CREATE TABLE for each table.
Edit
For
JOIN ...    ON rtr2.idTransaccion = t2.id
WHERE t2.confirmada = 'S'
  AND t2.codTipoTransaccion = 'ECTR'
  AND t2.idTransaccionOriginal IN (14748319, 14748519, ...)

it is probably better to have this:
INDEX(codTipoTransaccion, confirmada, idTransaccionOriginal)

with idTransaccionOriginal deliberately last (because of the IN).
That should encourage the optimizer to start with t2.  I see that idTransaccion is an index in the other table, so the JOIN should be efficient.  (On a cold cache, there could still be a lot of I/O.)
Your CREATE TABLE multiple not-so-good indexes for the optimizer (not the ORM) to choose from.  What I am proposing should be a 'better' index that the optimizer will readily pick.  The optimizer looks at all the indexes, ignores any that are obviously useless (for the given query), and looks at statistics.  In some situations (perhaps not yours), the statistics are poor, leading to a poor choice of INDEX.  The "statistics" for one index is one number; it assumes a balanced distribution (which you point out is wrong for confirmada='S').
Using a composite index (when it can be used) is almost always better than having shorter indexes.
(Unrelated) DROP the second of these, as being redundant:
 KEY `idxFechaHora_CodTipoTransaccion` (`fechaHora`,`codTipoTransaccion`),
 KEY `idxFechaHora`                    (`fechaHora`),

Also, my suggested index would make KEY idxCodTipoTransaccion (codTipoTransaccion) unnecessary.
More discussion on indexing.


text:
Q: div tag translate and i don't know why this is my first question on stackoverflow, hope to do it right.
so, the problem is that i want to put 2 div per row
https://i.imgur.com/dS7lEbo.png
but when i add the fourt , the third and the fourt go down one row each.
https://i.imgur.com/fxf8SiV.png
i've tried to play with magin-top but it kinda works only if the second div has 1% more than the other one (and that is non what i want).
https://i.imgur.com/dS7lEbo.png
{% extends "base.html" %}
{% block content %}

        {% for p in all_p %}

                    {{ p.nome.title }}

Category:
                    {{ p.categoria_primaria.name }}
                    {% for c in p.categoria_secondaria.all %}
                         {{ c.name }}
                    {% endfor %}

        {% endfor %}

{% endblock %}

.row-progetti-explorer {
    height: 100%;
    width: 100%;
    text-align: center;
    display:inline-block;
    background-color: blueviolet;
}

.div-progetti1{
    border: 2px solid darkgreen;
    float: left;
    width: 35%;
    background-color: red;
    color: black;
}

.div-progetti2{
    border: 2px solid darkgreen;
    float: right;
    width: 35%;
    background-color: palegoldenrod;
    color: black;
}

as i said i what 2 div per row (first link)

A: I believe there's an extra margin on your div-progetti2 class. You can check using Inspector of your browser.
Here's a tutorial on how to you use chrome inspector:
https://www.templatemonster.com/help/use-google-chrome-web-inspector.html

A: I think this can be help you, but you just need to redecorate or modify this code as per your language. this is front end only as per rules, and you can modify instead of
 tag to border bottom.header class

.row-progetti-explorer {
            width: 100%;
            max-width: 1140px;
            margin: auto;
        }

        .div-progetti2 {
            width: 50%;
            float: left;
        }

        .main-content {
            padding: 2%;
        }

        .header {
            text-align: center;
        }

        .img-responsive {
            width: 100%;
            height: auto;
        }

 Dummy Title

category: dummy

 Dummy Title

category: dummy

 Dummy Title

category: dummy

 Dummy Title

category: dummy


text:
Q: StackedBarChart row key is not added to DefaultCategoryDataSet I have two entity Classes: A and B. A has B entities, and I have a Map defined in the following format: Map<A, List<B>.
I want to add all map data to DefaultCategoryDataset with following code. For example, if have 5 A and each A has 4 B, I want to have 25 row keys. (A entity number * (A entityNumber + B entity number in each A). A Row key that stores A class must be same width; all other rows that store B entities must have same width. To succeed in this, I am giving the same values while adding A row keys((double) 1 / (1 + bResultList .size()), and giving smaller values while adding A row keys((double) 1 / (1 + bResultList .size() + 6).
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
/** for each workpoint */
for (A aResult : map.keySet()) {
    List<B> bResultList = map.get(aResult);
    dataset.addValue(
        (double) 1 / (1 + bResultList.size()),
        "WorkPoint " + aResult.getTimeStep(),
        "WP T=" + aResult.getTimeStep());
    /** for each contingency result */
    for (B bResult : bResultList) {
        dataset.addValue(
            (double) 1 / (1 + bResultList.size() + 6),
            bResult.getName(),
            "WP T=" + aResult.getTimeStep());
    }
}

But when I add all map data to data set all row keys are not stored. When I debug, Dataset only has 9 rows. (A1,B1,B2,B3,B4,A2,A3,A4,A5) Only B entities of first A entity is stored as row keys. Other B entities of other A entity is not stored in database.
But when I display graph, all data is displayed in graph but in wrong order.
Order is following.
A1-B1-B2-B3-B4
B1-B2-B3-B4-A2
B1-B2-B3-B4-A3
B1-B2-B3-B4-A4
B1-B2-B3-B4-A5

I want to display like
A1-B1-B2-B3-B4
A2-B1-B2-B3-B4
A3-B1-B2-B3-B4
A4-B1-B2-B3-B4
A5-B1-B2-B3-B4

A: Absent your sscce the problem is not apparent. It may help to compare your data set to a typical CategoryDataset such as this one that has distinct series (row) and category (column) keys. Also, adding a CategoryItemLabelGenerator may aid debugging.
renderer.setBaseItemLabelGenerator(
    new StandardCategoryItemLabelGenerator(
        "{0} {1} {2}", NumberFormat.getInstance()));
renderer.setBaseItemLabelsVisible(true);


text:
Q: make a div return to it's original position when animating to top( like jumping effect ) this is my code :
var pane = $('#Container'),
        box = $('#PLayer'),
        w = pane.width() - box.width(),
        d = {},
        x = 3;

    function newv(v, a, b) {
        var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
        return n < 0 ? 0 : n > w ? w : n;
    }

    $(window).keydown(function (e) { d[e.which] = true; });
    $(window).keyup(function (e) { d[e.which] = false; });

    setInterval(function () {
        box.css({
            left: function (i, v) { return newv(v, 37, 39); },
            top: function (i, v) { return newv(v, 38, 40); }
        });
    }, 20);

by this code i managed to make the div animate by using the arrow key but how can i make that jumping effect ? like the one used here

A: Here's a link to a fork of your fiddle:
http://jsfiddle.net/dJut2/
I made two changes:

*

*Jquery wanted top to have an initial value while using the 2-argument callback inside .css(...), so I set it to 50% in CSS: .player{ ... top: 50%; }

*I added "gravity" using another ternary check inside the input response/collision function. It checks against whether 38/the up-key is passed as an input case and adds 2 to the top: ... + (a==38 ? 2 : 0)
By the way, verbose variable names or comments could really make your code easier to read. Also, ternary operators aren't as efficient or readable as some if statements. Lastly, you should break your input response and collision functionality into specific cases so you can edit them each specifically later without having to refactor.
Lastly, if you want to simulate a 'jump', you'll need to have some kind of timed input case. This can be accomplished automatically with an acceleration variable (set it to a number, subtract it from the top every frame, and decrement it every frame flooring at 0 when on the ground; the gravity I added can be removed in this case) or some kind of specific animation (subtract 4 every frame for 20 frames).

A: If you want to do something similar to that platformer game you linked (which is awesome), why not just check out the source code for it? http://taffatech.com/Platformer.js
if(Player.isUpKey == true)
{

if(!Player.jumping){
       Player.jumping = true;
       Player.velY = -Player.speed*2;
      }

}

If you look there you see he's not actually using CSS animations, but recalculating the player's position every frame. If the player hit's the up key, their y velocity is increased, and then every frame this is called to move the player
//gravity would be a numeric variable, this makes the player  constantly move
//back downwards when they leave the ground

Player.velY += gravity;

//adjusting the player's position according to new
//calculated x and y velocity

Player.x += Player.velX;
Player.y += Player.velY;

This is similar to how most game engines work, recalculating the scenario and forces each frame so they can constantly react to what's going on. Instead of animations, a physics engine is doing the math and moving things accordingly on screen.


text:
Q: fourier transform of cumulative function Hi
I've encountered a test that uses the cumulative value of a finite time series to deterime the data set's stationarity.
I would like to know the characteristics of this test in frequency space, so would therefore need to know the fourier transform of this cummalative function.
I was assuming that the function could be writen as the product of the initial time series function, f, and a heavyside step function, H.  With the defining function written as:
$g(t) =  \sum^{t}_{n=1} f(n)  H(t-n) $
I would like to know fourier transform of the function g(t).  Is there a straightforward solution to this function or does the use of the discontinuous step function make a solution impossible.

A: Read
Discrete-Time Signal Processing (2nd Edition) (Prentice-Hall Signal Processing Series) [Hardcover]
Alan V. Oppenheim (Author), Ronald W. Schafer (Author), John R. Buck (Author)
and all will be revealed.