text:
Q: Decimal conversion localization(German) I have a decimal value 14780 in En-US locale , the expected output in German is 14.780. But the trailing zero is not taking.
Decimal.Parse(string.Format("{0:n0}", 14780),System.Globalization.CultureInfo.InvariantCulture)
Observed output : 14.78

A: *

*System.Globalization.CultureInfo.InvariantCulture is not the same as German (de-DE). When parsing and converting to string always use the same culture by specifying that culture in the Parse/TryParse and also the Format methods. Using English (invariant) for one and German for the other will lead to unexpected results because the decimal and comma have opposite meaning between the cultures. Never assume the thread supplies the culture unless you know what that culture is and it cant be changed.

*A trailing 0 would never be dropped from the left side of the decimal unless you are using scientific notation in which case even then it is preserved but using an exponent. Maybe you are did not type your question correctly and are referring to the right side (fractional part) of the number?

Code sample:
var value = 14780M;
var strValue = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:n0}", value)
// strValue is equal to "14.780"

Here is your code above showing that it works when using the same culture but breaks when you mix cultures.
// OK - using InvariantCulture for both
var culture = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), culture));

// OK - using de-DE for both
culture = System.Globalization.CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), culture));

// FAIL - mixing de-DE and InvariantCulture
culture = System.Globalization.CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine(Decimal.Parse(string.Format(culture, "{0:n0}", 14780), System.Globalization.CultureInfo.InvariantCulture));

See Fiddle

A: decimal type does not store thousands seperators. But you can reconstitute them again when converting the decimal back to a string.
decimal deci = Decimal.Parse(string.Format("{0:n0}", 14780), System.Globalization.CultureInfo.InvariantCulture); // 14780
string str = string.Format("{0:n0}", deci); // 14.780

.NET String.Format() to add commas in thousands place for a number.
.net Fiddle


text:
Q: New Project - Angular 1.4 or 2.0? We are about to start the new project with Angular and Kendo Components, using Angular latest version 1.4, but I am hearing too many new things with Angular 2.0 but at the same time, it does not have backward compatibility.
With no release date announced, we are kind of confused about whether to wait 2.0 release date or go ahead with 1.4 ?
Please suggest.

A: Angular 2 will certainly break backward compatibility, but it is not even a beta. That means that half of the implementation of Angular 2 is still on the air so you can't create a big Angular 2 application yet.
You need to wait a few months for Angular 2 to be stable + few months for the libraries to be ported to Angular 2.
In short, you better use angular 1.x for this project and maybe the next ;)

