text:
Q: apply a function which contains group_by within dplyr funciton to datalist in R I have a data.list like so:
list(structure(list(group = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), species = structure(c(3L, 3L, 1L, 3L, 3L, 2L, 3L, 1L, 3L,
1L, 3L, 1L, 3L, 1L, 2L, 4L, 1L, 4L, 2L, 3L, 3L, 3L, 2L, 2L), .Label =
c("Apiaceae",
"Ceyperaceae", "Magnoliaceae", "Vitaceae"), class = "factor"),
N = c(2L, 2L, 3L, 2L, 2L, 1L, 2L, 3L, 2L, 3L, 2L, 3L, 2L,
3L, 1L, 4L, 3L, 4L, 1L, 2L, 2L, 2L, 1L, 1L)), class = "data.frame",
row.names = c(NA,
-24L)), structure(list(group = c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), species = structure(c(3L, 3L, 1L, 3L, 3L, 2L, 3L, 1L, 3L,
1L, 3L, 1L, 3L, 1L, 2L, 4L, 1L, 4L, 2L, 3L, 3L, 3L, 2L, 2L), .Label =
c("Apiaceae",
"Ceyperaceae", "Magnoliaceae", "Vitaceae"), class = "factor"),
N = c(2L, 2L, 3L, 2L, 2L, 1L, 2L, 3L, 2L, 3L, 2L, 3L, 2L,
3L, 1L, 4L, 3L, 4L, 1L, 2L, 2L, 2L, 1L, 1L)), class = "data.frame",
row.names = c(NA,
-24L)))

I want to apply my.fun which was written within dplyr package to this list of data. First, I grouped data by "group" and get an output of the function which has already in R and then I applied this function to the data list. But output is 0. there isn't any output. Can you help me to find out the mistake?
 my.fun <- function(x, y){
    group_by(x, !!as.name(group)) %>%
    mutate(out = diversity(N, "shannon"))
 }

check <- lapply(colnames(list), function(x) {
  my.fun(x$group, x$N)
})

Thanks a lot!

A: Assuming that we are passing group column and the column going on which diversity is applied as strings,
library(tidyverse)
library(vegan)
my.fun <- function(data, grpCol, divCol) {
       data %>%
           group_by_at(grpCol) %>%
           mutate(out = diversity(!! rlang::sym(divCol), "shannon"))
           #or use mutate_at
           # mutate_at(vars(divCol), list(out = ~ diversity(., "shannon")))
    }

map(lst1, my.fun, grpCol = "group", divCol = "N")
#[[1]]
# A tibble: 24 x 4
# Groups:   group [3]
#   group species          N   out
#   <int> <fct>        <int> <dbl>
# 1     1 Magnoliaceae     2  1.75
# 2     1 Magnoliaceae     2  1.75
# 3     1 Apiaceae         3  1.75
# 4     1 Magnoliaceae     2  1.75
# 5     1 Magnoliaceae     2  1.75
# 6     1 Ceyperaceae      1  1.75
# 7     2 Magnoliaceae     2  2.06
# 8     2 Apiaceae         3  2.06
# 9     2 Magnoliaceae     2  2.06
#10     2 Apiaceae         3  2.06
# … with 14 more rows

#[[2]]
# A tibble: 24 x 4
# Groups:   group [3]
#   group species          N   out
#   <int> <fct>        <int> <dbl>
# 1     1 Magnoliaceae     2  1.75
# 2     1 Magnoliaceae     2  1.75
# 3     1 Apiaceae         3  1.75
# 4     1 Magnoliaceae     2  1.75
# 5     1 Magnoliaceae     2  1.75
# 6     1 Ceyperaceae      1  1.75
# 7     2 Magnoliaceae     2  2.06
# 8     2 Apiaceae         3  2.06
# 9     2 Magnoliaceae     2  2.06
#10     2 Apiaceae         3  2.06
# … with 14 more rows

Note that
identical(lst1[[1]], lst1[[2]])
#[1] TRUE


text:
Q: Jenkins: How to get value from a Groovy Script to be used in a downstream project? I need to be able to get some slave information to be used in one of my jobs.
I have a Groovy system script to access the slave information
for (aSlave in hudson.model.Hudson.instance.slaves) {
  println('====================');
  println('Name: ' + aSlave.name);
  println('getLabelString: ' + aSlave.getLabelString());

  ... In here I can dig out the information that I need
}

Is there a way how I can get the information back to use in a Post Build Job?
I need to add the output to a parameter or something that can be used by a Post Build Job?

A: If you are running windows I have got a solution for you: You can save your settings into environment varables, which are usable for the currently running job. They will no longer exist once the job is finished, but they are usable for post-build action. Here is an example:
//Creating String to make my example more clear
String myString = 'this is just a test!';

//Create an environment variable, so the Jenkins job can use the parameter
def pa = new ParametersAction([new StringParameterValue('PARAMETER_NAME', myString)]);

// Add variable to current jobs environment variables.
Thread.currentThread().executable.addAction(pa)
println 'Script finished! \n';

After the script ran you can use %PARAMETER_NAME% (if post-build-actions etc.) to gain access to its content.
Additional Hint: To see all available environment variables you can use the build step "execute windows batch command" and click on "See the list of available environment variables" on the buttom (the variables you create while executing scripts are excluded). But you can use these variables within your groovy script using e.g.:
String jenkinsHome = System.getenv('JENKINS_HOME');

A: I used The EnjEnv plugin and it has a 'Evaludated Groovy Script' section that basically you can do anything... but it should return a property map that will be used as Environment variables. I don't know how to return a value from a Groovy script so this worked kewl for me as I can reference property (or Environment variables) from almost anyware
import hudson.model.*

String labelIWantServersOf = TheLabelUsedOnTheElasticAxisPlugin; // This is the label assosiated with nodes for which i want the server names of
String serverList = '';

for (aSlave in hudson.model.Hudson.instance.slaves) {
  out.println('Evaluating Server(' + aSlave.name + ') with label = ' + aSlave.getLabelString());

  if (aSlave.getLabelString().indexOf(labelIWantServersOf ) > -1) {
    serverList += aSlave.name + ' ';
    out.println('Valid server found: ' + aSlave.name);
  }

}

out.println('Final server list where SOAP projects will run on = ' + serverList + ' which will be used in the environment envInject map');

Map<String, String> myMap = new HashMap<>(2);
myMap.put("serverNamesToExecuteSoapProjectOn", serverList );
return myMap;

And then I write the environment variable serverNamesToExecuteSoapProjectOn to a property file using a windows batch script and pass the property file to the next build as a parameterized build

redpajama_set_name: RedPajamaStackExchange


text:
Q: Safely create and manipulate HTML in Ruby, without Rails In Ruby, is there a library for creating HTML with the following characteristics:

*

*Is not dependent on, or a part of, Rails.

*All content is properly encoded, including attributes.

*Nodes are not immediately rendered into strings. That is, you can create a node, and then pass it to a method, append more nodes into it, or add and remove attributes. And then, sometime later, you can ask for the node to be rendered into HTML.

I am aware of the 'builder' and 'Nokogiri' libraries but they don't seem to be able to do all of the above.
There is a 'w3c-dom' library, which does do everything I want, but the DOM API is very low-level. Most libraries in other languages left the DOM API behind a long time ago.


text:
Q: Is there and R fucntion to mutate a variable on multiple columns conditions using If else or I am trying to create a variable in my data based on following conditions:
x y Z S T G
1 0 1 0 1 0
1 0 0 0 0 0
1 1 1 0 0 0
1 1 1 1 1 1

if x=1 then 1,
if y=1 then 2 if s=1 then 3,
if t=1 then 4 if G=1 then 5 if X==y==z==1 then 6 and so on.

Please tell me how can i write this using if else

A: Using if else?
You can calculate it without if else:
v <- 1:6
# this vector should give each column a the value
# 1 2 3 ... 6

# the most tedious part is to get your notes into a the R terminal
# as an R matrix.

# I used the fact that the string in R can span multiple lines:

s <- "x y Z S T G
1 0 1 0 1 0
1 0 0 0 0 0
1 1 1 0 0 0
1 1 1 1 1 1"
# it looks like this:

s
## [1] "x y Z S T G\n1 0 1 0 1 0\n1 0 0 0 0 0 \n1 1 1 0 0 0 \n1 1 1 1 1 1"

# after trying long around with the base R functions
# which led to errors and diverse problems, I found the most elegant way
# to transform this string into a matrix-like tabular form
# is to use tidyverse's read_delim().
# install.packages("tidyverse")

# load tidyverse:
require(tidyverse) # or: library(tidyverse)

tb <- read_delim(s, delim=" ") ## it complains about parsing failues, but
tb
# A tibble: 4 x 6
      x     y     Z     S     T     G
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     0     1     0     1     0
2     1     0     0     0     0     0
3     1     1     1     0     0     0
4     1     1     1     1     1     1
# so it is read correctly in!

# what you want to do actually is
# to multiply each row with `v` and sum this result:

tb[1, ]
# A tibble: 1 x 6
      x     y     Z     S     T     G
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     0     1     0     1     0

# you do:

v * tb[1, ]

  x y Z S T G
1 1 0 3 0 5 0

# if you build sum with this, then you get your desired numbers

sum(v * tb[1, ])
## [1] 9

# row-wise manipulation of matrix/data.frame/tibbles you do by
apply(tb, MARGIN=1, FUN=function(row) v * row)
  [,1] [,2] [,3] [,4]
x    1    1    1    1
y    0    0    2    2
Z    3    0    3    3
S    0    0    0    4
T    5    0    0    5
G    0    0    0    6

# very often such functions flip the results, so flip it back
# by the transpose function `t()`:
t(apply(tb, MARGIN=1, FUN=function(row) v * row))
     x y Z S T G
[1,] 1 0 3 0 5 0
[2,] 1 0 0 0 0 0
[3,] 1 2 3 0 0 0
[4,] 1 2 3 4 5 6

# to get directly the sum by row, do:
apply(tb, MARGIN=1, FUN=function(row) sum(v * row))
## [1]  9  1  6 21

# these are the values you wanted, isn't it?

# I see now, that

tb * v    # by using vectorization of R

     x y Z S T G
[1,] 1 0 3 0 5 0
[2,] 1 0 0 0 0 0
[3,] 1 2 3 0 0 0
[4,] 1 2 3 4 5 6

# therfore the rowSums are:

rowSums(tb * v)
## [1]  9  1  6 21

So this is the usual (messy) way how one often gets to the solution.
At the end, it boils down to this (and usually you find in Stack Overflow short answers like):
Short answer
require(tidyverse)

s <- "x y Z S T G
1 0 1 0 1 0
1 0 0 0 0 0
1 1 1 0 0 0
1 1 1 1 1 1"

