text:
Q: Retain and lag function in R as SAS I am looking for a function in R similar to lag1, lag2 and retain functions in SAS which I can use with data.tables.
I know there are functions like embed and lag in R but they don't return a single value or the previous value . They return a complete set of vectors.
Is there anything in R which I can use with data.table?
More info on the SAS functions :

*

*Retain

*Lag

A: You have to be aware that R works very different from the data step in SAS. The lag function in SAS is used in the data step, and is used within the implicit loop structure of that data step. The same goes for the retain function, which simply keeps the value constant when going through the data looping.
R on the other hand works completely vectorized. This means that you have to rethink what you want to do, and adapt accordingly.

*

*retain is simply useless in R, as R recycles arguments by default. If you want to do this explicitly, you might look at eg rep() to construct a vector with constant values and a certain length.

*lag is a matter of using indices, and just shifting position of all values in a vector. In order to keep a vector of the same length, you need to add some NA and remove some extra values.

A simple example: This SAS code lags a variable x and adds a variable year that has a constant value:
data one;
   retain year 2013;
   input x @@;
   y=lag1(x);
   z=lag2(x);
   datalines;
1 2 3 4 5 6
;

In R, you could write your own lag function like this:
mylag <- function(x,k) c(rep(NA,k),head(x,-k))

This single line adds k times NA at the beginning of the vector, and drops the last k values from the vector. The result is a lagged vector as given by lag1 etc. in SAS.
this allows something like :
nrs <- 1:6 # equivalent to datalines
one <- data.frame(
   x = nrs,
   y = mylag(nrs,1),
   z = mylag(nrs,2),
   year = 2013  # R automatically loops, so no extra command needed
)

The result is :
> one
  x  y  z year
1 1 NA NA 2013
2 2  1 NA 2013
3 3  2  1 2013
4 4  3  2 2013
5 5  4  3 2013
6 6  5  4 2013

Exactly the same would work with a data.table object. The important note here is to rethink your strategy: Instead of thinking loopwise as you do with the DATA step in SAS, you have to start thinking in terms of vectors and indices when using R.

A: I would say the closet equivalent to retain, lag1, and lag2 would be the Lag function in the quantmod package.
It's very easy to use with data.tables.  E.g.:
library(data.table)
library(quantmod)
d <- data.table(v1=c(rep('a', 10), rep('b', 10)), v2=1:20)
setkeyv(d, 'v1')
d[,new_var := Lag(v2, 1), by='v1']
d[,new_var2 := v2-Lag(v2, 3), by='v1']
d[,new_var3 := Next(v2, 2), by='v1']

This yields the following:
print(d)
    v1 v2 new_var new_var2 new_var3
 1:  a  1      NA       NA        3
 2:  a  2       1       NA        4
 3:  a  3       2       NA        5
 4:  a  4       3        3        6
 5:  a  5       4        3        7
 6:  a  6       5        3        8
 7:  a  7       6        3        9
 8:  a  8       7        3       10
 9:  a  9       8        3       NA
10:  a 10       9        3       NA
11:  b 11      NA       NA       13
12:  b 12      11       NA       14
13:  b 13      12       NA       15
14:  b 14      13        3       16
15:  b 15      14        3       17
16:  b 16      15        3       18
17:  b 17      16        3       19
18:  b 18      17        3       20
19:  b 19      18        3       NA
20:  b 20      19        3       NA

As you can see, Lag lets you look back and Next lets you look forward.  Both functions are nice because they pad the result with NAs such that it has the same length as the input.
If you want to get even fancier, and higher-performance, you can look into rolling joins with data.table objects.  This is a little bit different thab what you are asking for, but is conceptually related, and so powerful and awesome I have to share.
Start with a data.table:
library(data.table)
library(quantmod)
set.seed(42)
d1 <- data.table(
    id=c(rep('a', 10), rep('b', 10)),
    time=rep(1:10,2),
    value=runif(20))
setkeyv(d1, c('id', 'time'))
print(d1)

    id time     value
 1:  a    1 0.9148060
 2:  a    2 0.9370754
 3:  a    3 0.2861395
 4:  a    4 0.8304476
 5:  a    5 0.6417455
 6:  a    6 0.5190959
 7:  a    7 0.7365883
 8:  a    8 0.1346666
 9:  a    9 0.6569923
10:  a   10 0.7050648
11:  b    1 0.4577418
12:  b    2 0.7191123
13:  b    3 0.9346722
14:  b    4 0.2554288
15:  b    5 0.4622928
16:  b    6 0.9400145
17:  b    7 0.9782264
18:  b    8 0.1174874
19:  b    9 0.4749971
20:  b   10 0.5603327

You have another data.table you want to join, but not all time indexes are present in the second table:
d2 <- data.table(
        id=sample(c('a', 'b'), 5, replace=TRUE),
        time=sample(1:10, 5),
        value2=runif(5))
setkeyv(d2, c('id', 'time'))
print(d2)
   id time      value2
1:  a    4 0.811055141
2:  a   10 0.003948339
3:  b    6 0.737595618
4:  b    8 0.388108283
5:  b    9 0.685169729

A regular merge yields lots of missing values:
d2[d1,,roll=FALSE]
    id time      value2     value
 1:  a    1          NA 0.9148060
 2:  a    2          NA 0.9370754
 3:  a    3          NA 0.2861395
 4:  a    4 0.811055141 0.8304476
 5:  a    5          NA 0.6417455
 6:  a    6          NA 0.5190959
 7:  a    7          NA 0.7365883
 8:  a    8          NA 0.1346666
 9:  a    9          NA 0.6569923
10:  a   10 0.003948339 0.7050648
11:  b    1          NA 0.4577418
12:  b    2          NA 0.7191123
13:  b    3          NA 0.9346722
14:  b    4          NA 0.2554288
15:  b    5          NA 0.4622928
16:  b    6 0.737595618 0.9400145
17:  b    7          NA 0.9782264
18:  b    8 0.388108283 0.1174874
19:  b    9 0.685169729 0.4749971
20:  b   10          NA 0.5603327

However, data.table allows you to roll the secondary index forward, WITHIN THE PRIMARY INDEX!
d2[d1,,roll=TRUE]
    id time      value2     value
 1:  a    1          NA 0.9148060
 2:  a    2          NA 0.9370754
 3:  a    3          NA 0.2861395
 4:  a    4 0.811055141 0.8304476
 5:  a    5 0.811055141 0.6417455
 6:  a    6 0.811055141 0.5190959
 7:  a    7 0.811055141 0.7365883
 8:  a    8 0.811055141 0.1346666
 9:  a    9 0.811055141 0.6569923
10:  a   10 0.003948339 0.7050648
11:  b    1          NA 0.4577418
12:  b    2          NA 0.7191123
13:  b    3          NA 0.9346722
14:  b    4          NA 0.2554288
15:  b    5          NA 0.4622928
16:  b    6 0.737595618 0.9400145
17:  b    7 0.737595618 0.9782264
18:  b    8 0.388108283 0.1174874
19:  b    9 0.685169729 0.4749971
20:  b   10 0.685169729 0.5603327

This is pretty damn cool: Old observations are rolled forward in time, until they are replaced by new ones.  If you want to replace the NA values at the beggining of the series, you can do so by rolling the first observation backwards:
d2[d1,,roll=TRUE, rollends=c(TRUE, TRUE)]
    id time      value2     value
 1:  a    1 0.811055141 0.9148060
 2:  a    2 0.811055141 0.9370754
 3:  a    3 0.811055141 0.2861395
 4:  a    4 0.811055141 0.8304476
 5:  a    5 0.811055141 0.6417455
 6:  a    6 0.811055141 0.5190959
 7:  a    7 0.811055141 0.7365883
 8:  a    8 0.811055141 0.1346666
 9:  a    9 0.811055141 0.6569923
10:  a   10 0.003948339 0.7050648
11:  b    1 0.737595618 0.4577418
12:  b    2 0.737595618 0.7191123
13:  b    3 0.737595618 0.9346722
14:  b    4 0.737595618 0.2554288
15:  b    5 0.737595618 0.4622928
16:  b    6 0.737595618 0.9400145
17:  b    7 0.737595618 0.9782264
18:  b    8 0.388108283 0.1174874
19:  b    9 0.685169729 0.4749971
20:  b   10 0.685169729 0.5603327

These rolling joins are absolutely incredible, and I've never seen them implemented in any other open source package (see ?data.table for more info).  It will take a little while to turn off your "SAS brain" and turn on your "R brain", but once you get over that initial hump you'll find that the language is much more expressive.

A: For retain, try this :
retain<-function(x,event,outside=NA)
{
  indices <- c(1,which(event==TRUE), nrow(df)+1)
  values <- c(outside,x[event==TRUE])
  y<- rep(values, diff(indices))
}

With data : I want to retain down the value when w==b
df <- data.frame(w = c("a","b","c","a","b","c"), x = 1:6, y = c(1,1,2,2,2,3), stringsAsFactors = FALSE)
df$z<-retain(df$x-df$y,df$w=="b")
df

And here's the contrary obtain, that does not exist in SAS:
obtain<-function(x,event,outside=NA)
{
  indices <- c(0,which(event==TRUE), nrow(df))
  values <- c(x[event==TRUE],outside)
  y<- rep(values, diff(indices))
}

Here's an example. I want to obtain the value in advance where w==b
df$z2<-obtain(df$x-df$y,df$w=="b")
df

Thanks to Julien for helping.

