text:
Q: Why does "vectorizing" this simple R loop give a different result? Perhaps a very dumb question.
I am trying to "vectorize" the following loop:
set.seed(0)
x <- round(runif(10), 2)
# [1] 0.90 0.27 0.37 0.57 0.91 0.20 0.90 0.94 0.66 0.63
sig <- sample.int(10)
# [1]  1  2  9  5  3  4  8  6  7 10
for (i in seq_along(sig)) x[i] <- x[sig[i]]
x
# [1] 0.90 0.27 0.66 0.91 0.66 0.91 0.94 0.91 0.94 0.63

I think it is simply x[sig] but the result does not match.
set.seed(0)
x <- round(runif(10), 2)
x[] <- x[sig]
x
# [1] 0.90 0.27 0.66 0.91 0.37 0.57 0.94 0.20 0.90 0.63

What's wrong?

Remark
Obviously from the output we see that the for loop and x[sig] are different. The meaning of the latter is clear: permutation, hence many people tend to believe that the loop is just doing some wrong stuff. But never be so sure; it can be some well-defined dynamic process. The purpose of this Q & A is not to judge which is correct, but to explain why they are not equivalent. Hopefully it provides a solid case study for understanding "vectorization".

A: There is a simpler explanation. With your loop, you are overwriting one element of x at every step, replacing its former value by one of the other elements of x. So you get what you asked for. Essentially, it is a complicated form of sampling with replacement (sample(x, replace=TRUE)) -- whether you need such a complication, depends on what you want to achieve.
With your vectorized code, you are just asking for a certain permutation of x (without replacement), and that is what you get. The vectorized code is not doing the same thing as your loop. If you want to achieve the same result with a loop, you would first need to make a copy of x:
set.seed(0)
x <- x2 <- round(runif(10), 2)
# [1] 0.90 0.27 0.37 0.57 0.91 0.20 0.90 0.94 0.66 0.63
sig <- sample.int(10)
# [1]  1  2  9  5  3  4  8  6  7 10
for (i in seq_along(sig)) x2[i] <- x[sig[i]]
identical(x2, x[sig])
#TRUE

No danger of aliasing here: x and x2 refer initially to the same memory location but his will change as soon as you change the first element of  x2.

A: This has nothing to do with memory block aliasing (a term I have never encountered before). Take a particular permutation example and walk through the assignments that would occur regardless of the implementation at the C or assembly (or whatever) language level; It intrinsic to how any sequential for-loop would behave versus how any "true" permutation (what one gets with x[sig]) would occur:
sample(10)
 [1]  3  7  1  5  6  9 10  8  4  2

value at 1 goes to 3, and now there are two of those values
value at 2 goes to 7, and now there are two of those values
value at 3 (which was at 1) now goes back to 1 but the values remain unchanged

... can continue but this illustrates how this will usually not be a "true" permutation and very uncommonly would result in a complete redistribution of values. I'm guessing that only a completely ordered permutation (of which I think there is only one, i.e. 10:1) could result in a new set of x's that were unique.
replicate( 100, {x <- round(runif(10), 2);
                  sig <- sample.int(10);
                  for (i in seq_along(sig)){ x[i] <- x[sig[i]]};
                  sum(duplicated(x)) } )
 #[1] 4 4 4 5 5 5 4 5 6 5 5 5 4 5 5 6 3 4 2 5 4 4 4 4 3 5 3 5 4 5 5 5 5 5 5 5 4 5 5 5 5 4
 #[43] 5 3 4 6 6 6 3 4 5 3 5 4 6 4 5 5 6 4 4 4 5 3 4 3 4 4 3 6 4 7 6 5 6 6 5 4 7 5 6 3 6 4
 #[85] 8 4 5 5 4 5 5 5 4 5 5 4 4 5 4 5

I started wondering what the distribution of duplication counts might be in a large series. Looks pretty symmetric:
table( replicate( 1000000, {x <- round(runif(10), 5);
                            sig <- sample.int(10);
               for (i in seq_along(sig)){ x[i] <- x[sig[i]]};
                            sum(duplicated(x)) } ) )

     0      1      2      3      4      5      6      7      8
     1    269  13113 126104 360416 360827 125707  13269    294

A: Interesting to see that although R "vectorization" is different from "SIMD" (as OP nicely explained), the same logic applies when determining whether a loop is "vectorizable". Here is a demo using examples in OP's self-answer (with a little modification).
Example 1 with "write-after-read" dependency is "vectorizable".
// "ex1.c"
#include <stdlib.h>
void ex1 (size_t n, size_t *x) {
  for (size_t i = 1; i < n; i++) x[i - 1] = x[i] + 1;
}

gcc -O2 -c -ftree-vectorize -fopt-info-vec ex1.c
#ex1.c:3:3: note: loop vectorized

Example 2 with "read-after-write" dependency is not "vectorizable".
// "ex2.c"
#include <stdlib.h>
void ex2 (size_t n, size_t *x) {
  for (size_t i = 1; i < n; i++) x[i] = x[i - 1] + 1;
}

gcc -O2 -c -ftree-vectorize -fopt-info-vec-missed ex2.c
#ex2.c:3:3: note: not vectorized, possible dependence between data-refs
#ex2.c:3:3: note: bad data dependence

Use C99 restrict keyword to hint compiler of no memory block aliasing between three arrays.
// "ex3.c"
#include <stdlib.h>
void ex3 (size_t n, size_t * restrict a, size_t * restrict b, size_t * restrict c) {
  for (size_t i = 0; i < n; i++) a[i] = b[i] + c[i];
}

gcc -O2 -c -ftree-vectorize -fopt-info-vec ex3.c
#ex3.c:3:3: note: loop vectorized

A: warm-up
As a warm-up, consider two simpler examples.
## example 1
x <- 1:11
for (i in 1:10) x[i] <- x[i + 1]
x
# [1]  2  3  4  5  6  7  8  9 10 11 11

x <- 1:11
x[1:10] <- x[2:11]
x
# [1]  2  3  4  5  6  7  8  9 10 11 11

## example 2
x <- 1:11
for (i in 1:10) x[i + 1] <- x[i]
x
# [1] 1 1 1 1 1 1 1 1 1 1 1

x <- 1:11
x[2:11] <- x[1:10]
x
# [1]  1  1  2  3  4  5  6  7  8  9 10

"Vectorization" is successful in the 1st example but not the 2nd. Why?
Here is prudent analysis. "Vectorization" starts by loop unrolling, then executes several instructions in parallel. Whether a loop can be "vectorized" depends on the data dependency carried by the loop.
Unrolling the loop in example 1 gives
x[1]  <- x[2]
x[2]  <- x[3]
x[3]  <- x[4]
x[4]  <- x[5]
x[5]  <- x[6]
x[6]  <- x[7]
x[7]  <- x[8]
x[8]  <- x[9]
x[9]  <- x[10]
x[10] <- x[11]

Executing these instructions one by one and executing them simultaneously give identical result. So this loop can be "vectorized".
The loop in example 2 is
x[2]  <- x[1]
x[3]  <- x[2]
x[4]  <- x[3]
x[5]  <- x[4]
x[6]  <- x[5]
x[7]  <- x[6]
x[8]  <- x[7]
x[9]  <- x[8]
x[10] <- x[9]
x[11] <- x[10]

Unfortunately, executing these instructions one by one and executing them simultaneously would not give identical result. For example, when executing them one by one, x[2] is modified in the 1st instruction, then this modified value is passed to x[3] in the 2nd instruction. So x[3] would have the same value as x[1]. However, in parallel execution, x[3] equals x[2]. As the result, this loop can not be "vectorized".
In "vectorization" theory,

*

*Example 1 has a "write-after-read" dependency in data: x[i] is modified after it is read;

*Example 2 has a "read-after-write" dependency in data: x[i] is read after it is modified.

A loop with "write-after-read" data dependency can be "vectorized", while a loop with "read-after-write" data dependency can not.

in depth
Perhaps many people have been confused by now. "Vectorization" is a "parallel-processing"?
Yes. In 1960's when people wondered what kind of parallel processing computer be designed for high performance computing, Flynn classified the design ideas into 4 types. The category "SIMD" (single instruction, multiple data) is corned "vectorization", and a computer with "SIMD" cabability is called a "vector processor" or "array processor".
In 1960's there were not many programming languages. People wrote assembly (then FORTRAN when a compiler was invented) to program CPU registers directly. A "SIMD" computer is able to load multiple data into a vector register with a single instruction and do the same arithmetic on those data at the same time. So data processing is indeed parallel. Consider our example 1 again. Suppose a vector register can hold two vector elements, then the loop can be executed with 5 iterations using vector processing rather than 10 iterations as in scalar processing.
reg <- x[2:3]  ## load vector register
x[1:2] <- reg  ## store vector register
-------------
reg <- x[4:5]  ## load vector register
x[3:4] <- reg  ## store vector register
-------------
reg <- x[6:7]  ## load vector register
x[5:6] <- reg  ## store vector register
-------------
reg <- x[8:9]  ## load vector register
x[7:8] <- reg  ## store vector register
-------------
reg <- x[10:11] ## load vector register
x[9:10] <- reg  ## store vector register

Today there are many programming languages, like R. "Vectorization" no longer unambiguously refers to "SIMD". R is not a language where we can program CPU registers. The "vectorization" in R is just an analogy to "SIMD". In a previous Q & A: Does the term "vectorization" mean different things in different contexts? I have tried to explain this. The following map illustrates how this analogy is made:
single (assembly) instruction    -> single R instruction
CPU vector registers             -> temporary vectors
parallel processing in registers -> C/C++/FORTRAN loops with temporary vectors

So, the R "vectorization" of the loop in example 1 is something like
## the C-level loop is implemented by function "["
tmp <- x[2:11]  ## load data into a temporary vector
x[1:10] <- tmp  ## fill temporary vector into x

Most of the time we just do
x[1:10] <- x[2:10]

without explicitly assigning the temporary vector to a variable. The temporary memory block created is not pointed to by any R variable, and is therefore subject to garbage collection.

a complete picture
In the above, "vectorization" is not introduced with the simplest example. Very often, "vectorization" is introduced with something like
a[1] <- b[1] + c[1]
a[2] <- b[2] + c[2]
a[3] <- b[3] + c[3]
a[4] <- b[4] + c[4]

where a, b and c are not aliased in memory, that is, the memory blocks storing vectors a, b and c do not overlap. This is an ideal case, as no memory aliasing implies no data dependency.
Apart from "data dependency", there is also "control dependency", that is, dealing with "if ... else ..." in "vectorization". However, for time and space reason I will not elaborate on this issue.

back to the example in the question
Now it is time to investigate the loop in the question.
set.seed(0)
x <- round(runif(10), 2)
sig <- sample.int(10)
# [1]  1  2  9  5  3  4  8  6  7 10
for (i in seq_along(sig)) x[i] <- x[sig[i]]

Unrolling the loop gives
x[1]  <- x[1]
x[2]  <- x[2]
x[3]  <- x[9]   ## 3rd instruction
x[4]  <- x[5]
x[5]  <- x[3]   ## 5th instruction
x[6]  <- x[4]
x[7]  <- x[8]
x[8]  <- x[6]
x[9]  <- x[7]
x[10] <- x[10]

There is "read-after-write" data dependency between the 3rd and the 5th instruction, so the loop can not be "vectorized" (see Remark 1).
Well then, what does x[] <- x[sig] do? Let's first explicitly write out the temporary vector:
tmp <- x[sig]
x[] <- tmp