tb <- read_delim(s, delim=" ")
rowSums(tb * v)

And this is the beauty of R: If you know exactly what to do, it is just 1-3 lines of code (or a little more) ...


text:
Q: Ansible loops and conditions with arrays I want to be able to control the behaviour of a module by specifying a changed_when condition. This works fine when executing a simple task like the one in the docs:
- command: some command
  register: command_result
  changed_when: "command_result.rc != 2"

The problem comes when I start using loops. I can't figure out how to access stderr, stdout, rc results from the current iteration of a loop. For example:
- command: aptly mirror update some-mirror
  register: aptly_output
  changed_when: "?item?.stdout | search('Download queue: 0 items')"

All results go to aptly_output.results, but how do I access the result of the current iteration?

A: In one of our roles we do this:
- name: themes | activate
  command: "wp-cli --allow-root --no-color --path='{{ item.0.path }}' theme activate {{ item.1.name }}"
  register: check_activate_theme
  changed_when: "'Success: Switched to' in check_activate_theme.stdout"
  with_subelements:
    - wordpress_installs
    - themes
  when: item.1.name and item.1.activate | default(false)
  tags:
    - wordpress-themes-activate-theme

I think this should also work for your use case.


text:
Q: Missing lines in a Python list converted to csv I have a list (called 'empty_list') made of 2781 elements and each of the elements in the list is a list made of 51 strings.
For instance, element 2776 of the list looks like:

['213466', '010', '011', '011', '2', '', '', '', '8760', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

All other elements are similar.
However, when I try to export this list to a .csv file using:
out = csv.writer(open('h02_fin.csv','w'),delimiter=',',quoting=csv.QUOTE_ALL)
out.writerows(empty_list)

I find out that part of the element of empty_list indexed by 2776 (the list above) is missing in the .csv file.
And all the subsequent elements of the list are missing as well (i.e. elements 2777 to 2780 of empty_list).
Any idea where this might stem from knowing that the lenght is ok?


text:
Q: Remote call in Oracle I am currently working on an Oracle database that will use external bash scripts. For now, what I tried to do is to place simple bash script on a local server (the same as the database) and call with a java script.
Everything works fine for now.
But, as I said, I would like subsequently the database to call scripts that are not located on the same server as the database, and thus make "remote calls". Unfortunately I do not know at all how to do so and told myself that you would be able to give me a hand !

A: Are you 100% sure that you want your database to be calling external scripts? Sounds like an enormous security hole just waiting to happen.
If you really must, you could always try calling these scripts via a remote ssh invocation. But in all honestly, it might be worth re-evaluating your global design.


text:
Q: Delaying Attacks With TimerTask Not Working Well I'm making a fighting game and I want the actions of the player to be timed so you can't spam the attack key and win easily.
Here is where I do the keyboard stuff and delay.  It does delay the first time, but then it the delay slowly decreases in time and ends up being 0 and lets you spam the key.  As you can see I've done many things to try and stop the key from registering in the delay etc.
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (isAction == false) {
        if (key == KeyEvent.VK_LEFT) {
            dx = -1;
            if (nHeroX < -10) {
                dx = 0;
            }
            isRight = false;
            isMoving = true;
        } else if (key == KeyEvent.VK_RIGHT) {
            dx = 1;
            if (nHeroX > 1200) {
                dx = 0;
            }
            isRight = true;
            isMoving = true;
        } else if (key == KeyEvent.VK_C) {
            dx = 0;
            isAction = true;
            isMoving = false;
            isBlock = true;
            nImage = 1;
        } else if (key == KeyEvent.VK_X) {
            dx = 0;
            isAction = true;
            isMoving = false;
            isWeak = true;
            nImage = 2;
        } else if (key == KeyEvent.VK_Z) {
            dx = 0;
            isAction = true;
            isMoving = false;
            isStrong = true;
            nImage = 3;
        } else if (key == KeyEvent.VK_P) {
            if (!pause) {
                pause = true;
            } else if (pause) {
                pause = false;
            }
        }
    }
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
        dx = 0;
        isMoving = false;
        nState = nImage = 1;
    } else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
        delayTask = new DelayTask();
        tmrDelay.schedule(delayTask, 0, 500);
    } else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
        z = new DelayTask();
        tmrDelay.schedule(z, 0, 450);
    } else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
        x = new DelayTask();
        tmrDelay.schedule(x, 0, 1200);
    }
    nImgNum = (int) (Math.random() * 6 + 1);
    nDelay = 0;
}

//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {

    public int nTimes = 0;

    @Override
    public void run() {
        nTimes++;
        if (nTimes == 2) {
            isAction = isBlock = isStrong = isWeak = false;
            nState = nImage = 1;
        }
    }
}

Can someone explain why my delay is messed up?  Thank you.
Also this code:
private class Keys extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {
        hero.keyPressed(e);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        hero.keyReleased(e);
        if (hero.getPause()) {
            repaint();
        }
    }
}

A: The simplest way to do this is just to remember the last time.
So:
 private long lastTime = 0;

 void doAction() {
     long timeNow = System.currentTimeMillis()
     if (lastTime + MIN_DELAY < timeNow) {
        return;
     }
     lastTime = timeNow;

     // Do action
 }

All the stuff with timers etc is just approaching this from a much more complicated architecture than you need to.


text:
Q: Signalling Game - How to draw the normal form matrix? I am having trouble converting a signalling game with an extensive form representation to the normal form matrix.
E.g. this one from wikipedia:

I know each player has four strategies: P1: $\{AA, AB, BA, BB\}$ and P2: $\{XX, XY, YX, YY\}$ so we'll have a 4 by 4 table but then I am stuck.
For example, if player 1 plays $AA$, we are in the top part of the game, now if player 2 plays $X$ we get 2 possible payoffs, how do I discern which payoff is related to strategy $XX$ and which is $XY$ ?

A: The first step in the game is the central node labeled "N". It encodes that Nature (or the referee, or Lady Luck) makes a random choice (with probabilities $q$ and $1-q$) of whether we're in the left or right part of the game. Player 1 knows the outcome of this step, but player 2 doesn't (indicated by the dotted lines in the diagram).
If player 1's strategy is AA, then the second part of player 2's strategy (namely what P2 plays if P1 plays B) will never matter, and the outcome is the same in both cases.
However, since there is randomness involved, the payoff matrix should contain expected payoffs.
So in the case AA, XX (or AA, XY), the payoff is $1$ to each player with probability $q$ and $0$ to each player with probability $1-q$. The expected payoff for these strategies is therefore $q$.

A: If player 1 (the sender) plays $AA$ then the payoffs from player 2 (the receiver) playing $XX$ will be the same as playing $XY$.
In other words, if player 1 plays $A$ whichever type they are, and player  2 plays $X$ when player 1 plays $A$, then the world is unaffected by the hypothetical question of how player 2 might react to player 1 playing $B$
If player 1 has a strategy of $AA$ and player 2 has a strategy of $XX$ (or player 2 has a strategy of $XY$) then the payoff is $1,1$ when player 1 is of the left type, and the payoff is $0,0$ when player 1 is of the right type.  That makes the expected payoff $q,q$.
By comparison, if player 1 has a strategy of $AB$ (so top left and bottom right) and player 2 has a strategy of $XX$ then then the payoff is $1,1$ when player 1 is of the left type, and the payoff is $0,0$ when player 1 is of the right type, so the expected payoff is still $q,q$.
Meanwhile, if player 1 has a strategy of $AB$ (so top left and bottom right) and player 2 has a strategy of $XY$ then then the payoff is $1,1$ when player 1 is of the left type, and the payoff is $1,1$ when player 1 is of the right type, so the expected payoff is now $1,1$.   This shows the benefit of signalling

A: To summarize, it is important to remember P1 chooses his strategies based on his type and P2 chooses his strategies based on P1's choice.
So for example the strategy $AB$ for P1 means, if I am type 1 (left side of the graph) choose $A$ as an action, if I am type 2 (right side of the graph) choose $B$ as an action. Remember, P1 observes his type based on Natures probabilities of being type 1 or type 2. For P2, the strategy $XY$ would mean, if P1 plays $A$ play $X$, if P1 plays $B$ play $Y$. P2 does not know what P1's type is so his strategies must be based on P1's actions.
Since we don't know what side we are on because this always decided by Nature, there will always be two possible payoffs for any situation. Meaning, we need to calculate each player's expected payoff based on a situation.
Let's calculate a few to demonstrate this. If P1 plays $AA$, we are essentially in the top part of the graph as regardless of his type, he will play $A$. Now if P2 plays $XX$, he is basically saying, whatever action P1 takes, I'll play $X$, so this leaves only the $X$ branches to consider. And since we are only in the top part of the graph, the branches to consider are the $X$ branches yielding a payoff of (1,1) and (0,0). The expected playoff of P1 is $u_1 = 1 \times q + 0 \times (1-q) = q$ and for P2 it is
$u_2 = 1 \times q + 0 \times (1-q) = q$.
Using the same logic we can repeat this for all 16 scenarios. Here are a few more examples:

*

*$BA$ and $YX$ results in $u_1=u_2=1 \times q + 1 \times (1-q) = 1$

*$AB$ and $XY$ results in $u_1=u+2= 1 \times q + 1 \times (1-q) = 1$

Computing these for all the strategy profiles, we can create the following normal form representation:
$$
\begin{array}{c|lcr}
 & \text{XX} & \text{XY} & \text{YX} & \text{YY} \\
\hline
AA & q,q & q,q & 1-q,1-q & 1-q,1-q \\
AB & q,q & 1,1 & 0,0 & 1-q,1-q\\
BA & q,q & 0,0 & 1,1 & 1-q,1-q\\
BB & q,q & 1-q,1-q & q,q & 1-q,1-q
\end{array}
$$
Big thanks to Henry and Henning for providing intuition for this understanding.


text:
Q: Exponentiation of complex numbers and the absolute value I want to find all $w\in \mathbb{C}\setminus\{0\}$ and all $z\in \mathbb{C}$ such that the equation $|w^z|=|w|^z$ holds.
A first result is, that this is true for $z\in\mathbb{Z}$ by repeated multiplication.
For further results I've tried to write both expressions $|w^z|,|w|^z$ as in terms of the $\exp$ function and find some relations in the argument. Somehow I struggle to get the desired results here.
I would appreciate any hints!