A: here's an example: cumulate value with sqldf:
> w_cum <-
 sqldf("select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as cum_sum
       from w_cum       t1
       inner join w_cum t2 on t1.id >= t2.id
       group by t1.id, t1.SomeNumt
       order by t1.id

")
   id SomeNumt cum_sum

*

*1       11      11

*2       12      23

*3       13      36

*4       14      50

*5       15      65

*6       16      81

*7       17      98

*8       18     116

*9       19     135

*10       20     155


text:
Q: I want to interpret stdin as a binary file. Why is freopen failing on Windows? TL;DR: Why does freopen(NULL, "rb", stdin) always fail on Windows?
I'm trying to re-implement a base64 encoder in C that takes input from stdin and outputs the encoded equivalent into stdout. I had a problem in my previous post where fread was signalling EOF prematurely. Here is what my main method looks like:
int main(void)
{
    unsigned char buffer[BUFFER_SIZE];
    unsigned char base64_buffer[BASE64_BUFFER];

    while (1)
    {
        TRACE_PUTS("Reading in data from stdin...");
        size_t read = fread(buffer, 1, sizeof(buffer), stdin); /* Read the data in using fread(3) */

        /* Process the buffer */

        TRACE_PRINTF("Amount read: %zu\n", read);
        TRACE_PUTS("Beginning base64 encode of buffer");
        size_t encoded = base64_encode(buffer, read, base64_buffer, sizeof(base64_buffer));

        /* Write the data to stdout */
        TRACE_PUTS("Writing data to standard output");
        ...

        if (read < sizeof(buffer))
        {
            break; /* We reached EOF or had an error during the read */
        }
    }

    if (ferror(stdin))
    {
        /* Handle errors */
        fprintf(stderr, "%s\n", "There was a problem reading from the file.");
        exit(1);
    }

    puts(""); /* Output a newline before finishing */

    return 0;
}

Essentially, it reads in data from stdin using fread, encodes to base64, writes it to stdout, then checks if EOF has been reached at the end of the loop.
When I piped the contents of a binary file to this app's stdin, it would only read a fraction of the total bytes in the file. For example:
$ cat /bin/echo | my_base64_program >/dev/null # only view the trace output
TRACE: C:/Users/James/Code/c/base64/main.c:23: Reading in data from stdin...
TRACE: C:/Users/James/Code/c/base64/main.c:28: Amount read: 600
TRACE: C:/Users/James/Code/c/base64/main.c:29: Beginning base64 encode of buffer
TRACE: C:/Users/James/Code/c/base64/main.c:43: Writing data to standard output
TRACE: C:/Users/James/Code/c/base64/main.c:23: Reading in data from stdin...
TRACE: C:/Users/James/Code/c/base64/main.c:28: Amount read: 600
TRACE: C:/Users/James/Code/c/base64/main.c:29: Beginning base64 encode of buffer
TRACE: C:/Users/James/Code/c/base64/main.c:43: Writing data to standard output
TRACE: C:/Users/James/Code/c/base64/main.c:23: Reading in data from stdin...
TRACE: C:/Users/James/Code/c/base64/main.c:28: Amount read: 600
TRACE: C:/Users/James/Code/c/base64/main.c:29: Beginning base64 encode of buffer
TRACE: C:/Users/James/Code/c/base64/main.c:43: Writing data to standard output
TRACE: C:/Users/James/Code/c/base64/main.c:23: Reading in data from stdin...
TRACE: C:/Users/James/Code/c/base64/main.c:28: Amount read: 569
TRACE: C:/Users/James/Code/c/base64/main.c:29: Beginning base64 encode of buffer
TRACE: C:/Users/James/Code/c/base64/main.c:43: Writing data to standard output

$ cat /bin/echo | wc -c
28352

As you can see /bin/echo is 28352 bytes long, but only ~2400 of them are being processed. I believe the reason is because stdin is not being considered a binary file, so certain control characters (like Control-Z as mentioned in the linked post's answer) were prematurely signalling EOF.
I took a look at the base64 source code and it looks like they're using xfreopen (which is just a wrapper for freopen) to tell fread to interpret stdin as binary. So I went ahead and did that before the while-loop:
if (!freopen(NULL, "rb", stdin))
{
    fprintf(stderr, "freopen failed. error: %s\n", strerror(errno));
    exit(1);
}

However, now my app always exits at that point with:
$ cat /bin/echo | my_base64_program
freopen failed. error: Invalid argument

So why is freopen at that point failing, when it works for base64? I'm using MinGW-w64 with GCC on Windows if that's relevant.

A: Why freopen() might fail in general
The C standard says:

If filename is a null pointer, the freopen function attempts to change the mode of
  the stream to that specified by mode, as if the name of the file currently associated with
  the stream had been used. It is implementation-defined which changes of mode are
  permitted (if any), and under what circumstances.

Presumably, your implementation doesn't allow the changes you're trying to make.  On Mac OS X, for example, the man page for freopen() adds:

The new mode must be compatible with the mode that the stream was originally opened with:

*

*Streams originally opened with mode "r" can only be reopened with that same mode.

*Streams originally opened with mode "a" can be reopened with the same mode, or mode "w".

*Streams originally opened with mode ``w'' can be reopened with the same mode, or mode "a".

*Streams originally opened with mode "r+", "w+", or "a+" can be  reopened with any mode.

With that said, on Mac OS X (where b is a no-op anyway), you'd be OK.
Why freopen() fails on Windows specifically
However, you're on Windows.  You need to learn how to find and read the documentation.  I use a Google search with the term 'site:msdn.microsoft.com freopen' for whatever function I'm looking for.  That specific search yields the manual for freopen() where it says:

If path, mode, or stream is a null pointer, or if filename is an empty string, these functions invoke the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, these functions set errno to EINVAL and return NULL.

That's the documented behaviour: it is also the behaviour you are seeing.  The manual for your system is helpful.  It basically says "thou shalt not".
How to fix the input mode of standard input on Windows
I note that in my answer to your previous question, I pointed to _setmode():

However, it is more likely that you need _setmode():
_setmode(_fileno(stdin), O_BINARY);

This is the advice that is given in the answers to the question that deamentiaemundi pointed to.
I note in passing that the Microsoft manual page for setmode() says:

This POSIX function is deprecated. Use the ISO C++ conformant _setmode instead.

This is a curious comment because POSIX does not standardize a function setmode() in the first place.
You can find Microsoft's documentation for fileno().  It too has the spiel about POSIX (but this time it is accurate; POSIX does specify fileno()) and refers you to _fileno().

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to autoformat a text in Edit text to 00-0000-0000000-000 format in Android Kotlin? How can I autoformat a text typed in Edit text to 00-0000-0000000-000 format?
i.e. 2digits-4digits-7digits-(2/3)digits. The - should be added automatically while typing.
I am using normal Android EditText.
Can someone help ?


text:
Q: Domain Based Port Forwarding with VLAN routing At my new workspace I want to setup a network that enables me to deploy my web development work on Dev, Test and Accept servers (VMs) with (controlled) access from outside the network - based on different domains (multiple websites). Also I want to have remote access to my network through VPN.
The challenge however is that we have shared internal network and I won't be able to control the router / firewall myself (network is managed by an external party). An illustrated and well explained request is what they need in order to apply a new configuration.
I have limited knowledge of networking but research convinced me my network setup should be possible. Can someone confirm / comment on my ideas with regards to feasibility / best practices?

*

*The building with my workspace has a fibre (FTTO) connection with public IP 176.xx.xx.xxx. Network traffic is controlled at the Juniper SSG20 firewall (which I can't control but those have a public web interface running on port 80). The internal network has 192.168.30.0/24 range.

*I have a Netgear Prosafe GS105E switch with VLAN support.

*I have a Dell Server with VMware vSphere Hypervisor server (ESXi) with 5 VM's (running Ubuntu 12.04 Srv):

*

*(A) VM: Fileserver (only internal access for my local workstation (E)

*(B) VM: Webserver (Dev) should handle dev.domain-1.com

*(C) VM: Webserver (Test) should handle test.domain-1.com

*(D) VM: Webserver (Accept) should handle accept.domain-1.com

*The Dell Server has 3 NICs, I can create virtual switches to handle VLAN routing.

*I have a multifunction printer (F) with eth0 inferface that should only be accessible to me within a VLAN.

*The existing Apple Airport also provides WiFi access on the same subnet, but can I hide my VM's so they can't be accessed by other people in the building (VLAN config I guess).

In essence, my goal is:

*

*port forwarding (80, 443, 5000, 8080) based on domain

*dev.domain-a.com --> 192.168.1.10 (VM: B)

*dev.domain-b.com --> " "  "  "  "

*test.domain-a.com --> 192.168.1.11 (VM: C)

*test.domain-b.com --> " "  "  "  "

*accept.domain-a.com --> 192.168.1.12 (VM: D)

*limit access to Fileserver (VM: A) from my local workstation only

*be able to access network (and fileserver) through VPN

Relevant questions:

*

*Do I have to configure a Reverse Proxy at a new ESXi VM to be able to resolve the local machines from outside (how about Pound Reverse Proxy server on Ubuntu)?

*Does the Juniper SSG20 Firewall need to add my local servers / VLAN to a DMZ?

*How can the Juniper SSG20 Firewall still have web access (port 80) if I want to have port forwarding for port 80? Do I have to add a rule into the Reverse Proxy that redirects traffic back to the firewall?

Any thoughts would be very, very helpfull so that I can formulate the request to the external network managing party (through the property manager).
Please see the network layout diagram:

A:
Do I have to configure a Reverse Proxy at a new ESXi VM to be able to
  resolve the local machines from outside (how about Pound Reverse Proxy
  server on Ubuntu)?

No reverse proxies are needed based on your requirements/goals list.  All you really need are dedicated internet/WAN IPs and some basic NAT/MIP rules on the SSG20 setup.  You can lock down this access via firewall rules on the SSG20 if you want (like which client IPs can come in, etc.)

Does the Juniper SSG20 Firewall need to add my local servers / VLAN to
  a DMZ?

No, but you do need to have MULTIPLE external IP addresses available to do straight NATing (on the Juniper it would be a static NAT, which they call a MIP/mappedIP).  In that scenario you would have a single external IP for each internal VM (dev/test/accept) to easily do external to internal translations.
Otherwise, you'll need to PAT or what Juniper calls a VIP on the SSG and listen on different ports.  Meaning if you wanted just a single external IP, then you'd need to do something like normal port listening on dev and then increment something like 81/444/5001/8081 for test and so on.  Then in the SSG20 it would map externalIP:81 to 192.168.1.11:80 but that's really a PITA vs just getting a few additional external IPs from the provider.

How can the Juniper SSG20 Firewall still have web access (port 80) if
  I want to have port forwarding for port 80?

I'm assuming you mean external access to the SSG20's admin webui?  Personally, that shouldn't be open anyway...security hole especially over just http.  The admin/responsible party should lock it down to a different listening port over https and limit it to their incoming client IP ranges.  But again, I go back to Multiple external IPs.  If you have dedicated IPs for your VMs, then you can still (albeit not recommended) let them keep the normal external WAN IP and port 80 open on the Juniper SSG20.

Do I have to add a rule into the Reverse Proxy that redirects traffic
  back to the firewall?

No, this is unnecessary.  All you need is to make sure that the VMs can route out to the Juniper (normal internet traffic).  If they can already, then they are done.  You don't even need to get fancy with the vmware networking unless you require that each VM be segmented and can't send each other traffic, but you can do this within the VM's OS just as easily.


text:
Q: bootRepackage classifier is not working when upgrade to gradle 6.6.1 (also gralde 5) Our project still worked well in gradle 4.10.2 (Spring boot 1.5.22), but when i have upgraded gradle to 6.6.1 it thrown exception
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':my-app'.
Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener
Caused by: java.lang.NoSuchMethodError: org.gradle.api.tasks.TaskInputs.file(Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;
at org.springframework.boot.gradle.repackage.RepackagePluginFeatures$RegisterInputsOutputsAction.setupInputOutputs(RepackagePluginFeatures.java:150)
at org.springframework.boot.gradle.repackage.RepackagePluginFeatures$RegisterInputsOutputsAction.execute(RepackagePluginFeatures.java:136)

I have tried with gradle 5 it still happend.
This is my gradle.build bootRepackage section, when i removed classifier = "boot" it work without classifier feature
bootRepackage {
    enabled = true
    classifier = "boot"
    doLast{
        //some tasks
    }
}

Why could this be?

A: Gradle 5 has removed a method that Spring Boot 1.5's Gradle plugin requires. Spring Boot 1.5 supports Gradle 2.x or 3.x so it isn't surprising that it does not work with Gradle 5.
If you want to use a more up-to-date version of Gradle, you'll have to upgrade to a more up-to-date version of Spring Boot as well. At the time of writing 2.3.x is the oldest generation of Spring Boot that is still supported.


text:
Q: Passing date parameter in dymanic sql This procedure was working good until i decided to get the report by date range.
The CreatedDate column in table is of datatype datetime. I'm passing the dates from c# as text eg: '2014-09-31'. The argument can also be empty sometime.
Now I do not get any result. I also tried to convert into varchar instead of date. Where am i going wrong.
If i just remove the 'added' part, query works fine again.
ALTER PROCEDURE GetReport
(
 @StartDate varchar(10),
 @EndDate varchar(10)
)
AS
BEGIN
 SET NOCOUNT ON;
     IF (@StartDate = '')
     SET @StartDate = NULL

     IF (@EndDate = '')
     SET @EndDate = NULL

DECLARE @query VARCHAR(MAX)
DECLARE @questions VARCHAR(MAX)
SELECT @questions = STUFF((....some code)

SET @query = 'SELECT * FROM
                    (
                      SELECT asq.QuestionText, asa.Comments,
                             ROW_NUMBER() OVER(PARTITION BY asa.FkQuestionId
                             ORDER BY asa.Comments) Seq
                             FROM Answers AS asa
                             LEFT JOIN Questions AS asq ON
                             asa.FkQuestionId = asq.QuestionId

                  //---added this part------
                    WHERE (asa.CreatedDate) >= CONVERT(date,'+@StartDate+')
                    OR CONVERT(date,'+@StartDate+') IS NULL)
                    AND (asa.CreatedDate) <= CONVERT(date,'+@EndDate+') OR
                    CONVERT(date,'+@EndDate+') IS NULL)
                 //---end------

                     ) AS t
                     PIVOT
                        (
                          MIN(t.Comments)
                          FOR t.QuestionText IN ('+@questions+')
                        ) AS pvt'
            EXECUTE (@query)
END

A: If your column CreatedDate is datatype datetime then you need to cast to date to remove the time portion. The time portion may not be 00:00:00
                WHERE ( CAST(asa.CreatedDate AS DATE) >= CONVERT(date,'+@StartDate+')
                OR CONVERT(date,'+@StartDate+') IS NULL) )
                AND ( CAST(asa.CreatedDate AS DATE) <= CONVERT(date,'+@EndDate+') OR
                CONVERT(date,'+@EndDate+') IS NULL) )


text:
Q: Payara+Jenkins+VisualSVN build successful with no errors, but still not deploying to Payara applications
*

*I have created a simple web application in Netbeans 10.0

*Integrated successfully with Visual SVN. Regular commits are working fine.

*Installed Payara 5

*Installed Jenkins

*Successfully registered Visual SVN branch in Jenkins job

*Successfully configured Ant and DEPLOY TO CONTAINER plugins in Jenkins.

*Registered war filename, Context path, Server Glassfish 3.x, port and hostname in Jenkins

*Build Now in Jenkins

*Successful build.

*Logged into Payara Admin console and clicked Applications
WHOOOOOSHHHH... No application found there

There is absolutely no error any where. Tried all options including specifying Target/ Arg settings in build.xml
Nothing works.
Please help me as my job is on the stake.
*** P.S.
No where did I find any setting for Payara domain name. That could be a cause but not sure. How would Jenkins know in which Payara domain to deploy the compiled WAR file. May be I am wrong.
Thanks in anticipation.

A: Yesterday, I was able to deploy .war on Tomcat successfully. It went straight into webapps.
But the real issue is that when configuring Jenkins with GlassFish, Jenkins doesn't offer an input field for GlassFish Domain. Hence, compilation ends with BUILD SUCCESSFUL and FINISHED messages, but the application could not be seen in any of the Glassfish domains.


text:
Q: access "implicit" metavar value in argument help string When you call add_argument on an argparse.ArgumentParser() without an explicit action, you get the "store" action. In the auto-generated --help output you get the uppercase of the long option, unless you set metavar:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--version', metavar='X.Y.Z')
parser.add_argument('--date'),
parser.parse_args(['--help'])

displays:
usage: try.py [-h] [--version X.Y.Z] [--date DATE]

optional arguments:
  -h, --help       show this help message and exit
  --version X.Y.Z
  --date DATE

In this I would call X.Y.Z an explicit metavar, and DATE an implicit metavar.
If you want to have more useful help you can do:
parser.add_argument('--version', metavar='X.Y.Z',
                    help = "set version to % (metavar)s")

which gives (only changed lines shown):
  --version X.Y.Z  set version to X.Y.Z

and being able to use that %(metavar)s in the help string is nice because when you change metavar='MAJOR.MINOR', the help doesn't need to be updated (which you are bound to forget).
But if you add the help for the --date argument, with the implicit metavar:
parser.add_argument('--date',
                    help="use %(metavar)s instead of today's date")

you get:
  --date DATE      use None instead of today

And that None is not what I expected, nor what I want.
Of course I can always hard-code 'DATE' in the help, or explicitly provide the metavar (especially when it is used in the help string). But when I do that, I am bound to forget to update the metavar when I change the name of the long option.
Is there an "automatic" way to get DATE in the help string instead of None ?
Or am I using %(metavar)s where I should be using something else (and if so, what)?

A: One thing you can do before calling parser.parse_args() is update those actions added to the parser that have a metavar attribute that is None:
for action in parser._actions:
    if not hasattr(action, 'metavar') or not hasattr(action, 'dest'):
        continue
    metavar = getattr(action, 'metavar')
    if metavar is None:
        action.metavar = action.dest.upper()

That generates output like:
  --version X.Y.Z  set version to X.Y.Z
  --date DATE      use DATE instead of today

But as we say in the BDFL's native language: "mooi is anders" ¹

¹ beautiful looks different

A: It's not going to be easy, at least not within argparse.
When you add_argument it creates an Action class object, and assigns attributes:
 a1 = parser.add_argument('--version', metavar='X.Y.Z')
 a2 = parser.add_argument('--date')

a1.metavar will be 'X.Y.Z', a2.metavar will be the default None.
That's the value that is used in the help line, something like:
`'help %(metavar)`%{'metavar':action.metavar}'

That action.metavar attribute can be modified after creating the Action, as demonstrated in the other answer.
But for the usage and first part of help it does something like:
def _metavar_formatter(self, action, default_metavar):
        if action.metavar is not None:
            result = action.metavar
        elif action.choices is not None:
            choice_strs = [str(choice) for choice in action.choices]
            result = '{%s}' % ','.join(choice_strs)
        else:
            result = default_metavar
        ...

default_metavar is different for positionals and optionals, but basically is derived from action.dest.  So the displayed metavar is generated on the fly, and not stored anywhere.

The %(metavar)s is handled in:
def _expand_help(self, action):
    params = dict(vars(action), prog=self._prog)
    for name in list(params):
        if params[name] is SUPPRESS:
            del params[name]
    for name in list(params):
        if hasattr(params[name], '__name__'):
            params[name] = params[name].__name__
    if params.get('choices') is not None:
        choices_str = ', '.join([str(c) for c in params['choices']])
        params['choices'] = choices_str
    return self._get_help_string(action) % params

vars(action) makes a dictionary from all the attributes of the action.
I can imagine creating a Formatter subclass that modifies one or more of the methods.  The existing subclasses work by modifying just one or two low level methods.  But to do that requires studying the code.

In [329]: p = argparse.ArgumentParser()
In [330]: a1 = p.add_argument('--version', metavar='X.Y.Z')
In [331]: a1
Out[331]: _StoreAction(option_strings=['--version'], dest='version', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar='X.Y.Z')
In [332]: vars(a1)
Out[332]:
{'option_strings': ['--version'],
 'dest': 'version',
 'nargs': None,
 'const': None,
 'default': None,
 'type': None,
 'choices': None,
 'required': False,
 'help': None,
 'metavar': 'X.Y.Z',
 'container': <argparse._ArgumentGroup at 0x7f72ecc4b4a8>}

A help with several parameters:
In [333]: a1.help='help %(metavar)s, %(dest)s, %(required)s'
In [334]: p.print_help()
usage: ipython3 [-h] [--version X.Y.Z]

optional arguments:
  -h, --help       show this help message and exit
  --version X.Y.Z  help X.Y.Z, version, False


text: Q: How were Sine tables made during th Middle Ages? In previous questions during 2014 Ptolemy's chord method was stated to derive their length from angles. However his method was not described. It just stated the equation in modern terms. I have an extensive background in mathematics and was a professional navigator and surveyor during my career. I am writing a paper about Jewish Astronomers of the Middle Ages. I learned that Rabbi Levi ben Gershom (1288 - 1344) constructed sine tables that were correct to the 5th decimal. He was a mathematician and astronomer and he did work in math on series among other things. Therefore I first assumed he made use of the standard method with infinite series for which he would only have needed 3 terms to get this accuracy, however that method seems to have been developed only after his death. Does anyone have an idea how Rabbi Levi ben Gershom (aka Gersonides) calculated his sine values ?


text:
Q: what is the right way to update List view inside widget after changes made in config file i would like to know how to refresh listview inside widget .
on my config file i use
Intent intent = new Intent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(Activity.RESULT_OK, intent);

after you edit the config file .
maybe i can refresh the all widget somehow ?
i guess what i am asking is :
what is the right way to update list after changes made in config file .
note that if i remove the widget and add it again it shows the widget with the new config .
thanks for advance for explaining this issue .

A: You can get the instance of the adapter of the listview and call the notifyDataSetChanged() of the adapter instance.


text:
Q: Is there a tool for listing all the custom exceptions client code can throw I'm interested if there is a tool that could list all the custom exceptions the code, down the call stack, can throw?

A: You can open the Object Browser window in VS with your project open.  Click on View | Object Browser.  In the search bar, type "Exception" and hit enter or click on the magnifying glass.  it will filter the list of objects to include only those that have the word "Exception" somewhere in their fully qualified type name.
Edit:
Upon further inspection, it also returns methods and properties that have the word "Exception" in them, but this is free and while it might return more information that you're after, it doesn't miss anything either.


text:
Q: Как код сделать асинхронным? Как этот код можно выполнить асинхронно, он работает, но синхронно. Ведь я сравнивал по времени выполнения и разницы никакой нет
import asyncio
from selenium import webdriver
import time

def leagues_selection():
    driver = webdriver.Chrome()
    driver.get("https://www.flashscore.com")
    accept = driver.find_element_by_css_selector("#onetrust-accept-btn-handler").click()
    time.sleep(1)
    i = 0
    for country_block in driver.find_elements_by_css_selector(".lmc__block"):
        count = len(block)
        if block.is_displayed():
            block.click()
            i +=1
            print(f"Количество итераций: {i}/{count}")
    driver.close()

async def scraper():
    leagues_selection()

start_time = time.time()
def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(scraper())
if __name__ == '__main__':
    main()
print(f"Время выполнения кода: {time.time() - start_time} сек.")


text:
Q: Xaml Storyboard in a UserControl I have a problem with an animantion of an UserControl.

*

*The animation runs only once.

*If I have multiple instances of my UserControl in another window, the animation is called for every Instance of the UserControl.
<UserControl x:Class="My_UserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Margin="10,10">
    <UserControl.Resources>
        <Storyboard x:Key="CartTicket_Whip">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.LayoutTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)" Storyboard.TargetName="UserControlGrid">
                <SplineDoubleKeyFrame KeyTime="0:0:0.1" Value="-2"/>
                <SplineDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)" Storyboard.TargetName="UserControlGrid">
                <DiscreteBooleanKeyFrame KeyTime="0:0:0.1" Value="True"/>
                <DiscreteBooleanKeyFrame KeyTime="0:0:0.2" Value="False"/>
            </BooleanAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>

    <UserControl.Triggers>
        <EventTrigger RoutedEvent="Button.Click" SourceName="DecrementButton">
            <BeginStoryboard Storyboard="{StaticResource CartTicket_Whip}"/>
        </EventTrigger>
    </UserControl.Triggers>

    <Grid x:Name="UserControlGrid" Height="60">
        <Grid.LayoutTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.LayoutTransform>
        <Grid.Effect>
            <DropShadowEffect ShadowDepth="5" Color="Silver"></DropShadowEffect>
        </Grid.Effect>
        <DockPanel Background="White">
            <Button Name="DecrementButton" DockPanel.Dock="Left" Content="-" FontSize="40" Width="60">
            </Button>
            <TextBlock x:Name="TicketCount" DockPanel.Dock="Left" Text="2 x" VerticalAlignment="Center" HorizontalAlignment="Center"
                       FontSize="20" FontWeight="Bold" Margin="10">
                <TextBlock.Effect>
                    <DropShadowEffect ShadowDepth="4" Color="Silver"></DropShadowEffect>
                </TextBlock.Effect>
            </TextBlock>
            <StackPanel DockPanel.Dock="Left" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5">
                <TextBlock x:Name="TicketName" Text="Ticket type 01" HorizontalAlignment="Center"/>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,10,0,0">
                    <TextBlock x:Name="PriceTxt" Grid.Column="2" Text="100" HorizontalAlignment="Center"/>
                    <TextBlock x:Name="PriceTxt_currency" Grid.Column="2" Text=" EUR" HorizontalAlignment="Center"/>
                </StackPanel>
            </StackPanel>
        </DockPanel>
    </Grid>