Since "[" is called twice, there are actually two C-level loops behind this "vectorized" code:
tmp[1]  <- x[1]
tmp[2]  <- x[2]
tmp[3]  <- x[9]
tmp[4]  <- x[5]
tmp[5]  <- x[3]
tmp[6]  <- x[4]
tmp[7]  <- x[8]
tmp[8]  <- x[6]
tmp[9]  <- x[7]
tmp[10] <- x[10]

x[1]  <- tmp[1]
x[2]  <- tmp[2]
x[3]  <- tmp[3]
x[4]  <- tmp[4]
x[5]  <- tmp[5]
x[6]  <- tmp[6]
x[7]  <- tmp[7]
x[8]  <- tmp[8]
x[9]  <- tmp[9]
x[10] <- tmp[10]

So x[] <- x[sig] is equivalent to
for (i in 1:10) tmp[i] <- x[sig[i]]
for (i in 1:10) x[i] <- tmp[i]
rm(tmp); gc()

which is not at all the original loop given in the question.

Remark 1
If implementing the loop in Rcpp is seen as a "vectorization" then let it be. But there is no chance to further "vectorize" the C / C++ loop with "SIMD".

Remark 2
This Q & A is motivated by this Q & A. OP originally presented a loop
for (i in 1:num) {
  for (j in 1:num) {
    mat[i, j] <- mat[i, mat[j, "rm"]]
  }
}

It is tempting to "vectorize" it as
mat[1:num, 1:num] <- mat[1:num, mat[1:num, "rm"]]

but it is potentially wrong. Later OP changed the loop to
for (i in 1:num) {
  for (j in 1:num) {
    mat[i, j] <- mat[i, 1 + num + mat[j, "rm"]]
  }
}

which eliminates the memory aliasing issue, because the columns to be replaced are the first num columns, while the columns to be looked up are after the first num columns.

Remark 3
I got some comments regarding whether the loop in the question is making "in-place" modification of x. Yes, it is. We can use tracemem:
set.seed(0)
x <- round(runif(10), 2)
sig <- sample.int(10)
tracemem(x)
#[1] "<0x28f7340>"
for (i in seq_along(sig)) x[i] <- x[sig[i]]
tracemem(x)
#[1] "<0x28f7340>"

My R session has allocated a memory block pointed by address <0x28f7340> for x and you may see a different value when you run the code. However, the output of tracemem will not change after the loop, which means that no copy of x is made. So the loop is indeed doing "in-place" modification without using extra memory.
However, the loop is not doing "in-place" permutation. "In-place" permutation is a more complicated operation. Not only elements of x need be swapped along the loop, elements of sig also need be swapped (and in the end, sig would be 1:10).


text:
Q: What advantages does modern Fortran have over modern C++? I'm trying to decide between Fortran and C++ for an application in scientific computing.  It's not clear to me if Fortran still has advantages over other languages when it comes to performance.  For example, I believe since Fortran enforces strict aliasing, better optimizations could be made by the compiler when compared to C before C99.  I'm unsure of how C++ fits in here.
Any guidance?

A: Advantages of fortran95 and above  over c++(2003):

*

*As previously(by user4562) mentioned short learning curve(my first language was C and i still can't master it , similar is true for C++)

*(My personal opinion) Easy for code transition from Octave(for that matter Matlab)similar syntax,same modularity[I use Octave to prototype a program and rewrite in fortran95 for speed],though u can directly use octave code in C++.

*dynamic memory allocation is quite straight forward.(f77 didn't have this at all!)

*libraries support (u can do this in c++ as well , but its natural to use fortran)

*Co-array support for parallel computing (pity only cray supports them as  of feb 2011 gfortran work has started as of gfortran4.6 but still a long way to go)

in short if your program or application is purely scientific computation use fortran 95 and above if calculating a few numbers is just part of the story use C++ (or whatever u feel is better)

A: I am new to programming.I have been programming in the field of finite elements for about a year. After some research on the net I decided to use fortran 2003.I learned to program in the modular style in about ten days by studying the Chapman book. It's one year on and i have written about four thousands of code lines in modular format(maintainable,reusable and neat codes) and haven't used any character variable at all. I don't think that by studying C++,matlab,python,java ... for ten days you would be able to write numerical codes as efficient as in fortran. fortran 2003 also has all the necessary OOP capabilities which I am learning now.
   So in terms of language strength in the numerical aspect fortan doesn't lack anything(modular style,OOP style,powerful array capabilities,powerful libraries, free and commercial up to dated compilers,very easy to learn, very efficient ...). Languages like python/numpy has most of these capabilities but lack efficiency. Languages like C++ also has most of the capabilities of fortran(although for array computation which is the main core of numerical computation you have to import some libraries!!), but maybe a program written by someone like me in fortran would be more efficient than one written by some c++ programmer with 10+ years of experience.
   Finally I do my heavy numerical computations in fortran(modular or OOP format), and use python\numpy for small size computations(like creating plots,small size array computations ... ).

A: My experience with Fortran is that it's easy to learn, clean (being highly modularized), and thus well suited to a non-programmer whose main concern is doing highly optimized numerical computations.  Although equal optimization can be performed in c++, (even perhaps to a greater extent), it takes a lot of instrinsic understanding to achieve those level of optimizations.  When it comes to matrix calculations, out-of-the box a Fortran compiler will normally out-perform a c++ compiler.  I'd also add that Fortran has keywords that are specifically designed to help the programmer to squeeze more performance out of a numerical routine.  C++ has this too, but not to the extent Fortran does.
Another advantage is that Fortran is not operating system or architecture specific.  In other words the Fortran code you write on one operating system or architecture should easily port to another where there is a Fortran compiler.
Another advantage is that modern Fortran is normally backwards compatible with older code bases of Fortran.  And the code base that has been built over the years in Fortran is huge and extremely sophisticated (being mostly done by scientists and mathematicians).
Also, personally, I really enjoyed the built-in file handling functions that allow one to read a data file and perform operations on it almost instantly.  Many other built-in functions in Fortran are designed to allow this convenience.  C++ offers mainly building blocks to do this and this requires a bit of sweating it out just to read a data file b/c you need to know something about delimiters (where Fortran allows you to specify the delimiter).
Beyond this I can't think of advantages.  Most anything else would be string manipulations, or algorithmic based operations to which c++ as a language, and in general it's compilers, are better suited and most often will perform better.  A good knowledgeable programmer will likely prefer c++ as she/he would understand how to optimize a numerical routine in a way that could likely perform better than a Fortran compiled routine.  Additionally good reliable Fortran compilers are not as easy to come by as good reliable C++ compilers.

A: I took a look at some of the stuff in the latest Fortran standards, and frankly I'm impressed. A lot of what I hated about the language 20 years ago is gone now. No more line numbers and special columns (may they burn in hell).
Fortran has been heavily used in engineering circles for 50 years now. That gives you two advantages if you work in those circles. First off, these folks care a lot about optimization. That means Fortran compilers tend to have the best optimizers around. The language itself is a lot more optimizable than Cish languages too, thanks to its lack of aliasing.
The second advantage is that Fortran's library support for number crunching simply cannot be beat. The best code is nearly always going to be the well-debugged code you don't have to write.
If your application doesn't fall under scientific, engineering, or number crunching in general, then neither of the above will be a big deal for you, so you may be better off looking elsewhere.

A: IMHO, the only advantage that really matters is that programming FORTRAN allows you easier reuse of a lot of existing FORTRAN code and libraries. And if you have 50 FORTRAN programmers at hand for a project and a limited time frame, are you going first to teach them all C++, or will you accept to let them use their favorite language?

A: Given the existence of scientific computing packages like LAPACK++, which are highly optimized already, modern Fortran doesn't even have a performance advantage.  C++ may have its faults, but performance is not one of them.

A: The other major issue is the learning curve which is very huge for C++ and exceptionally small for Fortran (90 and later). Fortran is like MATLAB with operations like ...

*

*B'DB is matmul( matmul(transpose(B), D), B )

*L2 norm of a vector is norm2(x)

*SVD of a matrix using LAPACK is call gesvd(A,S,u,vt)
Fortran also has pointers, dynamic memory, user defined data types etc.
It is well supported by major vendors (Intel/Sun/IBM/Cray/PGI/NAG etc.), open source (gfortan/g95) communities and developers of numerical library/APIs such as PETSc, MPI etc.
Heck the new standard (Fortran 2008) even has co-arrays for doing parallel programming without the need for MPI/OpenMP and some Fortran compilers already support it (g95 and Cray).
Basically it has all the good qualities required for numerical computing, is easier than MATLAB, is standardized, free, scalable (with MPI/OpenMP and co-arrays), produces blazing fast/parallel code.
For numerics nothing beats Fortran but unfortunately for anything else everything beats Fortan. So if you are a scientist with a safe job and only do numerical/HPC computing then stick with Fortran otherwise learn and use C++ as it is widely used for non numerical software.

A: Fortran allows whole array operations and also operations on array sections. There are C++ classes for arrays, but I don't think you can refer to a slice such as x(:,2:,1:N3:2) as easily as in Fortran. This lets one express some algorithms pretty concisely.
The convenience of Fortran's array operations extends to arrays of derived types. Suppose you have a an array of dates:
type date
integer :: month,day,year
end type date
type(date) :: x(1000)
Then x refers to the array of dates, x%month refers to the array of months, and pack(x,x%month==1) refers to all dates in January. How many other programming languages offer this convenience?
Some of the earlier comments about Fortran -- "old and disgusting" -- are biased and should be discounted accordingly. Let me argue the opposite. In my opinion the free format of Fortran 90 looks better than the syntax of C and C++, with the curly braces and semicolons. Leaving them out or incorrectly putting them in can cause errors in C and C++ that have no counterpart in Fortran.

A: Fortran has been highly optimized for mathematical (especially matrix) like operations.
C++ has been highly optimized for object usage.
Which is more important to you.
As noted below C++ has an optimized matrix library.
But Fortran's whole purpose is optimization of mathematical processes (especially matrix operations). The fact that these optimizations are built into the foundation of the language (rather than a library) and have about a two decade head start on research over C++ I doubt (but don't know for a fact) that in this area Fortran is going to win hands down.

A: With the emergence of template-meta programming (especially expression templates), C++ reached FORTRAN's league in numerical computations, so speed should not be an issue anymore. However, there's still some things to be said about other issues:
Pro FORTRAN: The older folks might know it better than C++.
Contra FORTRAN: It's a disgusting, old, and mostly abandoned language, that's already outdated the moment your start your project. Whoever learns programming now, is very unlikely to learn FORTRAN, so you might run into problems finding programmers for the project later.
Pro C++: It's relatively modern, with compilers still improving in considerable strides. It allows you to write quite expressive code.
Contra C++: Some of those template error messages will make you weep.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to build a working jar file in Vaadin 14 + Spring Boot? Im trying to run my Vaadin14 project to production and my application cant find any vaadin flow components. I have a default application.properties and POM, and downloaded it from here https://vaadin.com/start/latest. I already have tried,
delete node modules
mvn clean
mvn clean install -Pproduction
mvn clean package -Pproduction
and I get this error
Failed to find the following imports in the `node_modules` tree:
  - @vaadin/flow-frontend/contextMenuConnector-es6.js
  - @vaadin/flow-frontend/comboBoxConnector.js
  - @vaadin/flow-frontend/gridConnector.js
  - @vaadin/flow-frontend/contextMenuConnector.js
  - @vaadin/flow-frontend/flow-component-renderer.js
  - @vaadin/flow-frontend/gridConnector-es6.js
  - @vaadin/flow-frontend/comboBoxConnector-es6.js
  - @vaadin/flow-frontend/vaadin-grid-flow-selection-column.js

If the build fails, check that npm packages are installed.
To fix the build remove node_modules directory to reset modules.
  In addition you may run npm install to fix node_modules tree structure.
TIA

A: nvm guys, already found the answer.. Vaadin 14.0.11v
add this to your application.properties
vaadin.productionMode = true <----- comment this line when in dev mode
spring.servlet.multipart.enabled = false


text:
Q: How to implement fancy scroll bar for multiline textbox? I want to implement a fancy scroll bar for a multiline textbox like the picture below:

Any ideas for that fancy scroll bar?
P/S: I want vb.net solution.

A: This code is very chunky and frustrating to work with but it's working

This is a fully drawn GDI+ custom
  scrollbar control class. All of its
  drawing methods are overrideable,
  allowing developers to paint it
  however they choose.
http://www.codeproject.com/KB/miscctrl/corescrollbar.aspx

A: If the fancy scroll bar can be implemented as another control (your image actually looks like that), here is the code of a ListBox that supports custom scrolling:
Imports System.Runtime.InteropServices

Public Class CustomScrollListBox
    Inherits ListBox

    Public Sub Scroll(ByVal percentage As Single)
        If (percentage < 0.0!) Then
            Throw New ArgumentException(Nothing, "percentage")
        End If

        ' Sends the scroll / set position Windows message
        Const WM_VSCROLL As Integer = &H115
        Const SB_THUMBPOSITION As Integer = 4
        Dim wp As Integer = CInt(((percentage * MyBase.Items.Count) * 65536.0!)) + SB_THUMBPOSITION
        CustomScrollListBox.SendMessage(MyBase.Handle, WM_VSCROLL, New IntPtr(wp), IntPtr.Zero)
    End Sub

    <DllImport("user32.dll")> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
    End Function

    Protected Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            ' Removes the vertical scroll window style
            Dim p As CreateParams = MyBase.CreateParams
            Const WS_VSCROLL As Integer = &H200000
            p.Style = (p.Style And -WS_VSCROLL)
            Return p
        End Get
    End Property

End Class

And here is a sample form that uses it. I have implemented the custom scroller as a standard Trackbar (trackBar1) for the example:
Public Class Form1

    Private trackBar As TrackBar
    Private listBox As CustomScrollListBox

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        ' initialize some listbox props
        listBox = New CustomScrollListBox
        listBox.Location = New Point(&H19, 210)
        listBox.Name = "listBox2"
        listBox.Size = New Size((&H17D - Me.TrackBar1.Width), &HAD)
        listBox.TabIndex = 1
        MyBase.Controls.Add(listBox)

       ' add some items
        Dim i As Integer
        For i = 0 To 100 - 1
            listBox.Items.Add(("item" & i))
        Next i

    End Sub

    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        ' compute trackbar's position as a percentage
        listBox.Scroll(CSng(TrackBar1.Maximum - TrackBar1.Value) / TrackBar1.Maximum - TrackBar1.Minimum)
    End Sub

End Class


text:
Q: HTML with TeX formulas to images How is it possible, with MathJax or another JavaScript lib, to parse an input HTML file with some TeX math formulas and produce an output file with the formulas replaced with images (gif, png, jpeg, ..)? (The final goal is to export the output HTML file to a PDF file using html-pdf).
For example:
The input file:

\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)