text:
Q: Fundo com gradiente em CSS funciona na horizontal mas não pra vertical A réplica do codigo:
https://codepen.io/utamo/pen/XoyzWN
ao aplicar no body:
background: linear-gradient(to right, #33ccff 0%, #ff99cc 100%);

tenho o seguinte resultado
mas ao trocar pra
background: linear-gradient(to bottom, #33ccff 0%, #ff99cc 100%);

acaba ficando assim
Sei que é algo simples mas me falta conhecimento no momento

A: Coloca seu html e body com height 100% e background-repeat: no-repeat


text:
Q: Angular4 component test error with Can't resolve all parameters for AutocompleteComponent: (?, ?, ?) i take a new position and now i must maintain angular4 custom components without unit test (i'm an angular noob;).
I'm strating writing unit test before adding new features (karma + jasmine framework) and i'm tripping over a problem with this error and cannot resolve this (try to provide parameters, change tests definition, ...):
  Failed: Can't resolve all parameters for AutocompleteComponent: (?, ?, ?).
    Error: Can't resolve all parameters for AutocompleteComponent: (?, ?, ?).
        at syntaxError (spec.bundle.js:36817:34)
        at CompileMetadataResolver._getDependenciesMetadata (spec.bundle.js:50893:35)
        at CompileMetadataResolver._getTypeMetadata (spec.bundle.js:50761:26)
        at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (spec.bundle.js:50356:24)
        at CompileMetadataResolver.loadDirectiveMetadata (spec.bundle.js:50220:25)
        at spec.bundle.js:61930:72
        at Array.forEach (<anonymous>)
        at spec.bundle.js:61929:72
        at Array.forEach (<anonymous>)
        at JitCompiler._loadModules (spec.bundle.js:61926:75)
        at JitCompiler._compileModuleAndAllComponents (spec.bundle.js:61909:36)
        at JitCompiler.compileModuleAndAllComponentsAsync (spec.bundle.js:61841:37)
        at TestingCompilerImpl.compileModuleAndAllComponentsAsync (spec.bundle.js:85709:31)
        at TestBed.compileComponents (spec.bundle.js:20190:31)
        at Function.TestBed.compileComponents (spec.bundle.js:20073:67)
        at UserContext.<anonymous> (spec.bundle.js:86201:14)
        at ZoneDelegate.invoke (spec.bundle.js:68195:26)
        at AsyncTestZoneSpec.onInvoke (spec.bundle.js:71078:39)
        at ProxyZoneSpec.onInvoke (spec.bundle.js:70777:39)
        at ZoneDelegate.invoke (spec.bundle.js:68194:32)
        at Zone.runGuarded (spec.bundle.js:67958:47)
        at runInTestZone (spec.bundle.js:19557:25)
        at UserContext.<anonymous> (spec.bundle.js:19496:13)
        at ZoneDelegate.invoke (spec.bundle.js:68195:26)
        at ProxyZoneSpec.onInvoke (spec.bundle.js:70780:39)
        at ZoneDelegate.invoke (spec.bundle.js:68194:32)
        at Zone.run (spec.bundle.js:67945:43)
        at UserContext.<anonymous> (spec.bundle.js:70986:34)
        at ZoneQueueRunner.jasmine.QueueRunner.ZoneQueueRunner.execute (spec.bundle.js:71016:42)
        at ZoneQueueRunner.jasmine.QueueRunner.ZoneQueueRunner.execute (spec.bundle.js:71016:42)
        at spec.bundle.js:71013:130
        at ZoneDelegate.invokeTask (spec.bundle.js:68228:31)
        at Zone.runTask (spec.bundle.js:67995:47)
        at drainMicroTaskQueue (spec.bundle.js:68399:35)
        at <anonymous>

The component:
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnChanges,
OnInit,
Output,
Renderer2,
SimpleChanges,
TemplateRef,
ViewChild
} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, NgControl}    from '@angular/forms';
import {Subject} from 'rxjs';
import {AbstractInput} from '../shared/abstract-input';
import {isNullOrUndefined, isString} from 'util';
import {IAutocompleteService} from './autocomplete-service';
import {TypeaheadMatch} from 'ngx-bootstrap';
import {HttpClient} from '@angular/common/http';

export const WH_AUTOCOMPLETE_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => AutocompleteComponent),
    multi: true
};

@Component({
    selector: 'cs-autocomplete',
    templateUrl: './autocomplete.component.html',
    styleUrls: ['./autocomplete.component.scss'],
    providers: [WH_AUTOCOMPLETE_VALUE_ACCESSOR],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AutocompleteComponent extends AbstractInput implements     AfterViewInit, ControlValueAccessor, OnChanges, OnInit {

values: Array<any> = [];
valueFilter: Observable<any>;
haveFocus: boolean;

@Input() width: string = this.DEFAULT_WIDTH;
@Input() editable: boolean = this.DEFAULT_EDITABLE;
@Input() numberOfValues: number = 1;
@Input() removeTag: boolean = false;
@Input() backendUrl: string;
@Input() dataSource: Array<any> = [];
filteredDataSource: Subject<any> = new Subject<any>();
@Input() typeaheadOptionField: string;
@Input() typeaheadOptionsLimit: number;
@Input() typeaheadMinLength: number = 2;
@Input() typeaheadWaitMs: number = 0;
@Input() typeaheadAsync: boolean = false;
@Input() typeaheadLatinize: boolean = true;
@Input() typeaheadSingleWords: boolean = true;
@Input() typeaheadWordDelimitaers: string = ' ';
@Input() typeaheadPhraseDelimiters: string = '\'"';
@Input() typeaheadItemTemplate: TemplateRef<any>;
@Input() nbResult: number = 10;
@Input() searchProperty: string;
@Input() service: IAutocompleteService<any>;
@Input() formControl: FormControl;
@Input() submitted: boolean;
@Input() autoSelectSingleResult: boolean = false;
@Input() params: any;
currentItemTemplate: TemplateRef<any>;
@Input() maxLength: string = 'number';

@Output() typeaheadLoading: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output() typeaheadNoResults: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output() selectionChanged: EventEmitter<any> = new EventEmitter<any>();

@ViewChild('input') input: ElementRef;
@ViewChild('button') button: ElementRef;
@ViewChild(NgControl) ngControl: NgControl;
@ViewChild('defaultItemTemplate') defaultItemTemplate: TemplateRef<any>;

current: any = '';
shouldRemovedTag: boolean = true;

constructor(private http: HttpClient, cdr: ChangeDetectorRef, private renderer: Renderer2) {
    super(cdr);
}

ngOnInit(): void {
    this.currentItemTemplate = this.defaultItemTemplate;
    if (this.typeaheadItemTemplate) {
        this.currentItemTemplate = this.typeaheadItemTemplate;
    }
}

ngOnChanges(changes: SimpleChanges): void {
    super.ngOnChanges(changes);

    if (changes.typeaheadItem) {
        this.currentItemTemplate = this.typeaheadItemTemplate;
    }

    if (changes.dataSource) {
        //console.log('dataSource', this.dataSource);
    }
}

ngAfterViewInit() {
    this.valueFilter = this.ngControl.valueChanges.filter(value => {
        return value.length >= this.typeaheadMinLength;
    });

    if (!this.backendUrl && !this.service) {
        this.valueFilter.subscribe(value => {
            let filteredData = this.dataSource.filter(state => {
                let s: string = state[this.typeaheadOptionField].toLowerCase();
                return !value || s.startsWith(value.toLowerCase());
            });
            this.filteredDataSource.next(filteredData);
            if (this.autoSelectSingleResult && filteredData.length === 1) {
                this.internalSelect(filteredData[0], true);
            }
        });
    } else {
        this.valueFilter
            .debounceTime(500)
            .filter((filter) => {
                return filter !== '' && this.numberOfValues > this.values.length;
            })
            .switchMap(filter => this.callService(filter))
            .subscribe((data: any[]) => {
                this.filteredDataSource.next(data);
                if (this.autoSelectSingleResult && data.length === 1) {
                    this.internalSelect(data[0], true);
                }
            });
    }
}

keyUp(event: KeyboardEvent) {
    if (event.keyCode === 8 && this.current.length === 0 && this.values.length > 0) { // BACK Key
        if (this.shouldRemovedTag) {
            if (this.removeTag) {
                this.values.pop()[this.typeaheadOptionField];
            } else {
                this.values.pop();
                this.current = '';
            }
            this.updateModel();
        }
        this.shouldRemovedTag = !this.shouldRemovedTag;
    } else if (event.keyCode === 32) { // SPACE Key
        this.current = this.current.replace(/ +/g, ' ');
    }
}

keyDown(event: KeyboardEvent) {
    return this.values.length !== this.numberOfValues || event.keyCode === 9;
}

blur() {
    this.current = '';
}

typeaheadOnSelectHandler(selected: TypeaheadMatch): void {
    const selectedItem = (selected && selected.item) ? selected.item : '';
    this.internalSelect(selectedItem, true);
}

typeaheadLoadingHandler($event: any): void {
    this.typeaheadLoading.emit($event);
}

typeaheadNoResultsHandler($event: any): void {
    this.typeaheadNoResults.emit($event);
}

removeTagHandler(tag: any): void {
    let index = this.values.indexOf(tag);
    this.values.splice(index, 1);
    this.shouldRemovedTag = false;
    this.updateModel();
    this.selectionChanged.emit(null);
}

writeValue(values: any): void {
    if (!isNullOrUndefined(values) && Array.isArray(values)) { // cas array non vide
        this.values = values;
    } else if (!isNullOrUndefined(values) && !Array.isArray(values) && !isString(values)) { // cas object non vide
        this.values = [values];
    } else if (!isNullOrUndefined(values) && !Array.isArray(values) && isString(values)) {
        this.current = values;
    } else if (isNullOrUndefined(values)) {
        this.values = [];
    }

    this.cdr.markForCheck();
}

setDisabledState(isDisabled: boolean): void {
    this.renderer.setProperty(this.input.nativeElement, 'disabled', isDisabled);
    if (this.button) {
        this.renderer.setProperty(this.button.nativeElement, 'disabled', isDisabled);
    }

    this.cdr.markForCheck();
}

onFocus() {
    this.haveFocus = true;
}

onFocusOut() {
    this.haveFocus = false;
}

public focus(): void {
    if (!isNullOrUndefined(this.input)) {
        this.input.nativeElement.focus();
    }
}

private updateModel() {
    if (this.numberOfValues > 1) {
        this.onChangeCallback(this.values && this.values.length > 0 ? this.values : null);
    } else {
        this.onChangeCallback(this.values && this.values.length > 0 ? this.values[0] : null);
    }
}

private callService(filter: string): Observable<any> {
    if (this.backendUrl) {
        return this.http.get(`${this.backendUrl}?q=${filter}`);
    }

    if (this.service) {
        const map = new Map();
        for (const p in this.params) {
            map.set(p, this.params[p]);
        }
        return this.service.findAutocomplete(filter, this.searchProperty ? this.searchProperty : this.typeaheadOptionField, this.nbResult, map);
    }
}

private internalSelect(selectedItem: any, emitEvents?: boolean): void {
    if (this.values.indexOf(selectedItem) < 0) {
        this.values.push(selectedItem);
    }
    this.current = '';
    this.input.nativeElement.focus();
    if (emitEvents) {
        this.updateModel();
        this.selectionChanged.emit(selectedItem);
    }
}

}
and the test:
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ChangeDetectorRef, Renderer2 } from '@angular/core';
import { AutocompleteComponent } from './autocomplete.component';
describe('Component: Autocomplete', () => {
let component: AutocompleteComponent;
let fixture: ComponentFixture<AutocompleteComponent>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    declarations: [AutocompleteComponent]
  })
  .overrideTemplate(AutocompleteComponent, '')
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(AutocompleteComponent);
  fixture.detectChanges();
  component = fixture.componentInstance;
});

 fit('should create an instance', () => {
 expect(component).toBeTruthy();
 });

});