A: Angular 1.x is here to stay for the next 3 years, at least. Here's why:
Originally Google said they would support AngularJS 1.x for approx. one year after the late-2015 release
of 2.0. (so for the entire 2016), and they received a harsh reaction from the community.
Then, they changed their tune, saying that they will support version 1 as long as there is a high demand.
This demand will be measured somehow by how well the community adopts version 2 as opposed to 1.
(let's assume another year of updates, 2017)
When it comes to job posts AngularJS is still HUGE from what I've seen, which shows that companies are still investing
heavily in 1.x. for new projects.
So, let's say Google will abandon the project for 2018. AngularJS is still open source (not like Windows XP), so there's an opportunity for others
to pick up development from where Google left off.
Even for version 1.4, Google states that:

"This Angular version is the first to be run by a much broader
  community oriented team, including many people from outside of the
  Google Angular team..."

(http://angularjs.blogspot.com/2015/05/angular-140-jaracimrman-existence.html)
This shows that Google is slowly releasing the project into the hands of the community.
There are many open source projects out there that are doing fine without Google's support. So will Angular 1.x.
By the time 3 years have past, version 2.x will be more stable and the migration path will be proven and tested.
If this sounds scary, you can just pick another framework, but chances are the same problems will arise.
It's a fast-paced front-end world.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a new RDD with wholeTextFiles in Spark I am trying to use wholeTextFiles of spark to read the directory, my file RDD contains (String,String) where first String is my filename and second my contents of the file.
I want to map this RDD to another one with just the contents of my file, how can I do it?
Thanks!
val file = sc.wholeTextFiles("./Desktop/093")

file.first
res0: (String, String) =
(file:/Users/Desktop/093/nc-no-na.clusters.093.001.txt,"199 197 5   5   168 0   0.932125    11101111000000110100000000000000000000000000001010100000011100001000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001101101111100000000000000000011100000000000000000000000000100000111011000000000000000000000000000000000000000000000000000000000000000011110010111001001110000000011100000000010000000000000000000000000010000000000000000000000000000000000000000011111111111101010111000000000000000000000000000000000000000000000000000000000000000001100000000000000000000000000000000000000000101110101110101011010000000000000000001100001100000011110000000000000000000011111011110011100...

A: For example like this:
import org.apache.spark.rdd.RDD

val content: RDD[String] = file.map(_._2)


text:
Q: Multiplicative Inverse for Generating Function I have a question based on Irreducible and Connected Permutations.
I was able to use the notion of connected permutations to construct a combinatoric proof for
\begin{equation}
\sum_{i=1}^{n}c_{i}(n-i)!=n!.
\end{equation}
Now let $\displaystyle F(x)=\sum_{n \geq 1} n! x^{n}$ and $\displaystyle G(x)=\sum_{n \geq 1} c_{n} x^{n}$.
I was then asked to prove that $1-G(x)$ and $1+F(x)$ are multiplicative inverses. It would seem to be an easy question but I cannot seem to see my mistake:
\begin{equation}
\begin{aligned}
(1-G(x))(1+F(x)) &= 1 \\
1 - G(x) + F(x) - G(x)F(x) &= 1 \\
1 - \sum_{n\geq 1}c_n x^n + \sum_{n \geq 1} n! x^{n}  - \sum_{n \geq 1} \left[ \sum_{i=1}^{n}c_{i}(n-i)! \right] x^{n}  &= 1 \\
1 - \sum_{n\geq 1}c_n x^n + \sum_{n \geq 1} n! x^{n}  - \sum_{n \geq 1}n! x^{n}  &= 1 \\
1 - \sum_{n\geq 1}c_n x^n &= 1 \\
\sum_{n\geq 1}c_n x^n &= 0 \\
\end{aligned}
\end{equation}
This would mean that every coefficient of $G(x)$ is zero, which is absurd.
Note that I substituted the coefficient of $G(x)F(x)$ with the combinatoric identity. I have approached the problem in many different ways (e.g. changing indices, constructing the inverse of $F(x)$ and comparing to $G(x)$) and I ultimately come to the same result.
I would appreciate if anyone could point out my error(s).
Thank you very much!

A: Let $a_0=1$ and $a_n=-c_n$ for $n\ge 1$; then
$$\begin{align*}
\big(1-G(x)\big)\big(1+F(x)\big)&=\left(\sum_{n\ge 0}a_nx^n\right)\left(\sum_{n\ge 0}n!x^n\right)\\\\
&=\sum_{n\ge 0}\sum_{k=0}^na_k(n-k)!x^n\\\\
&=1\;,
\end{align*}$$
since
$$\sum_{k=0}^na_k(n-k)!=\begin{cases}
1,&\text{if }n=0\\\\
n!-\sum\limits_{k=1}^nc_k(n-k)!=n!-n!=0,&\text{if }n\ge 1\;.
\end{cases}$$

A: When you multiply
two series that start at
$x$,
the resulting series
starts at $x^2$,
not $x$.


text:
Q: Dockers Job for docker.service failed because the control process exited with error code on redhat linux I installed Docker on redhat linux and trying to change the docker0 network ip to 10.10.10.10/24. For that i am following the link https://www.ibm.com/developerworks/community/blogs/powermeup/entry/Setting_up_a_Docker_Bridge?lang=en. Now i facing issue Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details. while starting the docker.service.
Could anybody suggest me how to resolve this issue?


text:
Q: Removing nested LaTeX `\index`es How would I, such as with regex and sed, remove all \index tags that occur inside any \index tags?
For example, a nested mess like this:
\index{Test\index{test\index{test}}ing One\index{one} Two\index{two} Three\index{three}}

would turn into
\index{Testing One Two Three}

I have complicated nested \indexes like this:
\documentclass{article}
\usepackage{makeidx}
\makeindex

\makeatletter
\let\oldtheindex\theindex
\renewcommand{\theindex}{%
  \oldtheindex%
  \let\index\@gobble}% Remove \index functionality
\makeatother

\begin{document}

a person\index{a person}\footnote{A. Person\index{a person}, \textit{On A. Person\index{a person!\textsc{some journal} or \textsc{His Papers\index{a person!\textit{His Papers}}of A. Person}!\textit{On His Papers}}\index{some other person}'s Lines of Force}, here's some lorem ipsum text (\textsc{Prestigious Journal}, vol. 10, part 1, pp. 27 to 83. — \textsc{His Papers\index{a person!\textit{His Papers}}of A. Person\index{a person}}, vol. 1, pp. 156 to 219; New York, 2005).}

\printindex

\end{document}

Yet, I get this error.
\\->\let \reserved@e
                     \relax \let \reserved@f \relax \@ifstar {\let \reserved...
l.14 ... vol. 1, pp. 156 to 219; New York, 2005).}

Why?

A: You can nullify the macro \index when inside the theindex environment:

\documentclass{article}
\usepackage{makeidx}
\makeindex

\makeatletter
\let\oldtheindex\theindex
\renewcommand{\theindex}{%
  \oldtheindex%
  \let\index\@gobble}% Remove \index functionality
\makeatother

\begin{document}

\index{Test\index{test\index{test}}ing One\index{one} Two\index{two} Three\index{three}}

\printindex

\end{document}

Here's a rundown of the problem:

*

*Compile the above file, which writes an .idx file containing:
\indexentry{Test\index{test\index{test}}ing One\index{one} Two\index{two} Three\index{three}}{1}

*Run makeindex on this file, and it creates a .ind file containing:
\begin{theindex}

  \item Test\index{test\index{test}}ing One\index{one} Two\index{two} Three\index{three},
        1

\end{theindex}

*Now compile the original file, which creates a new host of \index entries within the .ind, thereby making the new .idx resemble:
\indexentry{Test\index{test\index{test}}ing One\index{one} Two\index{two} Three\index{three}}{1}
\indexentry{test\index{test}}{1}
\indexentry{one}{1}
\indexentry{two}{1}
\indexentry{three}{1}

*...and so forth until all \index entries have been resolved.
The solution intervenes at the start of the theindex environment and removes any further functionality of \index. Since \begin{theindex}...\end{theindex} forms a group, the change to \index is local.

Based on your updated post, I would suggest removing nested \indexes at the call to \index by using the following definition:
\makeatletter
\let\oldindex\index
\renewcommand{\index}[1]{{%
  \let\index\@gobble%
  \oldindex{#1}%
}}
\maketother

Note that your way of using an index is not very effective. When you're using formatting commands within the index, the sorting is not correct. See the makeindex documentation on how to place entries with a different formatting yet still maintain the appropriate sorting (see the @ symbol).
Here is a complete MWE:

\documentclass{article}
\usepackage{makeidx}
\makeindex

\makeatletter
\let\oldindex\index
\renewcommand{\index}[1]{{%
  \let\index\@gobble%
  \oldindex{#1}%
}}
\makeatother

\begin{document}

a person%
\index{a person}% First entry
\footnote{A. Person%
  \index{a person}% Second entry
  , \textit{On A. Person%
    \index{a person!\textsc{some journal} or \textsc{His Papers\index{a person!\textit{His Papers}}of A. Person}!\textit{On His Papers}}% Third entry
    \index{some other person}% Fourth entry
    's Lines of Force}, here's some lorem ipsum text (\textsc{Prestigious Journal}, vol. 10, part 1, pp. 27 to 83. — \textsc{His Papers%
    \index{a person!\textit{His Papers}}% Fifth entry
    of A. Person%
    \index{a person}% Sixth entry
    }, vol. 1, pp. 156 to 219; New York, 2005).%
  }

\printindex

\end{document}

with the .idx showing the six marked entries:
\indexentry{a person}{1}
\indexentry{a person}{1}
\indexentry{a person!\textsc  {some journal} or \textsc  {His Papersof A. Person}!\textit  {On His Papers}}{1}
\indexentry{some other person}{1}
\indexentry{a person!\textit  {His Papers}}{1}
\indexentry{a person}{1}


text:
Q: $A\otimes B\cong A$? I am struggling for quite a while now with tensor products, since I have limeted time to learn to understand them. Now on several occasions I have read that we have $A\otimes_KK\cong A$ for $A$ an $K$-algebras. I convinced myself of this by "showing" the following function is an isomorphism:

\begin{align}f:A\otimes_KK&\to A\\a\otimes_Kk&\mapsto a\end{align}
  Surjectivity: obvious
Injectivity: $\ker(f)=\{a\otimes_Kk\in A\otimes_KK\mid f(a\otimes_Kb)=a=0\}=\{0\otimes_Kk\mid 0\in A, k\in K\}=\{0\}$ hence $f$ is injective.

I suspect something is terribly wrong with this proof, because we can do the same thing if we replace $K$ by any $K$-algebra $B$. In wich case $A\otimes B\cong A$, wich doesn't appear right...
My question is: What would be the correct way to show relations like this? (And implicitly: what am I not getting when using tensor products?)

A: This map is actually not even well defined. This is because $f(a \otimes 2) = a$, but $f(2a \otimes 1) = 2a$, even though $a \otimes 2 = 2a \otimes 1$ in $A \otimes_K K$. The correct map is $a \otimes k \mapsto ka$.

A: One of your errors is that you think every element of a tensor product $A\otimes_K B$ is an elementary tensor $a\otimes b$. I say this because from the way you are defining $f$ and trying to compute the kernel it seems you think every tensor is elementary. Elements of a tensor product are sums of elementary tensors $a_1\otimes b_1 + \cdots + a_r \otimes b_r$. Now it is true in $A \otimes_K K$ that all tensors are elementary, but it is not true in general tensor products. In particular, to show a linear map out of a tensor product is zero it is insufficient in general to show the only elementary tensor that goes to $0$ is the zero tensor. For example, there is an $\mathbf R$-linear map $\mathbf C \otimes_{\mathbf R} \mathbf C \rightarrow \mathbf C$ by $z \otimes w \mapsto zw$ on elementary tensors and the only elementary tensor that goes to $0$ is $0 \otimes 0$ (do you understand that $z \otimes 0 = 0 \otimes w = 0 \otimes 0$ in this tensor product?), but lots of non-elementary tensors also go to $0$ so the map is not injective. For instance, $1\otimes i - i \otimes 1$ is mapped to $0$ and $1\otimes i - i \otimes 1$ is not elementary in $\mathbf C \otimes_{\mathbf R} \mathbf C$. Being able to prove that tensor is not elementary is one indicator that you can work properly with tensors.

A: Your isomorphism should be
\begin{align}
f: A \otimes_K K& \to A\\
a \otimes_K k& \mapsto k \cdot a
\end{align}
This is a well-defined isomorphism and is $K$-linear, which your function wasn't. Because the scalar multiplication is only defined for scalars, this isomorphism can only be defined when one of the domain vector spaces is $K$ itself.


text:
Q: Application of the datepicker on css class to multiple input elements but it fails I want to apply jQuery ui datepicker on a multiple elements of css custom class but it only working with the first element and fails with the rest of elements please suggest the possible solution.

A: This works for me
$(".myClass").datepicker()

even this is failing?
$(".myClass").each(function(){
   $(this).datepicker();
}


text:
Q: Emacs align-regexp command does not prompt group select for regexp pattern I follow the steps which is on this article about command align-regexp to sort region text: http://ergoemacs.org/emacs/emacs_align_and_sort.html
I select the same sample with in upper example with region select.
And I executed [C-u M-x align-regexp RET .* \([0-9,]+\).* RET] on the select region, but did not get interactive group select prompt. Why?
EDIT:
My Emacs version:
24.3.50.1
System:
Ubuntu Linux 14.02 (x86_64)

A: My Helm config init setup caused this problem.
Here is the reason
(global-set-key (kbd "M-x") 'helm-M-x) ; conflict with {[C-u M-x align-regexp] on select region text.}


text:
Q: How to change the offset of an view using onTapGesture? I am trying to move a view when it is being tapped. But unfortunately nothing happens. How do I toggle the position of it using the offset y axis?
    struct Test: View {
    @State var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {
        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
                        .foregroundColor(Color.random).offset(y: self.cards[i].isFocus ? CGFloat(500) : CGFloat(i*50))
                        .zIndex(Double(i))
                        .onTapGesture {
                            self.cards[i].isFocus.toggle() // now the touched Card should move to an offset of y: 500, but nothing happens
                        }
                }
            }
            Spacer()
        }

    }
}

struct Card :Identifiable{
    @State var isFocus :Bool = false
    var id  = UUID()

}

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}

A: I see your code and I am sorry to say but its wrong in many aspects. I would recommend you to go through SwiftUI basics and understand how and when we use @State, @ObservedObject, @Binding etc. Also always try to break your Views into the smallest components.
Below is the code which I think fulfills your requirement.
struct Test: View {
    var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {

        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    CardView(card: self.cards[i], i: i)
                }
            }
            Spacer()
        }
    }
}

struct CardView: View {

    @ObservedObject var card: Card
    let i: Int

    var body: some View {

       RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
            .foregroundColor(Color.random)
            .offset(y: card.isFocus ? CGFloat(500) : CGFloat(i*10))
            .zIndex(Double(i))
            .onTapGesture {
                withAnimation {
                  self.card.isFocus.toggle()
                }
        }
    }
}

class Card: ObservableObject{
    @Published var isFocus: Bool = false
    var id  = UUID()

}


text:
Q: python pandas DataFrame subplot in columns and rows I would like to produce a subplot from data 4-column DataFrame into 2-rows and 2-columns.
df = pd.DataFrame(np.random.randn(6,4),index=pd.date_range('1/1/2000',periods=6, freq='1h'))

However, below will give a 4-row and 1-column plot
df.plot(use_index=False, title=f, subplots=True, sharey=True, figsize=(8, 6))

A: In current versions of Pandas, DataFrame.plot features the layout keyword for this purpose.
df.plot(subplots=True, layout=(2,2), ...)

A: cplcloud's answer works, but following code will give you a bit more structure so that you can start configuring more if you do not need the loop.
fig, axes = plt.subplots(nrows=2, ncols=2)
fig.set_figheight(6)
fig.set_figwidth(8)
df[0].plot(ax=axes[0,0], style='r', label='Series'); axes[0,0].set_title(0)
df[1].plot(ax=axes[0,1]); axes[0,1].set_title(1)
df[2].plot(ax=axes[1,0]); axes[1,0].set_title(2)
df[3].plot(ax=axes[1,1]); axes[1,1].set_title(3)
fig.tight_layout()

Added some example on axis 0 to show how you can further configure it.


text: Q: Storing Shapes in database What is more effective? Storing Shapes as shape column (http://webhelp.esri.com/arcgisserver/9.3/java/index.htm#geodatabases/topology_basics.htm) in database? Or maybe store shapes in seperate tables and join them?


text:
Q: Apache Redirect http -> https and non-www -> www, works all but 1 scenario I have the code below to redirect all traffic to https on the subdomain www. I am using a load balancer as well through AWS to serve the SSL cert, so all traffic is on port 80. The rules below will redirect all traffic to https://www.example.com (the only place the certificate is valid) under all circumstances, except for when you enter the following url:
URL:
https://example.com

Code:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=permanent]
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^(.*)$ https://%{HTTP:HOST}%{REQUEST_URI} [L,R=permanent]


text:
Q: Обновление блока div без перезагрузки страницы по нажатию на кнопку здравствуйте, мне нужно сделать обновление блока div без перезагрузки страницы по нажатию на кнопку, этот блог содержит в себе информацию из базы mysql. подскажите пожалуйста как?
A: Текст ссылки


text:
Q: VMware network connection I have Windows 7 installed on VMware Workstation 9 on computer. Is it possible to connect to this virtual Windows from the second computed for using? If so then do I need to have Windows on the second computer too to use the virtual one via RDC or something else?

A: I dont think this should be a problem. You can bridge the network adapter of the virtual machine to your host machine. That way, the VM will get an IP on your network.
You can connect to this VM using that ip address from any computer as you would from a normal computer as long as the OS has support for a Remote Desktop client. As far as i know, all major OS like Linux, Mac OS etc support RDP. So OS should not be an issue too.
In case you want to connect from outside network, you can set a Port forward from your router for the RDP port to your VM.


text:
Q: Show final time on victory screen In my game I have a chronometer running. The chronometer is defined in the  'Play' class(which is used for everything related to when the player is controlling the character), not in the 'Victory' class(which purpose is to show an image when you pass the level). Both classes are defined in the main.py file. I want to print on the final victory screen(the player wins when the character gets to a determinate position) the time that has taken the player to get to that position. How would I do that? Thanks. Unfortunately, I cannot show code.

A: I made a little piece of code that could help you building this timer.
import pygame

pygame.init() # init is important there because it starts the timer

screen = pygame.display.set_mode((500, 500))
running = True
victory = False

class Play:

    def __init__(self):

        # all infos about player
        self.time = pygame.time.get_ticks()
        self.end_time = 0

    def update_timer(self):

        # here we get the actual time after 'init' has been executed
        self.time = pygame.time.get_ticks()

        # we divide it by 1000 because we want seconds instead of ms
        self.end_time += self.time / 1000
        return self.end_time

class Victory:

    def __init__(self):

        self.play = Play()

    def pin_up_timer(self):

        # Here I chose to print it inside of the console but feel free to pin it up wherever you want.
        print(self.play.update_timer())

vic = Victory()
pl = Play()

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        # here I chose to end the game when I press KeyUp but you can do something else to stop it
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                victory = True

    # I update timer every frame and BEFORE checking if victory is True in order to get a result more accurate
    pl.update_timer()

    # if victory is True, I pin up the timer and I end the code
    if victory:
        vic.pin_up_timer()
        running = False

    pygame.display.flip()

pygame.quit()

If you want the timer begin only if the player has moved, detects the key and add a variable like:
# (this variable outside of the main loop)
moved = False

# left or anything else
if event.key == pygame.K_LEFT:
    moved = True

if moved:
    pl.update_timer()


text:
Q: How do I enforce a Windows Authentication After RDP? I would like to RDP into Windows server machine and after a successful RDP, I would like to configure my Windows to prompt for login again.
The reason for this requirement is because the RDP connection to the Windows server machine would be carried out by an RDP automation tool and upon reaching the target server machine from the RDP tunnel, the user would need to use their LDAP/Windows AD account to login again to ensure tighter security.
How do I implement this the second layer login once a user successfully RDP into a Windows server machine ?

A: Try to run this script after logon
rundll32.exe user32.dll,LockWorkStation
Setting startup script GPO

A: That is a GP option. On the server go to Windows Components/Remote Desktop Services/Remote Desktop Session Host/Security under Computer Configuration/Administrative Templates and look for the setting: Always prompt for password upon connection Set it to Enabled.


text:
Q: Passing data to nlopt in Rcpp? This is a rather simple question, but I haven't been able to quite find the answer on the web yet.
Wishing my latest attempt, here is latest compiler output:
note: candidate function not viable: no known conversion from 'double (unsigned int, const double *, void *, void )' to 'nlopt_func' (aka 'double ()(unsigned int, const double *, double *, void *)') for 2nd argument
From this error I surmise that I am now wrapping or 'type casting' the data argument correctly and also the parameter vector.  The discrepency between the third input, the gradient, confuses me.  As I am calling a gradient free optimization routine.
Here is a simple linear regression with a constant and a variable:
#include "RcppArmadillo.h"

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(nloptr)]]
//#include <vector>
#include <nloptrAPI.h>
using namespace arma;
using namespace Rcpp;