MathJax:
               |
               |
            Convert
               |
               ↓

The output file:

        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHsAAAAgCAQAAACYh8/AAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAJiS0dEAP+Hj8y/AAAACXBIWXMAAABIAAAASABGyWs+AAACq0lEQVRYw+WZ4XGbQBCFv824gHPSwaUDIlWQcwfYHQR1gMcVeEgHqIRYHYgObNSB1EEsOtj8AByQFAtJgJCz90Mzp+O9e+zusSyiDMvEMe+e5ercMjdEWzyVHniG5W2JddIHz6C8LZbl1pwP3PCkSatU2vLAscbbMR82uDbC1DFwhAqW9KA9xDnOOyvalq2w3i1p73Xm75o6Bo74wBtv31/zqfVAdRwbjg887sIQw23zjBcDvO5b1bpsbkCcRGIbbTKublezbQyx3OlEvMb8d9VTQELxxZe5GAAJJBAnPh3kdoqn4PNUBm4x0uI3rIXjnKCe13UMLEtS0qZBjsMoLPMgJyJQMHnK5Nx4pHrKSS4BX2sTc03EYHQBfM6nNOO+WB3p/SaCJgIx07qvqxi62uD4B++OiEEsgV4DI36BWEIV0IV8P+kBptMdkyMWANw0q7U0EcTXGQFxU4ydvLk5PksAWHxJGPFSwfHK80KzLnJ7BWKx72yubhEPwBddnYBR3pCZTnWqU2CmC17JMX0W4pOR5avEdVClScQzYx7zYBPDQ/FHeTr/1p8bV6xJuK/KrmMcyG8IiJgS6Upi5oAl40UXEvFMhiHRbADFqYSM9bZnzvPLBjHH+PXiZfdvVyAeljHPZEzKHKvkZGlbOXnRpuAUHGmTuvmjjCLIJTrUm5edHWW54vhRE7U3yPvogXRngoclYa1CXi/9Fyb4jFmSv6wlfT9Izib7olP0aBtQL00cHjCuF6od2bkfJW9vyiZ/E8dn2QPbueW+bcShhXzd1wk7fQwmyDWRbwCMoKgUQ1bAhNsODtpze3nL60Wbqd4Q+rBBXmwnKETbov91UKv4AoMcQByvRcHkag2h1q39ptLxoj3QGUggZqMh1D7XUMqVyvevTK+h3hBqm+0P6EpqX1Z9P+gAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTYtMDQtMTBUMTI6NTc6MzUrMDA6MDDUKQisAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE2LTA0LTEwVDEyOjU3OjM1KzAwOjAwpXSwEAAAACp0RVh0bGF0ZXgAeCA9IHstYiBccG0gXHNxcnR7Yl4yLTRhY30gXG92ZXIgMmF9Lum12QAAAAx0RVh0Y29sb3IAMDAwMDAwwp/2oQAAAA50RVh0cmVzb2x1dGlvbgAxMDD3McujAAAAAElFTkSuQmCC"/>

A:

\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)

you can get svg by mathjax first, then convert the svg to image(base64)


text:
Q: Storing large numbers of short-lived game objects in C++ How would I store massive amount of objects (Like bullets or such changing constantly), and then remove them by their index?
I've heard that vector::erase isn't very efficient.

A: Use std::map (or C++11s std::unordered_map), these containers have better amortized runtime complexity for insertion and erase operations. std::list is also an option (its the obvious option, but I mentioned the others first since they also allow quick lookup/search which is in many game scenarios even more important).
At a higher level, you should definitely read up on C++ containers and what runtime complexity is in general. A wise choice of container structures is essential to good performance.

A: unordered_set<Bullet*> will do fine. Then you can simply use a Bullet* everywhere and forget indexing. Best allocated from an object pool or something like that.
Or, since the Standard kindly screwed up the interface, you may need instead std::unordered_map<Bullet*, std::unique_ptr<Bullet>> for the better exception safety and such.

A: (in)Famous Alexandrescu  considers main problem with short-living dynamic small object slow new/free operators and recommends use of custom allocator. std::map will use much of such objects (it uses red-black tree internally), so it is a good idea to either use a pool of preallocated objects or std::map with custom allocator (possibly one taken from Alexandresu's Loki library)

A: From my extremely limited secondhand knowledge of game engine programming, dynamic memory allocation is avoided when possible.  So an unordered_set or list would be a major no for a "massive amount" with frequent removals.
Edit: after reading @James Kanze's answer I realize that @Cameron's suggestion of swapping removed bullets with the last element doesn't work because it changes the indices of live bullets.  I guess you'd have to use James's suggestion, or possibly a bit vector to mark dead bullets.
Keeping the bullets compacted in an array would be great for cache performance too.  A hash table would cache better than std::map's red-black tree, but why incur the overhead of hashing if you already refer to the bullets by index?

A: If you're identifying the bullets by their index in the vector, then erase isn't a good idea; it will change the index of all of the following elements.  The fact that a bullet is identified by its index constrains your choices somewhat.  The best solution in that case is probably to simply mark the entry as invalid, and reuse it later, either by keeping a list of invalid indexes (easily done in an std::vector), or simply by scanning the vector each time you want to create a new bullet.  If you have different types of bullets (and you probably will, as the game evolves), you'll need to allocate the bullets dynamically anyway, keeping a pointer in the vector; a null pointer is then a good choice for invalid.

A: vector::erase isn't very efficient since it needs to move all the following elements to fill the space in order to preserve the order. However, it sounds like you don't need to preserve the order, in which case you can remove an element much more quickly by replacing it with the one at the end, and then dropping the last element:
std::swap(bullets[index_to_remove], bullets.back());
bullets.pop_back();


text:
Q: What are the limitations of a password used to protected an Access 2010 database? According to this page:
http://office.microsoft.com/en-us/access-help/access-2010-specifications-HA010341462.aspx
The maximum number of characters in a password is 14.
But this page encourages you to use 14 or more characters in a password:
http://office.microsoft.com/en-us/access-help/introduction-to-access-2010-security-HA010341741.aspx?CTT=3
My own testing has shown that I can use up to 20 characters.
Has anyone found better (or more consistent documentation) on Access 2010 passwords?  Or perhaps done some extensive testing to determine what the real limits are?

A: Here is a different resource which confirms your 20 Character limit in MS Access 2010.
http://www.databasezone.com/techdocs/acclimit.html
It lists that up to MS Access 2003, the maximum password length was in fact 14 characters long.  In MS Access 2007, the introduction of the .accdb format did away with user account passwords and opted for a more robust cryptography API, which supports up to 20 characters.
I am unsure why the Microsoft website specifies a 14 character maximum. I can only speculate that this is to cover those who are using MS Access 2007+ to use an older .mdb format database which would not support a full 20 characters for the password.
Also, while not necessarily a limitation of the password itself, when using a password on a .accdb format database, the encryption forces page level locking on the database - which can limit the users ability to issue transactions against the underlying data in a shared environment (http://office.microsoft.com/en-us/access-help/introduction-to-access-2010-security-HA010341741.aspx  -- Search for "page-level").

A: I realise this page is very old and the Access specifications page hasn't been updated since with regard to password length.
However, following a question in another Access forum recently I did some testing. Access APPEARS to let you enter more than 20 characters as a password.
In fact I successfully tested with 26, 256 & even 512 password characters. However this was an illusion and only the first 20 characters entered are saved.
The limit remains as 20 characters with one proviso. If you use a 20 character password with a linked BE table, the link works but you will get a 'Not a Valid Password' error on opening the table. The effective limit for tables in linked databases = 19


text:
Q: The real and imaginary parts of the Incomplete Gamma function for second argument being purely imaginary Dear all,
I am looking for explicit (at least more explicit than the original expression) for
1) Re$(\Gamma(a, i\omega))$
as well as
2) Im$(\Gamma(a, i\omega)),$
where i Re and Im denote the real and imaginary part, and $\Gamma(a, i\omega)$ is the Incomplete Gamma function with the arguments $a$ and $i\omega$. The letter $i$ denotes imaginary unit, $a>0$ is a real number and $\omega$ is also a real number.
I would presume that 1) and 2) could be written as functions of $\Gamma(a, \omega)$, however by application of change of variables in the integral definition of the Incomplete Gamma function did not succeed for me.
Thank you in advance for any kind of input.