Any suggestion?


text:
Q: how to name dataset/variable using concatenation I have a problem with SAS 9.2.
I'm writing a simple macro which creates dataset and name it according to the variables submitted and some other words/letters/signs, for example
%macro example(var1,var2);

data &var1 || '_word_' || &var2;
    a=1;
run;

%mend;

Can anyone help?

A: *

*Pipes are only for strings within SAS, not within SAS macro. So don't use them here.

*SAS Macro does not interpret quotes as indicating a string, it will just read them, so leave out the quotes.

*If you want to concatenate elements in macro, you just need to write them appended to each other.

*To make clear where the macro variable name ends, append a dot.

This should work:
%macro example(var1,var2);
    data &var1._word_&var2.;
        a=1;
    run;
%mend;


text:
Q: Do I need a resistor or no? I'm working with 6 LEDs in series, which are rated at:

*

*3V Typical / 3.2V Maximum

*20mA.

My power supply is:

*

*19V

*3A Maximum

According to my calculations:

*

*I'd need a 50 ohm resistor at 3V

*I'd be in the negative at 3.2V.

Because my target resistance with the LEDs alone would be below the maximum LED voltage specification, do I need any sort of resistor at all?
Is this the appropriate use case for a 0 ohm resistor?
I plugged in the array last night for around 20 seconds or so, and the wiring seemed to get rather hot which is a bit worrisome... The LEDs however, didn't appear to be brighter than when connecting one at the appropriate resistance.

A: LEDs are diodes, so over the normal operating range the voltage is relatively stable for wide ranges in current.  However, this also means that if you were to drive a LED with voltage, small changes in that voltage will cause large changes in the current.  The characteristics are not definite enough to make this current predictable.  LEDs therefore need to be driven with a controlled current, not with a low impedance supply.
Your basic flaw is that you are trying to drive too many LEDs in series for the voltage you have.  Get a higher voltage supply, lower voltage LEDs, or put fewer of them in each series string.  With 5 LEDs in a series string, the nominal drop will be 15 V.  That leaves 4 V for a resistor to drop, which is good since that will reduce current variations as the LED voltages vary.  4 V / 20 mA = 200 Ω, which is the size resistor you should use with 5 LEDs in series driven from a 19 V supply.

A: If you want your LED works at 20mA of course you have to put a resistor.
But I would like you to provide the right voltage of the diode at 20mA because the voltage of te diode is different at diferent current rate.
see the image...

As you can see in the image the led voltage at 20mA is 2.2 volts...
for the right resistor you can use the next formula that I calculate for you.
R=-(6*Vd-Vs)/Id
where R is the resistor you have to use,
    Vd is the diode voltage at desired current rate (20mA)
    Vs is the source voltage
    and Id is the current operation (20mA)
The number 6 in the formula is because you are using 6 series leds...
If you do not know the voltage in the led at 20mA... you can use a potentiometer in series with one led, measure the current and the voltage in the diode, when you measure 20mA in the multimeter, then the voltage in the diode is the voltage at 20mA and you can use this value for the formula that I provide


text:
Q: MVC Kendo grid date validations giving error?
The field DateTime must be a date.

I am using Kendo grid in MVC project. I have both French and English version of the same application. The following is what I do in the _Layout.cshtml file:
<script>
    if ("@Session["Culture"]" === "en-CA") {
        kendo.culture("en-US");
        Globalize.culture('en-CA');
    } else {
        kendo.culture("fr-CA");
        Globalize.culture('fr-CA');
    }

    $.validator.methods.number = function (value, element) {
        return this.optional(element) || !isNaN(Globalize.parseFloat(value));
    }

    $.validator.methods.date = function (value, element) {
        if (this.optional(element))
            return true;

        var result = Globalize.parseDate(value, "@LCL.Common_Formats.DatePickerFormat", "@Session["Culture"]");

        return !isNaN(result) && (result != null);
    }

    $.validator.methods.min = function (value, element, param) {
        return this.optional(element) || Globalize.parseFloat(value) >= param;
    }

    $.validator.methods.max = function (value, element, param) {
        return this.optional(element) || Globalize.parseFloat(value) <= param;
    }

    $.validator.methods.range = function (value, element, param) {
        if (this.optional(element))
            return true;
        var result = Globalize.parseFloat(value);
        return (result >= param[0] && result <= param[1]);
    }
</script>

In the grid I have a datepicker as below:
 c.Bound(u => u.DateTime)
                    .Title(LCL.Common_Labels.PurchaseDate)
                    .Format("{0:" + LCL.Common_Formats.DatePickerFormat + "}")
                    .Width(smlColumn);

LCL.Common_Formats.DatePickerFormat is an entry in the Resources file for storing the datepicker formats. I have both English and French Resource files. My problem is that I am getting this weird exception:
The field DateTime must be a date
when editing the record in the French version.

But it works very well in the English version...

A: Those date formats ...
I had similar problem with formats. I can suggest you:
Get an instance of kendo validator with a configuration:
var kendoValudator = $('#yourFormId').kendoValidator({
    rules: {
        mvcdate: function (e) {
            if (e.is('[data-role="datepicker"]')) {
                var result = kendo.parseDate($(e).val(), 'dd/MM/yyyy');
                return !!result;
            }

            return true;
     }
}).data('kendoValidator');

Also if you are using jQuery on the page try adding:
jQuery.extend(jQuery.validator.methods, {
    date: function (value, element) {
        if ($(element).is('[data-role="datepicker"]')) {
            var res = this.optional(element) || kendo.parseDate(value, "dd/MM/yyyy") != null;
            return !!res;
        }

        return true;
    }
});

Then if your server receive a the default date (01/01/0001) you should change the server culture.
Example:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

I hope it helps.

A: I found the best solution for this:
var culture = kendo.culture();
if (culture.name === "fr-CA")
{
    culture.calendar.patterns.F = "dd/MM/yyyy";
}
else
{
    culture.calendar.patterns.F = "MM/dd/yyyy";
}

This has to be added at the document.ready() section.
I spend 3 days to find the solution for this...


text:
Q: XML Parser no connection error My XML parser works great when I have connection, if it is lost my activity will crash I am wanting to have a alert dialog popup saying that connection is lost instead of the activity crash but I do not know how to do this.
Any insight would help
    public class XMLParser {

    // constructor
    public XMLParser() {

    }

    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }
}