</UserControl>

A: You can set the FillBehavior property of your Storyboard to Stop in this way:
<UserControl.Resources>
    <Storyboard x:Key="CartTicket_Whip" FillBehavior="Stop">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.LayoutTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)" Storyboard.TargetName="UserControlGrid">
            <SplineDoubleKeyFrame KeyTime="0:0:0.1" Value="-2"/>
            <SplineDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
        <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)" Storyboard.TargetName="UserControlGrid">
            <DiscreteBooleanKeyFrame KeyTime="0:0:0.1" Value="True"/>
            <DiscreteBooleanKeyFrame KeyTime="0:0:0.2" Value="False"/>
        </BooleanAnimationUsingKeyFrames>
    </Storyboard>
</UserControl.Resources>

I hope it helps.

A: Ok, I got it... sorry it is a dump coincidance! Because I changed the skew of the Grid element, to have a bob up and down effect, the hole usercontrol had this effect.
Now in my window I put five of this UserControls in a Grid, under each other...
So there was the effect, that on every click it seems that evrey UserControl started the animation...
So here the new code, where I make the storyboard for a child element (the dockPanel):
<UserControl x:Class="MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Margin="10,10">
    <UserControl.Resources>
        <Storyboard x:Key="CartTicket_Whip">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)" Storyboard.TargetName="UserControlDockPanel">
                <SplineDoubleKeyFrame KeyTime="0:0:0.1" Value="-1.5"/>
                <SplineDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>

    <UserControl.Triggers>
        <EventTrigger RoutedEvent="Button.Click" SourceName="DecrementButton">
            <BeginStoryboard Storyboard="{StaticResource CartTicket_Whip}"/>
        </EventTrigger>
    </UserControl.Triggers>

    <Grid x:Name="UserControlGrid" Height="60">
        <Grid.LayoutTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.LayoutTransform>
        <Grid.Effect>
            <DropShadowEffect ShadowDepth="5" Color="Silver"></DropShadowEffect>
        </Grid.Effect>
        <DockPanel x:Name="UserControlDockPanel" Background="White" RenderTransformOrigin="0.5,0.5">
            <DockPanel.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </DockPanel.RenderTransform>
            <Button Name="DecrementButton" DockPanel.Dock="Left" Content="-" FontSize="40" Width="60">
            </Button>
            <TextBlock x:Name="TicketCount" DockPanel.Dock="Left" Text="2 x" VerticalAlignment="Center" HorizontalAlignment="Center"
                       FontSize="20" FontWeight="Bold" Margin="10">
                <TextBlock.Effect>
                    <DropShadowEffect ShadowDepth="4" Color="Silver"></DropShadowEffect>
                </TextBlock.Effect>
            </TextBlock>
            <StackPanel DockPanel.Dock="Left" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5">
                <TextBlock x:Name="TicketName" Text="Ticket type 01" HorizontalAlignment="Center"/>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,10,0,0">
                    <TextBlock x:Name="PriceTxt" Grid.Column="2" Text="100" HorizontalAlignment="Center"/>
                    <TextBlock x:Name="PriceTxt_currency" Grid.Column="2" Text=" EUR" HorizontalAlignment="Center"/>
                </StackPanel>
            </StackPanel>
        </DockPanel>
    </Grid>