A: The usual integral representation gives you
$$\Gamma(a,i\omega) = \Gamma(a) - (i\omega)^a \int_0^1 t^{a-1} e^{-i\omega t}\ dt$$
I assume you have no trouble writing $(i\omega)^a$ in terms of its real and imaginary parts.
As for the integral, Maple says
$$ \eqalign{\int_0^1 t^{a-1} \cos(\omega t)\ dt &=
{\frac { \left( {w}^{-a-1/2}\sin \left( w \right) -{w}^{-a+1/2}\cos \left( w
 \right)  \right) {S_1} \left( a+1/2,1/2,w \right) }{a}}\cr &-{\frac {{w}^{-a+1/2}{S_1} \left( a+3/2,3/2,w \right) \sin
 \left( w \right) }{ \left( 2+a \right) a}}\cr &+{\frac { \left( 2
+a \right) \cos \left( w \right) +w\sin \left( w \right) }{ \left( 2+a
 \right) a}}
\cr}
$$
$$ \eqalign{\int_0^1 t^{a-1} \sin(\omega t)\ dt &=-{\frac {{w}^{-a+1/2}\sin \left( w \right) {S_1} \left( a+1/2,3
/2,w \right) }{  a+1 }}\cr+&{\frac { \left( {w}^{-a
+1/2}\cos \left( w \right) -{w}^{-a-1/2}\sin \left( w \right)  \right) {S_1} \left( a+3/2,1/2,w \right) }{ \left( a+1 \right) a}
}\cr+&{\frac { \left( a+1 \right) \sin \left( w \right) -\cos \left( w
 \right) w}{ \left( a+1 \right) a}}
\cr}$$
where $S_1$ is the Lommel S1 function.


text:
Q: Second wifi router for internal LAN file transfer - freeing up main internet wifi signal We use Dropbox to share large files (100mb) which need to be kept in sync on multiple machines, this is fine, but slows down the network with it constantly uploading and downloading these files.
Is it possible to setup a second wifi network, which we wouldnt connect to the internet and run tell Dropbox to run on that network as it has LAN sharing, i know this wouldnt share the data to external devices, unitl we connected to an internet connection, but for our purposes this is fine.
While we want to have a second network we still need our main one to connect to the internet so is there a way we can get our computers all Mac OSX to connect to two wifi networks simultaneously and tell it to use one for Dropbox only and the other for everything else.

A: There is no problem with using multi-homed computers, either wired or wireless. You will just need to configure the route for the second network.
However if you use using wireless B/G (2.4GHz bands) then you will need to make sure that there are no overlapping channels.
For more information on wireless channels see this article on Wikipedia. Specifically the following graphs:

If you are using the 5GHz band then this should not be a problem since it has many more bands.

Not asked, but why not use a file-server to host your 100 mbit files?


text:
Q: Writing structs to a socket So I have some structs containing data that I want to send to another process using a unix socket. This process may not be compiled using the same compiler version, or even be written in C for that matter. This is the struct (note that some stuff is commented out):
struct nested_struct {
    uint8_t a;
    uint8_t b;
    uint16_t c;
} */__attribute__((packed))*/;

struct my_struct {
    uint32_t num_nested_structs;

    /* uint8_t padding[3];*/
    uint8_t   x;
    uint16_t  y;
    uint16_t  z;

    struct nested_struct nested[];
} /*__attribute__((packed))*/;

For convenience and performance, I'd like to get away with something like
write(socket, &data.x, data.num_nested_structs * sizeof(struct nested_struct) + 5)
or something -- but I doubt this would be safe, given that struct my_struct is not nicely aligned. But how about if we un-comment the packed attribute? This feels like it should work, but I've read that referencing fields in __packed__ structs by address can be dangerous.
What if we instead uncomment the uint8_t padding[3]; field? Now both structs are word size-aligned (on a system with WORD_BIT = 32). Is it safe to assume that the compiler won't add any padding in this case? If so, is this enough to ensure that accessing 5 + 4*num_nested_structs bytes of memory starting from &my_struct.x is safe?


text:
Q: Spark-Scala read multiple files and move to other directory I have multiple Csv files in hdfs and some of them not in good format, I would like to read the directory of csv files and then if successfully move the files to other directory. How can I achieve this using spark-scala

A: You need something like that :
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.SparkContext

val conf = sc.hadoopConfiguration
val fs = FileSystem.get(conf)

val srcPath = "dbfs:/src/"
val dest = "dbfs:/dest/"
val ls      = fs.listStatus(new Path(srcPath))

ls.foreach{ p => {
  if(true) spark.read.csv(p.getPath.toString).write.csv(dest + p.getName)
  else println("File ${p.getName} got wrong format")
}}


text:
Q: Static Imports and Constructors In Java, If I want to use a method without creating an instance object of a specific class I use static imports.
Something like:
import static com.company.SomeClass.*;

I can then call methods from that class in aother class without creating an instance of SomeClass.
Once I use a method from that class, is the constructor from that class called as well?
For example, if I call
SomeClass.doStuff();

Does the constructor get called for SomeClass behind the scenes?

A:
Does the constructor get called for SomeClass behind the scenes?

Invoking a method doesn't call constructor. Constructor is called when you create an instance of a class. Here, you aren't instantiating the SomeClass, but simply accessing the static method directly on class name. So, there is no point of constructor being called.
However, if you want to invoke an instance method, then first you would need an instance of the class containing that method. You can access an instance method only using an instance of class. But in this case also, calling the method doesn't call constructor behind the scene.

A: static import hasn't got anything to do with what you're talking about. It just makes sure that with
import static org.junit.Assert.assertEquals
you can use assertEquals() instead of Assert.assertEquals()
when you have the following signature:
public class Assert {
 public static bool assertEquals()
}

Other than that: no, you do not invoke the constructor when using a static method. Refer to @Rohit's answer for clarification on this aspect.

A: Constructors are called only when one does new MyClass() or Class.newInstance. You can write some static block in this case.


text:
Q: toLocaleString('en-IN') formatting different in browser and node.js environment const x = (1234567890).toLocaleString('en-IN');
const y = (1234567890).toLocaleString('hi-IN');

Both x and y results in "1,234,567,890" in Node.js
but "1,23,45,67,890" in browsers.
Any alternative to fix this problem in Node.js. I want browser output in Node.js too.

Node version: 8.9


text:
Q: access JavaScript variable in new window This is my first JavaScript attempt, so I apologize if things are a little mangled.
I have two html pages (Certificate1.html and Certificate2.html).  What I'm trying to do is prompt the user for his/her name on Certificate1.html, then pass that information to Certificate2.html.  At this point the user's name will be displayed in a certificate that (s)he can print.
Both html pages reference the same JavaScript file (Certificate1.js).  The first page calls passName():
function passName() {
    FirstN = document.frmUserName.inFirstN.value;
    LastN = document.frmUserName.inLastN.value;
   // alert(FirstN); // good
   // alert(LastN); // good
    var Cert = window.open("Certificate2.html");
    Cert.FirstN = FirstN;
    Cert.LastN = LastN;
    //alert(Cert.FirstN); //good
    //alert(Cert.LastN); //good
}

This seems to be working correctly.  Where I'm stuck is the function placeName() that Certificate2.html calls.  I have it firing onLoad, and I know it's accessing the function correctly (I just stuck an alert in there and it came up).  I don't know how to access the FirstN and LastN variables that I passed to Cert in passName().  I've tried document.FirstN but I get "undefined."  How can I access the FirstN and LastN variables that I (think I) passed?
Thanks!
-Kristin
UPDATE:
Got it!!!
I didn't need to access it via window.opener - I had passed in the variables to the window, so I was able to access them directly.
function placeName() {
    //alert(FirstN);
    document.getElementById("pUserName").innerHTML = FirstN + " " + LastN;
}

Thanks guys!!
-Kristin

A: HTML LocalStorage (HTML5)
http://diveintohtml5.info/storage.html
in your first file :
localStorage.setItem("FirstN", document.frmUserName.inFirstN.value);

in the second one :
var FirstN = localStorage.getItem("FirstN");

or simply set Cookies...
http://www.w3schools.com/js/js_cookies.asp
But i think this should be done using PHP or at least not JS

A: Use the window.opener object in the new window.
window.opener.FirstN

W3Schools Examples
Can I pass a JavaScript variable to another browser window?
The following works with my setup:
first.html
<html>
 <script>
   var Var1 = "MyStringVar";
   var Var2 = 123;
   var win = window.open("second.html");
 </script>
</html>

second.html
<html>
 <script>
   alert(window.opener.Var1);
   alert(window.opener.Var2);
 </script>
</html>

A: UPDATE:
Got it!!!
I didn't need to access it via window.opener - I had passed in the variables to the window, so I was able to access them directly.
function placeName() {
    //alert(FirstN);
    document.getElementById("pUserName").innerHTML = FirstN + " " + LastN;
}

Thanks guys!! -Kristin

A: In first window file:
window.yourVariable = value;
In second window file:
window.opener.yourVariable
decription : declare yourVariable as global and bind it to parent window.
If new window is opened from the parent window, then the data can be accessed from 'window.opener'. Since yourVariable is declared as global, the values of parent window can be accessed from the child window by using 'window.opener.yourVariable'


text:
Q: AttributeError: 'str' object has no attribute 'complement' Estoy trabajando con secuencias de ADN y necesito hacer una clase que tenga un método para calcular el ratio de guanina-citosina, otro para hacer el complementario de una cadena de ADN y otro más que haga el complementario y que además lo invierta, además de pruebas unitarias. El primer método consigo que me funcione, el problema viene en el segundo. Este es código que he hecho:
class SequenceBase:

    def __init__ (self, secuencia_nucleotidos):
        if len (secuencia_nucleotidos) == None:
            raise Exception
        else:
            self.secuencia_nucleotidos = secuencia_nucleotidos

    def __str__ (self):
        return self.secuencia_nucleotidos.upper()

    def cadenas_iguales (self, otra_secuencia_nucleotidos):
        return (self.secuencia_nucleotidos == otra_secuencia_nucleotidos.secuencia_nucleotidos)

    def gc_content (self):   #Cálculo ratio GC --> ((G+C)/(A+T+G+C))*100
        contador_guanina = self.secuencia_nucleotidos.count("G")
        contador_citosina = self.secuencia_nucleotidos.count ("C")
        contador_adenina = self.secuencia_nucleotidos.count ("A")
        contador_timina = self.secuencia_nucleotidos.count ("T")
        proporcion_guanina_citosina = float (((contador_guanina + contador_citosina)/(contador_adenina + contador_citosina + contador_timina + contador_guanina))*100)
        return round (proporcion_guanina_citosina, 2)

    def complement (self):
        complementario = self.secuencia_nucleotidos.maketrans ("ATCG","TAGC")
        ADN_complementario = self.secuencia_nucleotidos.translate(complementario)
        return ADN_complementario

    def reverse_complement (self):
        ADN_complementario = self.complement ()
        cadena_invertida_ADN = reversed(ADN_complementario)
        return SequenceBase (cadena_invertida_ADN)

Cuando quiero hacer la prueba unitaria para complement me sale el error AtributeError: 'str' object has no attribute 'complement'. Aquí están mis pruebas unitarias:
def test_complement (self):
    self.secuencia_ADN = "AAAACCCACGTTTGCCCG"
    self.secuencia_ADN_complementaria = "TTTTGGGTGCAAACGGGC"
    self.secuencia_ADN_no_complementaria = "ACCAGT"

    self.assertEqual (SequenceBase.complement (self.secuencia_ADN), self.secuencia_ADN_complementaria)
    self.assertEqual (SequenceBase.complement (self.secuencia_ADN_complementaria), self.secuencia_ADN)

    self.assertNotEqual (SequenceBase.complement (self.secuencia_ADN), self.secuencia_ADN_no_complementaria)
    self.assertNotEqual (SequenceBase.complement (self.secuencia_ADN_complementaria), self.secuencia_ADN_no_complementaria)