A: The above method may not work always. This one is foolproof
private boolean isOnline() {
        try {
            myurl = new URL("http://m.google.com");
        } catch (MalformedURLException e2) {
            e2.printStackTrace();
        }
        try {
            connection = myurl.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.setConnectTimeout(3000);
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        int responseCode = -1;
        try {
            responseCode = httpConnection.getResponseCode();
        } catch (Exception e1) {
                e1.printStackTrace();
        }
        if (!(responseCode == HttpURLConnection.HTTP_OK))
        {
            return false;
        }
        return true;


text:
Q: There is no module with the namespace "math" Angular 6 At first, I was getting some warnings like:
DEPRECATION WARNING: Using / for division is deprecated and will be removed in Dart Sass 2.0.0.

Recommendation: math.div($scrollview-pager-item-spacing, 4)

More info and automated migrator: https://sass-lang.com/d/slash-div

    ╷
144 │             bottom: ($scrollview-pager-offset - ($scrollview-pager-item-spacing / 4));
    │                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ╵
    node_modules\@progress\kendo-theme-default\scss\scrollview\_layout.scss 144:50      @content
    node_modules\@progress\kendo-theme-default\scss\mixins\core\_import-once.scss 12:9  exports()
    node_modules\@progress\kendo-theme-default\scss\scrollview\_layout.scss 4:1         @import
    node_modules\@progress\kendo-theme-default\scss\scrollview.scss 11:9                @import
    node_modules\@progress\kendo-theme-default\scss\all.scss 16:9                       @import
    stdin 3:9                                                                           root stylesheet

Recommendation: math.div($num, ch-pow($x, $n - 1))

More info and automated migrator: https://sass-lang.com/d/slash-div

   ╷
51 │         $x: math.div(1, $n) * (($n - 1) * $x + ($num / ch-pow($x, $n - 1)));
   │                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
    node_modules\@progress\kendo-theme-default\scss\mixins\vendor\color-helpers\_math.scss 51:49      ch-nth-root()
    node_modules\@progress\kendo-theme-default\scss\mixins\vendor\color-helpers\_math.scss 29:17      ch-pow()
    node_modules\@progress\kendo-theme-default\scss\mixins\vendor\color-helpers\_contrast.scss 16:56  ch-color-luminance()
    node_modules\@progress\kendo-theme-default\scss\mixins\_colors.scss 91:12                         contrast-wcag()
    node_modules\@progress\kendo-theme-default\scss\_variables.scss 210:19                            @import
    node_modules\@progress\kendo-theme-default\scss\all.scss 1:9                                      @import
    stdin 3:9                                                                                root stylesheet

then I opened files and fixed as recommended. Also, as suggested in : SassError: There is no module with the namespace "math", I installed:
npm install -g sass-migrator
npm i sass-migrator

But now I'm getting these Errors:
ERROR in ./src/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

undefined
                                               ^
      There is no module with the namespace "math".
    ╷
140 │             bottom: ($scrollview-pager-offset - math.div($scrollview-pager-item-spacing, 4));
    │                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ╵
  node_modules\@progress\kendo-theme-default\scss\scrollview\_layout.scss 140:49      @content
  node_modules\@progress\kendo-theme-default\scss\mixins\core\_import-once.scss 12:9  exports()
  node_modules\@progress\kendo-theme-default\scss\scrollview\_layout.scss 4:1         @import
  node_modules\@progress\kendo-theme-default\scss\scrollview.scss 11:9                @import
  node_modules\@progress\kendo-theme-default\scss\all.scss 16:9                       @import
  stdin 3:9                                                                           root stylesheet
      in C:\project path..\..\node_modules\@progress\kendo-theme-default\scss\scrollview\_layout.scss (line 140, column 49)

in package.json I have:
  "node-sass": "^4.9.4",
  "sass": "^1.41.0",

Please suggest how to fix error

A: You don't need to install node-sass or sass there are angular dependencies and you should use:
@use 'sass:math';

at top of your file to clear the warning.

A: You do not need to install any library. However, @use 'sass:math' did not work for me. I had to change it to @use 'sass:math' as math;.


text:
Q: Making a script output CSV friendly I've made a little script to extract the MD5Sum Hashes for each file in a users downloads directory.
I want to make the output CSV friendly by placing a , in between each MD5 hash, and the name of the file.
Current Output:
d35e918d05c615b430e055d06ad09e8f  JavaSetup_1376232357.exe
d35e918d05c615b430e055d06ad09e8f  JavaSetup_1848597537.exe
feca515ae90edd11e0dad95f0c123acc  javaSetup.exe

Desired Output:
d35e918d05c615b430e055d06ad09e8f,JavaSetup_1376232357.exe
d35e918d05c615b430e055d06ad09e8f,JavaSetup_1848597537.exe
feca515ae90edd11e0dad95f0c123acc,javaSetup.exe

Current script:
#!/usr/bin/env bash
cd /home/$USER/Downloads/
for file in *; do
    md5sum "$file"
done

A: You can use sed to substitute the two spaces for a comma:
   ...
done | sed 's/  /,/'


text:
Q: phpmyadmin 3.4.x drop/empty table tabs removed I've just updated to phpmyadmin 3.4.6 and I just realized that the drop/empty tabs are being removed and put under the operations tab.
Is there an option to enable those tabs again?
Thanks

A: Look at
http://mac.softpedia.com/progChangelog/phpMyAdmin-Changelog-3359.html

*

*Move drop/empty links from being tabs to Operations tab.

Its a change that done from phpMyAdmin 3.4.0
If you wanna do what you want you have to use older versions :-(


text:
Q: find git commits with no author Through use of an import tool I have ended up with some git commits that have no author. For example here is a git log output showing an authorless commit and a normal commit
commit 40c2638378b33ac98a8d9570552ecd01e38174be
Merge: c2c068f 8f0c30c

    Merge libde265 (1.0.2-2) import into refs/heads/workingbranch

commit c2c068f30652fd3e63b55c509ae50828c98daa22
Author: Debian Multimedia Maintainers <pkg-multimedia-maintainers@lists.alioth.debian.org>
Date:   Mon Jan 11 18:12:19 2016 +0000

     ffmpeg_2.9

     Gbp-Pq: Name ffmpeg_2.9.patch

github will not accept these commits. So I need to fix them up, to do that I need to find them.
How can I find such commits so that I can fix them?

A: You may utilize --pretty format to output full commits line-by-line.
git log --pretty=format:"%h%x09%an%x09%ad%x09%s"

Then from the output can check what commits have corresponding empty author (ie second column).

A: Well I found a soloution but it's a bit hacky.
git log > log1
git log --author "" > log2
diff -u log1 log2

For posterity the complete find and fix script (thanks to https://stackoverflow.com/a/28845565/5083516 for some hints on the fixup side)
 #!/bin/bash -ev
 rm -f loggood
 rm -f logall
 for TAG in $(git tag) ; do
     git log --pretty=format:"%H" --author="" $TAG >> loggood
     #git log doesn't seem to add a final newline, add one ourselves
     echo >> loggood
     git log --pretty=format:"%H" $TAG >> logall
     echo >> logall
 done

 LC_ALL=C cat loggood | sort | uniq | sponge loggood
 LC_ALL=C cat logall | sort | uniq | sponge logall
 LC_ALL=C comm -13 loggood logall > logbad

 for COMMIT in $(cat logbad) ; do
     git checkout $COMMIT
     git commit --amend --reset-author --no-edit
     git replace $COMMIT $(git log --pretty=format:"%H" -n 1)
 done

 git filter-branch -f -- --all

 for COMMIT in $(cat logbad) ; do
     git replace -d $COMMIT
 done


text:
Q: How to store a UserControl in PhoneApplicationService.Current.State without throw InvalidDataContractException [Windows Phone 8] I was storing a UserControl as state, to retrieve in a PhoneApplicationPage (this PhoneApplicationPage can show different UserControls):
PhoneApplicationService.Current.State["screen"] = new UserControlScreen();

It was working fine, until I pressed "home button" and threw this exception:
System.Runtime.Serialization.InvalidDataContractException: Type System.Windows.UIElement' cannot be serialized.

I read some articles and realized that UserControl can't be stored in a PhoneApplicationService as Current State.
Is there a way to implement a serialization to this User Control?
To workaround this problem, I tried passing a string containing the User Control's class name, but I don't know how add a User Control from it's class name either.
Does anyone know how to deal with this problem?

A: PhoneApplicationService.Current.State is not intended for storing large amount or data or entire controls. Just store the data the control needs and then use it to bring the control to the desired state.


text:
Q: I can't get setInterval to work for me I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>

    <meta charset="UTF-8"
    <title></title>
    <link rel="stylesheet" href="ColorPerceptionTest.css">

        <form>
            <input type="button" id="Button1" value="" onClick="">
            <input type="button" id="Button2" value="" onClick="">
            <input type="button" id="Button3" value="" onClick="">

            <input type="button" id="Start" value="Start" onClick="start()">
            <input type="button" id="Help" value="Help" onClick="help()">

        </form>

A: Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
    $("help").innerHTML = "";
    getRandomImage(imagesArray);
    $("Start").style.display = "none";
    $("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);

Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.


text:
Q: Proving Results from the Fisher Scoring Algorithm I was reading the following link (https://en.wikipedia.org/wiki/Scoring_algorithm) on the "Fisher Scoring Algorithm". As I understand, the Fisher Scoring Algorithm is similar to the Newton-Raphson Algorithm, but is used more to optimize Likelihood Functions of Statistical and Probabilistic Models.
Here is my understanding of this algorithm:

*

*Suppose we have observations: $$y_1, y_2, \dots$$

*And suppose these observations have a probability distribution function: $$f(y;\theta)$$

*If we consider the "Score Function" as the first derivative of the log-likelihood function, we can take the First Order Taylor Expansion of the Score Function and write it as follows: $$V(\theta) \approx V(\theta_0) - J(\theta_0)(\theta - \theta_0)$$

*Note that J(thetha) is the negative Hessian of the log-likelihood function : $$J(\theta_0) \approx -\sum_{i=1}^n \left(\triangledown_{\theta}^2 \log \left(f(y_i, \theta)\right)\right)$$

*We can then write the Fisher Scoring Algorithm as: $$\theta_{m+1} = \theta_m + J^{-1}(\theta_m)V(\theta_m)$$
In this article, the following two proofs are claimed about the Fisher Scoring Algorithm:

*

*Proof 1: As the number of iterations (i.e. "m") increases, the estimates from the Fisher Scoring Algorithm converges to the estimates that would have been obtained from Maximum Likelihood Estimation. As I understand, this is important for the following reason: Suppose you have some complicated Likelihood Function and have difficulty solving the resulting system of equations (e.g. multidimensional, non-linear, etc.) - then, the results of this proof would permit you to indirectly obtain estimates "close" to the estimates that you would have obtained via Maximum Likelihood Estimation (Note: Estimates obtained via MLE are "desirable" as these estimates have useful properties such as Unbiasedness, Consistency, Asymptotic Normality, etc.). In mathematical notation, this proof can be written like this:

$$\lim_{m\rightarrow\infty} \theta_m = \hat{\theta}_{MLE}$$

*

*Proof 2: To reduce the computational complexity of the Fisher Scoring Algorithm, we often replace J(thetha) with the "Expected Value" of J(thetha) -  we call this I(thetha):

$$\theta_{m+1} = \theta_m + I^{-1}(\theta_m)V(\theta_m)$$
Given this information - the estimates produced from the Fisher Scoring Algorithm (after many iterations) are expected to have same asymptotic distribution properties as the true estimates under Maximum Likelihood Estimation. As I understand, this result is important because it allows for statistical inferences made using the results of the Fisher Scoring Algorithm to have similar properties as statistical inferences made using estimates from MLE. In mathematical notation, this proof can be written like this:
$$\sqrt{n}(\theta_{m+1} - \theta_{MLE}) \stackrel{d}{\rightarrow} N(0, I^{-1}(\theta_{MLE}))$$
My Question: I am trying to understand why the ideas captured within Proof 1 and Proof 2 are true.
When looking online, I found different references on these topics - but none of these references explicitly explained why these two proofs are true. Can someone please help me understand why these two proofs are true?
Thanks!


text:
Q: how to predict related videos to a video in weka I'm trying to predict related videos to a video,
is that possible in weka?
the database takes the following structrue:
    video_id,catygory,keywords,related_videos_ids

a single keywords field might have many values (for ex: stackoverflow, predict, videos),so the related_videos (the video could have more than one related video).
The related videos depend on catygory an keywords
what's the way to do that in weka?? any ideas?

A: There is a way to do it in weka. You should look into clustering:
https://www.youtube.com/watch?v=zjYUYJ2b4r8
I would also suggest trying to get more features (more columns) for better results.


text:
Q: Why wouldn't this label show up despite its Visible parameter being set to True and its Text parameter containing a string?
As can be seen in the image above, I have four labels that are on top of some PictureBoxes. Note that I added the blue text and arrow in the image in Paint; they are not elements of the form.
By default, these labels have their Visible parameters set to False and their Text parameters are set to being empty. At specific points in the program, one of the labels is selected to both have Visible set to True and to have a 3-digit-or-less number alongside a percent sign(in the format ### % in which # is a digit) in black size 12.75 Microsoft Sans Serif font.
However, only the top label(the one being pointed at by the blue arrow) actually becomes visible and displays its text when its parameters are changed in this way. The top image below shows what the top label looks like when this happens, while the bottom image below shows what the other three labels look like when the same process is applied to any of them.

Ignoring the difference in aspect ratio between the two images, the only important difference between the two is that in the first one, the label is visible and is displaying "75 %", while in the second one, the label is not visible so there is no number or percent sign.
I know for a fact that in the second instance the label's Visible property is set to True and its text is set to "75 %" through debugging, but none of this shows up when the form is running. Another thing that I have determined through debugging is that this issue is either caused by or at least apparent in the function below, since this function is the only code block that:
a) is used in every instance in which the labels are set to having Visible be True and their text being set to that "### %" format, and also
b) distinguishes between the different labels.
private void UpdateHpText(PictureBox HPBox) //the function in question
        {
            //this conditional tree takes "HPBox," one of the Pictureboxes that the labels overlap(the green bars), and uses it to decide which label needs to be altered
            if(HPBox == side2HPbox1)
            {
                //Side2HPText1 is the top label, Side2HPText2 is the next from the top label, and etc.
                Side2HPText1.Visible = HPBox.Visible; //I know from debugging that HpBox.Visible should be set to True in the instance I am having trouble with
                side2HPbox1DisplayNum = (BasicProcess.side2[0].HP.value * 100) / (BasicProcess.side2[0].HP.max); //calculates the number displayed in the Label's text
                Side2HPText1.Text = side2HPbox1DisplayNum + " %"; //sets the label's text
                //in the above instance, the label should have Visible set to True, and its Text should be assigned to a string. However, I'm not having issues with this block.
            }
            //so tell me, is there ANY difference between the above block and the below block other than:(see differences in documentation of each line)
            else if (HPBox == side2HPbox2)
            {
                Side2HPText2.Visible = HPBox.Visible; //a different label is targeted here
                side2HPbox2DisplayNum = (BasicProcess.side2[1].HP.value * 100) / (BasicProcess.side2[1].HP.max); //BasicProcess.side2[1] is being used instead here because it targets the object that is assigned to the label in this block, and side2HPBoxDisplayNum is just used in the final line of this block for the displayed string
                Side2HPText2.Text = side2HPbox2DisplayNum + " %";
            //from what I see, both blocks are functionally the same, and I also know that to be the case from debugging, but when the form runs, I get a completely different result for each block.
            }
            else if (HPBox == side2HPbox3)
            {
                Side2HPText3.Visible = HPBox.Visible;
                side2HPbox3DisplayNum = (BasicProcess.side2[2].HP.value * 100) / BasicProcess.side2[2].HP.max;
                Side2HPText3.Text = side2HPbox3DisplayNum + " %";
            }
            else
            {
                Side2HPText4.Visible = HPBox.Visible;
                side2HPbox4DisplayNum = (BasicProcess.side2[3].HP.value * 100) / BasicProcess.side2[3].HP.max;
                Side2HPText4.Text = side2HPbox4DisplayNum + " %";
            }
        }

As you can read in the code above, there shouldn't be any difference between what the top label looks like when its block runs and what the second label looks like when its block runs, but there is. This makes me think that I might be having a GUI error that I'm not noticing in my code. One thing I've learned about GUI in Winforms is that that threading can have an impact on how the GUI updates itself. For that reason, I will post the relevant code in my program below that uses Async and Await, which might have an impact on threading.
                                    Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Visible = true; //sets one of the green bar PictureBox's Visible parameter to True
                                    await Task.Delay(500); //waits half a second
                                    targetList[0] = char1ChosenSkill.effect(targetList[0]); //this can be ignored since it does not effect the PictureBox or Label
                                    Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Image = UpdateHpBar(targetList[0], BasicProcess.side2); //runs UpdateHPBar
                                    UpdateHpText(Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])]);
                                    await Task.Delay(1500); //waits 1.5 seconds
                                    Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Visible = false; //sets one of the green bar PictureBox's Visible back to false
                                    Menu2Background.Visible = (char2 != null); //this can be ignored since it does not effect the PictureBox or Label

However, I don't think that Task.Delay could genuinely scuff up the GUI that much, especially considering that it runs for each and every label the same way.
Another potential reason for my program not running correctly is the properties of the labels. For that reason, I will post them below. Please don't forget that even though the Text and Visible elements are set to being empty and False respectively here, they should be set to containing a string and being True at the point in the program that I am having trouble with.
            //
            // Side2HPText1
            //
            this.Side2HPText1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.Side2HPText1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(2)))), ((int)(((byte)(218)))), ((int)(((byte)(55)))));
            this.Side2HPText1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Side2HPText1.Location = new System.Drawing.Point(1109, 127);
            this.Side2HPText1.Name = "Side2HPText1";
            this.Side2HPText1.Size = new System.Drawing.Size(58, 26);
            this.Side2HPText1.TabIndex = 66;
            this.Side2HPText1.Visible = false;

            //
            // Side2HPText2
            //
            this.Side2HPText2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.Side2HPText2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(2)))), ((int)(((byte)(218)))), ((int)(((byte)(55)))));
            this.Side2HPText2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Side2HPText2.Location = new System.Drawing.Point(1109, 279);
            this.Side2HPText2.Name = "Side2HPText2";
            this.Side2HPText2.Size = new System.Drawing.Size(58, 26);
            this.Side2HPText2.TabIndex = 70;
            this.Side2HPText2.Visible = false;