</UserControl>


text:
Q: Android Webview not rendering correctly on ICS 4.0 + I have a problem with an Android app I am working on.
I loaded a locally stored HTML into a WebView and set:
webSettings.setLoadWithOverviewMode(true);

webSettings.setUseWideViewPort(true);

webSettings.setJavaScriptEnabled(true);

It works great, but just not on ICS 4.0+.
Any ideas what to do?
Here are some screenshots to document the error:

Thanks in advance

A: Give this a try:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_HIGH:
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
    break;

case DisplayMetrics.DENSITY_MEDIUM:
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    break;

case DisplayMetrics.DENSITY_LOW:
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
    break;

default:
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    break;
}

See original post
OR Have you tried this?
WebView webview1 = (WebView) findViewById(R.id.webview1);
webview1.setInitialScale(90);
webview1.loadUrl("http://stackoverflow.com");

A: To me this looks more like a styling issue in your CSS code. Try playing around with the width sizes.
You might want to load a difference css for viewing it on a mobile device.


text:
Q: The library com.google.android.gms:play-services-base is being requested by various other libraries at [[15.0.1,15.0.1]], but resolves to 16.0.1 I see that this is a common issue apparently, but none of the posted solutions work for me. I have checked and all of my play services and firebase libraries are at the latest version.
app/build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "jobquals"
        minSdkVersion 22
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-database:16.0.3'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-core:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

}
//com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
apply plugin: 'com.google.gms.google-services'