typedef struct {
  arma::mat data_in;
} *my_func_data;

typedef struct {
  double a, b;
} my_theta;

double myfunc(unsigned n, const double *theta, void *grad, void *data){

  my_func_data &temp = (my_func_data &) data;
  arma::mat data_in = temp->data_in;

  my_theta *theta_temp = (my_theta *) theta;
  double a = theta_temp->a, b = theta_temp->b;

  int Len = arma::size(data_in)[0];
  arma::vec Y1 = data_in(span(0, Len-1), 1);
  arma::vec Y2 = data_in(span(0, Len-1), 2);
  arma::vec res = data_in(span(0, Len-1), 0) - a*Y1 - b*Y2 ;
  return sum(res);
}

// [[Rcpp::export]]
void test_nlopt_c() {

  arma::mat data_in(10,3);
  data_in(span(0,9),0) = arma::regspace(40, 49);
  data_in(span(0,9),1) = arma::ones(10);
  data_in(span(0,9),2) = arma::regspace(10, 19);

  my_func_data &temp = (my_func_data &) data_in;

  double lb[2] = { 0, 0,}; /* lower bounds */
  nlopt_opt opt;
  opt = nlopt_create(NLOPT_LN_NELDERMEAD, 2); /* algorithm and dimensionality */
  nlopt_set_lower_bounds(opt, lb);

  nlopt_set_min_objective(opt, myfunc, &data_in );

  nlopt_set_xtol_rel(opt, 1e-4);
  double minf; /* the minimum objective value, upon return */
  double x[2] = {0.5, 0.5};  /* some initial guess */
  nlopt_result result = nlopt_optimize(opt, x, &minf);
  Rcpp::Rcout << "result:" << result;
    return;
}

A: Got it figured out, stupid answer turns out to be correct, just change 'void' to 'double', no clue why.  Anyway, the example code needs some improving but it works.
#include "RcppArmadillo.h"

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(nloptr)]]
//#include <vector>
#include <nloptrAPI.h>
using namespace arma;
using namespace Rcpp;

typedef struct {
  arma::mat data_in;
} *my_func_data;

typedef struct {
  double a, b;
} my_theta;

double myfunc(unsigned n, const double *theta, double *grad, void *data){

  my_func_data &temp = (my_func_data &) data;
  arma::mat data_in = temp->data_in;

  my_theta *theta_temp = (my_theta *) theta;
  double a = theta_temp->a, b = theta_temp->b;

  int Len = arma::size(data_in)[0];
  arma::vec Y1 = data_in(span(0, Len-1), 1);
  arma::vec Y2 = data_in(span(0, Len-1), 2);
  arma::vec res = data_in(span(0, Len-1), 0) - a*Y1 - b*Y2 ;
  return sum(res);
}

// [[Rcpp::export]]
void test_nlopt_c() {

  arma::mat data_in(10,3);
  data_in(span(0,9),0) = arma::regspace(40, 49);
  data_in(span(0,9),1) = arma::ones(10);
  data_in(span(0,9),2) = arma::regspace(10, 19);

  my_func_data &temp = (my_func_data &) data_in;

  double lb[2] = { 0, 0,}; /* lower bounds */
  nlopt_opt opt;
  opt = nlopt_create(NLOPT_LN_NELDERMEAD, 2); /* algorithm and dimensionality */
  nlopt_set_lower_bounds(opt, lb);

  nlopt_set_min_objective(opt, myfunc, &data_in );

  nlopt_set_xtol_rel(opt, 1e-4);
  double minf; /* the minimum objective value, upon return */
  double x[2] = {0.5, 0.5};  /* some initial guess */
  nlopt_result result = nlopt_optimize(opt, x, &minf);
  Rcpp::Rcout << "result:" << result;
    return;
}


text:
Q: Proof about orders of groups Assume $f:G \rightarrow H$ is an isomorphism between groups $G$ and $H$ and that a is an element of $G$ then order(f(a))=order(a)
Approach:
let $l$ be the order of $a$ and $t$ be the order of $f(a)$, so $l$ and $t$ are smallest positive integers such that $a^l=1_G$ and $f(a)^t=1_H$. We have to show $l=t$
One crucial point is to note that if $a=1_G$ then $f(1_G)=1_H$. I proved this already, so we can say since f is homomorphic
$$1_H=f(a^l=1_G)=f(a*a^{l-1})=f(a)*f(a^{l-1})=f(a)*f(a*a^{l-2})=...=f(a)^l$$
I just used the fact that $f$ is homomorphic, but why is $f$ being bijective relevant?. Besides that, I am not sure if the proof is complete. It looks very incomplete to me. What if $l$ is a multiple of $t$?

A: What you have written seems good for a beginner. Here is a more refined proof.
Let $l$ be the order of $a$ in $G$.
Note that $(f(a))^l$ = $f(a) * f(a) * ... * f(a) = f(a * a * ... * a) = f(a^l)$.
Hence it follows that if $a^l = 1_G$ then $f(a^l) = f(1_G) = 1_H$.
Now, suppose there exists $m$ smaller than $l$ such  that $(f(a))^m = 1_H$. Then:
$1_H=(f(a))^m$ = $f(a) * f(a) * ... * f(a) = f(a * a * ... * a) = f(a^m)$.
Hence $f(a^m) = 1_H$ and $a^m$ is in the kernel of $f$. However, because $f$ is an isomorphism, the only element in the kernel of $f$ is $1_G$, hence $a^m=1_G$, which contradicts the fact that $l>m$ was the order of $a$ in $G$.
Hence $m$ cannot be the order of $f(a)$ for and $m<l$, and hence $\text{ord}(f(a)) = l = \text{ord}(a)$


text:
Q: splice function not removing 2 cosecutive string from array function filter_list(l) {
    l.map((item,i,main) => {
     if(typeof item==="string")
     {return main.splice(i,1);}
      else
      return item;
    });
  console.log(l);
}
filter_list([1,'a','b','c',0,15,'k','e']);

here i am expecting output of [1, 0, 15]. But instead it is giving me [1, "b", 0, 15, "e"]. it seems to not removing strings one exists after another. Also i am trying to get the updated array in a new array variable but i don't have any idea how to do that here.  Some help would be very much appreciated.

A: It's much easier to use the filter function and return true for everything that's not a string.
var a = [1, 'a', 'b', 'c', 0, 15, 'k', 'e'];
var b = a.filter(function (item) {
    return ! (typeof item === 'string');
});

A: Problem is that when you splice element from original array you get problem in iteration of map(), so for example when you remove a with index of 1 now the next element with index of 2 is c because original array is now this [ 1, "b", "c", 0, 15, "k", "e" ] so you skip b. If you don't remove elements you can see that map will match not numbers in your code.

function filter_list(l) {
  l.map((item, i, main) => {
    if (typeof item == "string") main[i] = null
  })
  return l;
}

console.log(filter_list([1, 'a', 'b', 'c', 0, 15, 'k', 'e']))


text:
Q: Suppose that i sub $n = 5%$ for all $n ≥ 1$. How long will it take an investment to triple in value? Suppose that i sub $n = 5%$ for all $n ≥ 1$. How long will it take an investment to triple in value?
I tried to use $3x=x(e^{.05t})$
then i got $\ln3+\ln x=\ln x+.05t$
so $t=\ln(3)/.05 = 21.97$
but i know that the answer is $22.5171$

A: The discrepancy in the value is due to the use of continuous compounding than the discrete compounding.
So $3X = X(1+.05)^t$
Taking logarithm on both sides, you get $\ln(3) = t\ln(1.05)$
$t = \ln(3)/\ln(1.05) = 22.5171$
There you go!!
I still wonder what n is? and x_n is ?
Goodluck

A: You will use the formula
$$A = P(1 + (r/n))nt$$
where:
$A$ = accumulated amount
$P$ = investment
$t$ = time
$r$ = interest rate
$n$ = number of times compounded per year
$$P = P$$
$$A = 3P$$
$$r = 0.05$$
$$n = 1$$
$$t = 1$$
Substituting these values into the formula,
$$3P = P(1 + 0.05)t$$
Divide by  $P$ on both sides of the equation.
$$3 = 1.05t$$
Log both sides of the equation
$$\log(3) = \log(1.05)t$$
Bring the exponent t down as the coefficient of the log(1.05)
$$\log(3) = t \log(1.05)$$
Divide by $log(1.05)$ into both sides of the equation
$$t = \log(3) / \log(1.05)$$
$$t = 22.52$$
It will take $22.52$ years to triple the investment at an interest rate of $5$%.