I haven't noticed any differences here that could be relevant to my issue, but maybe someone will.
Anyhow, if I haven't provided enough relevant information here, feel free to ask me to provide more.
EDIT:
I'm not entirely sure how to provide a reproducible example without sharing absolutely all of my code. I will start documenting a big chunk of it and tack it to the bottom of this post by the end of today, but it will take time. Hopefully doing that will help
EDIT 2:
Actually, I can provide some more info before I do that. Firstly, when I said that I determined that the Visible parameter was set to True and the Text was set to a string by debugging, I meant that I set up a breakpoint and looked in the Autos field in Debug mode to determine that this was the case.
I also have brought the Labels to the front several times now(thinking that maybe I did it wrong before or something), so I am confident that they are brought to the front. I also put a line of code in UpdateHPText saying:
Side2HPText2.Parent = Side2HPText2.Parent;

so I could see that value in the Autos field. It turns out that this value was set to the form it's on(BattleTemplate4), so I think that that is fine.
EDIT 3:
Here's a pastebin link to the InitializeComponent function since it won't fit the character limit: https://pastebin.com/WRRJ5n4d (a commenter asked for it)
EDIT 4:
Okay, I think I've determined that it's a painting issue. I'm going to switch over to having the text either drawn on since I don't think it's worth the trouble to resolve an issue that can be mollified by trying something else that's equally functional.
EDIT 5:
NEVERMIND! I didn't expand to the two comments that weren't visible, and used the .BringToFront() function on the text in UpdateHPText, and it worked. Thanks @Idle_Mind for resolving my issue.

A:
I also have brought the Labels to the front several times now(thinking
that maybe I did it wrong before or something), so I am confident that
they are brought to the front.

But have you tried doing that in the CODE itself after setting the .Text property?
...
Side2HPText2.Text = side2HPbox2DisplayNum + " %";
Side2HPText2.BringToFront();

@Idle_Mind that worked, thank you.

A: WinForms controls cannot overlap. There is a special-case for "transparent" control backgrounds, but that's just an trick (a "transparent" background control requests its parent form repaint its background first, then the control paints itself).
This is because WinForms controls are their own hWnd surfaces, and WinForms does not support transparent control backgrounds or alpha-blending.


text:
Q: Spectral Measures: Multi Version (II) This question is only Q&A!
Problem
Given a Hilbert space $\mathcal{H}$.
Consider a normal operator:
$$N:\mathcal{D}(N)\to\mathcal{H}:\quad N^*N=NN^*$$
And its spectral measure:
$$E:\mathcal{B}(\mathbb{C})\to\mathcal{B}(\mathcal{H}):\quad N=\int\lambda\mathrm{d}E(\lambda)$$
Suppose one has:
$$\varphi_0\in\mathcal{H}:\quad\mathcal{H}=\overline{\langle\{E(A)\varphi_0:A\in\mathcal{B}(\mathbb{C})\}\rangle}$$
Denote for shorthand:
$$\nu_0:=\nu_{\varphi_0}(A)=\|E(A)\varphi_0\|^2$$

Then one has:
  $$M_\mathrm{id}:\mathcal{D}(M_\mathrm{id})\to\mathcal{L}^2(\nu_0):\quad VM_\mathrm{id}=NV$$

How can I prove this?
Reference
This is a prep-up for: Multi Version (III)

A: Unitary Map
Construct the map:
$$V:\mathcal{L}^2(\nu_0)\to\mathcal{H}:\quad Vh:=h(N)\varphi_0$$
By Borel calculus:
$$h\in\mathcal{L}^2(\nu_0):\quad\|h(N)\varphi_0\|^2=\int|h|^2\mathrm{d}\nu_0$$
Especially one has:
$$V\chi_A=E(A)\varphi_0:\quad\mathcal{H}=\overline{\{V\chi_A:A\in\mathcal{B}(\mathbb{C})\}}$$
Concluding unitarity.
Multiplication
Remind that it holds:
$$f(N)g(N)\subseteq(fg)(N)$$
Observe also that:
$$h\in\mathcal{L}^2(\nu_0)\iff\varphi_0\in\mathcal{D}h(N)$$
Then one checks:
$$NVh=Nh(N)\varphi_0=(\mathrm{id}h)(N)\varphi_0=V(\mathrm{id}h)=VM_\mathrm{id}h$$
Concluding equivalence.


text:
Q: Programmatic update of InfoPath form XML is stripping off tags I have a C# program that is looping through all of the forms (browser enabled) in my forms library and injecting an XML node into each of them (for a newly promoted field).  For some reason, when the XML is saved back to the form, the first few tags are being stripped off.  Specifically, these tags are:
<?xml version="1.0"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:Contractor-DB-Form:-myXSD-2009-09-10T18-19-55" solutionVersion="1.0.1.1100" productVersion="12.0.0.0" PIVersion="1.0.0.0" href="http://echouat.rbs.us/npe/FormServerTemplates/Contractor_DB_Form.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<?mso-infoPath-file-attachment-present?>"

My code to update the XML is as follows:
    private static SPListItem InsertXmlNode(SPListItem infoPathForm, string nodeToUpdateStr, string nodeToInsertStr,
        string nodeInnerXmlStr, string firstNode)
    {
        //load form into xml document
        byte[] fileBytes = infoPathForm.File.OpenBinary();
        MemoryStream itemStream = new MemoryStream(fileBytes);
        //Stream itemStream = infoPathForm.File.OpenBinary();
        XmlDocument xmlDoc = new XmlDocument();
        XmlNamespaceManager xmlNameSpaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);
        xmlNameSpaceMgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");

        xmlDoc.Load(itemStream);
        itemStream.Close();

        //inject xml
        XmlNode nodeToUpdate = xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr, xmlNameSpaceMgr);

        //only insert if doesn't already exist
        if (xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr + "/" + nodeToInsertStr, xmlNameSpaceMgr) == null)
        {
            updateCounter++;

            XmlNode nodeToInsert = xmlDoc.CreateNode(XmlNodeType.Element, nodeToInsertStr, "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");
            nodeToInsert.InnerText = nodeInnerXmlStr;
            nodeToUpdate.AppendChild(nodeToInsert);

            //get binary data for updated xml
            byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);
            MemoryStream newMemStream = new MemoryStream(newXmlData);

            //write updated binary data to the form
            infoPathForm.File.SaveBinary(newMemStream);

            newMemStream.Close();

            infoPathForm.File.Update();
        }

        return infoPathForm;
    }

The addition of the new node is working properly; I can see that the new XML is properly formed.  It's just that the tags get stripped off once the file is loaded from the MemoryStream into the XmlDocument object.  And once these tags are missing, the forms won't open anymore in IP.
PLEASE HELP!
Thank you!