def test_reverse_complement (self):
    self.secuencia_ADN_complementaria = "AAACCAGTTGTGTACACAGT"
    self.secuencia_ADN_inversa = "TGACACATGTGTTGACCAAA"

    self.assertEqual (SequenceBase.reverse_complement (self.secuencia_ADN_complementaria),self.secuencia_ADN_inversa)
    self.assertEqual (SequenceBase.reverse_complement (self.secuencia_ADN_inversa),self.secuencia_ADN_complementaria)

Les agradecería si me pudiesen ayudar

A: El codigo que posteas esta incompleto ya que haces referencia en el codigo a atributos y metodos no definidos en el codigo mostrado en el posteo.
Siendo practico el error que se te genera es porque en la funcion test_complement en la linea 5, 6, 8,9 estas llamando al atributo complement de SequenceBase a traves de la nomenclatura del punto: SequenceBase.complement
Talves tu intencion era llamar a complement como metodo del objeto SequenceBase, para eso tendrias que escribir los parentesis sin espacio entre el nombre del metodo y el parentesis.
Tu error es meramente sintactico
Seria entonces llamando a complement como metodo
self.assertEqual (SequenceBase.complement(self.secuencia_ADN), self.secuencia_ADN_complementaria)
self.assertEqual (SequenceBase.complement(self.secuencia_ADN_complementaria), self.secuencia_ADN)

self.assertNotEqual (SequenceBase.complement(self.secuencia_ADN), self.secuencia_ADN_no_complementaria)
self.assertNotEqual (SequenceBase.complement(self.secuencia_ADN_complementaria), self.secuencia_ADN_no_complementaria)

realmente es bastante incomprensible el codigo y te volver a rrojar error con "self.assertNotEqual" y "self.assertEqual" ya que ambos presentan espacio.
Pasando a otra cosa sobre legibilidad de tu codigo te sugiero lo siguiente

*

*usa nombres acotados de variables

*usa variables para almacenar el resultado de operaciones parciales

*usa estas variables en la formula final

*el uso de "float()" en el calculo de guanina citosina es redundante porque todo resultado de division en python 3 lo convierte automaticamente a dato tipo float.

*Acompañar con comentarios facilitara la comprension y recuerdo del significado del codigo para ti en el futuro y para nosotros si pides ayudas

*El "else" del constructor es una redundancia y esta sobrando.

A: No puedes ejecutar SequenceBase.complement("AAGG") pues complement() es un método de instancia, no de clase. Un método de instancia debe ser aplicado a un objeto en concreto, mientras que los métodos de clase se aplican a la clase (métodos estáticos).
El método complement() no tiene parámetros. El self en cuestión no se pasa explícitamente; simplemente identifica el objeto al que se aplica.
En este método,
def test_complement (self):
    self.secuencia_ADN = "AAAACCCACGTTTGCCCG"
    self.secuencia_ADN_complementaria = "TTTTGGGTGCAAACGGGC"
    self.secuencia_ADN_no_complementaria = "ACCAGT"

    self.assertEqual (SequenceBase.complement (self.secuencia_ADN), self.secuencia_ADN_complementaria)
    ...

el self es un objeto de clase TestCase; no debes interferir con él, sólo ocupar sus métodos. Por tanto, las variables que vas a ocupar son locales a la función (sin self).
Segundo, tienes que crear un objeto SequenceBase para poder usar el método complement(). La forma correcta es:
secuencia = SequenceBase(secuencia_ADN)
self.assertEqual (secuencia.complement(), secuencia_ADN_complementaria)

Hay que aplicar lo mismo al resto de los casos de pruebas, que quedarían así:
def test_reverse_complement (self):
    secuencia_ADN_complementaria = "AAACCAGTTGTGTACACAGT"
    secuencia_ADN_inversa = "TGACACATGTGTTGACCAAA"

    sec_comp = SequenceBase(secuencia_ADN_complementaria)
    sec_inv = SequenceBase(secuencia_ADN_inversa)
    self.assertEqual (sec_comp.reverse_complement(), secuencia_ADN_inversa)
    self.assertEqual (sec_inv.reverse_complement(), secuencia_ADN_complementaria)