build.gradle project:
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I have tried commenting out the dependencies as well, and I get a different error (Unexpected end of ZLIB input stream)

A: Using the latest version of the library works
com.google.firebase:firebase-core:16.0.9
find the latest version frm maven:
https://dl.google.com/dl/android/maven2/index.html

A: Option 1
Downgrade your google service version to 3.2.1
classpath 'com.google.gms:google-services:3.2.1'

Option 2
right after the apply plugin: 'com.google.gms.google-services' at the bottom of your build.gradle the following can be added to work around the issue.
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

A: most likely ...without knowing what might be in the libs directory:
dependencies {
    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation (fileTree(dir: "libs", include: ["*.jar"])) {
        exclude group: "com.google.android.gms"
    }
}

or enforce the version to select:
configurations.all() {
    resolutionStrategy.force "com.google.android.gms:play-services-base:16.0.1"
}


text:
Q: Knockout JS changing my viewmodel creation to use mapping pulgin I am relatively new to Knockout.js and have a question regarding the creating of the view model.
What I am currently doing is:
viewModel = {

                Menu: ko.observableArray(ko.utils.parseJson(data)),

                editMenu: function (menu) {
                    ko.applyBindings(menu, document.getElementById("MenuCategories"));
                    $("#MenuCategories").bPopup();
                }

There is more than one function, but trying to keep it short.
What I want to do is use the mapping plugin because my json data that I am using contains arrays of objects with each object containing an array and each object in that array also contains an array. What the JSON looks like:
[
  {
    "Id": 1,
    "Name": "Test 5",
    "Description": "Testing menu",
    "BeveragesMenu": false,
    "Active": true,
    "Categories": [
      {
        "Id": 1,
        "Name": "Test 1",
        "Active": true,
        "MenuItems": [
        {
          "Id": 1,
          "Name": "Food",
          "Description": "2 Eggs and Bread",
          "Price": 50,
          "DateBased": false,
          "PriceOnRequest": false,
          "DateFrom": null,
          "DateTo": null,
          "Active": true
        }
      ]
    },
    {
      "Id": 2,
      "Name": "Test 2",
      "Active": true,
      "MenuItems": [
        ]
     },
     {
       "Id": 1004,
       "Name": "test",
       "Active": true,
       "MenuItems": [
        ]
     },
     {
       "Id": 1005,
       "Name": "Test 4",
       "Active": true,
       "MenuItems": [
         ]
     }
   ]
 },
 {
   "Id": 92,
   "Name": "Test 4",
   "Description": "",
   "BeveragesMenu": false,
   "Active": false,
   "Categories": [
   {
     "Id": 1006,
     "Name": "Test 1",
     "Active": true,
     "MenuItems": [
     {
       "Name": "Test",
       "Description": "",
       "Price": "",
       "DateBased": false,
       "PriceOnRequest": false
      }
    ]
  }
]
},
{
"Id": 93,
"Name": "Test 6",
"Description": "",
"BeveragesMenu": false,
"Active": false,
"Categories": [

]
},
{
"Id": 94,
"Name": "Test 9",
"Description": "",
"BeveragesMenu": false,
"Active": false,
"Categories": [

]
},
{
  "Id": 95,
  "Name": "Test 20]",
  "Description": "",
  "BeveragesMenu": false,
  "Active": false,
  "Categories": [
  {
    "Id": 4,
    "Name": "Test 6666",
    "Active": true,
    "MenuItems": [

    ]
  }
]
},
{
  "Id": 96,
  "Name": "Test 444",
  "Description": "",
  "BeveragesMenu": false,
  "Active": false,
  "Categories": [
  {
    "Id": 3,
    "Name": "Test 555",
    "Active": true,
    "MenuItems": [

    ]
  },
  {
    "Id": 5,
    "Name": "Test 6666",
    "Active": true,
    "MenuItems": [

    ]
  },
  {
    "Id": 1003,
    "Name": "test 777",
    "Active": true,
    "MenuItems": [

    ]
  }
]
}
]

Sorry for the long JSON code paste.
So now I am running into problems when updating certain parts of the objects within arrays withing objects etc.
So I taught that the mapping plugin might solve my problem as it creates all arrays as observable and I am assuming that is my problem.
So I tried:
viewModel = {
                Menu: ko.mapping.fromJSON(ko.utils.parseJson(data)),
                //Menu: ko.observableArray(ko.utils.parseJson(data)),

                editMenu: function (menu) {
                    ko.applyBindings(menu, document.getElementById("MenuCategories"));
                    $("#MenuCategories").bPopup();
                },

But then none of my binding are working and I can't seem to find the cause, any advice or tips on this matter would be appreciated.
Here is a Fiddle of all the things I have tried. http://jsfiddle.net/armandvdwalt/pjJc2/3/
Thanks

A: Try this fiddle, I switched the order of the resources. You were referencing the mapping plugin before knockout which was generating a script error about not recognizing "ko." Also, you don't need to use ko.utils.parseJson when using fromJSON, as fromJSON expects JSON as an argument.


text:
Q: Volley static callback listeners context GCed After using LeakCanary I found that there were many leaks in my app, most of them due to Volley's anonymous callback listeners. So I wrote a Util (below) class which uses static callbacks and WeakReference to keep reference to Context and an anonymous callback. But when I open the app for the first time, i.e. a cold start, the context is GCed soon after the request is made but during a warm start all works fine. Also this happens only for the first activity in the app.
Any alternative way of handling memory leaks with volley which works properly are also welcome.
public abstract class VUtil {

    public static final String TAG = VUtil.class.getSimpleName();

    public interface JsonCallback {
        void onSuccess(JSONObject response);
    }

    public interface StringCallback {
        void onSuccess(String response);
    }

    public interface ErrorCallback {
        void onError(VolleyError error);
    }

    public static class JsonResponseListener implements Response.Listener<JSONObject> {
        private final WeakReference<Context> mContextWeakReference;
        private final WeakReference<JsonCallback> mCallbackWeakReference;

        public JsonResponseListener(Context context, JsonCallback callback) {
            mContextWeakReference = new WeakReference<>(context);
            mCallbackWeakReference = new WeakReference<>(callback);
        }

        @Override
        public void onResponse(JSONObject jsonObject) {
            Context context = mContextWeakReference.get();
            JsonCallback callback = mCallbackWeakReference.get();
            if (context != null && callback != null) {
                callback.onSuccess(jsonObject);
            } else {
                Log.d(TAG, "Context was GCed");
            }
        }
    }

    public static class StringResponseListener implements Response.Listener<String> {
        private final WeakReference<Context> mContextWeakReference;
        private final WeakReference<StringCallback> mCallbackWeakReference;

        public StringResponseListener(Context context, StringCallback callback) {
            mContextWeakReference = new WeakReference<>(context);
            mCallbackWeakReference = new WeakReference<>(callback);
        }

        @Override
        public void onResponse(String response) {
            Context context = mContextWeakReference.get();
            StringCallback callback = mCallbackWeakReference.get();
            if (context != null && callback != null) {
                callback.onSuccess(response);
            } else {
                Log.d(TAG, "Context was GCed");
            }
        }
    }

    public static class ErrorListener implements Response.ErrorListener {

        private final WeakReference<Context> mContextWeakReference;
        private final WeakReference<ErrorCallback> mCallbackWeakReference;

        public ErrorListener(Context context, ErrorCallback callback) {
            mContextWeakReference = new WeakReference<>(context);
            mCallbackWeakReference = new WeakReference<>(callback);
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Context context = mContextWeakReference.get();
            ErrorCallback callback = mCallbackWeakReference.get();
            if (context != null && callback != null) {
                callback.onError(error);
            } else {
                Log.d(TAG, "Context was GCed");
            }
        }
    }
}

A: GC depends on many many things that are happening. One possible cause for your case is that when you do your first request after a 'cold boot' you app must init various custom objects, fragments, activities, views caches etc. and thus needs memory before increases the heap and thus do a GC.
The solution I propose however is to change your architecture.
1) it seems that u keep ref to context but it is never used. just drop it
2) you have Volley callbacks which delegates to your custom callbacks which you need to pass anyway, why don't you simply use 1 set of callbacks which you pass to the respective requests.
3) you WeekRef your custom callbacks but u cannot do without them. Week Referencing is not the ultimate solution to memory leaks. you have to find out why the ref is still there when you don't need it.
so if you leak issue is in JsonCallback, StringCallback and ErrorCallback implementations just try to figure this out instead of making the chain longer and cutting it at the end.

A: Thanks to djodjo's answer which helped me to reach a solution

*

*Always use addToRequestQueue(request, TAG). Here TAG bit is what we'll use to cancel requests when their Activity/Fragment/View or anything is GCed

*What i did is create a base activity and add all this request cancellation code in that activity. Here's what it looks like
public abstract class BaseActivity extends AppCompatActivity {

    public final String tag;

    public BaseActivity() {
        super();
        tag = getClass().getSimpleName();
    }

    @Override
    protected void onDestroy() {
        App.getInstance().cancelRequests(tag);
        super.onDestroy();
    }

    protected <T> void addToRequestQueue(Request<T> request) {
        App.getInstance().addToRequestQueue(request, tag);
    }

}

cancelRequests is just simple code
getRequestQueue().cancelAll(tag);

Extend your activities from this BaseActivity and use addToRequestQueue to make requests, which will get cancelled automatically when your activity is destroyed. Do similar thing for fragment / dialog / whatever else.
If you make requests from anywhere else which doesn't follow a life-cycle, make sure that it's not binding to any Context and you'll be fine.


text:
Q: Word: How to paste formatting from image to image? Say I have an image A. I paste it to Word, resize it, crop it, make border, change the wrap setting, etc. Then I find picture B will be more suitable.
How can I paste A's formatting from A to B? I don't want to do that again. I use Word 2013

A: As long as nothing too drastic has changed in Word 2013 you can right click on the image and choose "Change Picture" to replace the current picture with a new one while keeping the same formatting.


