text:
Q: Is it possible to append lines of code outside a specific function in Python3? I'm trying to fetch the orderbooks of crypto exchanges how support a specific pair (for example ETH/BTC). Because my function needs to run every minute it's very time consuming to check this every time. I'm using ccxt to fetch the orderbooks of the exchanges.
With this lines of code I check every exchange.
import ccxt

binance   = ccxt.binance()
livecoin  = ccxt.livecoin()
kucoin    = ccxt.kucoin()
hitbtc    = ccxt.hitbtc()
kraken    = ccxt.kraken()
crex24    = ccxt.crex24()
okex      = ccxt.okex()

headerList = ["time","type","pair"]

try:
    orderbookBinance = binance.fetch_order_book(self.pair,5)
    headerList.append("binance")
    headerList.append("binanceAmount")
except:
    print("Pair isn't available in binance")

try:
    orderbookLivecoin = livecoin.fetch_order_book(self.pair,5)
    headerList.append("livecoin")
    headerList.append("livecoinAmount")
except:
    print("Pair isn't available in livecoin")

try:
    orderbookKucoin = kucoin.fetch_order_book(self.pair,5)
    headerList.append("kucoin")
    headerList.append("kucoinAmount")
except:
    print("Pair isn't available in kucoin")

try:
    orderbookHitbtc = hitbtc.fetch_order_book(self.pair,5)
    headerList.append("hitbtc")
    headerList.append("hitbtcAmount")
except:
    print("Pair isn't available in hitbtc")

try:
    orderbookKraken = kraken.fetch_order_book(self.pair,5)
    headerList.append("kraken")
    headerList.append("krakenAmount")
except:
    print("Pair isn't available in kraken")

try:
    orderbookCrex24 = crex24.fetch_order_book(self.pair,5)
    headerList.append("crex24")
    headerList.append("crex24Amount")
except:
    print("Pair isn't available in crex24")

try:
    orderbookOkex = okex.fetch_order_book(self.pair,5)
    headerList.append("okex")
    headerList.append("okexAmount")
except:
    print("Pair isn't available in okex")

Now I need to add the first line of all the try-blocks if they can exetude. Is this possible in python?

A: You are taking the wrong approach there.
"Lines of code", just as variable names are supposed to be fixed in the program.
Python's super-dynamic nature would even allow one to "add lines of code", and recompile the module in runtime - but that would be complicated, complex, overkill and subject to a lot of error, when all you need is a staright-forward approach
What you need is to keep the objects that refer to your external exchanges in a data-structure, such as  plain dictionary. Then you just have to iterate over the dictionary to perform the method calls and other actions needed by each of those - and any part of the program can update the dictionary with a simple, ordinary attribution.
import ccxt

exchanges = {}
for exchange_name in "binance livecoin kucoin hitbtc kraken crex24 okex".split():
    exchanges[exchange_name] = getattr(ccxt, exchange_name)()

...
for exchange_name, exchange in exchange.items():
    try:
        orderbook = exchange.fetch_order_book(self.pair,5)
        headerList.append(exchange_name)
        headerList.append(f"{exchange_name}Amount")
    except:
        print(f"Pair isn't available in {exchange_name}")

If in your actual code for some exchanges you need to run different code, just improve the data structure: instead of associating the exchange name directly with the exchange instance, you can create another, inner dictionary, which will contain, in other key/value pairs not only the ccxt exchange instance, but the names of the methods to be called, the parameters to be passed to each, what to check in the response obtained and so on:
The code in your program is fixed! Parts of it can be run depending on configuration data that is present in your data structure.


text:
Q: Error in foreign key constraint of table univ/#sql-bf4_4: I am unable to add a foreign key with a relationship between members and campus tables. The specific fields are set to primary key. The datatypes are also the same.
The tables are:
+------------------+-------------+------+-----+---------+-------+
| Field            | Type        | Null | Key | Default | Extra |
+------------------+-------------+------+-----+---------+-------+
| memberid         | int(11)     | NO   | PRI | NULL    |       |
| lastname         | char(30)    | NO   |     | NULL    |       |
| firstname        | char(30)    | NO   |     | NULL    |       |
| campusaddress    | varchar(30) | NO   |     | NULL    |       |
| campusphone      | int(11)     | NO   |     | NULL    |       |
| campusid         | int(11)     | NO   |     | NULL    |       |
| positionid       | int(11)     | NO   |     | NULL    |       |
| contractduration | int(11)     | YES  |     | NULL    |       |
+------------------+-------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> desc campus;
+----------------+----------+------+-----+---------+-------+
| Field          | Type     | Null | Key | Default | Extra |
+----------------+----------+------+-----+---------+-------+
| campusid       | int(11)  | NO   | PRI | NULL    |       |
| campusname     | char(30) | NO   |     | NULL    |       |
| street         | char(30) | NO   |     | NULL    |       |
| city           | char(30) | NO   |     | NULL    |       |
| state          | char(15) | NO   |     | NULL    |       |
| pin            | int(11)  | NO   |     | NULL    |       |
| phone          | int(11)  | NO   |     | NULL    |       |
| campusdiscount | int(11)  | NO   |     | NULL    |       |
+----------------+----------+------+-----+---------+-------+
8 rows in set (0.00 sec)

ALTER TABLE members add foreign key (campusid) references campus;
ERROR 1215 (HY000): Cannot add foreign key constraint

OR
alter table members add constraint members_campusid_fk foreign key(campusid) references campus;
ERROR 1215 (HY000): Cannot add foreign key constraint

Specific error:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2020-02-10 09:23:38 0x2ccc Error in foreign key constraint of table univ/#sql-bf4_4:
 foreign key (positionid) references position:
Syntax error close to:

It may be something silly,as I'm an expert in making those. Please help!

A: You're so close, there's a slight missing thing which's the primary key column name(campusid) of the parent table (campus). Consider using
alter table members
  add constraint members_campusid_fk
  foreign key(campusid) references campus(campusid)

or constraint members_campusid_fk part ( the name of the constraint ) might be omitted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access methods of an arbitrary view helper by an arbitrary erb file? By convention, Rails only "attaches" the view helper which corresponds to the controller the erb file is called of.
How can I access a view helper's methods of an arbitrary view helper in Rails?

A: If you need to do that, something is wrong with the organization of your code. Instead, move the helper methods that both of your views need into a common module, and include that module in both.
For example, if you have:
module ApplesHelper
  def flavor_of(fruit)
  end
end

and you want /bananas views to have access to the flavor_of method, then do this:
module Flavored
  def flavor_of(fruit)
    # ...
  end
end

module ApplesHelper
  include Flavored
end

module BananasHelper
  include Flavored
end

Update: I realized that I didn't actually answer the original question directly. The way to include another helper in a view is with helper:
class BananasController ...
  helper ApplesHelper
end

Now all /bananas view also have the ApplesHelper methods available to them.

A: If I understood well the question, you have to define your method helper with:
module ControllerHelper
   def function_you_have_to_call
      some_code_here
   end
end

When you want to call your method helper by the *.erb file, you have to insert this in the view:
<% function_you_have_to_call %>

If your method has a return value and you want to store it in an local variable defined in your view, try:
<% value_you_want = function_you_have_to_call %>

Remember the code included by <% %> is only interpreted by ruby and not shown by view. In this case you have to use code included by <%= %>.
Now you can access value_you_want and maybe use for statements.


text:
Q: Undefined $post in wp_query I have a custom post type called resources. On it's post template, I have a widget which will display posts which have the same tags, i.e. If I'm on an article post, the widget will show other articles. To do this, I have the following query:
<?php

$args = array(
    'post_type' => 'resources',
    'category__in'   => wp_get_post_categories($post->ID ),
    'posts_per_page' => 3,
    'post__not_in'   => array($post->ID )
);
$relatedPosts = new WP_Query( $args );

     if( $relatedPosts->have_posts() ) {

        while( $relatedPosts->have_posts() ) {
            $relatedPosts->the_post(); ?>

test

        <?php }

        wp_reset_postdata();
    }

?>

But receiving Undefined variable: post errors. How do I avoid getting this error?

A: The most reliable way to get the current post being viewed is not the global $post variable. Instead you should first check is_singular(), and then use get_queried_object() to get the post object, or get_queried_object_id() to just get the ID.
if ( ! is_singular() ) {
    return;
}

$post_id = get_queried_object_id();

$args = array(
    'post_type'      => 'resources',
    'category__in'   => wp_get_post_categories( $post_id ),
    'posts_per_page' => 3,
    'post__not_in'   => array( $post_id )
);

// etc.


text:
Q: Group level random effect In a lab experiment Participants took part in four different treatment. At the beginning of each session they were randomly assigned to groups of 4 and played repeated public goods game for 30 periods.
So far I have collapsed the data to obtain group averages, so that observation in a period are independent. This data was used to estimate a model with group-level random effects. Since in some groups there were participants whose incentives were different than those of other members of their group, I would like to test whether difference in incentives lead to disparities in behaviour.
Would it be OK for me to split the group average into two observations:

*

*With the decisions made by the "special" individuals

*with the average of 3 others

The same random effect would be assigned to both.

A: Short answer & R Formula
I believe the R code you're looking for is something along the lines of the following, from the lme4 package.
myModel <- lmer(y ~ incentive + (1 | treatGroup/player), data = df)
Basically you're saying that there's a random effect for each player, who is nested inside of a treatment group with a random effect.  In addition, there is a fixed effect for incentive.
Longer answer / explanation
First of all, I personally find the terms "fixed effect" and "random effect" to be confusing and used somewhat inconsistently.  Andrew Gelman (Prof. at Columbia) has a great blog post on the topic.
Model formulation
So in lieu of using those terms, I'll try to write out the (basic) formulation based on what I understand from your question.  In particular, it sounds like we have:

*

*16 players (indexed by $i$)

*30 observations per player (indexed by $j$)

*4 possible groups (indexed by $k$)

*A binary "incentive" treatment $M$, where $m_{i(k)} = 1$ if the $i$-th player receives the incentive

Let $Y_{ij(k)}$ be the $j$-th observation for the $i$-th player, who is placed into the $k$-th group.
With these in mind, our regression model is as follows:
$$Y_{ij(k)} \sim N(\mu_{i(k)}, \sigma^2)$$
$$\mu_{i(k)} = \alpha_i + \alpha_k + \beta \cdot m_{i(k)}$$
Explanation of terms / quick notes
We have a few relevant terms:

*

*$\alpha_i$: The 'baseline' for this player

*$\alpha_k$: the effect of being in the $k$-th group

*$\beta$: The impact of the incentive treatement

Some quick notes:

*

*Using (1 | treatGroup / player) describes a nesting between levels (e.g., each player is in only one treatment group).

*To your point in the comments, 30 observations for each player are assumed to be drawn from a common distribution - Our goal is to estimate the impact of (a) incentives and (b) treatment group on the mean of that distribution.

*This answer assumes no interaction between the incentive and the treatment group.
Additional reading

*

*I used this to refresh my memory on lmer syntax since I'm more accustomed to using rstan (link).

*Skimming this tutorial (I haven't read the whole thing), it looks like a good resource, with an intuitive overview for the beginner!

*Also see this CV post on lmer formula syntax
If you really want to get into this stuff, then Gelman & Hill (2006) is an excellent book.


text:
Q: how can i extract feature by using VGG I want to extract features of my dataset by using VGG16 but when I research I find just how to classify images not how to extract their features.

can anyone help me by sharing an article that can help me, please

A: Just drop the last layer, output = 4096 feature
model = VGG19(input_shape=(224,224,3))
model_new = Model(model.input, model.layers[-2].output)


text:
Q: implementing Issue with ftp server "LIST" I am implementing FTP server,Here making winscp as a client.whenever client sends PASV command to me(server), i am giving reply with ip address and port to client,then client is sending LIST command, then i giving response to client as
150 Opening ASCII mode data connection for file list
-rwxrwxr-x 1 elmpc-162 elmpc-162 17608 Sep 16 12:13 a.out
226 File transfer completed...

These response i am send in second port.
like this but winscp is always showing "8failed to retrieve directory listings**"
but if i see in logs of winscp the data what ever i am sending to client is not present
you can see logs....
. 2020-09-17 16:02:54.408 Username prompt (no username provided)
. 2020-09-17 16:03:00.663 Connecting to 192.168.5.37:5005 ...
. 2020-09-17 16:03:00.663 Connected with 192.168.5.37:5005. Waiting for welcome message...
< 2020-09-17 16:03:00.663 220 Welcome to Alan's FTP site
> 2020-09-17 16:03:00.663 USER srihari
< 2020-09-17 16:03:00.663 331 Password required
> 2020-09-17 16:03:04.064 PASS *****
< 2020-09-17 16:03:04.064 230 Public login sucessful
> 2020-09-17 16:03:04.064 SYST
< 2020-09-17 16:03:04.064 215 AmigaOS
> 2020-09-17 16:03:04.064 FEAT
< 2020-09-17 16:03:04.064 202 Command not implemented, superfluous at this site.
. 2020-09-17 16:03:04.079 Connected
. 2020-09-17 16:03:04.079 --------------------------------------------------------------------------
. 2020-09-17 16:03:04.079 Using FTP protocol.
. 2020-09-17 16:03:04.079 Doing startup conversation with host.
> 2020-09-17 16:03:04.095 PWD
< 2020-09-17 16:03:04.095 257 "/home/elmpc-162/ftp_server"
. 2020-09-17 16:03:04.095 Getting current directory name.
. 2020-09-17 16:03:04.142 Retrieving directory listing...
> 2020-09-17 16:03:04.142 TYPE A
< 2020-09-17 16:03:04.142 200 Switching to ASCII mode.
> 2020-09-17 16:03:04.142 PASV
< 2020-09-17 16:03:04.142 227 Entering Passive Mode (192,168,5,37,23,112)
> 2020-09-17 16:03:04.142 LIST -a
. 2020-09-17 16:03:04.142 Connecting to 192.168.5.37:6000 ...
. 2020-09-17 16:03:19.757 Timeout detected. (data connection)

But in server it is showing client is connected.
here i am not able to find out,why response for LIST is not going
Can any one help me
Here is my code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT1 5013
#define PORT2 6004
#define SA struct sockaddr
#define SA struct sockaddr

char read_buffer[200],write_buffer[200];
char check=0;
void call_second(void);
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
void *first_thread(void *vargp)
{
    printf("in first thread.....\n");
    int sockfd, connfd, len;
    struct sockaddr_in servaddr, cli;

    // socket create and verification
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully created..\n");
    bzero(&servaddr, sizeof(servaddr));

    // assign IP, PORT
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(PORT1);

    // Binding newly created socket to given IP and verification
    if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
        printf("socket bind failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully binded..\n");

    // Now server is ready to listen and verification
    if ((listen(sockfd, 5)) != 0) {
        printf("Listen failed...\n");
        exit(0);
    }
    else
        printf("Server listening..\n");
    len = sizeof(cli);

    // Accept the data packet from client and verification
    connfd = accept(sockfd, (SA*)&cli, &len);
    if (connfd < 0) {
        printf("server acccept failed...\n");
        exit(0);
    }
    else
        printf("server acccept the client...\n");

    //bzero(buffer, 0);
        // sprintf(buffer,"\n220 Welcome to Alan's FTP site \r\n\n");

        //for (;;)
        //write(sockfd, "welcome", sizeof("welcome"));
    // Function for chatting between client and server
    //printf("after writing into sockbuffer ...\n");
    //func(connfd);

    int n,bytes;
    // infinite loop for chat
    for (;;)
    {

        //bzero(buff, MAX);
        memset(read_buffer,0,200);
        memset(write_buffer,0,200);
        sprintf(write_buffer,"\n220 Welcome to Alan's FTP site\r\n\n");
         write(connfd, write_buffer, sizeof(write_buffer));
        printf("come inside..\n");
        // read the message from client and copy it in buffer
        while(1)
        {
        //sleep(1);
        memset(read_buffer,0,200);
        memset(write_buffer,0,200);
        //printf("before reading....\n");
        bytes=read(connfd, read_buffer, sizeof(read_buffer));
        //printf("checking blocking or not..  %s\n",read_buffer);
        if(bytes>0)
        {
        printf("From client:%s%d\n", read_buffer,bytes);
        }
        // if(strstr(buff,"AUTH TLS")||strstr(buff,"AUTH SSL"))
        // {
        //  sprintf(buffer,"\n502 Command not implemented\r\n\n");
        //  write(sockfd, buffer, sizeof(buffer));
        // }
        if (strstr(read_buffer,"USER"))
            {
                printf("Logging in \n");
                sprintf(write_buffer,"331 Password required \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strncmp(read_buffer,"PASS",4)==0)
            {
                printf("Typing password (anything will do... \n");
                sprintf(write_buffer,"230 Public login sucessful \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strncmp(read_buffer,"SYST",4)==0)
            {
                printf("215 AmigaOS \n");
                //sprintf(write_buffer,"215 AmigaOS \r\n");
                sprintf(write_buffer,"215 UNIX emulated by FileZilla \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));

            }
        if (strncmp(read_buffer,"CLNT",4)==0)
            {
                printf("200 Don't care \n");
                sprintf(write_buffer,"200 Don't care \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strncmp(read_buffer,"OPTS UTF8 ON",4)==0)
            {
                printf("202 UTF8 mode is always enabled. No need to send this command. \n");
                sprintf(write_buffer,"202 UTF8 mode is always enabled. No need to send this command. \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strncmp(read_buffer,"FEAT",4)==0)
            {
               printf("211-Features:  \n");
                sprintf(write_buffer,"211-Features: \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                sprintf(write_buffer,"MDTM \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"REST STREAM \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"MLST type*;size*;modify*; \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                // memset(write_buffer,0,sizeof(write_buffer));
                // sprintf(write_buffer,"MLSD \r\n");
                // bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"UTF8 \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"CLNT \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"MFMT \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"CLNT \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"EPSV \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"EPRT \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"211 End \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                memset(write_buffer,0,sizeof(write_buffer));
                printf("211 end:  \n");

            }
        if (strncmp(read_buffer,"PWD",3)==0)
            {
                printf("present working directory \n");
                //  FILE *fpipe;
                 char pwd[100],i=5;
                // char *command = "pwd";
                // char c = 0;

                // if (0 == (fpipe = (FILE*)popen(command, "r")))
                // {
                //  perror("popen() failed.");
                //  exit(EXIT_FAILURE);
                // }
                // strcat(pwd,"257 \"");
                // printf("%s\n",pwd);
                // while (fread(&c, sizeof c, 1, fpipe))
                // {
                //  //printf("%c", c);
                //  pwd[i++]=c;

                // }
                // strcat(pwd,"\" \r\n");
                memset(pwd,0,sizeof(pwd));
                // strcat(pwd,"257 \"/\"\r\n");
                strcat(pwd,"257 \"/home/elmpc-162/ftp_server\" ");
                printf("%s\n",pwd);

                //pclose(fpipe);
                // sprintf(write_buffer,"202 Command not implemented, superfluous at this site. \r\n");
                bytes = write(connfd, pwd, sizeof(pwd));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"TYPE I"))
            {
                printf(" 200 Switching to Binary mode.\n");
                sprintf(write_buffer,"200 Switching to Binary mode. \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"TYPE A"))
            {
                printf(" 200 Switching to ASCII mode.\n");
                sprintf(write_buffer,"200 Switching to ASCII mode. \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"AUTH TLS"))
            {
                printf(" asking AUTHTLS\n");
                sprintf(write_buffer,"502 Explicit TLS authentication not allowed \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"AUTH SSL"))
            {
                printf(" asking AUTHTLS\n");
                sprintf(write_buffer,"502 Explicit TLS authentication not allowed \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"CDUP"))
            {
                printf(" got CDUP command \n");
                sprintf(write_buffer,"457 \"/home\" \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strstr(read_buffer,"CWD"))
            {
                printf(" got CWD command \n");
                sprintf(write_buffer,"457 \"/home/elmpc-162/ftp_server\" \r\n");
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
            }
        if (strncmp(read_buffer,"PASV",4)==0)
            {int a,b;
                //close(sockfd);
                a=PORT2/256;
                b=PORT2%256;
                printf("Entering into passvie mode \n");
                sprintf(write_buffer,"227 Entering Passive Mode (192,168,5,37,%d,%d) \r\n",a,b);
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;
                // check =1;
                   //exit(0);
            }
        if (strstr(read_buffer,"LIST")||strstr(read_buffer,"MLSD"))
            {
sprintf(write_buffer,"150 Transfering... \r\n");
                //printf("%s\n",write_buffer);
                bytes = write(connfd, write_buffer, sizeof(write_buffer));
                if (bytes < 0) break;

                memset(write_buffer,0,sizeof(write_buffer));
                //strcat(pwd,"-rwxrwxr-x 1 elmpc-162 elmpc-162 17608 Sep 16 12:13 a.out \r\n");
                // sprintf(write_buffer,"type=file;modify=20200902093315;size=302; a.cfg \r\n");
                // sprintf(write_buffer,"a.out \r\n");
                // sprintf(write_buffer,"%s",pwd);
                // write(connfd, write_buffer, sizeof(write_buffer));
                call_second();

                memset(write_buffer,0,sizeof(write_buffer));
                sprintf(write_buffer,"226 File transfer completed... \r\n");
                //printf("%s\n",write_buffer);
                write(connfd, write_buffer, sizeof(write_buffer));
                 printf("wrote==%d\n",n);
                memset(write_buffer,0,sizeof(write_buffer));

                check =1;
            }

        // // print buffer which contains the client contents

        }

        n = 0;

    }

    return NULL;
}
void *second_thread(void *vargp)
{
    while(1)
    {
        //printf("dfjhdkfhdf\n");
        // if(check==1)
        // call_second();
    }
}
void call_second(void)
{
    int sockfd_c, connfd_c, len_c;
    struct sockaddr_in servaddr_c, cli_c;

    // socket create and verification
    sockfd_c = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd_c == -1) {
        printf("socket creation failed...2\n");
        exit(0);
    }
    else
        printf("Socket successfully created..2\n");
    bzero(&servaddr_c, sizeof(servaddr_c));

    // assign IP, PORT
    servaddr_c.sin_family = AF_INET;
    servaddr_c.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr_c.sin_port = htons(PORT2);

    // if (connect(sockfd_c, (SA*)&servaddr_c, sizeof(servaddr_c)) != 0) {
    //  printf("connection with the server failed...\n");
    //  exit(0);
    // }
    // else
    //  printf("connected to the server..\n");

    // Binding newly created socket to given IP and verification
    if ((bind(sockfd_c, (SA*)&servaddr_c, sizeof(servaddr_c))) != 0) {
        printf("socket bind failed...2\n");
        exit(0);
    }
    else
        printf("Socket successfully binded..2\n");

    // Now server is ready to listen and verification
    if ((listen(sockfd_c, 5)) != 0) {
        printf("Listen failed...2\n");
        exit(0);
    }
    else
        printf("Server listening..2\n");
    len_c = sizeof(cli_c);

    // Accept the data packet from client and verification
    connfd_c = accept(sockfd_c, (SA*)&cli_c, &len_c);
    if (connfd_c < 0) {
        printf("server acccept failed...2\n");
        exit(0);
    }
    else
        printf("server acccept the client...2\n");

    char buff[MAX];
    int n;
    // infinite loop for chat
    //while(1)
    {
     if(check==1)
    {

                check =1;

                FILE *fpipe;
                int k=0;
                 char pwd[1500];int i=0;

                char *command = "ls -l";
                char c = 0;
                memset(pwd,0,sizeof(pwd));

                if (0 == (fpipe = (FILE*)popen(command, "r")))
                {
                    perror("popen() failed.");
                    exit(EXIT_FAILURE);
                }

                while (fread(&c, sizeof c, 1, fpipe))
                {
                    //printf("%c", c);
                    k++;
                    if(k>9)
                    pwd[i++]=c;

                }
                // printf("pwd==%s\n",pwd);
                k=0;

                memset(write_buffer,0,sizeof(write_buffer));
                // strcat(pwd,"-rwxrwxr-x 1 elmpc-162 elmpc-162 17608 Sep 16 12:13 a.out1 \r\n");
                // strcat(pwd,"-rwxrwxr-x 1 elmpc-162 elmpc-162 17608 Sep 16 12:14 a.out2 \r\n");
                // strcat(pwd,"-rwxrwxr-x 1 elmpc-162 elmpc-162 17608 Sep 16 12:15 a.out3 \r\n");
                sprintf(write_buffer,"%s",pwd);
                write(connfd_c, write_buffer, sizeof(write_buffer));

                sleep(3);

     check=0;

    }
    }
    // After chatting close the socket
    close(sockfd_c);
    printf("closed second connection...\n");
}

int main()
{
    pthread_t thread_id1,thread_id2;
    printf("Before Thread\n");
    pthread_create(&thread_id1, NULL, first_thread, (void *)&thread_id1);
    //pthread_join(thread_id1, NULL);
    pthread_create(&thread_id2, NULL, second_thread, (void *)&thread_id2);
    //pthread_join(thread_id2, NULL);
    printf("After Thread\n");
    pthread_exit(NULL);
    //exit(0);
}

A: . 2020-09-17 16:03:04.142 Connecting to 192.168.5.37:6000 ...
. 2020-09-17 16:03:19.757 Timeout detected. (data connection)

The client is unable to establish a data connection to the server. Given that the error is a Timeout and not a Connection refused I suspect that there is a firewall between client and server (or on the server) which is blocking the access (dropping the traffic). But, since there is nothing reproducible in your question (like code and server setup) this is only an educated guess.

A: Most FTP servers have a setting called IP masquerade that has to be configured to the public IP address if the FTP sever is sitting behind NAT.
this response "227 Entering Passive Mode (192,168,5,37,23,112) " should be sending the public IP address and the port forwarding on the server side has to be configured to establish the connection


text:
Q: Need explanation about LINQ GroupJoin syntax I am not strong in LINQ but I am trying to get familiar with GroupJoin
In the following code, which I am trying to understand
var result = authors.GroupJoin(books,
                               author => author.AuthorId,
                               book => book.AuthorId,
                               (author, booksByAuthor) =>
                                new { Author = author.Name, Books = booksByAuthor });

which was rewritten from this join into code
var result = from a in authors
             join b in books on a.AuthorId equals b.AuthorId into booksByAuthor
             select new { Author = a.Name, Books = booksByAuthor };

I am confused by the syntax in the GroupJoin. I understand that the tables authors is joined with books, but what is the meaning of the next few lines?
For example, what is the meaning of author => author.AuthorId, book => book.AuthorId? Is these two lines the equivalent of
on a.AuthorId equals b.AuthorId

?
And what is the meaning of this line:
(author, booksByAuthor) => new { Author = author.Name, Books = booksByAuthor }

I can read/understand the Join into statement but having some difficulties with the GroupJoin. Thanks.

A: Probably you get confused because the two examples use different aliases for one and the same things. So let fix that:
var result = from a in authors
             join b in books on a.AuthorId equals b.AuthorId into booksByAuthor
             select new { Author = a.Name, Books = booksByAuthor };

and
var result =
    // authors join books
    authors.GroupJoin(books,
    // on a.AuthorId equals b.AuthorId
    a => a.AuthorId, b => b.AuthorId,
    // select new { Author = a.Name, Books = booksByAuthor }
    (a, booksByAuthor) => new { Author = a.Name, Books = booksByAuthor }
);

Hope that helps.


text:
Q: data encoding for JSON.parse( ) unexpected token I am pulling down some data from my server and manipulating it and then trying to load the string into an object using JSON.parse(). However whenever I try to do it I get an Unexpected Token  error. The weird thing is that usually chrome tells me what the unexpected token is (usually 'o' or something). This time it is just a space. Which makes me think that there is some type of ascii encoding error or something going on. If I print the json string to the console doing console.log() and then paste it directly into the code then it has no problem parsing the string.
 var testString = '[ { "pk": 1663, "state": "IO", "group": "ALO", "species": "", "application_link": "" } ]';
var testObject = JSON.parse(testString);
alert(testObject);

Works exactly how I expect it to. But this doesn't:
function hex2ascii(hexx) { //stolen off stackoverflow
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

function decodeData(encoded){
    var original_string = '';
    for (var i = 0; i < encoded.length; i+=2) {
        var index = i/2;
        var hex_value = encoded[i]+encoded[i+1];
        var ochar = hex2ascii(hex_value);
        original_string += ochar;
    }
    return original_string;
}
$.get(url, function(data) {
     var testString = decodeData(data); //decodeData grabs a hex string and then decodes it into a json formatted string
    var testObject = JSON.parse(testString); //Unexpected Token
    alert(testObject);
});

Anybody have any ideas on how to go about troubleshooting this?
Edit:
I don't know why but I have a bunch of null's in my string. When I iterate through the json string and convert it back to hex I get:
hex_string = ''
for(var i = 0; i < decoded_data.length; i++){
    if (i < 10){
        alert(decoded_data[i]);
    }
    hex_string += ascii2hex(decoded_data[i])+' ';
}
console.log(hex_string);

>>>0 0 5b 0 0 7b 0 0 22 0 0 70 0 0 6b 0 0 22 0 0 3a 0 0 20 0 0 31 0 0 36 0 0 36 0 0

Edit again:
Ok so I have pinned it down to my concatenation method. For some reason in the decodeData function when I concatenate it together doing
original_string += ochar;

It's throwing in a bunch of null characters. Is there another way to concatenate the string together?
Edit answer:
Ok, so the problem lied within the hex2ascii function. It was adding in a bunch of null characters. It was code I stole off of stack overflow and wasn't what I expected. I ended up changing it to this and now it's golden.
function hex2ascii(hexx) {
   var hex = hexx.toString();//force conversion
   return String.fromCharCode(parseInt(hex, 16));
}

A: you could not juz input break line in javascript string, it will make it invalid.
Invalid
var testString = '[ {
        "pk": 1663,
        "state": "IO",
        "group": "ALO",
        "species": ""
]}';

Valid
var testString = '[ {"pk": 1663,"state": "IO","group": "ALO","species": ""]}';

A: I think that the reason you are getting an Unexpected Token error is because you have that extra close parenthesis on the line that says
$.get(url, function(data)) {

and you are missing a parenthesis at the end.

A: Ok, so the problem lied within the hex2ascii function. It was adding in a bunch of null characters. It was code I stole off of stack overflow and wasn't what I expected. I ended up changing it to this and now it's golden.
function hex2ascii(hexx) {
   var hex = hexx.toString();//force conversion
   return String.fromCharCode(parseInt(hex, 16));
}


text:
Q: Copying Cygwin symlinks through Windows Explorer won't make them working Given two paths with the same content:
D:\dir1\file1
D:\dir1\symlink1-to-file1

D:\dir2\file1
D:\dir2\symlink1-to-file1

If I create D:\dir2\symlink1-to-file1 by windows-copying it from D:\dir1\symlink1-to-file1, the link won't work and the file command will output :
D:\dir2\symlink1-to-file1: data

Why ?

A: Check file attribute with CMD command attrib
https://cygwin.com/cygwin-ug-net/using.html#pathnames-symlinks

if the default plain file symlink type is lacking its DOS SYSTEM bit,
  or if the shortcut file is lacking the DOS READONLY attribute, they
  are not recognized as symlink.

A: This is not a bug in Cygwin but in copy/paste function of the Windows Explorer

*

*moving the folder will keep the symlink as is

*copy/paste the symlink will destroy the symlink

and it happens with symlinks created with cmd /C mklink too not only cygwin
few solutions exist for this:
Windows 7 / Symlinks - How do I copy a Symlink to a directory?
Gui solution:

*

*Download Link Shell Extension

*Run "C:\Program Files\LinkShellExtension\LSEConfig.exe" and change
the "Outer Junction/Symbolic Link" setting to "Splice".

*Right-click the folder you want to copy and click "Pick Link Source"

*To paste the folder click "Drop As: Smart Copy" , or mirror.

CLI solution:
I found only two solutions that works:
ln - command line hardlinks
this is not the ln you know in cygwin but other thing, made by the same creator of Link Shell Extension, download it from here
ln.exe --splice --backup --mirror source_dir  destination_dir

strarc
link, this was made by the same creator of the well known ImDisk, and is suggested by most of people

strarc may be used to copy a complete directory tree from one NTFS
volume to another, including all special attributes of NTFS such as
security information, permissions, ownership, auditing settings etc.

Say you have a directory called C:\dir and you want to copy it to D:\dirbk. Because strarc as default archives to stdout and extracts from stdin you can type as follows:
strarc -cjd:C:\dir | strarc -xd:D:\dirbk -w:8

NTFS in Windows 2000 and later has an option to create "reparse
points" of empty directories. The implementation involves a "reparse
data block" which specifies which filesystem filter should handle the
reparse point and some parameters to the filter about what the
specific reparse point should do. Windows 2000 natively supports e.g.
"junction" and "remote storage" type reparse points. The "junction"
type is actually a link to another native path, very much like a
symbolic link to a directory path on Unix filesystems. Volume mount
point directories use this method to make the mount point directory
actually redirect to the target filesystem. When backing up a
filesystem with reparse point you have two options. Without special
switches strarc follows the reparse points as a normal application
would do. That could be what you want in many cases, but if the
directory tree you are archiving have e.g. junctions pointing to
directories above the junction in the tree (making an infinitely deep
directory tree) or junctions pointing to other filesystems etc you may
want to backup the reparse points themselves instead of the
directories they are pointing to. To select the second method, use the
-j switch to strarc.

rsync
the well known rsync in cygwin is not a solution, because it changes symlinks to a different thing, read about how symlinks work in cygwin in this nice article
Robocopy
Robocopy is used normally for this and suggested by a lot of articles, but few people know that robocopy is full of bugs and should not be used:

*

*serious robocopy bug (robocopy vulnerable to symlink attack) link

*robocopy doesn't create symlinks when using /sl and /b together, when
invoked again it will copy at least a file's flags again link

*Robocopy corrupting deduplicated volume link
Who would have thought that such a simple thing like copy a folder needed all this...


text:
Q: ASP.NET cookies in Mobile and Tablet PC Funny problem has occurred... I'm developing ASP.NET Web site and there is one issue, which I can't explain. I've tried to google it, but no success.
Main problem is: I've defined a button exit for users and I'm using session, which uses cookies ( I'm using such mechanism of the session, because cookieless session won't allow users from one external IP address to authorize at my server, that's why I'm using it to allow users to use my website from one external IP, but if they have different internal IPs ) mechanism.
So on PC I can exit from website and cookies values are cleaning.
But my friend have tried to access website from Android on his smartphone and iPad.
All works fine except exit function. He said, that from PC all works, but from iPad or Android phone he can't exit. He authorizes in website, can do all things, which he can on PC, but can't exit.
I wonder, what could appear, that exactly from iPad/Android smartphone it's impossible to exit.
Any suggestions?
PS, piece of code:
void btnQuit_Click(object sender, ImageClickEventArgs e)
{
    string[] myCookies = Request.Cookies.AllKeys;

    foreach (string cookie in myCookies)
    {
        Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
    }

    Response.Redirect("Default.aspx");
}


text:
Q: Does asp.net core kestrel need to run on https in production? I am potentially planning to run asp.net core on linux behind an apache reverse proxy.
when running the asp.net core does it need to be running on https?
I can set apache https directive as follow - and when i access this from the browser it is working fine.
ProxyPass / http://127.0.0.1:5000/
ProxyPassReverse / http://127.0.0.1:5000/
ServerName app.domain.com
ServerAlias *.app.domain.com
ErrorLog ${APACHE_LOG_DIR}helloapp-error.log
CustomLog ${APACHE_LOG_DIR}helloapp-access.log common

Are there any issues with this?

A: In my opinion, if you has enabled the https on the apache and just use http redirect between the apache and the kestrel server, you could use http. Like this:
Brower --->https ---> Apache --> http ---> kestrel.
This will not causing the security issue. HTTPS helps prevent intruders from tampering with the communications between your websites and your users' browsers. Since if someone hack your server to capture the http request, he could also get your server's all information.


text:
Q: RAILS - SCOPE WITH 2 TABLES RAILS - SCOPE FILTER THROUGH 2 TABLES
Hi, I'm new to Rails and I'm using Translate to post here.
I have the scenario below:
Ata_Public -> Ata_Object -> Products
How can I set up a filter to select all Ata_publics through the category_id inside Products?
         scope :filter_category, -> (params) {
           params[:category_id].present? ?
             joins(:ata_objects)
             .joins(:products)
             .where("ata_objects.products.category_id = ?", params[:category_id])
           :
             all
         }

I'm doing it this way, but I don't have the expected result.
What should my scope look like?
Relationships are right.
clarifying, inside the Ata_Public model, I'm creating this scope: filter_category, to pass the ID and list only the minutes that have the product with this category_id.
https://i.stack.imgur.com/V0I0s.png

A: This should work:
scope :filter_category, -> (params) {
  joins(ata_objects: :products).where(
    products: { category_id: params[:category_id] }
  ) if params[:category_id].present?
}


text:
Q: Android Studio: Minimum working example how to download expansion files I've looked at quite some many sources that try to explain how to download / extract / use expansion files in Android such as  a) this stackoverflow question or b) this official documentation, but I'm still struggling with getting my app to download the expansion files.
Does someone have a minimum working example, how I can download and expansion file from inside my existing app?
Regarding the two sources given above:
a) I copied all the helper libraries to my project as described, but I would still need a minimum toy example how to download the expansion files now.
b) In section Starting the download point 3 it gives an example how to modify my onCreate method to start the download. However I'm not sure how to adapt it:
@Override
public void onCreate(Bundle savedInstanceState) {
    // Check if expansion files are available before going any further
    if (!expansionFilesDelivered()) {
    // Build an Intent to start this activity from the Notification
    Intent notifierIntent = new Intent(this, MainActivity.getClass());
    notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                            Intent.FLAG_ACTIVITY_CLEAR_TOP);
    ...
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Start the download service (if required)
    int startResult =
        DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
                    pendingIntent, SampleDownloaderService.class);
    // If download has started, initialize this activity to show
    // download progress
    if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
        // This is where you do set up to display the download progress
        //...
        // Instantiate a member instance of IStub
        mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
                SampleDownloaderService.class);
        // Inflate layout that shows download progress
        setContentView(R.layout.downloader_ui);
        return;
    } // If the download wasn't necessary, fall through to start the app
    }
    startApp(); // Expansion files are available, start the app
}

I'm not sure about the interface downloader_ui that should show the downloading progress. What should be the content of downloader_ui? Is this an activity that pops up ontop of my app and closes after finishing the download?
The startApp() is also meaningless in my case, since I'm already in the onCreate method of my app. Rather I would need my app to wait until the download is finished and then continue with the rest of the onCreate method...
Sorry for editing my question that much, but the problem is evolving ;)


text:
Q: Only numbers as keyboard input for ipad I have to display a number pad as keyboard for a textfield (it can take only numerals) in case of ipad.setting keyboard type as UIKeyboardTypeNumberPad displays numeric keyboard but user can switch back to alphabets.Is there any keyboard for ipad that just displays numbers?

A: You would have to create your own keyboard to accomplish this.

A: Use the input type "number"
<input type="number" />

or failing that use a validation pattern which only accepts numbers.
<input type="text" pattern="[0-9]*" />

Both of these should bring up the num pad on iPhones and bring up the iPad keyboard with the numbers exposed (amongst the other keys)

A: You could get calculator app with open source code and use their keypad code, or do what I did. Made my own by coding the buttons you want and displaying them how you want eg in a square like a calculator. By using on click event to update a numeric variable. Eg multiply the last entered integer by 10 and add the new integer supplied by the on click code. Ie press button 2 and var = 2. Press another 2 and the var is multiplied by 10 and new var is added , to give 22 . Etc


text:
Q: Item Response Theory vs Confirmatory Factor Analysis I was wondering what the core, meaningful differences are between Item Response Theory and Confirmatory Factor Analysis.
I understand that there are differences in the calculations (focusing more on item vs. covariances; log-linear vs. linear).
However, I have no idea what this means from a higher-level perspective - does this mean that IRT is better than CFA in some circumstances? Or for slightly different end-purposes?
Any musings would be useful as a scan of the research literature led to more a description of IRT and CFA than any useful comparison of the core differences between them.

A: @Philchalmers answer is on point, and if you want a reference from one of the leaders in the field, Muthen (creator of Mplus), here you go:
(Edited to include direct quote)

An MPlus user asks: I am trying to describe and illustrate current
  similarities and differences between binary CFA and IRT for my thesis.
  The default estimation method in Mplus for categorical CFA is WLSMV.
  To run an IRT model, the example in your manual suggests to use MLR as
  the estimation method. When I use MLR, is the data input still the
  tetrachoric correlation matrix or is the original response data matrix
  used?
Bengt Muthen responds: I don't think there is a difference between CFA
  of categorical variables and IRT. It is sometimes claimed but I don't
  agree. Which estimator is typically used may differ, but that's not
  essential. MLR uses the raw data, not a sample tetrachoric correlation
  matrix.  ... The ML(R) approach is the same as the "marginal ML (MML)"
  approach described in e.g. Bock's work. So using the raw data and
  integrating over the factors using numerical integration. MML being
  contrasted with "conditional ML" used e.g. with Rasch approaches.
Assuming normal factors, probit (normal ogive) item-factor relations,
  and conditional independence, the assumptions are the same for ML and
  for WLSMV, where the latter uses tetrachorics. This is because those
  assumptions correspond to assuming multivariate normal underlying
  continuous latent response variables behind the categorical outcomes.
  So WLSMV only uses 1st- and 2nd-order information, whereas ML goes all
  the way up to the highest order. The loss of info appears small,
  however. ML doesn't fit the model to these sample tetrachorics, so
  perhaps one can say that WLSMV marginalizes in a different way. It's a
  matter of estimator differences rather than model differences.
We have an IRT note on our web site:
http://www.statmodel.com/download/MplusIRT2.pdf
but again, the ML(R) approach is nothing different from what's used in
  IRT MML.

Source:
http://www.statmodel.com/discussion/messages/9/10401.html?1347474605

A: I believe Yves Rosseel discusses it briefly in slides 91-93 of his 2014 workshop:
http://www.personality-project.org/r/tutorials/summerschool.14/rosseel_sem_cat.pdf

Taken from Rosseel (2014, link above):

Full information approach: marginal maximum likelihood

origins: IRT models (eg Bock & Lieberman, 1970) and GLMMs

...

the connection with IRT

•  the theoretical relationship between SEM and IRT has been well documented:

Takane, Y., & De Leeuw, J. (1987).  On the relationship between item response theory and factor analysis of discretized variables. Psychometrika, 52, 393-408.

Kamata, A., & Bauer, D. J. (2008). A note on the relation between factor analytic and item response theory models.  Structural Equation Modeling, 15, 136-153.

Joreskog, K. G., & Moustaki, I. (2001). Factor analysis of ordinal variables: A comparison of three approaches. Multivariate
Behavioral Research, 36, 347-387.

when are they equivalent?

•  probit (normal-ogive) versus logit: both metrics are used in practice

•  a single-factor CFA on binary items is equivalent to a 2-parameter IRT model (Birnbaum, 1968):

In CFA: ...   In IRT: ...  (see slide)

•  a single-factor CFA on polychotomous (ordinal) items is equivalent to the graded response model (Samejima, 1969)

•  there is no CFA equivalent for the 3-parameter model (with a guessing parameter)

•  the Rasch model is equivalent to a single-factor CFA on binary items, but where all factor loadings are constrained to be equal (and the probit metric is converted to a logit metric)

A: In some ways you are right, CFA and IRT are cut from the same cloth. But it many ways they are quite different as well. CFA, or more appropriately item CFA, is an adaption of the structural equation/covariance modeling framework to account for a specific type of covariation between categorical items. IRT is more directly about modeling categorical variable relationships without using only first- and second-order information in the variables (it's full information, so its requirements generally aren't as strict).
Item CFA has several benefits in that it falls within the SEM framework, and therefore has very wide application to multivariate systems of relationships to other variables. IRT, on the other hand, primarily focuses on the test itself, though covariates can also be included in the test directly (e.g., see topics on explanatory IRT). I've also found that item modeling relationships are far more general in the IRT framework in that non-monotonic, non-parametric, or just plain customized item response models are easier to cope with because one doesn't have to worry about the sufficiency of using the polychoric correlation matrix.
Both frameworks have their pros and cons, but in general the CFA is more flexible when the level of modeling abstraction/inference is focused on the relationship within a system of variables, while IRT is generally preferred if the test itself (and items therein) are the focus of interest.


text:
Q: Neo4j webadmin panel not opening I downloaded neo4j community version for linux and installed successfully. The neo4j server is also running. i am not able to open web admin panel
(http://localhost:7474/webadmin/).

I searched for answers in google groups and stack overflow and uncommented the
    org.neo4j.server.webserver.address =0.0.0.0

line in neo4j.server.properties file. But still i am not able to connect to webadmin panel. I am stuck in it. Any help would be appreciated. Dont mark it as duplicate and ignore it as i have referred all the previous questions on this.


text:
Q: Avoiding deadlocks in bidirectional communication between goroutines I am making my first experiences in Go, and so far I really like the goroutine and channels construct. I am wondering if there is an idiomatic way to avoid deadlocks in bidirectional communication between multiple goroutines. Consider the following example. There are three goroutines: producer, worker and controller.

*

*The producer produces integers. In reality this could be data coming
from a network connection for example.

*The worker receives data from the producer and does some operation on
it. Then, the worker directs the modified data to the controller.

*The controller sends a command to the worker in some cases. In the
example this would happen if the received integer is bigger than 180.
The deadlock happens when the controller tries to send a command to the worker, while the worker tries to send an integer to the controller.
producerToWorker := make(chan int)
workerToController := make(chan int)
controllerToWorker := make(chan bool) // bool represents a command for this example

// Worker
go func() {
    for {
        select {
        case i := <-producerToWorker:
            // Do some processing and send to controller
            workerToController <- (2 * i) + 1
        case <-controllerToWorker:
            // Would react to the command here
        }
    }
}()

// Controller
go func() {
    for {
        select {
        case i := <-workerToController:
            fmt.Println(i)
            if i > 180 {
                // Send a command to the worker
                controllerToWorker <- true
            }
        }
    }
}()

// Producer
for {
    producerToWorker <- rand.Intn(100)
}

Example output:
163
175
95
113
1
189 // No deadlock
23
125
179
57
149
23
91
191 // No deadlock
133
95
175
177
181 // No deadlock
17
175
63
27
181 // Deadlock!
fatal error: all goroutines are asleep - deadlock!

Buffering the channels would make this deadlock more unlikely, but not solve it logically. I would like to avoid mutexes if possible. How do you handle such situations in Go?
Edit: To give a more real-world description: I came across this problem when I tried to implement a websocket client. The websocket client (worker) connects to an external service (producer) and receives messages from it (producerToWorker) and passes them to the controller (workerToController) to handle the received messages. The controller needs to react to the received messages, for example send a response or disconnect the client when an invalid message is received (controllerToWorker).

A:
[Is there ]an idiomatic way to avoid deadlocks in bidirectional communication between multiple goroutines?

No. Nothing "idiomatic" or based on a "pattern".

How do you handle such situations in Go?

You redesign. Concurrent circular data flow is best avoided.


text:
Q: StopWatch vs Timer - When to Use Forgive me for this question, but I can't seem to find a good source of when to use which. Would be happy if you can explain it in simple terms.
Furthermore, I am facing this dilemma:
See, I am coding a simple application. I want it to show the elapsed time (hh:mm:ss format or something). But also, to be able to "speed up" or "slow down" its time intervals (i.e. speed up so that a minute in real time equals an hour in the app).
For example, in Youtube videos (* let's not consider the fact that we can jump to specific parts of the vid *), we see the actual time spent in watching that video on the bottom left corner of the screen, but through navigating in the options menu, we are able to speed the video up or down.

And we can actually see that the time gets updated in a manner that agrees with the speed factor (like, if you choose twice the speed, the timer below gets updated twice faster than normal), and you can change this speed rate whenever you want.

This is what I'm kinda after. Something like how Youtube videos measure the time elapsed and the fact that they can change the time intervals. So, which of the two do you think I should choose? Timer or StopWatch?
I'm just coding a Windows Form Application, by the way. I'm simulating something and I want the user to be able to speed up whenever he or she wishes to. Simple as this may be, I wish to implement a proper approach.

A: As far as I know the main differences are:
Timer

*

*Timer is just a simple scheduler that runs some operation/method once in a while

*It executes method in a separate thread. This prevents blocking of the main thread

Timer is good when we need to execute some task in certain time interval without blocking anything.
Stopwatch

*

*Stopwatch by default runs on the same thread

*It counts time and returns TimeSpan struct that can be useful in case when we need some additional information

Stopwatch is good when we need to watch the time and get some additional information about how much elapsed processor ticks does the method take etc.

A: This has already been covered in a number of other questions including
here. Basically, you can either have Stopwatch with a Speed factor then the result is your "elapsed time". A more complicated approach is to implement Timer and changing the Interval property.


text:
Q: Copy operator not working in Quick Fast C++ Now currently I am working on copy operator. What I understand from all the document and other material available on net is that Quickfast maintains a dictionary which is used by multiples entries  within a UDP message to check the previous value.
eg:  Lets say in the below given template we can have multiple MDEntries depending upon NoMDEntries tag value. Lets say we have 2 as the value .
What I did was ,  I put the value of MDEntryType (with copy oprerator ) as 1 (some random value)  in the first entry, but for the second entry I did not put any value.
After I decode the message the value of MDEntryType should be 1 for both the entries.
Is my understanding correct ?

<template dictionary="1" id="1" name="MDIncRefreshSample_1">
 <string id="35" name="MessageType">
    <constant value="X"></constant>
 </string>     <string id="49" name="SenderCompID">
    <constant value="Client"></constant>
</string>     <string id="56" name="TargetCompID">
    <constant value="Server"></constant>
</string>     <uint32 id="34" name="MsgSeqNum"></uint32>
<uint64 id="52" name="SendingTime"></uint64>
<sequence name="MDEntries">
    <length id="268" name="NoMDEntries"></length>
    <uint32 id="279" name="MDUpdateAction">
        <copy value="1"></copy>
    </uint32>
    <string id="269" name="MDEntryType">
        <copy value="0"></copy>
    </string>
    <uint32 id="278" name="MDEntryID"></uint32>
    <uint32 id="48" name="SecurityID">
        <delta></delta>
    </uint32>
    <decimal id="270" name="MDEntryPx">
        <exponent>
            <default value="-2"></default>
        </exponent>
        <mantissa>
            <delta></delta>
        </mantissa>
    </decimal>
    <int32 id="271" name="MDEntrySize">
        <delta></delta>
    </int32>
    <string id="37" name="OrderID"></string>
    <uint32 id="273" name="MDEntryTime">
        <copy></copy>
    </uint32>
 </sequence>
 </template>

Now when I try to implement the above in my code, I am not able to copy the value in the second entry.
Here is the snippet of the code I used (help  taken from testRoundTrip.cpp)
Template Created :

  <templates>
    <template dictionary="InstrumentReferenceData"
     name="InstrumentReferenceData" id="3">
     <typeRef name="instrumentreferencedata"/>
     <uInt32 name="timestamp" id="52"> <delta/>    </uInt32>
     <uInt32 name="srcId" id="50">      <copy/>    </uInt32>
     <uInt32 name="seqNum" id="34">      <increment value="1"/>    </uInt32>
     <uInt32 name="isix" id="48">      <delta/>    </uInt32>
    <string name="isin" id="455">      <delta/>    </string>
    <string name="exchId" id="207">      <copy/>    </string>
    <string name="instGrp" id="1151">      <copy/>    </string>
    <string name="instTypCod" id="461">      <copy/>    </string>
    <string name="currCode" id="15">      <copy/>    </string>
    <decimal name="ticSiz" id="969">      <delta/>    </decimal>
    <uInt32 name="setId" id="TBD">      <copy/>    </uInt32>
     <sequence name="MDFeedTypes">
     <length name="noOfStreams" id="1141"/>
     <string name="streamType" id="1022">      <copy dictionary="template" />
    </string>
    <string name="streamService">      <copy/>      </string>
     <string name="inetAddr">        <delta/>      </string>
  <uInt32 name="port" id="TBD">        <delta/>      </uInt32>
  <uInt32 name="mktDepth" id="264" presence="optional"/>   </uInt32>
  <uInt32 name="mdBookType" id="1021" presence="optional"/>   </uInt32>
    </sequence>
    </template>
    </templates>

Message creation plus encoding and decoding:  (I have poulated the value in streamtype field only once)
 Messages::MessagePtr msg(new Messages::Message(templateRegistry->maxFieldCount()));
  msg->addField(identity_timestamp, Messages::FieldUInt32::create(1));

  msg->addField(identity_srcId, Messages::FieldUInt32::create(2));

  msg->addField(identity_seqNum, Messages::FieldUInt32::create(3));

  msg->addField(identity_isix, Messages::FieldUInt32::create(4));

  msg->addField(identity_isin, Messages::FieldAscii::create("isin"));

  msg->addField(identity_exchId, Messages::FieldAscii::create("exchId"));

  msg->addField(identity_instGrp, Messages::FieldAscii::create("instGrp"));

  msg->addField(identity_instTypCod, Messages::FieldAscii::create("instTypCod"));

  msg->addField(identity_currCode, Messages::FieldAscii::create("currCode"));

  msg->addField(identity_ticSiz, Messages::FieldDecimal::create(Decimal(123, -1)));

  msg->addField(identity_setId, Messages::FieldUInt32::create(5));

  lengthIdentity.setId("1141");
  Messages::SequencePtr sequence_MDFeedTypes(new Messages::Sequence(lengthIdentity, 2));
  Messages::FieldSetPtr entry(new Messages::FieldSet(6)); // todo Hardcoded 6?

  entry->addField(identity_streamType, Messages::FieldAscii::create("streamType"));    // Populated the value 1st time

  entry->addField(identity_streamService, Messages::FieldAscii::create("streamService"));

  entry->addField(identity_inetAddr, Messages::FieldAscii::create("inetAddr.com"));

  entry->addField(identity_port, Messages::FieldUInt32::create(2222));

  entry->addField(identity_mktDepth, Messages::FieldUInt32::create(10));

  sequence_MDFeedTypes->addEntry(Messages::FieldSetCPtr(entry));

  entry.reset(new Messages::FieldSet(6));

  entry->addField(identity_streamType, Messages::FieldAscii::create(""));     // Did not Populate the value 2nd time

  entry->addField(identity_streamService, Messages::FieldAscii::create(""));

  entry->addField(identity_inetAddr, Messages::FieldAscii::create("inetAddr.org"));

  entry->addField(identity_port, Messages::FieldUInt32::create(2224));

  entry->addField(identity_mdBookType, Messages::FieldUInt32::create(3));

  sequence_MDFeedTypes->addEntry(Messages::FieldSetCPtr(entry));

  msg->addField(identity_MDFeedTypes, Messages::FieldSequence::create(sequence_MDFeedTypes));

  Codecs::Encoder encoder(templateRegistry);
  Codecs::DataDestination destination;
  template_id_t templId = 3; // from the XML above
  encoder.encodeMessage(destination, templId, *msg);
  std::string fastString;
  destination.toString(fastString);
  std::cout<<"fastString is "<<fastString<<std::endl;

  destination.clear();

  Codecs::Decoder decoder(templateRegistry);
  Codecs::DataSourceString source(fastString);
  Codecs::SingleMessageConsumer consumer;
  Codecs::GenericMessageBuilder builder(consumer);
  decoder.decodeMessage(source, builder);

  Messages::Message & msgOut(consumer.message());

        Messages::MessageFormatter formatter(std::cout);
        formatter.formatMessage(msgOut);                                   // I have made some printing changes to print the ouptut per tag

  validateMessage1(msgOut);

  encoder.reset();
  encoder.encodeMessage(destination, templId, msgOut);
  std::string reencoded;
  destination.toString(reencoded);

  destination.clear();

I am able to encode and successfully decode the message, but the value is not getting copied in the second entry (streamType tag).
Here is my decoded ouput:
 1st entry:
 streamType[1022]=streamType
 streamService[]=streamService
 inetAddr[]=inetAddr.com
 port[TBD]= 2045

 2nd entry:
streamType[1022]=                     //value not copied
streamService[]=
 inetAddr[]=inetAddr.org
 port[TBD]= 2046

Could you please let us know, if we are making a mistake somewhere. I am very new to this :)
I have following queries too :
1/ Do we need to explicitly need to enable/disable dictionary in quickfast ? (In FIX we could do that with flag, DataDictionary = Y/N).
Also  in the template created above , I found this line:
<string name="streamType" id="1022">      <copy dictionary="template" />      </string>

Is it neccesary to give dictionary name while using operators and how are they related?
2/ Do we also need to explicitly mention that PMAP bits are required?
Codecs::PresenceMap pmap(1);     // I came across this function, so I got this doubt whether  we need to explicitly mention about pmap.


text:
Q: Crystal reports remove variable substrings I am trying to remove HTML style tags from my Crystal report text. I have data like the below:
hello worldhello again world
hello once again

I want the result to be:
hello worldhello again world
hello once again

I've used:
replace({IncidentNarrative.text},ExtractString(Totext({IncidentNarrative.text}),""),"")
replace({IncidentNarrative.text},ExtractString(Totext({IncidentNarrative.text}),"
"),"")

But this will only remove the first instance of the span or p. It does not look for all instances of the span or p. I've tried FOR loops and extracting the sub-strings into arrays, but always run into problems.

A: The following formula looks for the term style= and removes it and everything between style= to the next occurence of >:
StringVar output := {IncidentNarrative.text};

While InStr(output, " style=")>0 And InStr(InStr(output, " style=")+7, output, ">")>0 Do
(
    output := Left(output, InStr(output, " style=")-1) &
                Mid(output, InStr(InStr(output, " style=")+7, output, ">"))
);

output;


text:
Q: sprintf throws warning with % in string I am using sprintf on some html that contains a table:
<table width="100%"....

It seems that % symbol is causing warnings.  How do I properly escape that character?
Doing
<table width="100%%"....

Strips the trailing " as well as the % symbol giving me
<table width="100 border="0"...

A: You need to escape it with another %:
<table width="100%%"....


text:
Q: In C#, how an method can be called on a possibly null instance? I was wondering, using an hypothetic IsNullOrEmpty() method on a List instance (not in .NET Framework), if the instance is effectively null, it will throw an Object reference not set to an instance of an object exception, or something like this.  Considering this, is it possible to call a method on a null instance?

A: Extension methods can take a null "this" parameter.  I don't know of any method IsNullOrEmpty for a List in the Framework, but imagine it would be implemented something like:
public bool IsNullOrEmpty<T>(this IList<T> list)
{
    if (list == null) return true;
    return list.Count == 0;
}

You can call this (or any other) extension method on a null reference without any problem:
List<int> nullList = null;
if (nullList.IsNullOrEmpty())
{
    ...
}

A: AFAIK IsNullOrEmpty is only a method of class System.String, and is not available for List. It is a static method, not an extension method. you call like this:
string.IsNullOrEmpty(text);

and not like this
text.IsNullOrEmpty();

Therefore there is no problem checking whether the reference is not set to the instance of an object or not.

A: There isn't an IsNullOrEmpty() for a List only String. In the latters case it's a static method so doesn't need an instance, you pass in a string reference to check and it can check for null there.

A: It is a static method that takes the instance of the string in question as parameter.
public static bool IsNullOrEmpty(
    string value
)

http://msdn.microsoft.com/en-us/library/system.string.isnullorempty%28v=vs.110%29.aspx
There is not IsNullOrEmpty method in BLC defined for List
You could create an extension method easily:
namespace System
{
    public static class StringExtensions
    {
        public static bool IsNullOrEmpty(this string s)
        {
            return string.IsNullOrEmpty(s);
        }
    }
}

A: As has been pointed out, there is no such method for lists. Easy enough to write an extension method, however:
public static bool IsNullOrEmpty<T>(this IList<T> list)
{
     return (list == null || list.Count == 0);
}

If you want to throw an exception for nulls:
public static bool IsEmpty<T>(this IList<T> list)
{
    if (list == null)
        throw new ArgumentNullException("list");

    return (list.Count == 0);
}

A: There is no List<T>.IsNullOrEmpty() in the CLR.
However, perhaps someone wrote an extension method for List. It would look something like this:
public static class ListExt
{
    public static bool IsNullOrEmpty<T>(this List<T> self)
    {
        return (self == null) || (self.Count == 0);
    }
}

If so, you can see from the implementation that you can safely pass null for the self parameter. That would happen with this code:
List<int> lint = null;

if (lint.IsNullOrEmpty())
{
    // ...

This calls the extension method passing lint to it; in this case, it passes null and the (self == null) check in the implementation will cause false to be returned, and will prevent any NullReferenceException from being thrown.

A: IsNullOrEmpty() doesn't support for a List it's only for String.Following is the implimentaion of IsNullOrEmpty from msdn.
result = s == null || s == String.Empty;

If you want to check the list you can write your own extension method to do that as following.
  public static bool IsNullOrEmpty<T>(this ICollection<T> collection)
    {
        if (collection == null)
            return true;

        return collection.Count == 0;
    }


text:
Q: Setting up ReactJS in windows 10 giving error i am new reactjs. i want to setup for react js in windows 10 when i install react displaying some following error

npm ERR! Windows_NT 10.0.10240
      npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"
      npm ERR! node v6.9.5
      npm ERR! npm  v3.10.10
      npm ERR! path C:\Users\username\package.json
      npm ERR! code ENOENT
      npm ERR! errno -4058
      npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\username\package.json'
      npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\username\package.json'
      npm ERR! enoent This is most likely not a problem with npm itself
      npm ERR! enoent and is related to npm not being able to find a file.
      npm ERR! enoent
npm ERR! Please include the following file with any support request:
      npm ERR!     C:\Users\username\npm-debug.log

A: From the error it seems like that the directory from where you are trying to install react using npm install -S react doesn't contain package.json file. You will need to set up your project with package.json to install react in a local directory. To do that, run the command
npm init

and follow the instructions
In case you want to install globally, you can run
npm install -g react

A: Run npm install from the same directory as the project's package.json
e.g. if the package.json is at
C:\users\josh\myproject\package.json
then you need to run npm install from inside the myproject folder


text:
Q: can't figure out serving static images in django dev environment I've read the article (and few others on the subject), but still can't figure out how to show an image unless a link to a file existing on a web-service is hard-coded into the html template.
I've got in urls.py:
...
(r'^galleries/(landscapes)/(?P<path>.jpg)$',
    'django.views.static.serve', {'document_root': settings.MEDIA_URL}),

...

where 'landscapes' is one of the albums I'm trying to show images from. (There are several more of them.)
In views.py it calls the template with code like that:
...

...

which resolves the image link in html into:
http://127.0.0.1:8000/galleries/landscapes/160.jpg

In settings.py I have:
MEDIA_ROOT = 'C:/siteURL/galleries/'
MEDIA_URL = 'http://some-good-URL/galleries/'

In file system there is a file C:/siteURL/galleries/landscapes/160.jpg and I do have the same file at http://some-good-URL/galleries/landscapes/160.jpg
No matter what I use in urls.py — MEDIA_ROOT or MEDIA_URL (with expectation to have either local images served or from the web-server) — I get following in the source code in the browser:

There is no image shown in the browser.
What am I doing wrong?

A: This looks buggy...:
r'^galleries/(landscapes)/(?P<path>.jpg)$'

this RE will only match image names with a single character begore the jpg suffix, not four (as in, e.g., '160.jpg').  Maybe you meant...
r'^galleries/(landscapes)/(?P<path>.*jpg)$'

...?

A: This is a long post, basically summarizing all the things I learned about Django in order to get static files to work (it took me a while to understand how all the different parts fit together).
To serve static images in your development server (and later, your real server), you're going to have to do a few things (note specifically the third and fourth steps):
Set MEDIA_ROOT
MEDIA_ROOT is a constant which tells Django the physical path of the file (on your filesystem). Using your example, MEDIA_ROOT needs to be set to 'C:/siteURL/galleries/', like you wrote. MEDIA_ROOT is going to be used in one of the following steps, which is why we set it.
Set MEDIA_URL
MEDIA_URL is the "url" at which your images sit. In other words, whenever you want to get an image, the url to look for starts with MEDIA_URL. Usually this is not going to start with "http", since you're serving from your own server (my MEDIA_URL is usually set to '/site_media/', meaning to start from the root domain, then go to site_media etc.)
Use MEDIA_URL
MEDIA_URL doesn't work by magic, you actually have to use it. For example, when you're writing the HTML which gets a file, it needs to look like this:

See how I'm telling the template to use the MEDIA_URL prefix? That eventually translates to 'http://some-good-URL/galleries/160.jpg'.
Note that to be able to actually use the MEDIA_URL in your templates, you're going to have to add the line 'django.core.context_processors.media' to your TEMPLATE_CONTEXT_PROCESSORS setting in your settings.py file, if I'm not mistaken.
Make your dev server serve static files
In a real environment, you will configure files with addresses like "static_media" to be served without going through Django. But in a dev environment, you'll want to server them from Django as well, so you should add this generic line to the end of your urls.py file:
if settings.DEBUG:
# Serve static files in debug.
urlpatterns += patterns('',
    (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': settings.MEDIA_ROOT,
    'show_indexes' : True}),
)

Note how that takes anything with the url "site_media/*" (which is actually my MEDIA_URL) and serves it from my MEDIA_ROOT folder, which is the place where the MEDIA_ROOT setting comes into play.
Final note
What confused me is that a lot of the things here are for convenience. For example, MEDIA_ROOT is only used in your debug url pattern, to tell Django where to load from. And MEDIA_URL is only  there to encourage you not to put in absolute URLs in all your HTML files, because then when you decide to move the files to a different server, you'd have to manually change them all (instead of just changing the MEDIA_URL constant).
Of course, none of this is necessary: you can hard-code the debug url patter with your own folder, make sure that the static files really are being server from the url (by visiting it in your browser), and then hand-code that without using the MEDIA_URL setting into the HTML file, just to make sure things work.

A: Take this as a cross between the two previous answers, both of which are good. First, your regex is incorrect as Alex pointed out. I would suggest setting it as:
   (r'^local_media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), # static content

Because you're probably going to want to server css and js files too, not just images. This regex takes care of any and every static file you might want to serve.
Next, you'll want to specify the MEDIA_URL for your img tags. You currently have:

Instead, it needs to be something like:

The trick I use is easy. At the top of my views.py, I have the following code:
from django.conf import settings
resp = {}
resp['MEDIA_URL'] = settings.MEDIA_URL

and then I just pass the resp dictionary to every template I render. Now I can write those same img tags as:

Best of all, this part of your code can be used in production as well (not the regexes, just the MEDIA_URL bit).


text:
Q: Add and Remove Strikethrough of TextView Android Hello guys I'm having an issue putting strikethrough in my textview. This is what I'm doing right now:
  private void initControls() {

    tvNote = (TextView) findViewById (R.id.textView1);
    tvNote.setVisibility(View.GONE);

    fillData();

}

private void fillData() {

      dbConnect();

      // Array list of sync data items
      ArrayList<SyncDataItems> itemList = new ArrayList<SyncDataItems>();

      List<Todos> todos = dbHelper.getAllTodos();

      SyncDataItems _items;

      for (Todos cn : todos) {
          String log = "ID: " + cn.getID() + " , Todo: " + cn.getTodo();
          Log.e("Todo List ", log);
          _items = new SyncDataItems(cn.getTodo(), cn.getTodo(), true);
          itemList.add(_items);
      }

      dataAdapter = new MyCustomAdapter(this, R.layout.item_info, itemList);
      listView = (ListView) findViewById(R.id.listView1);
      // Assign adapter to ListView
      listView.setAdapter(dataAdapter);

      if(dataAdapter.getCount() == 0) {
          tvNote.setVisibility(View.VISIBLE);
          tvNote.setText("No Records Yet");
      }

}

  private class MyCustomAdapter extends ArrayAdapter<SyncDataItems> {

      private ArrayList<SyncDataItems> itemList;

      public MyCustomAdapter(Context context, int textViewResourceId,

      ArrayList<SyncDataItems> itemList) {
       super(context, textViewResourceId, itemList);
           this.itemList = new ArrayList<SyncDataItems>();
           this.itemList.addAll(itemList);
      }

      private class ViewHolder {
           TextView code;
           CheckBox name;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {

            holder = null;

            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {

                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                convertView = vi.inflate(R.layout.item_info, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);

                convertView.setTag(holder);

                holder.name.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        SyncDataItems _item = (SyncDataItems) cb.getTag();

                        _item.setSelected(cb.isChecked());

                        holder.name.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                if ( isChecked ) {
                                    Log.e("TAG", "Checked!");
                                    holder.code.append("Checked!");
                                    holder.code.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                } else {
                                    holder.code.setPaintFlags(holder.code.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
                                    Log.e("TAG", "Unchecked!");
                                }
                            }
                        });

                    }
                });

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final SyncDataItems item = itemList.get(position);

            holder.code.setText(item.getItem());
            holder.name.setChecked(item.isSelected());

            holder.name.setTag(item);

            return convertView;
        }

}

But the strikethrough effect is not working when I check or uncheck the checkbox. any ideas? Your help will be truly appreciated. Thanks.

A: You can use :
holder.code.setPaintFlags(tv.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));

A: On Checked, change
holder.code.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

to
holder.code.setPaintFlags(holder.code.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

it should work.

A: shortest way to remove strike through any text which is part of some view
tvNote.setPaintFlags(0);


text:
Q: MediaWiki removed MathJax. Can MathJax be forced on client side another way? Much to my displeasure, MediaWiki has recently disabled support for MathJax (ticket: T99369) rendering of TeX formulae wikipedia-wide.
Since me (and others, if you skim the ticket's discussion thread) find the rendering with the remaining options (MathML, PNG) inferior, I would like to "slipstream" MathJax into Wikipedia.
Since loading further JavaScript files directly via the custom JavaScript settings in Wikipedia does not seem possible using <script> elements, I am at a loss on how to achieve this feat. Would it be, MathJax could be included via CDN most easily.
I am using current Edge and Firefox browsers, so any solution working with one or both of them would be greatly appreciated!

Meanwhile, I found Greasemonkey for Firefox, which might be able to accomplish this, given a suitable script. Since I am neither a Greasemonkey-, nor a JavaScript-expert, any hint on how to proceed to write such a script would be helpful.

A: It appears that GreaseMonkey scripts to use client-side MathJax are now listed in the MathJax docs.
Updated from there:
// ==UserScript==
// @name           MathJax in Wikipedia
// @namespace      http://www.mathjax.org/
// @description    Insert MathJax into Wikipedia pages
// @include        https://*.wikipedia.org/wiki/*
// ==/UserScript==

// replace the images with MathJax scripts of type math/tex
if (window.MathJax) throw "MathJax already loaded!";
var imgs = document.querySelectorAll('.mwe-math-fallback-image-inline')
if (!imgs.length) throw "no matches!";
imgs.forEach((img) => {
    var script = document.createElement("script");
    script.type = 'math/tex';
    script[window.opera ? 'innerHTML' : 'text'] = img.alt;
    img.parentNode.replaceChild(script, img);
})
// Load MathJax and have it process the page
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.mathjax.org/mathjax/2.7-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full';
document.querySelector('head').appendChild(script);

A: As a registered user, you can do the following:
Under user preferences => appearance, switch on the "MathML with SVG or PNG fallback" mode. (The other two modes require a slightly different script but imho that mode is the best option right now.)
Next edit your user specific scripts page at https://en.wikipedia.org/wiki/User:YOURHANDLE/common.js [Don't forget to change user name!] and add the following custom script to it:
// add to User:YOURNAME/common.js to get smooth MathJax rendering
var mathTags = $('.mwe-math-mathml-a11y');
if (mathTags.length > 0){ //only do something when there's math on the page
  window.MathJax = { //hook into MathJax's configuration
    AuthorInit: function () {
      MathJax.Hub.Register.StartupHook("End",function () { //when MathJax is done...
        MathJax.Hub.Queue(
            function(){
             mathTags.removeClass('mwe-math-mathml-a11y'); // .. make the span around MathML (now MathJax output) visible
             $('.mwe-math-fallback-image-inline').addClass('mwe-math-mathml-a11y'); //hide fallback images
            }
        );
      });
    }
  };
  mw.loader.load('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=MML_HTMLorMML-full');//load MathJax with a suitable combined config file
}

This script loads MathJax only when there's math in the page, renders it, and (when rendering its done) replaces the fallback images with the results.
This way, you have very little jitter. From a quick test this seems to work on Chrome 43, Firefox 39, IE8 and Edge, and WebKit 2.6.2 (so should work on Safari).


text:
Q: How big do squares need to be to fit a box, tesselating, with minimal remainder? A geometry question that I feel utterly defeated by. I'm trying to design a responsive user interface that efficiently fits a variable number of square elements on a screen, by adjusting the size of the squares. With a known square size, the number of squares along and up will be implicit. I'm also very interested to know the answer.
I describe the problem as thus:
A known number of squares, n, must be fit as efficiently as possible (least remaining area) into a rectangle of known dimensions x & y. The dimension (equal width and height) of the squares, s, must be adjusted to achieve this. The squares must be axis-aligned. Find s.
All I've been able to establish is that where n/(w/h) is an integer, n + 1 is a worst case scenario of remainder. I can't seem to get any more facts to come out in the wash, but am interested in the working of the answer.
Update:
I've worked out (I hope), the maximum number of squares that may be fit, as follows:
max squares =
( floor( longest side / shortest side ) * divisor^2 ) +
( floor( r / ( shortest side / divisor ) ) * divisor )

Based on fitting squares with a size of the shortest side of the rectangle, dividing them down by the divisor (iteratively until enough squares are achieved), each time seeing how much of the remainder can be occupied by the divided down dimension.
Now I just need to turn this into a single formula so it doesn't have to be computed iteratively, if possible.

A: I'm decently sure this can be accomplished by simply adding the largest possible square i.e. has the minimum of width or height as side length.  put square on side of rectangle and you end with a rectangle demension $x$ and $y-x$ without loss of generality.  then simply repeat until either there's no remainder or your out of number of squares.


text:
Q: always download sources (and javadocs) from maven ant task I am trying to get this ant-based project's init target to download all the sources and javadocs.
I added the following to my ~/.m2/settings.xml (as per Maven – Always download sources and javadocs) but it doesn't force source downloads when used from ant:
<profiles>
    <profile>
      <id>downloadSources</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <downloadSources>true</downloadSources>
      </properties>
    </profile>
 </profiles>

The only way I could get the sources to download was by hacking build.xml so that all <artifact:dependencies> elements include sourcesFilesetId="sources.dependency.fileset", but this is a pretty distasteful commit that is unlikely to be accepted by the maintainers. A better solution would exist with a property file definition, preferably in the user's settings (not something that mutates the project definition)
Is there a simpler way to ensure that all the sources (and potentially javadocs) are globally downloaded in maven ant tasks?


text:
Q: Why function pointer address is printing in bool type in c++? From the below code snippet I am getting the address of the function is 1. why ?
#include<iostream>
using namespace std;
int  add(int x, int y)
{
  int z;
  z = x+y;
  cout<<"Ans:"<<z<<endl;
}

int main()
{
  int a=10, b= 10;
  int (*func_ptr) (int,int);
  func_ptr  = &add;
  cout<<"The address of function add()is :"<<func_ptr<<endl;
  (*func_ptr) (a,b);
}

A: Function pointers aren't convertible to data pointers. You'd get a compiler error if you were to try and assign one to a void* variable. But they are implicitly convertible to bool!
That is why the bool overload for operator<< is chosen over the const void* one.
To force the overload you want, you'd need to use a very strong C++ cast, that will almost completely ignore the static type information.
#include<iostream>
using namespace std;
int  add(int x, int y)
{
  int z;
  z = x+y;
  cout<<"Ans:"<<z<<endl;
}

int main()
{
  int a=10, b= 10;
  int (*func_ptr) (int,int);
  func_ptr  = &add;
  cout<<"The address of function add()is :"<< reinterpret_cast<void*>(func_ptr) <<endl;
  (*func_ptr) (a,b);
}

Note that casting and treating function pointers as data pointers is only conditionally supported (from the C++ standard standpoint). Using it for anything other than casting back to the same function pointer will have an implementation specific outcome, that can very greatly among compilers.

A: The overload used is
ostream& ostream::operator<< (bool val);

Which prints 1 as your function pointer is not null.


text:
Q: Keep element vertically and horizontally centered in another element while allowing it to grow and be panned I am trying to keep an element horizontally and vertically centered while it grows inside a container, but while also allowing you to scroll and see the rest of the growing element.  I made a codepen that demonstrates my problem.
I am using transformX and transformY while also using position:absolute with left and right set to 50% as well.  The goal is that when you click the grow button, you should be able to scroll up, down left and right and see the whole image.  Currently something with the transform seems to be preventing you from getting back to the top and the far left of the image.  Any ideas?
CodePen
EDIT
I am using flexbox instead now, but still have the same problem.  Its visible in the updated CodePen.


text:
Q: Hosting/Server for high traffic website What setup would you recommend for Wordpress website with average daily traffic ~250,000 sessions per day (~130K unique users). In peak hours we can get ~25K users in hour, and non peak ~10-17k per hour.
Monthly bandwidth is ~14TB.
I'll be happy to hear suggestions on what is the best setup:
Note: it should be cpanel server (apache)

*

*Server - cloud or dedicated (all except google cloud and amazon)

*CPU/Memory/etc ?

*CDN ?

*Apache/MySQL specific setup?

*High availability?

*Any other suggestion

Very appreciated for any advice

A: It depends what type of traffic do you have?
Is this just one page traffic (bringing referrals from sources like social media, forums, blogs, etc..). Why i'm asking this?
Yes! it really matters.....
Traffic::
Usually traffic brought from sources, browse a landing page there's wouldn't be any unique counts, so in that case your cache plugins can't spend more effort in terms of performance. If users are giving you nice no of pageviews in that case your cache plugin will manage the performance and will give you the best result.
Hosting:
Definitely that you cannot run your website through any shared hosting OR WORDPRESS HOSTING if you are going to have this much of volume. Don't consider having a VPS/Dedicated through any hosting company, it doesn't matter how big that hosting company is. Third party hosting companies will never give you prompt support and will never even guarantee you that if you bring that much of traffic, it will remain as stable as in fully working condition. so consider having VPS/Dedicated hosted in Data Center not through any third party vendors. Try if you could get Cloud VPS OR cloud solution as a service part.
CDN:
If you have good budget then consider using Amazon, Avg. budget use Cloudflare OR MaxCDN.
Hardware: 16GB Ram, 8 Core CPU, 60GB (If you are not planning much updates on your website), 20Gbps Network, 25TB Bandwidth. VPS would do your job and can manage the traffic you considering. I don't think so you should go for dedicated.
Setup & Configuration:
Install Debian 8, Virtualmin (Free) + Nginx and optimize it to use for high traffic. Do not install WHM, don't do this mistake, if you do then you might need premium support to fix issues every single day. Virtualmin is light panel and wordpress is it's specialty. Nginx has ability to deliver high traffic website, mysql optimization, cache management and it can deliver what you looking at.
Themes & Plugins:
Try to go with light wordpress theme, install minimal plugins. Must have plugins are Nginx Helper & W3C Total cache.
There's lot of things on this to talk about, but i think these are important once and should be helpful. Hope my explanation helps you to understand! If you have any doubt feel free to ask...
Attached is the proof of what i explained. This server has configuration of 4GB Ram, 4 Core CPU & Cloud VPS


text:
Q: Trying to access elements within XML response using JavaScript So - I'm pretty new to JavaScript so this may be a dumb question -
I'm running a POST API call that returns an XML file of the data I need, but I'm unsure how to access specific tags within the XML file from the site that is running the call.
I set my url2 previous to this:

$j.post(url2, function(data, status){
     console.log(data);
    });

and it returns:

#document
  <xml>
    <Meta>...</Meta>
      <Result>
        <Recipient>

          ...

Which is perfect. However, I'm unsure how I would access the elements within the snippet. For example, within 'Recipient' is a tag called 'userTime'. If I want to access that value with JS, I was hoping for something like:

var ut = data.getElementByTagName('userTime');

But that returns: Uncaught TypeError: data.getElementByTagName is not a function
I just don't know what notation I need to use to access elements within the XML return. Any help is appreciated!

A:  $j.post(url2, function(data, status){
    var result=data;
});
var data=result.find("Recipient[name='default'][type='primary']"); //XML Parent Node. 'name' is attribute & 'type' is also attribute of node.

var tagdata=data.find('child node tagname').attr(''); //Node under Parent Node, attr contain

A: in this code.
$j.post(url2, function(data, status){

data is not node. use this code.
$.ajax({
    url:"some Url"
    ,dataType:"xml"
    ,method :"post"
}).done(function(data){
    alert($(data).find("somequery").val());
});