text:
Q: Can't modify hugepage size once DPDK application is stopped I am running a DPDK application and for that i allocate huge pages using a script. Allocation and starting the application is fine. But later when I stop the application and release the hugepages by deleting the mount point and modifying below nr_hugepages for a numa system.
Later when I try to allocate further hugepages it doesn't seem to be working.
How I release hugepages :
echo 0 > /sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages

echo 0 > sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages

 echo "Unmounting /mnt/huge and removing directory"
 grep -s '/mnt/huge' /proc/mounts > /dev/null
 if [ $? -eq 0 ] ; then
     sudo umount /mnt/huge
 fi

 if [ -d /mnt/huge ] ; then
     sudo rm -R /mnt/huge
 fi

Then later when I try to write any new value to the nr_hugepages but it is not taking any value. It is stuck with previous value
# echo 0 > /sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages
# echo 0 > /sys/devices/system/node/node1/hugepages/hugepages-2048kB/nr_hugepages
#
# cat /sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages
2048
# cat /sys/devices/system/node/node1/hugepages/hugepages-2048kB/nr_hugepages
2048
# cat /sys/devices/system/node/node0/meminfo | fgrep Huge
Node 0 AnonHugePages:     10240 kB
Node 0 HugePages_Total:  2048
Node 0 HugePages_Free:   1024
Node 0 HugePages_Surp:      0
# cat /sys/devices/system/node/node1/meminfo | fgrep Huge
Node 1 AnonHugePages:    145408 kB
Node 1 HugePages_Total:  2048
Node 1 HugePages_Free:   1024
Node 1 HugePages_Surp:   2048

# cat /proc/sys/vm/nr_hugepages
2048
# echo 0 > /proc/sys/vm/nr_hugepages
# cat /proc/sys/vm/nr_hugepages
0
# cat /sys/devices/system/node/node0/meminfo | fgrep Huge
Node 0 AnonHugePages:     10240 kB
Node 0 HugePages_Total:  2048
Node 0 HugePages_Free:   1024
Node 0 HugePages_Surp:   2048

# cat /sys/devices/system/node/node1/meminfo | fgrep Huge
Node 1 AnonHugePages:    145408 kB
Node 1 HugePages_Total:  2048
Node 1 HugePages_Free:   1024
Node 1 HugePages_Surp:   2048
# cat /sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages
2048
# cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
4096

If anyone has faced this issue earlier and what did you do to get rid of this ? Any pointer or workaround will be of great help.

A: Remove huge page mmapping files after process exit. Search/dev/hugepages or /mnt/huge or any other place mounted as hugetlbfs for file with  rte_ prefix. Each file in these locations is consuming at least one hugepage.


text:
Q: I'm trying to encode csv file to utf8 using python I'm using python to read and encode many files to utf8 using python,I try it with the code below:
import os
from os import listdir

def find_csv_filenames(path_to_dir, suffix=".csv" ):
    path_to_dir = os.path.normpath(path_to_dir)
    filenames = listdir(path_to_dir)
#Check *csv directory

    fp = lambda f: not os.path.isdir(path_to_dir+"/"+f) and f.endswith(suffix)
    return [path_to_dir+"/"+fname for fname in filenames if fp(fname)]

def convert_files(files, ascii, to="utf-8"):
    count = 0
    lineno = 0
    for name in files:
        lineno = lineno+1
        with open(name) as f:
            file_target = open(name, mode='r', encoding='latin-1')
            file_content = file_target.read()
            file_target.close

        print(lineno)
        file_source = open("./csv/data{}.csv".format(lineno), mode='w', encoding='utf-8')
        file_source.write(file_content)

csv_files = find_csv_filenames('./csv', ".csv")
convert_files(csv_files, "cp866")

The problem is that after I read and write data to other files and set encode it to utf8 but it still not work.

A: Before you open a file which encoding is not clear, you could use chardet to detect the file's encoding rather than use a encoding guessed to open a file. Usage is like this:
>>> import chardet
>>> encoding = chardet.detect('PATH/TO/FILE')['encoding']

And then open the file with the encoding detected and write the contents into a file opened with 'utf-8' encoding.
If you're not sure whether the file is converted using 'utf-8' encoding, you could use enca to see if the encoding of the file is 'ASCII' or 'utf-8' like this in Linux shell:
$ enca FILENAME


text:
Q: SQL pre login handshake error I have window service installed on my server.
Sometimes it gets me error in SQL login.
after 10-15 minutes it again start working fine.
During the error period i tried to login through SQL server management, from there also it's giving me loging issue.
I checked with all the solution on this site also on other site.I tried for -SQL protocol enabling and setting "TrustServerCertificate=True;" in connection string.
What can be the cause ??
The error i got is -
System.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.) ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean& marsCapable)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()

On my server .net framework, IIS and sql are the main setup installed.


text:
Q: android: Error when use setAdapter in Fragment to call Activity I'm doing the application fetches the data from the database and displayed in  Listview
and Must be all the Classes be a Fragment so I can put it in tabs
The error is:
  this.getlistdata.setAdapter(new GetAllSongs(jsonArray,this));

Exactly ... (jsonArray,this)
Full code.
public class GetListData extends Fragment
{
    ListView getlistdata;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.getActivity().setContentView(R.layout.activity_main2);

        this.getlistdata =  (ListView)this.getActivity().findViewById(R.id.listgetdata);

        new GetAllCustomerTask().execute(new ApiConnector());
    }

    public  void setListAdapter (JSONArray jsonArray)
    {
        this.getlistdata.setAdapter(new GetAllSongs(jsonArray,this));
    }

    private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
    {
        @Override
        protected JSONArray doInBackground(ApiConnector... params)
        {
            return params[0].GetAllCustomers();
        }

        @Override
        protected void onPostExecute(JSONArray jsonArray)
        {
            setListAdapter(jsonArray);
        }
    }

The error is ::

can't cast Fragment To Activity

How can I fix it?

A: GetAllSongs() is expecting an Activity as the second argument, but you are passing a Fragment.
The following statement should eliminate the exception:
this.getlistdata.setAdapter(new GetAllSongs(jsonArray, getActivity()))


text:
Q: can't convert to "string" C# I am creating a school project, the teacher said something with privacy, I'm making a encryption tool but always in EncryptFile(files, password) code return me this error

can't convert System.Collections.Generic.List to "string"

This is the function then list all files from specific directory to List string, ignoring the exceptions
public List<string> GetFiles(string path, string pattern)
{
    var files = new List<string>();
    try
    {
        files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
        foreach (var directory in Directory.GetDirectories(path))
            files.AddRange(GetFiles(directory, pattern));
    }
    catch (Exception ex)
    {
        // unnautorized files
    }
    return files;

    string password = ChooseUrPass.Text
    EncryptFile(files, password); //here happen the error
}

How can I bypass this error? sorry if its a bad question, I'm newbie
If need theres is the function then encrypt the files
public void EncryptFile(string file, string password)
{

    byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

    // Hash the password with SHA256
    passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

    byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

    File.WriteAllBytes(file, bytesEncrypted);
    System.IO.File.Move(file, file+".SafeFile");
}

thanks for your time

A: Looks like EncryptFile needs its first argument to be a string, and you give it files, which is an list of strings.
I'd suggest solving it this way :
foreach(string s in files)
{
    EncryptFile(s, password);
}

A: The function EncryptFile(string file, string password) is expecting type string but you are passing a variable of type List<string>
Try this:
foreach(string file in files) {
    EncryptFile(file, password);
}

A: You do not need a List<string> and hand made recursion. Try this code:
public List<string> GetFiles(string path, string pattern)
{
    foreach (var file in Directory.GetFiles(path, pattern))
    {
        EncryptFile(file, password);
    }
}


text:
Q: UITableViewHeaderFooterView* header =[self.tableView headerViewForSection:0]; So I have the following header of a tableview:
UITableViewHeaderFooterView* header =[self.tableView headerViewForSection:0];

This header has an imageview which I added programatically as a subview. How can I modify and reload this image or anything in header, without having to do a [tableView reloadData]?

A: I Think u can enumerate on the subviews of header like this:
UITableViewHeaderFooterView* header =[self.tableView headerViewForSection:0];
for(UIView *v in header.subviews){
    if([v isKindOfClass:[UIImageView class]])
         {
           UIImageView *imgView = (UImageView*)v;
           //do ur stuff here for modification
            break;
         }
    }

if u have multiple ImageViews u can differ between them with tag

A: you can set an IBOUTLET property for the view you would like to access.


text:
Q: How to integrate $\int e^{2x} \sec{3x} \,dx$ $\int e^{2x} \sec{3x} \,dx$
I have tried every elementary (e.g. methods taught in first course of integration) way to integrate this function . But couldn't make it.
Please someone solve it and mention the concepts you have used to solve it.

A: As said in comments, there is no closed form solution and the only possible result is a gaussian hypergeometric function ... which corresponds to an infinite summation.
So, as @ person suggested, use
$$\sec(t)=\sum_{n=0}^\infty  \frac{\left|E_{2 n}\right|}{(2 n)!}t^{2n}$$ making
$$I=\int e^{2x} \sec(3x) \,dx=\sum_{n=0}^\infty 9^n \int \frac{\left|E_{2 n}\right|}{(2 n)!}x^{2n}\,e^{2x}\,dx$$ that is to say
$$I=\sum_{n=0}^\infty \frac{ 9^n \left|E_{2 n}\right| }{2^{2 n+1}\,(2 n)!}\,\Gamma (2 n+1,-2 x)$$
$$J=\int_0^t e^{2x} \sec(3x) \,dx=\sum_{n=0}^\infty \frac{ 9^n \left|E_{2 n}\right| }{2^{2 n+1}\,(2 n)!}\,\Big[\Gamma (2 n+1,-2 t)-\Gamma (2 n+1)\Big]$$
Expanded as a Taylor series
$$J=\sum_{n=1}^\infty \frac{a_n}{n!} t^n$$ coefficients $a_n$ make the sequence
$$\{1,2,13,62,637,4802,70993,742142,14537497,195123842,\cdots\}$$ which is not found in $OEIS$.


text:
Q: Python model with a list of self references I would like to do something like this:
class Author(db.Model):
    influencedBy = db.ListProperty(db.SelfReferenceProperty())
    influenced = db.ListProperty(db.SelfReferenceProperty())

I know I can use self.author_set to get the reverse relationship, but I need to add multiple Author objects to influenced and influencedBy.

A: Unfortunately you can't do what you propose. As you probably have realized you will get ValueError: Item type ReferenceProperty is not acceptable
You could do influencedBy = db.ListProperty(db.Key)
or if you used ndb  influencedBy = ndb.KeyProperty(kind=Author,repeated=True)
Once thing to consider is how many members might be in influencedBy and influenced. If its possible for there to be large numbers then you might run into entity size issues. If that is a possibility you then need to consider using a separate entity to record influence.