text:
Q: Touchpad not working in gnome on wayland I am using Gnome desktop with wayland on fedora 37 with kernel version and arch 6.1.6-200.fc37.x86_64.
Touchpad suddenly stopped working after booting the system, it was previously working.
$ libinput list-devices
....

Device:           MSFT0001:01 04F3:3186 Touchpad
Kernel:           /dev/input/event14
Group:            8
Seat:             seat0, default
Size:             100x66mm
Capabilities:     pointer gesture
Tap-to-click:     disabled
Tap-and-drag:     enabled
Tap drag lock:    disabled
Left-handed:      disabled
Nat.scrolling:    disabled
Middle emulation: disabled
Calibration:      n/a
Scroll methods:   *two-finger edge
Click methods:    *button-areas clickfinger
Disable-w-typing: enabled
Disable-w-trackpointing: enabled
Accel profiles:   flat *adaptive
Rotation:         n/a

....

I have enabled the touchpad in gnome settings, but still it is not working.
I tested on various desktop environments but the touchpad is enabled everywhere and still is not working, the device itself is working (checked in windows).
I tried every possible solution but it isn't working.

A: While self (laptop Ubuntu 20.04) does NOT know how this works when my mouse just stops moving, most times (70%?) when I do below mouse re-starts working again.
BTW on some occasions it just does nothing, most times it re-starts, if tried 5 times without success...  command on terminal to re-boot while I take a short break...
sudo fwupdtool get-devices
Using above command re-started my dead mouse

The fwupdmgr is a tool that allows an administrator to query and control
the fwupd daemon, allowing them to perform actions such as installing or
downgrading firmware.


text:
Q: R: Interaction term test among all variables I'm trying to perform interaction test on a dataset with 23 variables. Following is a loop for interaction terms test among all variables, but the code does not retain variable tested before. How to make the correction allowing summary to display interaction among all variable such as xyz rather than xy and yx separately?
vars=colnames(happiness_logper1)[-1]
varHap <- rep(0,100)
for (i in vars)  {
for (j in vars) {
if (i != j) {
varHap= paste(i,j,sep='*')}
lm.fit <- lm(paste("Happiness.in.life ~", varHap), data=happiness_logper1)
     print(summary(lm.fit))
}
  }


text:
Q: Specify a format to store data in rabbitMQ message queue I am using RabbitMQ as message broker and Celery as task queue to process my queue content. Lets take a basic example where we want to add two numbers x and y.
I have created the shared task as :
tasks.py
from celery import shared_task

@shared_task
def add(x, y):
    return x + y

I see when I am pushing the content to the queue, the data is stored as

(myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-02:/etc/myproject# python manage.py shell
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from myproject.tasks import add
>>> add.delay(5, 5)
<AsyncResult: 88f4d5c2-f68a-42c1-acda-d64593df1899>

But instead I would like my data to be stored in a different format like
{operation : 'add', listOfNumbers : [5, 5]}

How can I change the way in which my data is actually getting pushed into the queue? While fetching the same I can get the dictionary and unpack the values and process the same

A: {
    "task": "myapp.tasks.add",
    "id": "54086c5e-6193-4575-8308-dbab76798756",
    "args": [4, 4],
    "kwargs": {}
}


text:
Q: SQL syntax error - incorrect syntax near ' ' I'm using Visual Studio 2012 and have created a simple app. I've created a database called Personnel with a table called Employee. I've worked through all of my syntax errors and the code looks fine, but my form - Form1.cs throws an error when I try to insert data into the database using the form.
After I insert data into the fields - ID, Name, Position and Hourly Pay Rate, then click add, it chokes on the Position field and the error reads whatever I've typed into that field.
For instance, If I enter "Manager" into that form field, the error window reads:
Incorrect syntax near 'Manager'.
Any help here would be greatly appreciated. Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Personnel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'personnelDataSet.Employee' table. You can move, or remove it, as needed.
            this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            SqlConnection cn = new SqlConnection(global::Personnel.Properties.Settings.Default.PersonnelConnectionString);
            try
            {
                string sql = "INSERT INTO Employee (employeeID,Name,Position,HourlyPayRate) values("+txtemployeeID.Text+",'"+txtName.Text+",'"+txtPosition.Text+",'"+txtHourlyPayRate.Text+"')";
                SqlCommand exeSQL = new SqlCommand(sql, cn);
                cn.Open();
                exeSQL.ExecuteNonQuery();

                MessageBox.Show("New record added!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cn.Close();
            }
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            this.employeeTableAdapter.Fill(this.personnelDataSet.Employee);
        }
    }
}

A: Please Read the comments under your post they answered your question.

*

*Your sql syntax is missing a single quote after one of the field
values; Name – Andrew Barber

*SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection – marc_s
Here is how you should adjust your code:
string sql = @"INSERT INTO Employee (employeeID,Name,Position,HourlyPayRate)
              VALUES(@employeeID, @Name, @Position, @HourlyPayRate )";
SqlCommand exeSQL = new SqlCommand(sql, cn);
cn.Open();
cmd.Parameters.AddWithValue("@employeeID", txtemployeeID.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Position", txtPosition.Text);
cmd.Parameters.AddWithValue("@HourlyPayRate", txtHourlyPayRate.Text);
exeSQL.ExecuteNonQuery();

Read up on SqlCommand.Parameters Property
Edit:
AddWithValue is not 100% safe, it is better to be explicit using Add() for example:
cmd.Parameters.Add("@employeeID", SqlDbType.Int).Value = Convert.ToInt32(txtemployeeID.Text);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text;
cmd.Parameters.Add("@Position", SqlDbType.VarChar).Value = txtPosition.Text;
cmd.Parameters.Add("@HourlyPayRate", SqlDbType.Decimal).Value = Convert.ToDecimal(txtHourlyPayRate.Text);

Use the proper SqlDbType Enumeration and convert the values accordingly.

A: Try this one
the single code should be added before and after every respective textbox values
 string sql = "INSERT INTO Employee (employeeID,Name,Position,HourlyPayRate) values('"+txtemployeeID.Text+"','"+txtName.Text+"','"+txtPosition.Text+"','"+txtHourlyPayRate.Text+"')";

A: Seems you should add escape character because values("+txtemployeeID.Text+"... expands in values(Manager,... instead of values("Manager",...


text:
Q: send data in another ViewController I need to pass the class PassengerNavi data server Parse give authorized users. And then write the data to the NSString. And how to get data from PFUser I do not know, I really need help developers)
My ViewController.m file:
    #import <CloudKit/CloudKit.h>
#import <Parse/Parse.h>
#import "PassengerNavi.h"
#import "ViewController.h"
#import "RegistrationConsole.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)authorizationController:(id)sender {
    [PFUser logInWithUsernameInBackground:self.username.text
                                 password:self.password.text block:^(PFUser *user, NSError *error)
     {
         if (!error) {

             PassengerNavi *PassengerViewController = [[PassengerNavi alloc]initWithNibName:@"PassengerNavi" bundle:nil];
             [self presentViewController:PassengerViewController animated:YES completion:nil];
         } else {
             UIAlertView *errorAlertView = [[UIAlertView alloc]initWithTitle:@"British Airways" message:@"Your have Business Class ticket. Please use First Class ticket or contact with British Airways customer center." delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
             [errorAlertView show];
         }
     }];
}

- (IBAction)registrationController:(id)sender {
    RegistrationConsole *RegistrationViewController = [[RegistrationConsole alloc]initWithNibName:@"RegistrationConsole" bundle:nil];
    [self presentViewController:RegistrationViewController animated:nil completion:nil];
}

@end

My PassengerNavi.m:
#import "ViewController.h"
#import <Parse/Parse.h>

@interface PassengerNavi ()

@end

@implementation PassengerNavi

- (void)viewDidLoad {
    [super viewDidLoad];

    [[[[UIApplication sharedApplication] delegate] window] rootViewController];

    PFQuery *test = [PFQuery queryWithClassName:@"_User"];
    [test whereKey:@"google" equalTo:[PFUser currentUser]];
    [test whereKey:@"objectId" equalTo:[NSNumber numberWithInt:1]];
    NSArray *arrayofObjectIds = [test findObjects];

    PFQuery *query = [PFUser query];
    [query whereKey:@"objectId" containedIn:arrayofObjectIds];
    NSArray *followingArray = [query findObjects];
    NSLog(@"%@",followingArray);

    self.clubWorldID = followingArray;

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ba_fc_wallpaper.jpg"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)britishDialler:(id)sender {
    BACalling *CallerViewController = [[BACalling alloc]initWithNibName:@"BACalling" bundle:nil];
    [self presentViewController:CallerViewController animated:YES completion:NULL];
}

- (IBAction)britishMessenger:(id)sender {
    BAMessenger *MessengerViewController = [[BAMessenger alloc]initWithNibName:@"BAMessenger" bundle:nil];
    [self presentViewController:MessengerViewController animated:YES completion:nil];
}

- (IBAction)personalProfileView:(id)sender {
    PersonalProfile *PersonalViewController = [[PersonalProfile alloc]initWithNibName:@"PersonalProfile" bundle:nil];
    [self presentViewController:PersonalViewController animated:YES completion:nil];
}

- (IBAction)aboutSoftwareView:(id)sender {
    AboutSoftware *AboutViewController = [[AboutSoftware alloc]initWithNibName:@"AboutSoftware" bundle:nil];
    [self presentViewController:AboutViewController animated:YES completion:nil];
}

@end

A: Try this code:
SecondViewController *vc = [[SecondViewController alloc] init];
vc.usernameObjectId      = // <-- however you store/produce the value in FirstViewController

After that, push/display/whatever vc.
FYI: It's better to declare an NSString property as:
@property (copy, nonatomic) NSString *...


text:
Q: Want normal back button functionality of browser while loading pages with ajax request I have developing web application in php and used ajax request's to get page from server
example on click of menu tabs ajax request a page from server and load it into a specific HTMl div of index.php . so always all the pages get in index.php specific htmi div.
So on click of browser back button it always remains on default page. how can i enable browser back/forward button functionality so that it will maintain previous page states

A: As mentioned in the comment, the HTML5 History API provides the functionality you're looking for, but if you must support browsers without a guarantee that those browsers will support the History API, take a look at the jQuery BBQ plugin, it'll get you where you need to go.  The important point to remember is that you're going to be using the URL hashtag to record "page loads" that are only really ajax loads.

A: Something like this should do the trick, but I haven't tested:
(function($, window) {
    function supports_history_api() {
        return !!(window.history && history.pushState);
    }

    if (!supports_history_api()) { return; }  // Doesn't support so return

    function swapContent(href) {
        $.ajax({
            url: href,
            cache: false
        }).done(function( data ) {
            var parser = $("#parser"); //Some empty and hidden element for parsing
            parser.html(data);

            var parsed = parser.find(".container").contents(), //Get the loaded stuff
                realContainer = $(".container").first(); //This one wasn't loaded

            realContainer.html(parsed);
            parser.contents().remove(); //Empty the div again
        });
    }

    $(".aTag").on("click", function(e) { //Select the links to do work on
        var href = $(this).attr("href");
        swapContent(href);
        e.preventDefault();
        history.pushState(null, null, href); //Push state to history, check out HTML 5 History API
    });

    window.onpopstate = function() {
        swapContent(location.href);
    };
})(jQuery, window);

Some HTML:

//Loaded content gets pushed here for parsing


text:
Q: In Pandas, is there an elegant way to assign a category to an item based on whether it contains particular strings? I have a .csv file with the following column headers:
Identifier, Date, Task, Category, Person
I want to assign a category or categories to each task, based on whether the task string contains any of a number of substrings, such as:
"met", "fix, "corresp", "particip", "update", "sent", "attend", "help", "assist", "research", "create", "meet, "send", "devel", "source"
I want to write the assigned category(ies) in the 'Category' column for each task in each row.
I've tried several different approaches. For example, I can get the script to indicate whether a substring exists in the task item and return either a Boolean or binary result:
df['Task'].str.contains('work', case=False).fillna(0).astype(int)
or
df['Task'].str.contains('work', case=False).fillna(0)
I can also get it to return a list of the tasks that contain a substring:
df[df > 0]
But I can't get the code to write the category into the Category column. I've tried every approach I could find, but I think I'm missing something straightforward. I was optimistic about the numpy np.where function, but no dice.
Many thanks in advance for your guidance.
import pandas as pd
import numpy as np

df = pd.read_csv('CAPA Tasks.csv')
df.head()

df['Identifier'].is_unique
df = df.set_index('Identifier')
df.head()

df['Task'] = df['Task'].astype(str)

df['Category'] = np.where(['Task'].str.contains('work', case=False), "Work",
         np.where(['Task'].str.contains('corresp', case=False), "Correspond",
                  np.where(['Task'].str.contains('order', case=False), "Order",
                           np.where(['Task'].str.contains('met with', case=False), "Meet",

...
                                                                                np.where(['Task'].str.contains('receive', case=False), "Administration"))))))))))))))))))))