A: Change the line which reads:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);

to read:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);


text:
Q: In Excel, can you create a conditional statement that applies to every row in an excel sheet? I'm not just trying to highlight a whole row based on one cell's value in that row, I'm trying to apply that conditional statement to every single row.
Do i need to go through the effort to create a conditional statement to all 100 rows? or can I create one that checks what row that value is in, then highlights that particular row accordingly.
I haven't tried VBA, I entered this equation using conditional statement

A: Just change 'Tests'!$3:$3 to 'Tests'!$3:$103 in "Apply To" section - it'll apply CF for rows 3:103.
In that case your formula =$C3 = "fail" would be adjusted for each row:

*

*for row №3: =$C3 = "fail"

*for row №4: =$C4 = "fail"

*...

*for row №103: =$C103 = "fail"


text:
Q: Using variables in Objective-C I just want to open a webpage providing an URL. My code is:
 void openURL(char const *message)
{

   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];
}

And the error I get is:
 cannot initialize a parameter of type 'NSString *' with an lvalue of type 'const char *'
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];

I am not familiar with Objective-C nor learning it. I just need to use this simple code in a project.

A: One solution is to convert message to NSString, like this:
void openURL(char const *message)
{
    NSString *messageStr = [NSString stringWithCString:message
                                           encoding:NSUTF8StringEncoding];
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:messageStr]];
}

Another solution is to pass NSString (this wold require constructing NSStrings in all places where openURL is called:
void openURL(NSString *message)
{
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message]];
}

A: Try to convert char array to nsstring object first and then make url of that string.
likebelow:-
void openURL(char const message)
{
NSString s = [[NSString alloc] initWithBytes:buffer length:sizeof(message) encoding:NSASCIIStringEncoding];
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:s]];
}