text:
Q: How to Update FormView? I have FormView:
 <asp:FormView ID="fvReport" runat="server" AllowPaging="false"
        OnModeChanging="fvReport_ModeChanging"
        OnItemUpdating="fvReport_ItemUpdating"
        DataKeyNames="id" DataSourceID="ObjectReport">
    <ItemTemplate>
        <asp:LinkButton ID="lbEdit" runat="server" CausesValidation="true" CommandName="Edit" >Edit</asp:LinkButton>

               order:
               <asp:textbox ID="Textbox7" runat="server" Text='<%# Eval("order") %>' Width="600px" TextMode="MultiLine" ReadOnly="True" Rows="3" BorderStyle="NotSet" CssClass="text-details"></asp:textbox>

               purpose:
               <asp:textbox ID="Textbox8" runat="server" Text='<%# Eval("purpose") %>' Height="34px" Width="600px" TextMode="MultiLine" ReadOnly="True" CssClass="text-details"></asp:textbox>

               features:
               <asp:textbox ID="Textbox9" runat="server" Text='<%# Convert.ToString(Eval("features")).Replace( "Esc", "Еsс")%>' Height="52px" Width="600px"  ReadOnly="True" TextMode="MultiLine" Font-Italic="True" ForeColor="Red" Enabled="false" CssClass="text-details"></asp:textbox>

               settings:
               <asp:textbox ID="Textbox10" runat="server" Text='<%# Convert.ToString(Eval("settings")).Replace( "Esc", "Еsс") %>' Height="44px" Width="600px"  TextMode="MultiLine" ReadOnly="True" CssClass="text-details"></asp:textbox>

    </ItemTemplate>
    <EditItemTemplate>

               order:
               <asp:textbox ID="Textbox7" runat="server" Text='<%# Eval("order") %>' Width="600px" TextMode="MultiLine" ReadOnly="True" Rows="3" BorderStyle="NotSet" CssClass="text-details"></asp:textbox>

               purpose:
               <asp:textbox ID="Textbox8" runat="server" Text='<%# Eval("purpose") %>' Height="34px" Width="600px" TextMode="MultiLine" ReadOnly="True" CssClass="text-details"></asp:textbox>

               features:
               <asp:textbox ID="Textbox9" runat="server" Text='<%# Convert.ToString(Eval("features")).Replace( "Esc", "Еsс")%>' Height="52px" Width="600px"  ReadOnly="True" TextMode="MultiLine" Font-Italic="True" ForeColor="Red" Enabled="false" CssClass="text-details"></asp:textbox>

               settings:
               <asp:textbox ID="Textbox10" runat="server" Text='<%# Convert.ToString(Eval("settings")).Replace( "Esc", "Еsс") %>' Height="44px" Width="600px"  TextMode="MultiLine" ReadOnly="True" CssClass="text-details"></asp:textbox>

        <asp:LinkButton ID="lbUpdate" runat="server" CausesValidation="true" CommandName="Update" >Save</asp:LinkButton>
        <asp:LinkButton ID="lbCancel" runat="server" CausesValidation="false" CommandName="Cancel">Cancel</asp:LinkButton>
    </EditItemTemplate>
    </asp:FormView>

ObjectDataSource :
<asp:ObjectDataSource ID="ObjectReport" runat="server"
       TypeName = "ObjectDataSources.CS.ConnectionToDB"
       SelectMethod = "GetReportById" UpdateMethod="">
   <SelectParameters>
       <asp:Parameter Name="report_id" Type ="Int32" />
   </SelectParameters>
   <UpdateParameters>
       <asp:Parameter Name="report_id" Type ="Int32" />
       <asp:Parameter Name="settings" Type = "String" />
       <asp:Parameter Name="purpose" Type = "String" />
       <asp:Parameter Name="order" Type = "String" />
       <asp:Parameter Name="features" Type = "String" />
   </UpdateParameters>
</asp:ObjectDataSource>