I think I'm failing to convert the task items to strings correctly and am starting to make a mess of my code.
I've also tried iterating through each row with if and elseif, but that didn't work either.
UPDATE: Here's the functioning code, using the second approach suggested by @mohanys:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('CAPA Tasks.csv')

df['Identifier'].is_unique
df = df.set_index('Identifier')

df['Task'] = df['Task'].astype(str)

df['Category'] = np.select([df['Task'].str.contains('work', case=False), df['Task'].str.contains('corresp', case=False), df['Task'].str.contains('met ', case=False), df['Task'].str.contains('share', case=False), df['Task'].str.contains('made', case=False), df['Task'].str.contains('fix', case=False), df['Task'].str.contains('sent', case=False), df['Task'].str.contains('update', case=False), df['Task'].str.contains('set ', case=False), df['Task'].str.contains('stood up', case=False), df['Task'].str.contains('file', case=False), df['Task'].str.contains('worked with', case=False), df['Task'].str.contains('help', case=False), df['Task'].str.contains('print', case=False), df['Task'].str.contains('develop', case=False), df['Task'].str.contains('partici', case=False), df['Task'].str.contains('attend', case=False), df['Task'].str.contains('talk', case=False), df['Task'].str.contains('plan', case=False), df['Task'].str.contains('order', case=False), df['Task'].str.contains('discuss', case=False), df['Task'].str.contains('taught', case=False), df['Task'].str.contains('teach', case=False), df['Task'].str.contains('writ', case=False), df['Task'].str.contains('research', case=False)],["Develop","Correspond","Meet","Provide","Create","Problem Solve", "Provide", "Maintain & Enhance", "Develop", "Meet", "Administer & Document", "Assist", "Assist", "Produce", "Develop", "Participate", "Meet", "Correspond", "Plan", "Order", "Correspond", "Teach", "Teach", "Write", "Research"])
                          ````

A: df.loc[masked_df,'Category'] == 'whatever_you_want'

where masked_df is your boolean result

A: @DerekEden answer
df.loc[masked_df,'Category'] == 'whatever_you_want'

is close, but s/==/= to actually change the 'Category' field.
I had a similar issue where I wanted to make a category field based on arbitrary text in a 'summary' field. This is the answer:
df.loc[df['summary'].str.contains('phishing', case=False),'category']='Phishing'

A: Using np.select looks more organized and readable:
cond_list = [df['Task'].str.contains('within', case=False),
             df['Task'].str.contains('corresp', case=False),
             df['Task'].str.contains('order', case=False),
             df['Task'].str.contains('met with', case=False)]
choice_list = ['Work', 'Correspond', 'Order', 'Meet']

df['Category'] = np.select(cond_list, choice_list)