text:
Q: Send HTML tables with SendMail I'm trying to send some HTML table using Mathematica SendMail function. To do it I wrote this function:
createHTMLTable[list_List] /; Length[Dimensions@list] == 2 :=
 Module[{r, head, data}, head = First@list;
  data = Rest@list;
  head = Map["   " <> ToString[#] <> "	\n" &, {head}, {2}];
  data = Map["   " <> ToString[#] <> "	\n" &, data, {2}];
  headData = Join[{head}, data];
  r = "
\n" <> StringJoin[##] <> "
\n" & /@ headData // StringJoin;
  r = "<!DOCTYPE html>

                    " <> r <> "

            "
  ]

When I send the mail, as in this example:
list = RandomInteger[100000, {10, 3}]

SendMail["From" -> "test@test.com", "To" -> "test@test.com",
 "Subject" -> "Sending Email from Mathematica", "Body" -> createHTMLTable[list],
 "Server" -> "XXXXX"]

there is no table in the mail, but only the HTML text.
Anyone knows how to correct this?
Is there another way to do it?

A: Using JLink and Apache Commons Email and Java Mail it is not that hard to get MIME controlling working. I just modified some code I wrote some time ago (mostly for being able to send Email from within webMathematica) and added the ability to send HTML emails. It is a whole package with the jar files in subfolder and a Notebook with an example, so I hope it is o.k. if I point interested users to my Mercurial repository here (zip download enabled):
http://code.gluonvision.com/SendEmail/
An HTML example is in SendMail.nb
Let me know if it works for you.
Rolf


text:
Q: How to compare the relative Z order of two WPF controls that are part of the same logical/visual tree? Is it possible to compare the relative Z order (which one will draw on top) of two WPF controls regardless of their relation in the logical/visual tree structure and what layout containers are used?
I need this to be able to determine the visible regions of a control that might be overlapped by others.  My plan is to start with the control geometry and intersect with the geometries of all the controls that will draw on top using CombinedGeometry having the GeometryCombineMode property set to "Exclude".
Update:
If everyone is interested I've used gdi32 API to calculate the visible area.

    [DllImport("gdi32.dll")]
    static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

    [DllImport("gdi32.dll")]
    static extern int CombineRgn(IntPtr hrgnDest, IntPtr hrgnSrc1, IntPtr hrgnSrc2, int fnCombineMode);

    [DllImport("gdi32.dll")]
    static extern int GetRegionData(IntPtr hRgn, uint dwCount, IntPtr lpRgnData);

    [DllImport("gdi32.dll")]
    static extern bool SetRectRgn(IntPtr hRgn, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

    [DllImport("gdi32.dll")]
    static extern bool DeleteObject(IntPtr hObject);

A: I ran into a similar problem last night. The goal for me was to determine whether one control would be drawn in front of another. I searched for about 45 minutes and couldn't find a solution provided by APIs so I had to traverse the visual tree to find out which one would be drawn on top. So, I guess based on my research my answer is no, you can't compare relative z order without looking at the visual tree yourself.
In case you still need, here is the code I used to find the relative z order of controls (InFrontOf method), which also takes into account manually setting the .ZOrder property of controls (works for my code but not thoroughly tested, does not work if ZOrder property of control is set to negative value).
private bool InFrontOf(FrameworkElement c1, FrameworkElement c2){
    Panel root = FindWindowRoot(c1); // Find the root of the document, assumes that c1 and c2 are part of the same document
    Trace.Assert(root != null, "root of ui element is not a window or a panel that contains children");

    int z1 = Math.Max(Panel.GetZIndex(c1), GetDrawOrder(root, c1));
    int z2 = Math.Max(Panel.GetZIndex(c2), GetDrawOrder(root, c2));

    return z1 > z2;
}

private Panel FindWindowRoot(FrameworkElement child)
{
    FrameworkElement current = child;
    while(current as Window == null)
    {
        current = (FrameworkElement)VisualTreeHelper.GetParent(current);
    }
    return ((Window)current).Content as Panel;
}

private int GetDrawOrder(Panel root, FrameworkElement needle)
{
    int result = 0;
    FrameworkElement current = root;
    Queue<FrameworkElement> toSearch = new Queue<FrameworkElement>();
    toSearch.Enqueue(current);
    while(needle != current)
    {
        if(current is Panel)
        {
            Panel p = (Panel) current;
            foreach (FrameworkElement frameworkElement in p.Children)
            {
                toSearch.Enqueue(frameworkElement);
            }
        }
        if (current is ContentControl)
        {
            ContentControl cc = (ContentControl)current;
            if(cc.Content as FrameworkElement != null)
                toSearch.Enqueue(cc.Content as FrameworkElement);
        }
        current = toSearch.Dequeue();
        result++;
    }
    return result;
}


text:
Q: How to save latitude, longitude in my db. Using leaflet map I am building an app that uses leaflet map and mongoDB as my db. I want the user to be able to click on a place on the map and edit the details on the marker and then i want to save these places on my db. How do i do that? I am relatively new and i have to do this for my diploma thesis and i have no previous experience with databases and javascript.
I have already setup my db using mongoose.
I searched on stackorverflow for a similar question but i couldn't find anything new, if i just missed it, please redirect me there.
Thanks!

A: Saving data into the database.
// 1. make a mongoose model
const schema = new mongoose.Schema({
  name: {
    type: String,
    default: "Placeholder Location Name"
  },
  coordinates: {
    type: [Number],
    default: [0, 0]
  }
});
const Location = mongoose.model('Location', schema);

// 2. example of making a Location
const exampleLocation = new Location({
  name: "My First Location",
  coordinates: [41.40338, 2.17403] // This is where your example coordinates go.
})

exampleLocation.save((err) => {
  if (err) console.log("An error occured while trying to save: " + err)
  else console.log("Success") // the object is saved
})

Capturing a click on the map
let map = document.getElementById('your-leaflet-map-id')

map.addEventListener('click', (event) => {
  console.log('The clicked coordinates were: ' + event.latlng.lat + ',' + event.latlng.lng)
  // feel free to use these coordinates as you wish
  yourMethodToSaveLocation(event.latlng.lat, event.latlng.lng)
})


text:
Q: How can I get axes not touching each other? Hi I am trying to plot a figure like this:
The right side
The line is not importand, it could be a sine curve or anything like that
thanks!

A: The gnuplot keyword is rangelimited
 set xtics nomirror rangelimited
 set ytics nomirror rangelimited
 set border 3       # only left + bottom
 set offset 5,5,5,5 # this much space between axes and data on all sides
 plot 'hull.dat' with points notitle

A: I don't know if there were a feature like that. What you can do is to manually define the x and y tics, remove them from the top and right side, remove the axis all 4 sides, and then draw where you need them.
Here is an example that plots a range from x^2, and showing only the relevant axis range.
f(x) = x>2 ? ( x<4 ? x**2 : 1/0) : 1/0
set xrange [0:5]
set yrange [0:20]
set ytics 4,2,16 nomirror
set xtics 2,1,4 nomirror
unset border
set arrow from 2,0 to 4,0 nohead
set arrow from 0,4 to 0,16 nohead
p f(x)

It looks like:

The idea was from here: http://www.phyast.pitt.edu/~zov1/


text:
Q: After connecting to Azure SSO, when testing the API in the publisher UI, the API call does not work I still haven't been able to solve this problem..
when I call the API from "Tryout" in Publisher, it comes out like the error message below. No matter how much I regenerate the key, it keeps saying that it is not valid.
Please help me on this.
Command
curl -X 'GET' \
  'https://xxxxx:8243/systemname/1.0.0/AMTSrestapi/api/getdoclist' \
  -H 'accept: */*' \
  -H 'Internal-Key: eyJraWQiOiJnYXRld2F5X2NlcnRpZmljYXRlX2FsaWFzIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiI0ODM3MDlAY2FyYm9uLnN1cGVyIiwiaXNzIjoiaHR0cHM6XC9cL3Nnc2RpYXBpbDAwMS5zZWFnYXRlLmNvbTo5NDQzXC9vYXV0aDJcL3Rva2VuIiwia2V5dHlwZSI6IlBST0RVQ1RJT04iLCJzdWJzY3JpYmVkQVBJcyI6W3sic3Vic2NyaWJlclRlbmFudERvbWFpbiI6bnVsbCwibmFtZSI6IkdBTVRTIiwiY29udGV4dCI6IlwvZ21hdHNcLzEuMC4wIiwicHVibGlzaGVyIjoiNDgzNzA5IiwidmVyc2lvbiI6IjEuMC4wIiwic3Vic2NyaXB0aW9uVGllciI6bnVsbH1dLCJleHAiOjE2MzM3MzI3MjgsInRva2VuX3R5cGUiOiJJbnRlcm5hbEtleSIsImlhdCI6MTYzMzY3MjcyOCwianRpIjoiNDg2YmY4MmItYTMyYi00ZWQ1LTk4NDItNmE4ODU5OTZkZWU4In0.n_DPcyZ7DfPwc_nQTbSB6buHQnacAHGAWsIqVE0UvezrFjF5wu9mQ0UGPO8rBzN_uABoEpscR1PxI5A0LLicP566_H61hwl2hy4dUvYhZwVrCLVneBCxlmO4o9b3d1nJcOcsBf9zAmUDn3_M0K-yBxVrXYZuiA3FFRBK0YyzZQAmhmUatVvh_D7gTXVHR2STYeaRYPqSalbxxyaWLCzhD2sY66BdSD2q476dmXGhYMYTRuMFZrqiALcdhlZpdjAlTHJz0G7q6rCv5EHzuUnGRpBvNaYzzQPjYmHYIBf7RKfXjHMXlHQIp7KCdi9WbrLIUYvQ-Tj5a5v8BVv1d8wW6Q'

Error message.
{
  "code": "900901",
  "message": "Invalid Credentials",
  "description": "Invalid Credentials. Make sure you have provided the correct security credentials"
}

wso2carbon.log
Log file [2021-10-06 13:50:07,068] ERROR - InternalAPIKeyAuthenticator Invalid Internal Key.XXXXXUlMyNTYifQ [2021-10-06 13:50:07,069] WARN - APIAuthenticationHandler API authentication failure due to Invalid Credentials

https://i.stack.imgur.com/uHbWF.png

A: The mentioned error can occur when the API Manager was not able to validate or verify the Signature of the Internal Key access token.
Explanation
The API Manager generates the Internal Key access token (a JWT Token) and signs it with the private key of the Primary Keystore (which is configured under keystore.primary with alias).
During the validation process, the API Manager searches for the public cert of the specific private key using the alias gateway_certificate_alias (this can be configured as well from the TOML).
Hence, if the default shipped Keystore is changed or replaced and the Primary Keystore configurations are updated in the TOML, then it is also required to export and import the public certificate of the relevant private key with the alias gateway_certificate_alias to the client-truststore.jks.
Recovery Steps
*Go through the question comments to understand the steps and shared information
As per the shared information, you have generated a new Keystore with an existing cert for the SSL communication and have replaced the wso2carbon.jks as well as configured the new keystore in the TOML configurations. Therefore, it is required to update the public certs in the client-truststore with relevant credentials.
Follow the given steps to update the cert that has been aliased as gateway_certificate_alias in the client-truststore.jks

*

*Export the public cert of your new Keystore (enter the Keystore password when prompted)
keytool -export -alias apimanagercert7 -file wso2.crt -keystore newkeystore7.jks

*Import the public cert to the client-truststore with the alias gateway_certificate_alias (enter the Truststore password when prompted)
keytool -import -trustcacerts -keystore client-truststore.jks -alias gateway_certificate_alias -file wso2.crt

If you get any errors when trying to import the certs to the truststore mentioning the alias exists, then execute the following command to delete the alias and perform the above-given steps again to import it
keytool -delete -alias gateway_certificate_alias -keystore client-truststore.jks

After performing the steps, restart the API Manager server and try invoking the API using the Internal Key from the Publisher portal.


text:
Q: Geocoding nearby locations uses too many Google Maps queries I'm using this code to get all ads on my site which are within a given distance. I have two models, Ad and Location. Every Ad has_one Location. I am geocoding the address field of every Location to find those which are within range of a user's search.
This code probably needs refactoring, but I managed to get it to do what I need it to; when a user searches an address, all ads within a certain distance are displayed.
The problem is that the code performs a query on every ad, and with 1000 ads in my database, this quickly goes over Google Maps' limit. I have buttons which the user can click to change the distance to search, and each click again performs a query on every ad. Is there another way I can code this which will not require so many queries?
    #find ads with locations in range of user address search
    ads_within_distance = Ad.select { |ad| ad.location.distance_from(cookies[:search_address]) <= distance.to_f }

    ads_within_distance.each do |ad|
        nearby_ads_id_array = ad.id
    end

    @nearby_ads = Ads.where(id: nearby_ads_id_array).paginate(:page => params[:page], :per_page => 5).order('created_at DESC')

This can obviously be done, as many sites such as meetup.com have this feature. I'm willing to use whatever method is most efficient. I'd really appreciate any input.

A: There are two problems with your approach. I am assuming that a location can have many ads. If this is the case, your associations should be:
class Location < ActiveRecord::Base
  has_many :ads
  ...
end

class Ad < ActiveRecord::Base
  belongs_to :location
  ...
end

Since you are iterating over ads, you are potentially checking distances many times for the same location.
Secondly, since you are passing in an address, you are geocoding for each ad even though you only have a single address which you don't have a lat and long for (the user-entered address). I am assuming that your locations in the database have already been geocoded and you have a lat and long for each.
If you are using the geocoder gem (https://github.com/alexreisner/geocoder), you can write:
nearby_locations = Location.near(cookies[:search_address], distance.to_f)

Then you can find all the ads which belong to those locations by:
nearby_ads = Ad.where(location_id: nearby_locations)

Good luck.


text: Q: What's the best way to render Visual Composer in posts, not pages? I have a page with layout and ui content I'd love to use in my posts.  Is that possible without running through all the shortcodes with do_shortcode?


text:
Q: how to run Qt project on iOS simulator and android simulator using QT Creator on mac Yosemite i am new with QT development. i am trying to run Qt sample project on iOS simulator and android emulator.
it runs fine on real iPhone device but
run on iOS simulator, Qt Creator gives me Application Output:
error loading  iPhoneSimulatorRemoteClientRun ended unexpectedly.

i have already installed Xcode 6.3.2 with command line developer tools and using QT Creator 3.0 with QT 5.2.0
when run on android emulator, the virtual device (AVD for Nexus One By Google Android4.3.1 API level 18, CPU\ABI: ARMeabi-v7a ) i created in AVD Manager shown as incompatible
i have already given the paths of sdk, ndk, jdk, ant in QT Creator and i also have set the environment variable by creating a file named .bash_profile  in Home directory and puts these lines into this file
export JAVA_HOME= /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
export PATH= $PATH:/Users/graphics/Desktop/Android/AndroidSDK/tools
export PATH= $PATH:/Users/graphics/Desktop/Android/AndroidSDK/platform-tools
export ANDROID_NDK_ROOT= /Users/graphics/Desktop/Android/android-ndk-r10e
export ANDROID_SDK_ROOT= /Users/graphics/Desktop/Android/AndroidSDK
export ANDROID_HOME= "$ANDROID_SDK_ROOT"

i don't know either its a correct method to set environment variables or not.
i need your help to resolve this issue.Your effort will be of great help. Thank you.

A: you have to download just only Qt 5.5.0 for Android and iOS (Mac, 1.7 GB) file from https://www.qt.io/download-open-source/ and install it.
when it is completely installed, open up the terminal and enter
export ANDROID_HOME=/Users/graphics/Desktop/Android/AndroidSDK
export PATH=$PATH:$ANDROID_HOME/bin

commands to set the environment for android development.
to set your android configuration just give these paths into the QTCreator
JDK Location:
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home

Android SDK Location:
/Users/graphics/Desktop/Android/AndroidSDK

Android NDK Location:
/Users/graphics/Desktop/Android/android-ndk-r10e

Ant executable:
/Users/graphics/Desktop/Android/apache-ant-1.9.5/bin/ant

and must allow Automatically create kits for Android tool chains
this is how you can get your JDK location on mac :
just enter
/usr/libexec/java_home

in terminal.
Now create your virtual device as what you need every thing will be fine. no worries then. you can run your apps on both android emulator and iPhone simulator.
Notice: give path of AndroidSDK, Android NDK, Ant executable location according to yours.
one more thing that i did, previously installed Xcode 6.3


text:
Q: How to check for spaces before or after a string in excel I have a column containing values spread over several rows. Some of the values have a space either in front or at the end of the value. Is there a simple way to find out such occurences in a excel sheet.

A: Yes there is.  So the original length is
=len(A1)

right?  If you trim it and it returns a different length, then there was a space at either the beginning or end of the value, which would be-
=if(len(A1)-len(trim(A1))>0,"yes","no")

A: Do you want the check in a separate column? If so, try adding this in a column next to the data (or anywhere you want, as long as you reference the column):
=IF(LEN(A1)-LEN(TRIM(A1))>0,"SPACE!","")

This would go in cell B1. Note that this will also catch instances with multiple spaces before/after the string. However as @YograjGupta mentions, this will also return true if there are consecutive spaces inside the string.

A: If none of the other answers in this post work, but Sachin Pandit's "CODE(160)" formula does, then you didn't actually have "spaces" as such [CHAR(32)] but rather some non-breaking whitespaces [CHAR(160)].
To deal with text that has double (or more) CHAR(32) spaces between words, you could use this formula:
=IF(OR(LEFT(SUBSTITUTE(A1,"  ",""),1)=" ",RIGHT(SUBSTITUTE(A1,"  ",""),1)=" "),TRUE,FALSE)

A: Assuming you have the data in column A, you could enter the following formula in any column starting from row 1 and drag down to identify spaces
=IF(OR(LEFT(A1,1)=" ",RIGHT(A1,1)=" "),TRUE,FALSE)
TRUE will identify data with a leading or trailing space

A: Other than below code, rest did not work - This is to only find leading spaces ,
=IF(CODE(LEFT(<reference cell>,1))=160,"Leading Space","No Leading space")


text:
Q: C++ ternary assignment of lambda Any idea why the following snippet doesn't compile? It complains with an error "error: operands to ?: have different types"
  auto lambda1 = [&](T& arg) {
      ...
  };
  auto lambda2 = [&](T& arg) {
      ...
  };
  auto lambda = condition ? lambda1 : lambda2;

A: Since 2 lambdas(lambda1 and lambda2) are 2 different types, ?: cannot deduce return type for lambda from lambda1 and lambda2. This happens because these 2 are not convertible to each other.

A: It doesn't compile because each lambda has a unique type, there isn't a common type for ?:.
You could wrap them in std::function<void(T&)>, e.g.
auto lamba1 = [&](T& arg) {
  ...
};
auto lambda2 = [&](T& arg) {
  ...
};
auto lambda = condition ? std::function(lambda1) : lambda2; // C++17 class template deduction

A: Curiously, if lambdas are capture-less, operator + trick can be employed:
auto lambda1 = [](int arg) { ... };
auto lambda2 = [](int arg) { ... };

auto lambda = condition ? +lambda1 : +lambda2; // This compiles!
lambda(2019);

This works, because + will convert lambda into a function pointer, and both function pointers have the same type (something like void (*)(int)).
With GCC and Clang (but not with MSVC), + can be omitted, lambdas will still be converted into function pointers.

A: Individual lambdas are translated to different classes by the compiler.
For example, lambda1's definition is equivalent to:
class SomeCompilerGeneratedTypeName {
public:
  SomeCompilerGeneratedTypeName(...) { // Capture all the required variables here
  }

  void operator()(T& arg) const {
    // ...
  }

private:
  // All the captured variables here ...
};

Therefore, two different types are generated by the compiler, which causes a type incompatibility for auto lambda = condition ? lambda1 : lambda2;
The following would work:
auto lambda = condition ? std::function<void(T&)>(lambda1) : std::function<void(T&)>(lambda2);

To highlight that both lambdas are indeed different types, we can use <typeinfo> from the standard library and the typeid operator. Lambdas are not polymorphic types, so the standard guarantees that the 'typeid' operator is evaluated at compile time. This shows that the following example is valid even if RTTI is disabled:
#include <iostream>
#include <typeinfo>

int main()
{
    struct T {

    };

    auto lambda1 = [&](T& arg) {
        return;
    };

    auto lambda2 = [&](T& arg) {
      return;
    };

    std::cout << typeid(lambda1).name() << "/" << typeid(lambda1).hash_code() << std::endl;
    std::cout << typeid(lambda2).name() << "/" << typeid(lambda2).hash_code() << std::endl;

    return 0;
}

The output of the program is (with GCC 8.3, see on Gobolt):
Z4mainEUlRZ4mainE1TE_/7654536205164302515
Z4mainEUlRZ4mainE1TE0_/10614161759544824066

A: The compiler can't decide what type auto should be:
auto lambda = condition ? lambda1 : lambda2;

since every lambda has a different and unique type.
One way that'll work is:
auto lambda = [&](T& arg) {
     return (condition ? lambda1(arg) : lambda2(arg));
}


text:
Q: How to set text over bottom button background in tablelayout Here's what i have:
Here's the layout:`

<TextView
    android:id="@+id/process_search"
    android:text="@string/home_screen"
    style="@style/SubPageHeader"/>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bottom_round_edges"
    android:padding="1dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/bottom_round_edges_white_back"
        android:gravity="center_vertical">

        <TableLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:stretchColumns="1">
               <!-- android:layout_gravity="center|bottom"-->

            <TableRow>

                <Button
                        android:id="@+id/btn_home_dados_pessoais"
                        android:layout_width="0dip"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|bottom"
                        android:padding="10dip"
                        android:background="@android:color/transparent"
                        android:drawableTop="@drawable/ic_dados_pessoais_complete"
                        android:text="@string/home_dados_pessoais"
                        android:textColor="@android:color/darker_gray"
                        android:textSize="12sp"
                        android:textStyle="bold"/>

                <Button
                        android:id="@+id/btn_home_historico_pesquisas"
                        android:layout_width="0dip"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="10dip"
                        android:background="@android:color/transparent"
                        android:drawableTop="@drawable/ic_pesquisa_complete"
                        android:text="@string/home_historico_pesquisas"
                        android:textColor="@android:color/darker_gray"
                        android:textSize="12sp"
                        android:textStyle="bold"  />
            </TableRow>

            <TableRow>

                <Button
                        android:id="@+id/btn_home_configuracoes"
                        android:layout_width="0dip"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="10dip"
                        android:background="@android:color/transparent"
                        android:drawableTop="@drawable/ic_config_complete"
                        android:text="@string/home_configuracoes"
                        android:textColor="@android:color/darker_gray"
                        android:textSize="12sp"
                        android:textStyle="bold"/>

                <Button
                        android:id="@+id/btn_home_opcoes"
                        android:layout_width="0dip"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:padding="10dip"
                        android:background="@android:color/transparent"
                        android:drawableTop="@drawable/ic_android_complete"
                        android:text="template"
                        android:textColor="@android:color/darker_gray"
                        android:textSize="12sp"
                        android:textStyle="bold" />
            </TableRow>
        </TableLayout>
    </LinearLayout>
</LinearLayout>

`
What i want is put the text in the button area but at the bottom. How can i do this?

A: You can use a FrameLayout. According to the docs:

You can, however, add multiple children to a FrameLayout and control
  their position within the FrameLayout by assigning gravity to each
  child, using the android:layout_gravity attribute.

In your case, the xml would become:
<TableRow>
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_home_dados_pessoais"
        android:layout_width="0dip"
        android:layout_gravity="center"
        android:padding="10dip"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/ic_dados_pessoais_complete" />
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/home_dados_pessoais"
        android:textColor="@android:color/darker_gray"
        android:textSize="12sp"
        android:layout_gravity="bottom"
        android:textStyle="bold">
      <!-- The rest of the row -->
</FrameLayout>
</TableRow>

On a side note, I suggest you use a style for your buttons: most of their styling is redundant. Check out this page for an example.

A: Create a new drawable that is that grey square "background" of your button, and set that to the android:background. Modify your button drawable to only be the icons, with a transparent background. Just doing this will get you what you want, a button with grey background, text on the bottom, image on the top.
Edit: added example below
Icon Drawable (R.drawable.btnIcon1)

Background Drawable (R.drawable.btnBackground)

<Button
    android:id="@+id/btn_home_dados_pessoais"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center|bottom"
    android:padding="10dip"
    android:background="@drawable/btnBackground"
    android:drawableTop="@drawable/btnIcon1"
    android:text="@string/home_dados_pessoais"
    android:textColor="@android:color/darker_gray"
    android:textSize="12sp"
    android:textStyle="bold"/>


text:
Q: Editing .resx files on a Mac Is there any app that I can use to edit .resx files on a Mac running OSX?
I just need to be able to edit string resources.
Edit. I know .resx files are XML files. However, I am looking for an app that can edit .resx files using a clean user interface, very much like Visual Studio does, hiding the complexity of the XML. I don't want users to be able to accidentally modify the XML structure.

A: As far as I'm aware, not directly. However, .resx files are XML, so you if you're comfortable with their syntax, open them in your favorite plain-text editor (XCode, BBEdit, whatever) and hack away.
Edit based on the update to the question
Nothing, as far as my Google-fu can find, currently exists to fill this need. However, .resx files are relatively straightforward XML, so if you have a Mac and XCode, you can probably whip up something with an NSTableView that operates similarly to Visual Studio's in-box .resx editor for strings.
Now, it's considerably less trivial to support other resource formats (particularly binary data), but strings at least shouldn't be terribly complicated.
I wish I could give you a "proper" answer, but unfortunately, I simply cannot locate anything appropriate. I see many .resx editors out on the web, but all are for Windows. To get you started building something (I know this wasn't your intent, but it's likely your only answer), check these APIs:

*

*Mac XML APIs, courtesy of Apple's Developer site.

*NSTableView class reference

*NSTableViewDataSource class reference
If building something is truly not viable, your other option is to either virtualize Windows (using VMWare Fusion or Parallels Desktop), or to use Boot Camp and create a Windows partition. Then you can install any of the zillion and one .resx editors for Windows -- or even a Visual Studio Express instance, which will also contain .resx editing in-box.

A: There is now a macOS app for editing regex files in the App Store.
https://apps.apple.com/us/app/resx-editor/id1484612171?mt=12
I've just started using it, so I can't offer much of a review, but it does seem to work fine so far, and at that price, I figured it was worth checking out.

A: The best App is ResX Editor, it is for Mac user.
It do the job like a charm! this is worth it for 2$!
You can get it for free on source forge

A: If you are still looking for an option for your mac, I used an extension (free) for VisualStudio Code called ResXpress: https://marketplace.visualstudio.com/items?itemName=PrateekMahendrakar.resxpress


text:
Q: Clicking a Button in Google Chrome using JavaScript (Tampermonkey extension) What I am trying to do
I am new to JavaScript and I am trying to code button 1 so that when it is clicked, button 2 is also clicked. (This function/ button 1 click is running completely fine as I have tested it multiple times.) The problem is that button 2 is not clicking for some reason.
What I have tried
I have tried using this code
window.deactivateAutoBuyer = function() {

    document.getElementsByClassName("btn-standard increment-value")[0].click();

    window.autoBuyerActive = false;
    window.notify('Autobuyer Stopped');

}

However, the only result I get is the notification that says "AutoBuyer Stopped".
HTML Code for the button
<button class="btn-standard increment-value"></button>

A: You could call the function associated with button 2 or you can use an event listener on the first button to then click the second button.
const button1 = document.getElementsByClassName("btn-standard increment-value")[0];
const button2 = document.getElementsByClassName("btn-standard increment-value")[0];

button1.addEventListener('click', () => { button2.click() });


text:
Q: How does exec family of functions work internally? Does execv() family of functions call mmap() functions internally to load text,data,bss segments from elf file? Can any one please share the blocks or steps involved in the working of exec() functions. Also please suggest some links or books to learn about how exec works internally.

A: The execv() is a userspace libc wrapper which pass control through syscall to kernel side into do_execve() .
do_execve() finds appropriate binary handler for exec file to load. We will next consider example for ELF executable format.
The appropriate binary handler for elf format is load_elf_binary() . It uses elf_map() to map appropriate elf segments to memory through vm_mmap() API.
Is that what are you asking about?


text:
Q: Prove an elementary inequality In the book Linear Integral Equations by Rainer Kress at page 138 is stated without giving a proof this inequality:
$$v^\delta e^{-v}\leq \delta^\delta e^{-\delta},$$
for all $v,\delta\in]0,\infty[$. I've tried to prove it, but I haven't succeed.
 Any ideas?

A: One has $\ln(x)\leq x-1$ for all positive $x$, and so in particular for $x=\frac{v}{\delta}$. Playing around with $\ln(\frac{v}{\delta})\leq \frac{v}{\delta}-1$ results in your inequality.


text:
Q: Getting the Age using Parameter Value and Current Date [CRYSTAL REPORT] I'm trying to get the age of my user in crystal report using parameter and current date.
This is my formula for the crystal report.
INT ((CurrentDate - {?txtbdate}) / 365.25)

For example: the date in {?txtbdate} is 1996-07-29 and today
  is 2018-10-25.
The age must be 22.

When I execute it, a popup message appear saying "A number is required here."

A: This is just a blind guest, but you must first convert the data before doing the math,
For ex. (INT (CurrentDate) - INT ({?txtbdate})) / 365.25
each value must be Identified as integer before subtracting
The Right way of doing it:
you can use the DateDiff function on the
ex. DateDiff("yyyy", CurrentDate, {?txtbdate})


text:
Q: XSLT 2.0 - Template Matching With Contains() I'm wondering if it is possible to write a template match with the contains() function.
I have a document that has multiple elements that need to be renamed to a common element. All of the following need to be renamed to just OP: OP1.2, OP7.3, OP2.4, OP5.6`, etc.

A: Yes, you can use contains() inside of a predicate filter in the match criteria for elements.
<xsl:template match="*[contains(local-name(),'OP')]>
  <OP>
    <xsl:apply-templates select="@*|node()"/>
  </OP>
</xsl:template>

You could also use starts-with()
*[starts-with(local-name(),'OP')]

If you are using XSLT 2.0 you could use the matches() function, which supports REGEX patterns for more complex matching.
*[matches(local-name(),'^OP')]


text:
Q: Show $P(X|Z_1,...,Z_n,Y)\not = P(X|Z_1,...,Z_n) \Leftrightarrow P(Y|Z_1,...,Z_n,X)\not = P(Y|Z_1,...Z_n)$ If we have two random variables $X,Y$ and a set of random variables $\{Z_1,...,Z_n\}$, are there any common proofs of the result in the title? Which theorems does this follow after?

A: The starting point here is the definition of conditional probability:
$$
P(X|Y) = {P(X,Y) \over P(Y)}
$$
Then just repeatedly applying that gets the result.
Just to make it easier to view, write $Z\equiv Z_1, Z_2, ..., Z_n$. Then
$$
P(X|Z,Y)={P(X,Y,Z)\over P(Y,Z)}={P(Y|Z,X)\times P(Z,X) \over P(Y|Z)\times P(Z)} = {P(Y|Z,X)\times P(X|Z) \over P(Y|Z)}
$$
Thus
$$
{P(X|Z,Y)\over P(X|Z)}= {P(Y|Z,X) \over P(Y|Z)}
$$


text:
Q: How do you pronounce "HTTPS"? When I refer HTTPS, I pronounce it by reading each character. However, I wonder whether there is a quicker and easier way to pronounce it.

A: HTTPS is pronounced as you said you pronounce it, by reading each letter.
It's also referred to as HTTP Secure or Secure HTTP. It stands for Hypertext Transfer Protocol Secure.


text:
Q: Log In/Registration PHP Object Oriented style error I'm new to Object-Oriented in PHP I'm trying to put a login and registration form into my social media site project. And I encounter this error Uncaught Error: Call to a member function query() on null in [DIRECTORY]/user.php:11 which is this (the whole code of user.php):
<?php
    include_once 'lib/database_config.php';

    class User {
        public $db;

        public function reg_user($name, $userName, $userPassword, $email) {
            $userPassword = md5($userPassword);
            $sql = "SELECT * FROM users WHERE username='$userName' OR email='$email'";

            // the error line
            $check = $this->db->query($sql);
            // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            $count_row = $check->num_rows;

            if($count_row == 0) {
                $sql1 = "INSERT INTO users SET username='$userName', password='$userPassword', fullName='$name', email='$email'";
                $result = mysqli_query($this->db, $sql1) or die(mysqli_connect_errno()."Data can't insert.");
                return $result;
            } else {
                return false;
            }
        }

        // Login Process
        public function check_login($emailusername, $password) {
            $password = md5($password);
            $sql2 = "SELECT id from users WHERE email='$emailusername' or username='$emailusername' and password='$password'";

            // Check if the username is available in the table
            $result = mysqli_query($this->db, $sql2);
            $user_data = mysqli_fetch_array($result);
            $count_row = $result->num_rows;

            if($count_row == 1) {
                $_SESSION['login'] = true;
                $_SESSION['id'] = $user_data['id'];
                return true;
            } else {
                return false;
            }
        }

        // Session start
        public function get_session() {
            return $_SESSION['login'];
        }

        public function user_logout() {
            $_SESSION['login'] = FALSE;
            session_destroy();
        }
    }

?>

The purpose of the above code is mainly for all the functionality of login and registration form (there are some function code blocks in other files.) but I think the problem is around the user.php(this one) & I think it's lacking of something that I've been figuring out for an hour.

A: you are calling $this->db->query($sql);
But at no time did you assign value to the $this->db variable


text:
Q: Replacing Double quotes from json request objective c Stuck on below.
I am going to replace "" (Double quotes) from textfield text and send that text in json request parameter but below code is not working
NSString * mString = textfield.text; // Input through ipad/iphone/simulator keypad.

[mString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mString length])];.

But if i hardcode NSString * mString = @"\"test"; // Input through xcode
replaceOccurrencesOfString: is working.
Is the issue with Double quote Input encoding.?
Why does the Double quote from ipad/iphone/simulator keypad not working same as xcode Double quote.
Thanks.

A: By default, the iOS keyboard uses "smart" quotes... it uses left double quotation mark when you open a quoted string portion, and right double quotation mark when you close the quoted portion.
So to strip those, you'll need to replace double-quote AND left-double-quote AND right-double-quote.
Here's a quick example:
NSString *origString = _myTextField.text;
NSString *strippedString = [origString copy];

NSArray *replaceChars = @[@""", @""", @"\""];

for (NSString *c in replaceChars) {
    strippedString = [strippedString
                      stringByReplacingOccurrencesOfString:c
                      withString:@""];
}

NSLog(@"Orig: [%@] / Stripped: [%@]", origString, strippedString);

Example output:
Orig: ["test"] / Stripped: [test]

You have to look close, but you'll see the left- and right-double-quote-marks.

Edit
A much more concise way:
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"""\""];
NSString *strippedString = [origString stringByTrimmingCharactersInSet:set];
NSLog(@"Orig: [%@] / Stripped: [%@]", origString, strippedString);

But, as noted by Sulthan, you may need to consider other languages' punctuation.


text:
Q: highcharts stacked column draw horizontal line I need to draw horizontal line on highcharts stacked column as image below

In image Bold black line is showing, I need to draw same, however Bar color opacity changes when it split columns.


text:
Q: Uploading lots of raster files/georeferenced maps to ArcGIS Online? The end goal is to build a web application where people can explore the historical maps I've georeferenced - among other things. ArcGIS online is the ideal venue for everything else I want, but for whatever reason it seems I can't easily upload raster files as in ArcMap. And I have approx. 12 rasters I want to upload (about the size of Bermuda).
There seems to be some confusing work arounds, but my concern is that a lot of credits will be used. Also, even more importantly, it seems I have to publish my rasters as layer files to ArcGIS online as a work around, but I feel this makes my work public to use by other users. I want only those in my organization to be able to access and use my georeferenced work in their maps. The work I've performed isn't mine to share, it belongs to my educational institution.
What's the best route for me to go? Is there a way to publish these layers to ArcGIS Online in a way that makes the layers accessible only to my organization?

A: To reduce credit usage first build tile packages in ArcMap or Pro. Then you will upload the tpks to AGOL which will create a hosted tile service of your raster data. Then you can have control to share the layer to your organization and not to everyone. This will keep the content inside your organization and will not be accessible to users outside your org.

A: From your original post it sounds like you may have already found info on how to publish tile layers online, but here's a link to the step-by-step process I used when I've done this in the past (I followed the "Define and publish a map in ArcMap" instructions): http://doc.arcgis.com/en/arcgis-online/share-maps/publish-tiles.htm
If your ESRI license is through your educational institution, make sure that your administrator gives your account the privileges to publish tile layers; I had to ask for it.
Also, you can still limit access to these layers like other maps/KMLs. On the My Content page, select the tile layer you just uploaded and click "Share" at the top of the window. Then check who you want to have access to your files (you can even limit access to a specific group smaller than your organization; see below).


text:
Q: Second part of Sylow's Theorem about conjugacy Let $G$ be a group. Part two of Sylow's theorem says that all Sylow $p$-groups (for a given $p$) are conjugate. So I assume that means given two Sylow $p$-groups $P$ and $Q$ there exists $g\in G$ such that $gPg^{-1}=Q$. Of course this is a different statement from: for all $g\in G$, $gPg^{-1}$ is a Sylow-$p$ group. Right? I ask because my lecturer keeps using the latter property, which does not seem to me to follow from the former. For example, to prove that if there is only one Sylow p-group (for a given $p$), that that subgroup must be normal, he says for all $g \in G$, $gPg^{-1}=P$, because $P$ is the only one. A bit confusing.

A: If $P$ is a Sylow $p-$subgroup, then so is $gPg^{-1},$ since they have the same cardinality. So if the Sylow $p-$subgroup is unique, we must have $$gPg^{-1}=P$$ for all $g \in G.$ Hence, $P$ is normal.


text:
Q: syntax error at or near ";" LINE 22 - Postgresql I am creating a user defined function in PostgreSQL and facing error.
Also, please suggest a better way (if any) to execute this function.
CREATE FUNCTION public.mark_enrollment_completed(IN enrollment_id text)
    RETURNS boolean
    LANGUAGE plpgsql
AS $BODY$

DECLARE
    total_contents INTEGER;
    completed_content_count INTEGER;
    user_id TEXT;
    course_id TEXT;
    was_marked BOOLEAN;
BEGIN
    SELECT user_id, course_id INTO user_id, course_id FROM enrollments WHERE enrollment_id = enrollment_id;
    SELECT count(*) INTO total_contents FROM course_contents WHERE course_id = course_id;
    SELECT count(*) INTO completed_content_count FROM completed_contents WHERE user_id = user_id;
    IF total_contents = completed_content_count THEN
        UPDATE enrollments SET is_completed = true WHERE enrollment_id = enrollment_id;
        SET was_marked = true;
    ELSE
        SET was_marked = false;
    RETURN was_marked;
END;
$BODY$;

Error:
ERROR:  syntax error at or near ";"
LINE 22: END;
            ^
SQL state: 42601
Character: 750

A: As documented in the manual assignment is done using := operator - there is no SET in PL/pgSQL.
You are also missing the END IF
IF total_contents = completed_content_count THEN
    UPDATE enrollments SET is_completed = true WHERE enrollment_id = enrollment_id;
    was_marked := true;
ELSE
    was_marked := false;
END IF;
RETURN was_marked;


text:
Q: Sampling metric data in Application Insights The documentation page for Azure Application Insights sampling mentions the following:

A semi-colon delimited list of types that you want to be sampled.
  Recognized types are: Dependency, Event, Exception, PageView, Request,
  Trace. The specified types are sampled; all instances of the other
  types will always be transmitted.

Does it mean that Metrics data (Performance counters) are always transmitted? Doesn't it make sense to sample metrics before all other types?

A: For Metrics it makes sense to aggregate and then send. This is how Performance counters work (one value per minute).
For custom metrics (TrackMetric) usually some layer aggregates (calculates average, min, max, etc.) and then call AI SDK to track aggregated value.
For these scenarios sampling is not needed.
In parallel AI team is working on layer which will take care of aggregation. So it would be possible to track individual values.


text:
Q: Create new-line in .replace() Everywhere I look, people say do this:
 .replace(/\"/g, '
')

but is just prints
 in the string..
I'm using this in a custom pipe in Angular.

   {{message.content | jsonpipe}}

'message is an array of JSON objects
@Pipe({ name: 'jsonpipe' })
export class Jsonpipe implements PipeTransform {
  transform(value: string): string {
    let newStr = '';
    newStr = value.replace(/{/g, '').replace(/\"/g, '').replace(/}/g,
    '').replace(/:/g, ': ').replace(/,/g, '\
');
    return newStr;
  }
}


text:
Q: Django easy-thumbnails plugin makes darker images I get this behavior only while using easy_thumbnails. If the image is not processed through easy_thumbnails it works well.
When cropping (through easy_thumbnails) images get darker and with different hue (more green). Could it be something with the colorspace through the process?
Did anyone have a similar issue?
Thanks