UpdateMetod:
    public int UpdateReportById(int report_id, string settings, string purpose, string order, string features)
        {
            SqlConnection conn = new SqlConnection(_connectionString);
            SqlCommand cmd = new SqlCommand("Update main_report SET settings = @settings, " +
                "purpose = @purpose, order = @order, " +
                "features = @features WHERE id = @id", conn);
            cmd.Parameters.Add("@id", SqlDbType.Int).Value = report_id;
            cmd.Parameters.Add("@settings", SqlDbType.VarChar).Value = settings;
            cmd.Parameters.Add("@purpose", SqlDbType.VarChar).Value = purpose;
            cmd.Parameters.Add("@order", SqlDbType.VarChar).Value = order;
            cmd.Parameters.Add("@features", SqlDbType.VarChar).Value = features;
            int result = 0;
            try
            {
                conn.Open();
                result = cmd.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                throw new Exception("UpdateReportById Exception.");
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

fvReport_ItemUpdating:
protected void fvReport_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
{
    switch (fvReport.CurrentMode)
    {
        case FormViewMode.Edit:
            fvReport.AllowPaging = false;
            lbl.Text = "Update!!!";
            fvReport.ChangeMode(FormViewMode.ReadOnly);
            fvReport.DataBind();
            break;
    }
    fvReport.DataBind();
}

but the data is not updated (label is updated :) ). What am I doing wrong?

A: You need to put updatedEvent in your code instead of updatingEvent
switch (fvReport.CurrentMode)
{
    case FormViewMode.Edit:
        fvReport.AllowPaging = false;
        lbl.Text = "Update!!!";
        fvReport.ChangeMode(FormViewMode.ReadOnly);
        fvReport.DataBind();
        break;
}
fvReport.DataBind();

Edit: After you posted your complete form design I have noticed that in your edit profile you have bound your value like...
Text='<%# Eval("order") %>'

But this function provides only one way binding. It means it will populate the value from your DB to control.
However this will not pass the values back when you are trying to update your values.
You have to use Bind instead Eval, that provide two way binding. like..
Text='<%# Bind("order") %>'

Add in all your controls in the Edit and Insert template.

A: You have to set the DataSourceControlID property of your FormView
    <asp:FormView ID="fvReport" runat="server" AllowPaging="false"
                OnModeChanging="fvReport_ModeChanging"
                OnItemUpdating="fvReport_ItemUpdating"
                DataKeyNames="id"
                DataSourceID="ObjectReport">


text:
Q: Add/attach AWS IAM Role to EC2 instance via terraform i have a quick question here..
I am using terraform to deploy ec2 instances on AWS, and i need a way to attach AWS IAM Role to the instance.
I have created manuall on AWS console an IAM Policy + role, and attached to EC2 instance and tested, it works.
Now i need to use same role (i created earlier manually) to automatically attach to new ec2 instances via terraform
I am tring to do this:
resource "aws_instance" "test-ec2" {
  ami                         = "ami-xxxxxxxxxx"
  instance_type               = "t3.large"
  iam_instance_profile        = "arn:aws:iam::1234567890:role/my-role-name" ## I know i am missing something here... (:facepalm:)
  key_name                    = "my-key"
  subnet_id                   = "subnet-some-subnet-d"
  vpc_security_group_ids      = ["sg-some-group-id"]
  associate_public_ip_address = true
  root_block_device {
    delete_on_termination = true
    volume_type           = "gp3"
    volume_size           = 40
}

The reason i am doing it that way (create manualy role once and not via terraform) is becouse i dont
want to give terraform ability to create roles and permissions, only ec2 instances and attach only existing
role, less permissions on jenkins/terraform = better security (at least this is what i think is proper..)
Will be glad for any ideas..:)
Thanx alot!


text:
Q: Node.js server is not stopping on forever stop 0 My case is this:
I am running a node.js server at domain.com:54321
The command I use to start the server is:
forever start -l forever.log -a -o out.log -e err.log index.js

However, there are some cases where our code gets into a high demanding function, causing the script to work very slow or unresponsive. We are trying to optimize it.
In that case, I stop the server, and start a new one if needed, lets say domain.com:67890
forever stop 0

But if I want to start again the recently stopped node.js server domain.com:54321 (or restart it instead of stopping it) with this, I was expecting the processes to stop and run as fresh and fast again.
The thing that if I start it again, or restart it, it continues to go high on resources. I found out that I need to leave it for a couple of hours to start it again.
My question is, are there any other commands that will make sure that every instance, resource of that server is stopped, so I can start using it again immediately?
Thank you

A: You can stop a Forever daemon using the id of forever running using four different ways:

*

*index

*id

*uid

*pid

I can see one of the answer to covering the stopping a forever running daemon using pid, I can add for other methods.
List running Forever instances:
$ forever list
info:    Forever processes running
|data: | index | uid | command          | script      |forever pid|id   | logfile                |uptime        |
|------|-------|-----|------------------|-------------|-----------|-----|------------------------|--------------|
|data: | [0]   |f4Kt |/usr/bin/nodejs   | src/index.js|2131       | 2146|/root/.forever/f4Kt.log | 0:0:0:11.485 |

$ forever stop 0 index
$ forever stop 2146 id
$ forever stop --uid f4Kt uid
$ forever stop --pidFile 2131 pid

A: To make sure to stop the process you can use the pid option:
forever start -l forever.log -a -o out.log -e err.log --pidFile ~/app_pid index.js

forever stop --pidFile ~/app_pid

A: Run forever list then forever stop **id**
Here is a sample output
$ forever list
info:    Forever processes running
data:        uid  command                                                  script forever pid   id logfile                          uptime
data:    [0] 9Xzw ng serve --host 0.0.0.0 --port 300         1111   2312    /home/ec2-user/.forever/9Xzw.log 1:3:20:50.412
data:    [1] wOj1 npm run-script app-start-dev                                    29500   24978    /home/ec2-user/.forever/wOj1.log 0:0:5:3.433

Check your process id and kill
forever stop 0 OR forever stop 1 OR forever stop 2
Here 0, 1, 2 index of process, data:[0], data:[1]

A: May be kill all node processes forcefully if that is what you want.
follow this answer to kill all node process : https://stackoverflow.com/a/14790921/5055850

A: check this, if your port are 8000 , it will stop forever
sudo kill -9 `sudo lsof -t -i:8000`

A: I had the same problem. For me this worked:
forever stopall.


text:
Q: sort version nicely with letters and numbers for some reason I cannot find this example
I want to sort version numbers nicely.
for example
[v2,v10,v1]
to
[v1,v2,v10]
I really only need the max but I can't find anything for that either.

A: Don't reinvent the .whl, you can use pkg_resources

parse_version(version)
  Parsed a project's version string as defined by PEP 440. The returned value will be an object that represents the version. These objects may be compared to each other and sorted.

Demo:
>>> from pkg_resources import parse_version
>>> data = ['v2', 'v10', 'v1', 'v2.1', 'v2.1.1']
>>> sorted(data, key=parse_version)
['v1', 'v2', 'v2.1', 'v2.1.1', 'v10']

You could also pass it as the key to find the latest version:
>>> max(data, key=parse_version)
'v10'


text:
Q: Is there a way to rebind an event handler referenced in a jQuery plugin? I'm using the leanModal plug-in on a site I'm building.  I'm currently working on an administrator page and want to disable the overlay click event handler until the user has successfully authenticated. I can successfully unbind all event handlers using $("#lean_overlay").off("click");, but I'm unable unbind/rebind the specific event handler when it's stored in a variable.  I'm using jQuery 1.10.2 and the most up-to-date leanModal.
Here's a snippet of my code:
var overlay_event = $._data($('#lean_overlay')[0], "events");
$('#lean_overlay').off('click', overlay_event);
    // insert code to check if user's logged in
$('#lean_overlay').on('click', overlay_event);

Is this the proper way to store a handler in a variable using jQuery 1.8+?
EDIT:
I neglected to mention that I've tried event.preventDefault(); and return false; to stop the event from firing.  My logic for checking the user's authentication state is working.  What's not working is the disabling of the click event handler for the overlay to force users to use the login modal before accessing the page. I'm unsure if that was clear in my original post.  Storing the event handler seemed like the best option...
2nd EDIT:
I figured out how to stop the overlay click event handler from firing using a botched version of namespacing:
$('#lean_overlay').off('click', $(this).leanModal.close_modal);
The removal of the event handler works, but the re-bind doesn't appear to be working.  I can't seem to find an easy way of re-binding an event handler function found in a linked plug-in.  Ideas?

A: So, no way I could find to "capture" the event handler referenced by the plug-in.  My solution was to make my own overlay and use that for the login screen.  Works perfectly because it's MINE! :)


text:
Q: How to use logical And in VoiceXML I am try to use "logical and" in voicexml(with Viecore extensions)
Here is my code:
<if cond="(menuChangeOn == 'YES')&&(businessGroup == '<%=Viecore.ABCCompany.DataAccess.Constants.CURRENT_MODULE.Main_Number%>')">

The "&&" seems to cause trouble while the voice xml file is parsed.
What's the best practice to resolve this common problem?

A: It XML, so you must use XML entities & for the ampersand symbol. So instead of &&, use &&.


text:
Q: Given $T_n = \sum_{i=1}^{n} \frac{(-1)^{i+1}}{2i-1}$, show $\sum_{n=1}^{\infty} (T_n-T) = \frac{\pi}{8} -\frac{1}{4}$. Let $\displaystyle T_n = \sum_{i=1}^{n} \dfrac{(-1)^{i+1}}{2i-1}$, then show that $$\sum_{n=1}^{\infty} (T_n-T) = \dfrac{\pi}{8} -\dfrac{1}{4}$$ where $\displaystyle T = \lim_{n\rightarrow \infty} T_n$.
My approach for this was to define the function $\displaystyle F(x) = \sum_{n=1}\sum_{i=1} \dfrac{x^{i+n}}{2(i+n)-1}$ and figure out what $F(x)$ is. So far, I got $$\displaystyle 2F'(x)- \dfrac{F(x^2)}{x^2} = \dfrac{1}{(1+x)^2}.$$ I know $\arctan x$ shows up somewhere but that's about what I have. Any hints? I prefer hints to complete solutions.

A: $$T_n=\sum_{k=0}^{n-1}\frac{(-1)^k}{2k+1}=\int_0^1\sum_{k=0}^{n-1}(-x^2)^k\,dx=\int_0^1\frac{1-(-x^2)^n}{1+x^2}\,dx;\\\sum_{n=1}^\infty(T_n-T)=\sum_{n=1}^\infty\int_0^1\frac{-(-x^2)^n}{1+x^2}\,dx=\int_0^1\frac{x^2\,dx}{(1+x^2)^2}.$$ Now write the integrand as $x\cdot x(1+x^2)^{-2}$ and integrate by parts.

A: Note that $$L= \lim_{n\to \infty} T_n -T_n =\sum_{k=1}^{\infty}\frac{(-1)^{k-1}}{2k-1}-\sum_{k=1}^{n}\frac{(-1)^{k-1}}{2k-1}=\sum_{k=1}^{\infty}\frac{(-1)^{k+n}}{2k-1+2n}=\sum_{k=1}^{\infty}(-1)^{k+n}\int_{0}^1  x^{2k+2n-2}dx =(-1)^{n}\int_0^1\left[\sum_{k=1}^{\infty} (-1)^{k-1}x^{2k+2n}\right]\frac{dx}{x^2}=(-1)^{n+1}\int_0^{1} \frac{x^{2n}}{1+x^2}dx $$  Therefore,$$\sum_{n\geq 1}L =\int_0^1\frac{1}{1+x^2}\left(\sum_{n\geq 1}(-1)^{n+1}x^{2n}\right)dx=\int_0^1\frac{x^2}{(1+x^2)^2}dx\underbrace {=}_{ x=\tan y} \int_0^{\frac{\pi}{4}}\sin^2ydy =\int_0^{\frac{\pi}{4}}\left(1-\cos^2y\right)dy=\frac{y}{2}-\frac{\sin2y }{4}\Biggr|_0^{\frac{\pi}{4}}=\frac{\pi}{8}-\frac{1}{4}$$


text:
Q: Returning a std::vector - right approach I am trying to create a class method that will return a std::vector, and am a bit confused about the best way to do this.
The approach I've used is to define the following method:
std::vector<double>* GetBins(void);

and in the method, allocate a new std::vector, which I fill with data. I'm returning a pointer to this ie.
std::vector<double>* Frequency::GetBins(void) {
    std::vector<double> *rtnVec = new std::vector<double>();
    for (_itMap = _mapFreq.begin(); _itMap != _mapFreq.end(); _itMap++ ) {
        rtnVec->push_back((*_itMap).first);
    }
    return rtnVec;
 }

(_itMap is a class-defined iterator).
In my main.cpp, I've done the following:
 std::vector<double>* myBins;
 myBins = myFreq3->GetBins();
 delete myBins;

I know with this approach, I'm going to get a dangling pointer unless I delete the pointer in the main.cpp code, so it's already a bit 'dangerous'. What's the best way to return a new std::vector from a class method?
Thanks guys
Pete

A: Return by value
std::vector<double> Frequency::GetBins(void) {
    std::vector<double> rtnVec;

    // ...

    return rtnVec;
 }

However if you want return by pointer, you can use smart pointers:
std::unique_ptr<std::vector<double>> Frequency::GetBins(void) {
    std::unique_ptr<std::vector<double>> rtnVec(new std::vector<double>());

    //...

    return rtnVec;
 }

A: If you want to avoid copies/ dangling pointers/..., another way is simply to pass your std::vector by reference to the method:
void Frequency::GetBins( std::vector<double>& bins ) {
    for (_itMap = _mapFreq.begin(); _itMap != _mapFreq.end(); _itMap++ ) {
        bins->push_back((*_itMap).first);
    }
 }

You just need then to define it before:
 std::vector<double> myBins;
 myFreq3->GetBins(myBins);

A: The best way is to return by value:
std::vector<double> Frequency::GetBins() {
    std::vector<double> rtnVec;
    rtnVec.reserve(_mapFreq.size()); // reserve enough size, no reallocations
    for (_itMap = _mapFreq.begin(); _itMap != _mapFreq.end(); ++_itMap ) {
        rtnVec.push_back(_itMap->first);
    }
    return rtnVec;
}

Then you'd use the function like this:
std::vector<double> myBins = myFreq3->GetBins();
// no need for delete!

The compiler will probably use RVO and perform no copies. If you're using C++11, then move semantics will ensure that no copies are performed.


text:
Q: Hide User Snap Button I have a button:
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.src ="my user snap api key";
  const firstScript = document.getElementsByTagName('script')[0];
  firstScript.parentNode.insertBefore(script, firstScript);
  script.id = "userSnap";

I want to hide it when a certain event is called:
I have tried this but it doesnt disappear
document.getElementById('userSnap').remove()
the button is still there...
There is no css for it in it or anything so i cant adjust a css file it is just dont through user snap

A: The UserSnap script adds a button to the DOM. You can't hide the effects a script has had on the DOM by removing the script after it has run, instead you need to manipulate the DOM to hide or remove the button itself.
Use your browser's developer tools to figure out if the button has some kind of unique identifying attribute like an ID or class name, and use that to select and remove the button.

A: Please try this

    just testing

remove

Fiddle


text:
Q: MySql stored procedure returns value error I am using the following stored procedure:
DELIMITER $$
USE `customer`$$
DROP PROCEDURE IF EXISTS `InsertCustomerEmail`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertCustomerEmail`(IN p_Customer_ID INT(11),
                                  IN p_from_who VARCHAR(50),
                                  IN p_to_whom VARCHAR(50),
                                  IN p_CC VARCHAR(50),
                                  IN p_BCC VARCHAR(50),
                                  IN p_Subject VARCHAR(500),
                                  IN p_Massage VARCHAR(4000),
                                  IN p_Is_Sent BIT(1),
                                  IN p_Sent_When DATE,
                                  IN p_Is_Active BIT(1),
                                  OUT new_ID INT)
BEGIN
    INSERT INTO customer_emails (
        `Customer_ID`,
        `from_who`,
        `to_whom`,
        `CC`,
        `BCC`,
        `Subject`,
        `Massage`,
        `Is_Sent`,
        `Sent_When`,
        `Is_Active`
        ) VALUES (p_Customer_ID,
              p_from_who,
              p_to_whom,
              p_CC,
              p_BCC,
              p_Subject,
              p_Massage,
              p_Is_Sent,
              p_Sent_When,
              p_Is_Active);
    SET @new_ID=SCOPE_IDENTITY();
END$$
DELIMITER ;

My database has an auto increment ID column, I would like to return this ID (the last one added) in the New_ID variable but when I run the CALL for the procedure it returns NULL for the New_ID.
Any suggestions?
Thanks!

A: The reason being the @new_ID assignment is not considered part of the transaction; the INSERT statement is. Move the following line outside the BEGIN ... END
SET @new_ID=SCOPE_IDENTITY();

Since you have only one operation in the batch, you can loose the BEGIN...END
EDIT
As Thorsten Dittmar suggested I need to explain a bit further.
The @new_ID assignment is executed right away, since it is not considered DML action and is not part of the batch. Thus SCOPE_IDENTITTY() is executed, but there is no identity generated yet, because the INSERT statement IS considered part of the batch and it is executed at its end.
EDIT 2
Since the OP added MySQL tag, above statement won't work, since there is no SCOPE_IDENTITY() in MySQL. Instead the correct function is LAST_INSERT_ID().
SET @new_ID=LAST_INSERT_ID();


text:
Q: Not all TTF fonts visible from the (Sun) JDK I wanted to use Monaco.ttf with IntelliJ. Unfortunately it doesn't show up.
I also noticed that the Monaco font doesn't appear in the list of fonts got from awt:
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()

I installed Monaco.ttf  in /usr/share/fonts/truetype/osx
I also tried to copy it in /usr/lib/jvm/java-6-sun/jre/lib/fonts and even tried to manually update the /usr/lib/jvm/java-6-sun/jre/lib/fonts/fonts.dir file
I restarted the jvm at each try, but the fonts is not visible from the sun jdk.
All other applications see that font (even eclipse, which is in java but uses the SWT library)
Does anybody know how to make jdk see additional fonts?

A: The problem is with the Monaco font itself, it doesn't seem to have appropriate metadata and is a hacky port, so Java doesn't recognize it. Probably you can find some other version of this TTF file which will work better or try to fix it yourself using FontForge.
See also my comment in the IntelliJ IDEA issue tracker.

A: You need to run the mkfontscale and mkfontdir utilities in this order, in order to update the fonts.dir file.
Enter the /usr/lib/jvm/java-6-sun/jre/lib/fonts directory from your terminal and run
sudo mkfontscale
sudo mkfontdir

mkfontscale creates the fonts.scale file which mkfontdir can use to create fonts.dir.

A: Update your font cache
sudo fc-cache -f -v

A: Have you tried calling:
java.awt.GraphicsEnvironment.getAllFonts()

It seems that the Java font system is kinda messed up:
http://www.sabi.co.uk/Notes/linuxFonts.html#fontSwJava
You may have to work around issues with finding the fonts. But if eclipse can see the font, then there is no reason why your application can not. You can even choose to look at the eclipse code to see how they've done it.
http://java.sun.com/products/java-media/2D/reference/faqs/#Font_and_Text_questions


text:
Q: Obtain numbers from a field and process them I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
    writeInput(input, one); // var one = 1;
});

Next I have the function "write Input" (This is where the numbers are displayed on a "screen")

function writeInput(field, str){
    $input = $(field);
    var text = $input.val($input.val() + str);
    $input.text(text);
    convert(text);
}

And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
    var divide = (input / 12);
    $("#output").html(divide); //output is a paragraph where the number is displayed
}

When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!

A: In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
    var text = $(field).val(function(i, v){
                  return v + str;
               }).text(function(i, t){
                  return t + str
               }).val();
    convert(text);
}


text:
Q: WAI-ARIA: Why does it recommend breadcrumbs have a link to the current page? The WAI-ARIA breadcrumb example has the following rule:

The link to the current page has aria-current set to page. If the element representing the current page is not a link, aria-current is optional.

However, it was my understanding that the current page in a breadcrumb shouldn't be a link, as this link would simply take the user to the page they are already on? Is this just an oversight of the example, or is there a reasoning behind this?

A: There is no usability reason to have a link to the current page and from a purely user experience and accessibility perspective it serves no purpose and actually adds another tab stop and possible confusion.
However accessibility doesn't live in isolation and so we need to decide if having a link to the current page has other benefits.
Now Stack Overflow isn't the place for SEO discussion but this is something that is debated regularly as it can affect 'link juice' proportions based on the number of links on the page, I don't think there is any truth to that but that is the world of SEO for you and something you can research / consider.
The other reason is if using structured data such as schema.org breadcumbList.
Although there are ways to use structured data without a hyperlink for the last breadcrumb it just leaves the flexibility there for if using microFormats instead of JSON-LD
Conclusion
If it is easy enough to not use a link and change your generated 'microFormats' or 'JSON-LD' then it would be preferable to not have a hyperlink for the current page in your breadcrumbs. This would improve usability and UX.
However if you do need to have a hyperlink due to other constraints then make sure you add aria-current="page" and possibly some visually-hidden text that says it is the current page.
For example: page name (current page))


text:
Q: Adding table data element identifier in JS I need to create an edit button for each data cell in the column and I saw in this tutorial that to start things of I need to add an identifier to the Table Data Cell element (  ): https://www.youtube.com/watch?v=pNxWUfw1J_w, but I have those tds defined in JS:
function refresh_row(row, values) {
  var tds = $(row).children('td');
  var ii = 0;

  $(tds[ii]).html(values.type.name);
  ii++;
  $(tds[ii]).html(values.description);
  ii++;
  $(tds[ii]).html(values.company);
  ii++;
  $(tds[ii]).html(values.place);
  ii++;
}

Is there any way to add an identifier like:
id="result-${obj.id}" data-testid="${obj.id}""

to the values.description data cell elements?
If it makes it any easier, values is a Python dictionary populated with JSON data similar to the one used in this question: Is transferring JSON data in Django possible without JS / JQuery?

A: You could use attr('id'...) and data('testid'...) to achieve this:
  $(tds[ii]).html(values.description).attr('id', 'result-${obj.id}').data('testid', '${obj.id}')


text:
Q: Flash AS3 sorton() difficulty I'm struggling on this. I've gone through other questions here and as far as I can tell I'm doing what I'm supposed to. Seems like it should be simple enough, but I'm still hung up. Here's my XML:
<?xml version="1.0" encoding="UTF-8"?>
<objects>
    <player>
        <score Name="Josh" Company="AB" Email="josh@ab">200</score>
    </player>
    <player>
        <score Name="Shain" Company="AC" Email="shain@AC.com">1800</score>
    </player>
    <player>
        <score Name="Jessica" Company="AD" Email="jessica@AD.com">20000</score>
    </player>

</objects>

And here's my code. I'm putting the XML "scores" data into an Array "myArray" with the "for each" loop, and that traces fine, but the sort isn't sorting them by scores as it should be.
var myArray:Array = new Array();

    for each (var item:XML in scores)
    {
        myArray.push(item);
    }
    trace("pre-sort "+myArray);

    myArray.sortOn("score", Array.NUMERIC | Array.DESCENDING);

    trace("post-sort "+myArray);

Again, this seems really simple, but I'm beating my head against the keyboard on it. Any help is much appreciated.

A: I am not good with XML but this seems to work for me. I just changed the scores to scores.children().
var scores:XML = <objects>
        <player>
          <score Name="Josh" Company="AB" Email="josh@ab">200</score>
        </player>
        <player>
          <score Name="Shain" Company="AC" Email="shain@AC.com">1800</score>
        </player>
        <player>
          <score Name="Jessica" Company="AD" Email="jessica@AD.com">20000</score>
        </player>
        </objects>;

var myArray:Array = new Array();

for each (var item:XML in scores.children())
{
    myArray.push(item);
}
trace("pre-sort "+myArray);

myArray.sortOn("score", Array.NUMERIC | Array.DESCENDING);

trace("post-sort "+myArray);

A: Well sortOn is for sorting an Array filled by Objects and based on a property field, but you are filling the array with XML node and there is no property directly named 'score' on these node.
You can use the function sort by itself to get the result you want.
var xml:XML=
<objects>
    <player>
        <score Name="Josh" Company="AB" Email="josh@ab">200</score>
    </player>
    <player>
        <score Name="Shain" Company="AC" Email="shain@AC.com">1800</score>
    </player>
    <player>
        <score Name="Jessica" Company="AD" Email="jessica@AD.com">20000</score>
    </player>
</objects>;

var myArray=[];
for each (var score:XML in xml..score) {
 myArray[myArray.length] = score;
}

myArray.sort(Array.NUMERIC | Array.DESCENDING);
trace("post-sort "+myArray);

Here a live example on wonderfl:
http://wonderfl.net/c/c6av


text:
Q: QLineEdit Qt in c++ removing QLineEdit I'm trying to make an adress book in Qt and i am using the following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"

int counter = 1;

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QLineEdit* Voornaam = new QLineEdit(this);
    Voornaam->setObjectName(QString::fromUtf8("lineEdit_4"));
    Voornaam->setGeometry(QRect(10, 65+ 33*counter, 113, 24));
    Voornaam->show();

    QLineEdit* Achternaam = new QLineEdit(this);
    Achternaam->setObjectName(QString::fromUtf8("lineEdit_5"));
    Achternaam->setGeometry(QRect(140, 65+ 33*counter, 113, 24));
    Achternaam->show();

    QLineEdit* Adres = new QLineEdit(this);
    Adres->setObjectName(QString::fromUtf8("lineEdit_6"));
    Adres->setGeometry(QRect(270, 65+ 33*counter, 113, 24));
    Adres->show();

    counter+= 1;
}

void MainWindow::on_pushButton_2_clicked()
{
}

As you can see in the second function the pushbutton_2_clicked i haven't put anything yet.
The program works like this: it adds a QLineEdit every time I push a button(the first function). Then it displays it on the ui. Also I just make a new QLineEdit everytime and move it a bit down so I get a list of these.
Voornaam, achternaam and adress are just names for information I want to type in these QLineEdits in my program.
What I want to do now is delete these QLineEdit but i don't know how, I've searched this on the internet but i can't find examples. So I want to delete these previously made QLineEdits. Do I have to use the name ? LineEdit_4 for example. I've found a widget function removewidget, do I use this?
Is there a way to easier display these widgets? Now I'm just making rectangles and placing them beneath eachother using the counter.

A: Why don't you use for example a QTableWidget. You can add/remove rows from that (and columns if you like). And you use setCellWidget function to add QLineEdits into the cells.
You could have a button to add a new line. And you could have a button to delete the selected lines from the table.


text:
Q: ios app rejected because of ipv6 incompatibility after making all suggestion My app has been rejected 4 times because of ipv6 incompatibility.But I have already made changes in my app to support ipv6.
1) I have used latest AFNetworking class
2) checking reachability with hostname method
3) Even made our server fully ipv6 supported.
Then also app gets rejected with following reason:
We discovered one or more bugs in your app when reviewed on iPhone running iOS 10.2.1 on Wi-Fi connected to an IPv6 network.
Specifically, launching your app, resolves to a black screen.

A: I already have this issue with Apple guys, even with an IPV6 compatible app. Make sure the server you are calling is IPV6 compliant. You can use for example This site to test that the WS/server/machine you want to reach can "talk" with this protocol.
If it's the case, you can easily explain to Apple that the app is IPV6 compatible, by using URLSession only (for example), but it's the distant server which is not.
Got the problem twice, twice explain as above: succeed.
EDIT: Be sure by using AFNetworking, you are using 3.x version, and not 2.x (not IPV-6 compatible because using NSURLConnection instead of NSURLSession)

A: I had faced same issue. Mine was also rejected due to IPV6. Check below two things for your application:
1) Make sure you API link which you used in your application, doesn't have any ip address. If you calling API using IPAddress then your application will rejected.
2) Do testing your application using IPV6 network thorugh your system. Here is the link.
If your application is fullfill both testcase, then don't do any thing, just right comment in iTuneConnect and told them that my application is running in IPV6 network. Can you please guide to find my issue? If possible then can I have a call with your representative?
So they ask your contact detail and give you call and your issue will resvoled. I have wasted around 20 days to solved this issue. But apple representative told that this is them internal issue.
So my humble advice to contact Apple representative as soon as possible and your issue will resolve without doing anything.


text:
Q: Split a long string into smaller strings based on delimiter and max length? I have long strings in a bash script that I would like to break up into substrings. The delimiters are && or || and also (the difficult part) each substring can be no more than 70 characters.
For ex., a long single string like this:
(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) || (First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa && Third_Down_or_Up && Fourth_Up_or_Down

Broken up into:
(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) ||
(First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa &&
Third_Down_or_Up && Fourth_Up_or_Down

So far I was using awk like this:

*

*Get the max# of fields
max_fields=$(echo $long_string | awk -F'[&][&]|[|][|]' '{ print NF }')

*Calculate the length of each field

*If length less than 70, print out all fields under length 70

*Keep going for remaining fields

But with awk I loose my && and || symbols. So I ended up printing out:
Dfa_and_Cfa Second_Up_or_Down Third_Down_or_Up_or_Positive

I don't think this is the right approach anymore. Any help?

A: Why not try using fold?
$ str='(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) || (First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa && Third_Down_or_Up && Fourth_Up_or_Down'
$ fold -sw70 <<< "$str"
(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) ||
(First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa &&
Third_Down_or_Up && Fourth_Up_or_Down

A: With GNU awk for the 4th arg to split():
$ cat tst.awk
{
    prev = ""
    nf = split($0,f,/\s*(&&|\|\|)\s*/,s)
    for (i=1;i<=nf;i++) {
        curr = f[i] s[i]
        if ( length(prev curr) > 70 ) {
            print prev
        }
        else {
            curr = prev curr
        }
        prev = curr
    }
    print curr
}

$ awk -f tst.awk file
(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) ||
(First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa &&
Third_Down_or_Up && Fourth_Up_or_Down

A: Give this a try:
longstring="(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) || (First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa && Third_Down_or_Up && Fourth_Up_or_Down"

printf "%s" "${longstring}" | sed -e 's/\(&&\)/\1\n/g' -e 's/\(||\)/\1\n/g' |\
 awk -v maxlen=70 '{
   stringlen=length(string);
   if (stringlen == 0 || ((stringlen + length($0)) <= maxlen)) string=string $0
   else { print string; string=$0}}
   END {if (length(string)>0) print string}'

(Dfa_and_Cfa && Second_Up_or_Down && Third_Down_or_Up_or_Positive) ||
 (First_Up_or_Down) && Third_Down_or_Up && Dfa_and_Cfa &&
 Third_Down_or_Up && Fourth_Up_or_Down

The first sed command uses 2 regex to add new lines after && and ||.
The awk command reads each line ($0) and build a string which is the concatenation of the lines. If the sum of the lengths of string and $0 exceeds maxlen (70) then the current string is printed, and the string is set to current line.

A: One solution using awk:
The code:
echo $long_string | awk -F'[&][&]|[|][|]' '{ for(i=1;i<NF;i++) print $i }' | awk  '{if(length($0)<70) print}'

The explanation:
I separate the fields by space with:
 for(i=1;i<NF;i++) print $i

Then I consume the output with the pipe and I print only if the length is less than 70:
 | awk  '{if(length($0)<70) print}'

I you want to use the remaining fields shorter than 70 you have to add a pipe (|) and put another command


text:
Q: pandas dataframe get row numbers and add to list Lets assume we have a panda dataframes with three features as represented below.

Each rows is representing a customer and each column representing some features of this customer.
I would like to get row number and add them to a list or not add them to list according to their feature values.
Lets say, we would like to find row numbers if FEATUREA less than 100 or FEATUREB more than 500.
I have written some code for this as you can see below.
import pandas as pd

d = [{'feature1': 100, 'feature2': 520, 'feature3': 54},
     {'feature1': 102, 'feature2': 504, 'feature3': 51},
     {'feature1': 241, 'feature2': 124, 'feature3': 4},
     {'feature1': 340, 'feature2': 830, 'feature3': 700},
     {'feature1': 98, 'feature2': 430, 'feature3': 123}]

df = DataFrame(d)
print(df)
print("----")

dataframe1 = df[(df['feature1'] < 100)]
dataframe2 = df[(df['feature2'] > 500)]

print(dataframe1)
print(dataframe2)
# here I would like to get row number temp and add them to result list

Output of the program
      feature1  feature2  feature3
0       100       520        54
1       102       504        51
2       241       124         4
3       340       830       700
4        98       430       123
----
   feature1  feature2  feature3
4        98       430       123
   feature1  feature2  feature3
0       100       520        54
1       102       504        51
3       340       830       700

I could not figure out how to combine dataframe1 and dataframe2 and then get theirs row number. Could you please share if you know how to do it?
I would like to see a result list like that
result = [ 4, 0, 1, 3]

A: Not real clear... but maybe this:
df.query('feature1 < 100 | feature2 > 500').index.tolist()

[0, 1, 3, 4]

A: How about like this?
ls = []

ls.extend(df.index[(df['feature1'] < 100 )])
ls.extend(df.index[(df['feature2'] > 500 )])

print(ls)
[4, 0, 1, 3]

A: You want to output the index as a list.
print(df[df['feature2'] > 500].index.tolist())

[0, 1, 3]


text:
Q: processes that run during new user creation I have two questions:

*

*What processes typically run when a new user is created?

*What processes run when an existing (regular) user escalates his privileges to gain root-access?

I Googled a lot and could not find anything.
Thanks.

A: useradd is the process that is run when you execute the compiled useradd (non-official).
As for the second question, Privilege escalation is when someone exploits a vulnerability to gain more rights in the operating system. For example if you find a bug like buffer overflow in a service run by root.


text:
Q: Logback Kafka Appender Not Writing Logs to Topic I am trying to do a simple test of Logback Kafka Appender. Following is what I have in  my logback.xml which I have placed in src/main/resources:
<?xml version="1.0" encoding="UTF-8"?>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

<!-- This is the kafkaAppender -->
<appender name="kafkaAppender"
    class="com.github.danielwegener.logback.kafka.KafkaAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        </pattern>
    </encoder>
    <topic>test</topic>
    <keyingStrategy
        class="com.github.danielwegener.logback.kafka.keying.NoKeyKeyingStrategy" />
    <deliveryStrategy
        class="com.github.danielwegener.logback.kafka.delivery.AsynchronousDeliveryStrategy" />

    <!-- Optional parameter to use a fixed partition -->
    <!-- <partition>0</partition> -->

    <!-- Optional parameter to include log timestamps into the kafka message -->
    <!-- <appendTimestamp>true</appendTimestamp> -->

    <!-- each <producerConfig> translates to regular kafka-client config (format:
        key=value) -->
    <!-- producer configs are documented here: https://kafka.apache.org/documentation.html#newproducerconfigs -->
    <!-- bootstrap.servers is the only mandatory producerConfig -->
    <producerConfig>bootstrap.servers=localhost:9092</producerConfig>

    <!-- this is the fallback appender if kafka is not available. -->
    <!-- <appender-ref ref="STDOUT" /> -->
</appender>

<logger name="com.my.package" level="info" additivity="false">
    <appender-ref ref="kafkaAppender" />
</logger>
<root level="info">
    <appender-ref ref="kafkaAppender" />
</root>

I have started a Kafka server on Windows with a separate Zookeeper. I have created a test topic as well.
Started Zookeeper on Windows with : zkServer.cmd
Started Kafka Server on Windows with : kafka-server-start.bat config\server.properties
Created a topic : kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
Started a consumer on Windows with : kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --from-beginning
In my Java class all I have is a logger inside a method.
private static final Logger logger =
LoggerFactory.getLogger(FormController.class);
    logger.debug("DEBUG :: Inside do post method");
    logger.info("INFO :: Inside do post method");

My imports are:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

My pom.xml is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.my.package</groupId>
<artifactId>SampleIGApp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SampleIGApp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>1.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.github.danielwegener/logback-kafka-appender -->
    <dependency>
        <groupId>com.github.danielwegener</groupId>
        <artifactId>logback-kafka-appender</artifactId>
        <version>0.2.0-RC1</version>
    </dependency>
</dependencies>
<build>
    <finalName>MyApp</finalName>
</build>

Can someone please tell me as to what am I doing wrong? Even if I comment out STDOUT appender-name, then also logs keep getting written to console, which in my case is Tomcat's catalina.out. I would appreciate any help. Thank you.

A: The documentation  says you need to add logback-classic as dependency:
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
    <scope>runtime</scope>
</dependency>

logback-kafka-appender


text:
Q: IE  scrollTop I have found that with a select element in IE (IE7 and IE9 anyway) where the size attribute is specified, using .scrollTop can result in some weird behavior.  I'm hoping there is a way around it.
If a user manually scrolls to a position, then a script scrolls it to another position, if the user clicks the up or down, the scrolling begins from the position before the script ran.
Here's a very simple example:
http://jsfiddle.net/7yHH7/
If you scroll manually, note the position, then "script" scroll with the button (one or more times), then start to manually scroll again, you'll notice in IE the scrolling begins where the manual scroll left off.
I would like to find a way to make IE work correctly.  I had hopes that jQuery's .scrollTo() might make things right, but unfortunately, no.

A: I am not too sure about the grammar with the .scrolltop function however, I do know that there are various jQuery scripts written for just that. @ http://www.dynamicdrive.com/dynamicindex2/ there are some really nice scripts that may be worth having a look at. Sorry I couldn't help more than that.


text:
Q: javascript: passing value from inside promise then() function I have a promise/global object that outputs as follows in the console:
console.log(globalInfo);

Promise
__proto__:Promise
    [[PromiseStatus]]:"resolved"
    [[PromiseValue]]:globalInfo
        item1:"12345"
        item2:"something else"
        item3:"www.stackoverflow.com"
        __proto__:Object

And am successfully pulling out the value for "item2" as such:
globalInfo.then(function(val) {
  newVar = val.item2;
  console.log('newVar inside: ' + newVar);
});
console.log('newVar outside: ' + newVar);

But, I am not able to pass that variable/value outside of the then() function. Nothing outputs to the console for the second console.log ("newVar outside").
How do I make the variable "newVar" with the the value for "item2" available globally outside of the then() function?


text: Q: Angular Page Showing Blank I have a slight issue. I am trying to access a page (made with angular) through a page (made with bootstrap) but the page made with Angular keeps showing a blank white page. I opened the developer tools and saw the following messages:"Failed to load resource: the server responded with a status of 404 ()" , "Failed to load resource: the server responded with a status of 404 ()" "Failed to load resource: the server responded with a status of 404 ()" All the messages refer to a  CSS page. What do you think could be the issue? I tried reuploading the files before deployment but still no luck. Thanks a lot for your help!