A: Try this. you are just missing df infront of the column name Task (in every instant)
df['Category'] = np.where(df['Task'].str.contains('work', case=False), "Work",
     np.where(df['Task'].str.contains('corresp', case=False), "Correspond",
              np.where(df['Task'].str.contains('order', case=False), "Order",
                       np.where(df['Task'].str.contains('met with', case=False), "Meet",.....

you can also use np.select instead of np.where like below (shown only for 2 items, you can expand it to as many). This might be easier on the eyes
df['Category'] = np.select([df['Task'].str.contains('work', case=False), df['Task'].str.contains('corresp', case=False)],["Work","Correspond"])


text:
Q: SPSS data restructuring I need to change my SPSS data restructuring from
this
ID1:reading comprehension 1,reading comprehension 2 reading comprehension 3,
ID2:reading comprehension 1,reading comprehension 2 reading comprehension 3,

to
ID1 reading comprehension 1
ID1 reading comprehension 2
ID1 reading comprehension 3

this is the syntax I have tried:
SORT CASES BY ID PunkteT1 PunkteT2 PunkteT3 MW1 MW2 MW3 IMW1 IMW2 IMW3 Vorwissen_T1 Vorwissen_T2
    Vorwissen_T3 Interesse_T1 Interesse_T2 Interesse_T3 UMW1 UMW2 UMW3.
CASESTOVARS
  /ID=ID
  /INDEX=PunkteT1 PunkteT2 PunkteT3 MW1 MW2 MW3 IMW1 IMW2 IMW3 Vorwissen_T1 Vorwissen_T2
    Vorwissen_T3 Interesse_T1 Interesse_T2 Interesse_T3 UMW1 UMW2 UMW3
  /GROUPBY=VARIABLE.

It doesn't work out because of this warnings:

In case 2, an invalid index value was determined. String index values
  can not be empty. Numeric index values must not be negative integers.
  The execution of this command has been stopped.

I already tried to solve this but without any success.
Do you have any ideas?
Thanks,
Kathrin

A: What you have right now are extra variables that you want to turn into cases, so the kind of restructure you need, as @andyW says, is varstocases and not casestovars.
The command will take each set of three variables and turn them into one variable over three cases instead:
varstocases
  /make ReadComp FROM ReadComp1 ReadComp2 ReadComp3
  /make PunkteT from PunkteT1 PunkteT2 PunkteT3
  /make MW from MW1 MW2 MW3
  /make IMW from IMW1 IMW2 IMW3
  /make Vorwissen_T from Vorwissen_T1 Vorwissen_T2 Vorwissen_T3
  /make Interesse_T from Interesse_T1 Interesse_T2 Interesse_T3
  /INDEX=OrigVarOrder.


text:
Q: python fabric no host found must manually set 'env.host_string' Is there any way to get this to work with env.hosts? As opposed to having to loop manually whenever I have multiple hosts to run this on?
I am trying to use the fabric api, to not have to use the very inconvenient and kludgey fabric command line call. I set the env.hosts variable in one module/class and then call a another class instance method to run a fabric command. In the called class instance I can print out the env.hosts list. Yet when I try to run a command it tells me it can't find a host.
If I loop through the env.hosts array and manually set the env.host variable for each host in the env.hosts array, I can get the run command to work. What is odd is that I also set the env.user variable in the calling class and it is picked up.
e.g. this works:
    def upTest(self):
        print('env.hosts = ' + str(env.hosts))
        for host in env.hosts:
            env.host_string = host
            print('env.host_string = ' + env.host_string)
            run("uptime")

output from this:
env.hosts = ['ec2-....amazonaws.com']
env.host_string = ec2-....amazonaws.com
[ec2-....amazonaws.com] run: uptime
[ec2-....amazonaws.com] out:  18:21:15 up 2 days,  2:13,  1 user,  load average: 0.00, 0.01, 0.05
[ec2-....amazonaws.com] out:

This doesn't work... but it does work if you run it from a "fab" file... makes no sense to me.
    def upTest(self):
        print('env.hosts = ' + str(env.hosts))
        run("uptime")

This is the output:
No hosts found. Please specify (single) host string for connection:

I did try putting an @task decorator on the method (and removing the 'self' reference since the decorator didn't like that). But to no help.
Is there any way to get this to work with env.hosts? As opposed to having to loop manually whenever I have multiple hosts to run this on?

A: Finally, I fixed this problem by using execute() and exec.
main.py
#!/usr/bin/env python

from demo import FabricSupport

hosts = ['localhost']

myfab = FabricSupport()
myfab.execute("df",hosts)

demo.py
#!/usr/bin/env python

from fabric.api import env, run, execute

class FabricSupport:
    def __init__(self):
        pass

    def hostname(self):
        run("hostname")

    def df(self):
        run("df -h")

    def execute(self,task,hosts):
        get_task = "task = self.%s" % task
        exec get_task
        execute(task,hosts=hosts)

python main.py
[localhost] Executing task 'hostname'
[localhost] run: hostname
[localhost] out: heydevops-workspace

A: I've found that it's best not to set env.hosts in code but instead to define roles based on your config file and use the fab tool to specify a role. It worked for me
my_roles.json
{
    "web": [ "user@web1.example.com", "user@web2.example.com" ],
    "db": [ "user@db1.example.com", "user@db2.example.com" ]
}

fabfile.py
from fabric.api import env, run, task
import json

def load_roles():
    with open('my_roles.json') as f:
        env.roledefs = json.load(f)

load_roles()

@task
def my_task():
    run("hostname")

CLI
fab -R web my_task
output from running my_task for each of web1 and web2 is here


text:
Q: ESP32-S3 TensorFlow Lite Model Issues I worked with the new ESP32-S3 Development Board and an I2S microphone in order to create a simple voice recognition system. The software and firmware behind this are based on this project: Voice Controlled Robot - Atomic14 https://github.com/atomic14/voice-controlled-robot
This project worked flawlessly on the developer kit so I moved forward and created my own board. This schematic is inspired by the design made by Espressif: ESP32-s3 Dev Kit Schematics https://dl.espressif.com/dl/SCH_ESP32-S3-DEVKITC-1_V1_20210312C.pdf
The flashing works perfectly. I am able to use different code that uses the microphone and record sounds. No issues with programming whatsoever. But when I upload the same code that uses TFLITE (the first provided link), the code uploads, runs, and prints outputs, but the neural network does not process or output anything.
Please note that there are no differences between the code uploaded to my board and the one uploaded to the dev kit (on which everything works as it should).
There are only small differences between the two boards, but everything else (code-wise) works on my board so I am not sure what hardware issue would affect only the neural network.
The ESP32-s3 used in my design is the same one as the one on the dev kit, the only difference is the 16MB Flash in my design and 8MB Flash in the ESP32-s3 dev kit design (smaller flash memory on the board that works with the nn, compared to larger flash on the board that doesn't work with the nn).
-> Could it be a memory problem caused by an incorrectly used capacitor that could create small differences in the voltage that powers the memory?
My schematics design is attached below
ESP32-s3 my PCB design for the voice recognition module


text:
Q: Error checking fopen from argv[i] in C I have been trying to do error checking with my code to make sure that the argument given is a valid file. The following code:
int main(int argc, char *argv[]){
    for(int i = 1, i <=argc, i++){
         FILE *fileIn = fopen(argv[i],"r");
         if(fileIn == NULL){
                fprintf(stderr,"The file %s doesn't exist.",fileIn);
         }
         else if (fileIn != NULL){
             do a bunch of stuff, including printing out values from a struct
         }

The problem I am having is when I run my program I get this as an output:
The (null) file doesn't exist
Output from else if loop

So basically, it is saying that fileIn is null and is not null at the same time. It is reading the file normally and doing it as it should, but it runs through the error each time. Is there any way to assign a pointer to argv[i or something? How is this happening?

A: The code is looping one too many times.  The <= argc is evaluating one more argument than actually exists.  It should be:
for(int i = 1, i < argc, i++){

Also, the printf for the non-existent file should be as follows (it needs the name):
fprintf(stderr,"The file %s doesn't exist.",argv[i]);

A: Change the inequality in
for(int i = 1, i <=argc, i++){

to
for(int i = 1, i < argc, i++){

If argc is 2, then
argv[0] = the program name
argv[1] = the first argument
Also, since you're checking if (fileIn == NULL), you don't need to check again; just use else.


text:
Q: Where does the concept of quantum entanglement originate? A video I watched from PBS spacetime talked about how the pilot wave theory provides an explanation for why quantum entanglement occurs, where it is a result of having global hidden variables. I just want to know if there is an explanation like this in the standard interpretation.
How does quantum mechanics predict quantum entanglement? Does the concept of entanglement come from any mathematical equations?

A: Entanglement arises from the mathematical structure of quantum mechanical states. It is not exclusive to quantum mechanics - here is a non-quantum example of entanglement.
Suppose I have a bag containing $40$ balls. An experiment consists of drawing a ball at random from the bag and then putting it back again. After doing many experiments I know that half the balls in the bag are red and half are blue. I also know that half the balls in the bag are large and half are small. I draw a ball from the bag and it is a red ball. What is the probability that it is also a large ball ?
It is tempting to say $50\%$ since half the balls in the bag are large and half are small. And indeed this is possible; if the bag contains $10$ large red balls, $10$ large blue balls, $10$ small red balls and $10$ small blue balls, then the probability of drawing a red or a blue ball is independent of the probability of drawing a large or a small ball. We could say the bag is a "tensor" product of two separate probability distributions or "states":
$(0.5 \text{ red} + 0.5 \text{ blue}) \otimes (0.5 \text{ large} + 0.5 \text{ small})$
But suppose the bag contains $20$ large red balls and $20$ small blue balls. The probability of drawing a red or blue ball and the probability of drawing a large or a small ball are now interdependent - we could say they are "entangled". There are now no values $p$ and $q$ that will let us write the  contents of the bag as a tensor product
$(p \text{ red} + (1-p) \text{ blue}) \otimes (q \text{ large} + (1-q) \text{ small})$
Quantum entanglement arises in a similar way, although there are several important differences that mean the "bag of balls" analogy is not exact:

*

*The amplitudes in a quantum mechanical state are complex numbers, not real numbers.

*We may not be able to determine the colour and the size of a ball at the same time, because of Heisenberg's uncertainty principle.

*We think there is no exact equivalent of the bag of balls in quantum mechanics, because this would make quantum mechanics a hidden variable theory.


text:
Q: How to slice a np.array using a list of unknown length?
I am probably using the wrong names/notation (and an answer probably exists on SO, but I can't find it). Please help me clarify so that I can update the post, and help people like me in the future.

I have an array A of unknown dimension n, and a list of indexes of unknown length l, where l<=n.
I want to be able to select the slice of A that correspond to the indexes in l. I.e I want:
A = np.zeros([3,4,5])
idx = [1,3]
B = # general command I am looking for

B_bad = A[idx] # shape = (2,4,5), not what I want!
B_manual = A[idx[0], idx[1]] # shape = (5), what I want, but as a general expression.
# it is okay that the indexes are in order i.e. 0, 1, 2, ...

A: You need a tuple:
>>> A[tuple(idx)]
array([0., 0., 0., 0., 0.])
>>> A[tuple(idx)].shape
(5,)

Indexing with a list doesn't have the same meaning. See numpy's documentation on indexing for more information.


text:
Q: mysql trigger with php script I have the next mysql trigger:
DELIMITER @@

CREATE TRIGGER Test_Insert
BEFORE INSERT ON sat_clientLocation
FOR EACH ROW
BEGIN
DECLARE cmd CHAR(255);
DECLARE result int(10);
SET cmd=CONCAT('/usr/bin/php ', '/var/www/html/poi/insertTest.php' , NEW.idLocation);
SET result = sys_exec(cmd);

END;
@@
DELIMITER ;

It's possible to use NEW.idLocation in my php file?
I try some methods, but don't work.

A: According to that solution:
SET cmd=CONCAT('/usr/bin/php ',
               '/var/www/html/poi/insertTest.php?location=' ,
               NEW.idLocation);

That will be passed to your script as $_GET[]  variable:
<?php
echo $_GET['location'];
?>


text:
Q: Ruby Rails 1.9.4-perf Zeus server not working, dies Terminal Output:
joe@peteimac:~
> zeus start
Starting Zeus server
ready   : boot
died    : boot

:After this it doesn't quit, it just seems to hang...
Zeus is like Spork only more so. It lets you load your application in the background so things like tests run really fast. https://github.com/burke/zeus
My colleagues and I are struggling to get it to work. Here is the list of commands you would type on a brand new mac to get to where I am now, though perhaps I missed something?
THE MIGHTY LIST
#The github links below contain guides, this assumes they are followed, with the exception that variables go in .zshrc rather than .zshenv
#Install ZSH | https://github.com/robbyrussell/oh-my-zsh | This means I ditch paths into .zshrc rather than .bash_profile etc
#Install RBENV | https://github.com/sstephenson/rbenv | Colleague using RVM is also having problemos
#Install ruby-build | https://github.com/sstephenson/ruby-build | handy for installing ruby versions
#Continue setting up RBENV and install Bundler | https://gist.github.com/1384279 | Bundler manages the gems, no need for rbenv bundler
# Install patched ruby version using Rbenv and ruby-build | https://gist.github.com/1688857 | "rbenv versions" should show something like:
> rbenv versions
  1.9.3-p194
* 1.9.3-p194-perf (set by /Users/joe/.rbenv/version)
# Rehash
rbenv rehash
# Reload .zshrc, as have added parameters to it following the gist guide for installing 194-perf
exec $SHELL
# Zeus expects a few things, rails should install to ~/.rbenv/versions/1.9.3-p194-perf/bin i think
gem install rails
# The init file Zeus.json mentions cucmber and rspec, so they need to be install globally in rbenv rather than just locally bundled in your projects
gem install cucumber
gem install rspec
rbenv rehash
zeus init
zeus start
# Later, when I get zeus to work globally, I will:
##git pull project_stuff to ~/my_project
cd my_project
rbenv local 1.9.3-p194-perf
bundle install
rbenv rehash
zeus init
zeus start

Also tried rebooting
SOLUTION SUMMARY
This problem was because i was trying to start zeus in the home folder rather than my_project folder. Doing it in there gives a different error though, it hangs. Moved to https://stackoverflow.com/questions/12473539/ruby-rails-1-9-4-zeus-server-hangs-after-zeus-start

A: Does rails server work in the first place?