text:
Q: use of unassigned local variable "acc_pay" here is a piece of code where i used this variable
 float acc_pay;
            float x = float.Parse(tb_quantity.Text) * float.Parse(tb_Price.Text);
        if (comboBox1.Text == "OK")
        {
            acc_pay = 0;
        }
        else if (comboBox1.Text == "NOT OK")
        {

            acc_pay = x;
        }
        else
        {
            MessageBox.Show("Select Any Status ...", "Warining", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

        con.Open();
            String query = "INSERT INTO tbl_insertData(Name,Quantity,Unit_Price,Net_Cash,Acc_Payable,Status,Date) VALUES(" +
                "'" + tb_Item_Name.Text + "'," +
                "'" + tb_quantity.Text + "'," +
                "'" + tb_Price.Text + "'," +
                "'" + tb_Net_Cash.Text + "'," +
                "'" + acc_pay + "'," + //here is error generated on "acc_pay" variable
                "'" + comboBox1.Text + "'," +
                "'" + tb_Date.Text + "')";
            SqlDataAdapter adp = new SqlDataAdapter(query, con);
            adp.SelectCommand.ExecuteNonQuery();
            con.Close();


text:
Q: Can't connect to SQL Server instance through my app but I can with SqlCmd I can't connect my VB app to an SQL Server 2005 instance because "server don't exist or access has been denied" (the Conection String is correct because the app works in other networks and also i wrote the server's ip instead his name). However I can connect from the same network with SqlCmd (tcp protocol).
Does anyone knows possible reasons for the error?
Thanks.

Dim StringConexion As String = "Provider=SQLOLEDB;Data Source=server's_ip\myInstance;Initial Catalog=mydb;User ID=myUser;Password=myPassword"

The error message is generated by .NET Framework (it was my spanish translation so myabe you can't recognize it). I will try to translate it better:

Unhandled exception in the application. If you click Continue, the
  application will ignore this error and attempt to continue. If you
  click on the application will close out immediately.
[DBNETLIB] [ConnectionOpen (Connect ()).] SQL Server does not exist s
  Server or denied access.

A: You can try the following to troubleshoot the error you are getting:

*

*Run your application in the VB IDE setting a breakpoint when the database connects. If this is VB 6 you want to look for  the Open() method of an instance of the ADO.Connection object. you can then step through the apps behavior to see what is happening.

*You can Look at the error log on the server. This is on the server's hard drive in a folder similar to C:\Program Files\Microsoft SQL Server\MSSQL10.<instance_name>\MSSQL\Log\ERRORLOG. This will only be useful if the app is actually establishing a connection with the SQL server and there is some kind of authentication error.

*You can run a packet sniffer like Wireshark and look for connection attempts when the app runs.

A: I think this connections can help you
Dim conn As String ="Data Source = Servername in you login to Ms sql server;database = your database; user ID = sa ; password = your password"


text:
Q: Discord Python Bot Add Color to Role to set the color of an existing role?
This is my code that create roles:
roles = ["SSS | Weeb", "SS Rang | Weeb", "S Rang | Weeb", "A Rang | Weeb", "B Rang | Weeb",
                 "C Rang | Weeb", "D Rang | Weeb", "E Rang | Weeb", "F Rang | Weeb", "Junior Rang | Weeb"]
        for i in roles:
            seasons = discord.utils.get(message.guild.roles, name=str(i))
            if str(seasons) == str(i):
                pass
            else:
                await message.guild.create_role(name=str(i))

Now I want there to set sth like
roles = ["SSS | Weeb", "SS Rang | Weeb", "S Rang | Weeb", "A Rang | Weeb", "B Rang | Weeb",
                 "C Rang | Weeb", "D Rang | Weeb", "E Rang | Weeb", "F Rang | Weeb", "Junior Rang | Weeb"]
        colors = ["red, green", "blue"] # and much more
        for i in range(len(roles)):
            seasons = discord.utils.get(message.guild.roles, name=str(roles[i]))
            if str(seasons) == str(roles[i]):
                pass
            else:
                await message.guild.create_role(name=str(roles[i]))
            ->  await message.guild.add_color_to_role(role_name=str(roles[i]), color=colors[i])

I didn't found anything ...

A: There's no such thing as Guild.add_color_to_role, it's Role.edit and pass the color as a kwargs, also you can pass the color when creating the role:
# Editing the role
await role.edit(colour=discord.Colour.blue())
# Creating a role with the color
await guild.create_role(name="whatever", colour=discord.Colour.blue())

You can also pass hex values to the colour kwarg
await guild.create_role(name="whatever", colour=0xff0000) # Red color

So, your colour list must be either a list of discord.Colour instances or a list of ints
colors = [0xff0000, discord.Colour.blue(), 0x00ff00]

To go through both of the list at the same time you can use the zip function (Note: both lists should be the same length)
role_names = ["name1", "name2", "name3"]
role_colors = [0xff0000, 0x00ff00, 0x0000ff]

for name, color in zip(role_names, role_colors):
    print(f"Name: {name}, color: {color}")

# Name: name1, color: 0xff0000
# Name: name2, color: 0x00ff00
# ...

Your code would look something like this
role_names = ["name1", "name2", "name3"]
role_colors = [0xff0000, 0x00ff00, 0x0000ff] # The default color is 0x000000 (white)

for name, color in zip(role_names, role_colors):
    print(f"Name: {name}, color: {color}") # -> Name: name1, color: 0xff0000 ...

    # Getting the role
    role = discord.utils.get(message.guild.roles, name=name)
    # Checking if the role exists (in other words - if the `role` variable is not a NoneType)
    if role is not None:
        # Role does not exist, create it here
        role = await message.guild.create_role(name=name, colour=color)

EDIT
To use colors like #5482a5
color = "#5482a5"
color = color[1:] # removing the initial `#`
color = int(color, 16) # pass this as the colour kwarg

Reference:

*

*Role.edit

*Guild.create_role

*zip

A: You can specify a colour when you create the role.
await message.guild.create_role(name=str(roles[i], colour=discord.Color.blue()))

Since you've actually asked for how to edit the colour you can do this:
role = await message.guild.create_role(name=str(roles[i]))
await role.edit(colour = discord.Colour.orange())


text:
Q: Java Multi Client server socket I am trying to establish a communication between a server (NewServer class) and a client (NewClient class), accepting two Client communications. I know how to do it with one client but not multiple client connections.

*

*Do I have to create 2 readers in the Client class?

*Can I do this in a recursive way?
Server Class:
import java.net.*;
import java.io.*;

public class NewServer
{
    //Create Server Socket and a Client Socket for each Client.
    static ServerSocket server;
    static Socket client1;
    static Socket client2;

    //Create OutputStreams to send information to each Client.
    static DataOutputStream client1writer;
    static DataOutputStream client2writer;

    static final int PORT = 9999;

    //Main Method
    public static void main(String[]args)
    {
        //Try-Catch Block for Socket Errors.
        try
        {
            //Create the Server Socket as a Host.
            server = new ServerSocket(PORT);

            //Connect Client 1 – First run of the Client class.
            client1 = server.accept();
            client1writer = new
            DataOutputStream(client1.getOutputStream());

            //Connect Client 2 – Second run of the Client class.
            client2 = server.accept();
            client2writer = new
            DataOutputStream(client2.getOutputStream());

            //Assign each Client an ID number – this is how the Client will know
            //    which individual Client it's representing in RunTime.
            int ID1 = 8675309;
            int ID2 = 8675308;

            //Tell both Clients which one they are representing.
            client1writer.writeInt(ID1);
            client2writer.writeInt(ID2);

            //Close all Sockets when finished.
            client1.close();
            client2.close();
            server.close();
        }
        catch (IOException IOex)
        {
            System.out.println("Server Error.");
        }
    }
}

Client class:
import java.net.*;
import java.io.*;

public class NewClient {

    static Socket client = null;
    static final int PORT = 9999;
    static final String IP = "localhost";

    public static void main(String[] args) throws IOException {

        int id1;
        int id2;

        try{
            client = new Socket(IP,PORT);
            System.out.println("Connection successful!");

            reader = new DataInputStream(client.getInputStream());

            id1 = reader.readInt();
            id2 = reader.readInt();

            System.out.println("The id of the user is " + id);

            //Closing everything
            client.close();
            reader.close();

        }catch(IOException error) {
            System.err.println("Server error.");
        }
    }
}

A: You can achieve it by starting a separate thread (also known as Plain threads for every new client connection and then call server.accept() which runs in a loop. It is useful as an learning example but will not help you achieve what you need as you loose control of threads.
Second way is to use Executor Service which provides better management control over the above solution.


text:
Q: I am weak in such integral. May someone offer some method to solve it. Thanks $$\lim_{n\rightarrow\infty}\int_0^1 \int_0^1 \cdots\int_0^1 {n \over x_1+x_2+\cdots+x_n} \, dx_1 \, dx_2 \cdots dx_n$$
Sorry for don't give details. It's not a test from class or textbook. First I have no idea, then I see a similar problem which use the law of large numbers. But I don't know how to apply it.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\lim_{n \to \infty}\int_{0}^{1}\cdots\int_{0}^{1}
{n \over x_{1} +  \cdots + x_{n}}\,\dd x_{1}\cdots\dd x_{n}
\\[5mm] = &
\lim_{n \to \infty}\braces{n\int_{0}^{1}\cdots\int_{0}^{1}
\bracks{\int_{0}^{\infty}\expo{-\pars{x_{1} +  \cdots + x_{n}}t}\dd t}
\dd x_{1}\cdots\dd x_{n}}
\\[5mm] = &\
\lim_{n \to \infty}\bracks{n\int_{0}^{\infty}\pars{\int_{0}^{1}\expo{-tx}
\,\dd x}^{n}\dd t} =
\lim_{n \to \infty}\bracks{n\int_{0}^{\infty}
\pars{1 - \expo{-t} \over t}^{n}\dd t}
\\[5mm] & =
\lim_{n \to \infty}\bracks{n\int_{0}^{\infty}
\exp\pars{n\,\ln\pars{1 - \expo{-t} \over t}}\dd t}
\\[5mm] & =
\lim_{n \to \infty}\bracks{n\int_{0}^{\infty}
\exp\pars{-\,{n \over 2}\,t}\dd t} = \bbx{2}
\end{align}

In the last two lines I used the
  Laplace Method.


text:
Q: Need XML root element without end tag using JAXB STAX in combination I am trying to marshal list to xml. As the xml contains list and I do not want to create separate class for outer tag I am using STAX and JAXB in combination.
The issue is I am getting element with end tag.
actual output
<WRAPPER>
    <ROOT att1="val1" att2="val2"></ROOT>
    <ROOT att1="val1" att2="val2"></ROOT>
</WRAPPER>

Expected Output
<WRAPPER>
    <ROOT att1="val1" att2="val2"/>
    <ROOT att1="val1" att2="val2"/>
</WRAPPER>

Class file
@XmlRootElement(name="ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class ROOT {

    @XmlAttribute(name = "att1")
    String att1;

    @XmlAttribute(name = "att2")
    String att2;

    public String getAtt1() {
        return att1;
    }

    public void setAtt1(String att1) {
        this.att1 = att1;
    }

    public String getAtt2() {
        return att2;
    }

    public void setAtt2(String att2) {
        this.att2 = att2;
    }
}

Method
public static String marshal(List<ROOT> list)
    throws XMLStreamException, JAXBException, IOException {
    JAXBElement<ROOT> jaxb = null;
    String xmlString = null;
    if (!CollectionUtils.isEmpty(list)) {
        QName root = new QName("ROOT");
        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        StringWriter stringWriter = new StringWriter();

        XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(stringWriter);
        streamWriter.writeStartElement("WRAPPER");
        JAXBContext jc = JAXBContext.newInstance(ROOT.class);
        Marshaller marshaller = jc.createMarshaller();
        for (ROOT t : list) {
            jaxb = new JAXBElement<ROOT>(root, ROOT.class, t);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            marshaller.marshal(jaxb, streamWriter);
        }
        streamWriter.writeEndDocument();
        xmlString = stringWriter.toString();
        stringWriter.close();
        streamWriter.close();
        }
    return xmlString;
}

Problem is nillable cannot be applied to XmlRootElement

A: Although both expected and actual are technically equal I found no way to modify that in the way without creating additional wrapper class.


text:
Q: Click event is just refreshing the page? When I click the 'Submit' button the page just seems to refresh and no messages are displayed that are suppose to read either 'Completed' or 'Not'. I added was some Ajax functions to populate some drop down list dynamically for information from MySQL database.
Question: Why is my page not submitting, it is just 'refreshing'? (after adding the Ajax function and populating drop down list from php file)


text:
Q: How to type '$' in jupyter notebook text cell? When I try to type $ in the text cell of Jupyter notebook then it is recognized as a special character for math typesetting. How to prevent this? I have tried using '\$' but it doesn't work.

A: I ran into this some time ago and ended up double escaping it:
\\$test\\$

This will result in $test$
I'm not sure if this is the official way to do it though.


text:
Q: how to return false when mail transport failed in zend framework 2? I am trying to return fail message with json if the mail sending is failed, here is my code:
$transport = new SmtpTransport();
            $options   = new SmtpOptions(array(
                    'name'              => 'localhost',
                    'host'              => 'localhost',
                    'connection_class'  => 'login',
                    'connection_config' => array(
                            'username' => 'cscsacsac',
                            'password' => 'csdca',
                            //'ssl'=>'ssl',
                            //'port' => '465',
                    ),
            ));

            $transport->setOptions($options);
            $sent = true;
            try {

                $transport->send($mail);
            }
            catch (\Zend\Mail\Transport\Exception\DomainException $e) {
                $sent = false;
            }

            if($sent){

                echo "success";

                exit;
            }

            elseif(!$sent){

                echo "fail";

                exit;
            }

and here is the ajax:
$.ajax({
          type: "POST",
          url: '<?php echo MAIN_URL?>cases',
          data: { name: name, email: email, mobile: mobile, address: address, compliant: compliant },
          success:function(data){

            if(data =='success'){

                $('.casesMailResponse').css({'color':'#00917D'});
                $('.casesMailResponse').html('Your case has been sent successfully.');
            }

            else if(data == 'fail'){

                $('.casesMailResponse').css({'color':'#F6565B'});
                $('.casesMailResponse').html('Some errors occurred, please try again.');
            }
          },
        });

but in case of failure I got Internal server error due to Incorrect authentication data, so the failure message is not displayed

A: You are catching only Zend\Mail\Transport\Exception\DomainException, but SMTP transport adapter can throw other exceptions too. For example in send method it can throw Zend\Mail\Transport\Exception\RuntimeException.
I suggest to catch exception interface of mail package:
    $sent = true;
    try {
        $transport->send($mail);
    } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) {
        $sent = false;
    }

A: Could you try :
 }
 catch (\Zend\Mail\Transport\Exception\DomainException $e) {
    $sent = false;
 } catch (Exception $e) {
    $sent = false;
}

Just a guess....


text:
Q: Ruby where clause looking for a specific condition and nil values together I have this scope in my Variant Model. I am looking for Products where published_on is dated not today, and at the same time I am looking for where published_on is nil. I came up with this but it seems like it only gets the Variants where the product.published_on is not dated today. and not the nil ones. I would like to know what is wrong with my code.
  scope :not_new_items, lambda {
    joins(:product).where("products.published_on < ? OR products.published_on = ?", Time.zone.now, nil)
  }

I also have a scope to get nil values of product.published_on and this works, though I want them in one scope
  scope :null_items, lambda {
    joins(:product).where(
      products: { published_on: nil }
    )
  }

A: In Postgresql NULL is not equal to NULL so the following expression returns false:
NULL = NULL
To check whether a value is NULL or not, you use the IS NULL operator instead:
value IS NULL
So in your case it would be something like this:
scope :not_new_items, lambda {
    joins(:product).where("products.published_on < ? OR products.published_on IS NULL", Time.zone.now)
  }

If you look on the query which produces ActiveRecord for field: nil it would be SELECT "table_name".* FROM "table_name" WHERE "table_name"."field" IS NULL

A: A NULL value indicates an unavailable or unassigned value. The value NULL does not equal zero (0), nor does it equal space (' '). Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.
So you have to replace = with is
  scope :not_new_items, lambda {
           joins(:product).where("products.published_on < ? OR
      products.published_on IS ?", Time.zone.now, nil)
 }


text:
Q: How to create a function type boolean that checks to see if the command line argument is in fact a digit? I am currently taking cs50 introduction into computer science.
I'm trying to create a type bool function with argument string named only_digits that will check to see if the command line argument that the user inputs is in fact a digit. I don't think I'm using the isdigit correctly. What I am trying to accomplish is not only checking to see if it is a decimal digit but also returning it back to main to continue with the program and furthermore convert the key from a string to an int inside main.
I have tried so many different ways. I refuse to go look at other solutions to the whole program because I really want to understand this and be able to learn and progress. It is the "Caesar" cipher "Problem Set 2" in "Week 2 Arrays" of the "Introduction to computer science course."
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool only_digits(string s);

int main(int argc, string argv[])
{
   if(argc != 2)
   {
      printf("USAGE: ./caesar KEY\n");
      return 1;
   }
   return 0;
}

bool only_digits(string s)

if (! isdigit, (argv[1]))
{
   printf("INVAILD: USAGE: ./caesar KEY\n");
   return 1;
}
return 0;

Now, I have tried implementing that function multiple different ways. I have tried...
if ((isdigit, s) == 0)...if (!isdigit, argv[1])
but I know that I haven't declared s yet for argv[1] which I am having problems with that also. Every time I try to declare it I get an error. I would list more examples of what I have tried and the errors but to be honest I have tried so many different ways that I can't even remember all of them now.
Also, please tell me if I'm wrong on this assumption. The command line argument is stored as a string so it's for example stored in this fashion: if the user typed "./caesar 3" argv["3"] and not argv[3]. So meaning it is stored as a string and not the decimal number 3. So I'm actually trying to check if it is a string and if it is to be able to change it into an int. I don't know if I'm fully understanding that or not and that could be a huge reason to why I'm not able to implement this function due to not grasping the concept.
I checked all the suggested questions and answers that they wanted me to review before submitting this and to be honest I just skimmed through them because there was solutions to other sections of the program and I didn't want to accidentally come across that and lose the ability to try on my own at first. This specific part of implementing the function is the part I'm stuck on for now.

A: isdigit() only checks for one 'character' (of the string).
//do not have this
//#include <cs50.h>
//
#include <stdbool.h> //included for bool
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h> // for exit()

#define string char* // emulate string as keyword

bool only_digits(string s);

int main(int argc, string argv[])
{
        if(argc != 2)
        {
                printf("USAGE: ./caesar KEY\n");
                return 1;
        }
        only_digits(argv[1]);

        return 0;
}

bool only_digits(string s) {
        int len = strlen(s);
        for (int x=0;x<len; x++)
        {
                if (!isdigit( (unsigned char) s[x] ))
                {
                        printf("INVAILD: USAGE: ./caesar KEY\n");
                        exit(1); // hard exit, or change it to return(1) to 'fail'
                }
        }
        return 0;
}

Good luck


text:
Q: Leave out views Android XML Runtime I am using this app as a source for my company's personal OpenVPN App: ICS-OpenVPN
And I want to use the existing about-page and add a couple of my own links. However, these links are only available when you're connected to our local network. Is there any way I can remove the links from the page if the user is not connected to that network?
Thanks

A: I already found the answer: http://developer.android.com/training/basics/fragments/fragment-ui.html
For anyone else having this question.