text:
Q: How to use a Trie data structure to find the sum of LCPs for all possible substrings? Problem Description:

References: Fun With Strings
Based on the problem description, a naive approach to find sum of length of LCP for all possible substrings (for a given string) is as follows :
#include <cstring>
#include <iostream>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int lcp(string str1, string str2)
{
    string result;
    int n1 = str1.length(), n2 = str2.length();

    // Compare str1 and str2
    for (int i=0, j=0; i<=n1-1 && j<=n2-1; i++,j++)
    {
        if (str1[i] != str2[j])
            break;
        result.push_back(str1[i]);
    }

    return (result.length());
}

int main()
{
    string s;
    cin>>s;
    int sum = 0;

    for(int i = 0; i < s.length(); i++)
        for(int j = i; j < s.length(); j++)
            for(int k = 0; k < s.length(); k++)
                for(int l = k; l < s.length(); l++)
                    sum += lcp(s.substr(i,j - i + 1),s.substr(k,l - k + 1));
    cout<<sum<<endl;
    return 0;
}

Based on further reading and research on LCP's, I found this document which specifies a way to efficiently find a LCP using an Advanced Data Structure called Tries. I implemented a Trie and a Compressed Trie (Suffix Tree) as follows:
#include <iostream>
#include <cstring>

using std::cout;
using std::cin;
using std::endl;
using std::string;
const int ALPHA_SIZE = 26;

struct TrieNode
{
    struct TrieNode *children[ALPHA_SIZE];
    string label;
    bool isEndOfWord;
};
typedef struct TrieNode Trie;

Trie *getNode(void)
{
    Trie *parent = new Trie;
    parent->isEndOfWord = false;
    parent->label = "";
    for(int i = 0; i <ALPHA_SIZE; i++)
        parent->children[i] = NULL;

    return parent;
}

void insert(Trie *root, string key)
{
    Trie *temp = root;

    for(int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';
        if(!temp->children[index])
        {
            temp->children[index] = getNode();
            temp->children[index]->label = key[i];
        }
        temp = temp->children[index];
        temp->isEndOfWord = false;
    }
    temp->isEndOfWord = true;
}

int countChildren(Trie *node, int *index)
{
    int count = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(node->children[i] != NULL)
        {
            count++;
            *index = i;
        }
    }
    return count;
}

void display(Trie *root)
{
    Trie *temp = root;
    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i] != NULL)
        {
            cout<<temp->label<<"->"<<temp->children[i]->label<<endl;
            if(!temp->isEndOfWord)
                display(temp->children[i]);
        }
    }
}

void compress(Trie *root)
{
    Trie *temp = root;
    int index = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i])
        {
            Trie *child = temp->children[i];

            if(!child->isEndOfWord)
            {
                if(countChildren(child,&index) >= 2)
                {
                    compress(child);
                }
                else if(countChildren(child,&index) == 1)
                {
                    while(countChildren(child,&index) < 2 and countChildren(child,&index) > 0)
                    {
                        Trie *sub_child = child->children[index];

                        child->label = child->label + sub_child->label;
                        child->isEndOfWord = sub_child->isEndOfWord;
                        memcpy(child->children,sub_child->children,sizeof(sub_child->children));

                        delete(sub_child);
                    }
                    compress(child);
                }
            }
        }
    }
}

bool search(Trie *root, string key)
{
    Trie *temp = root;

    for(int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';
        if(!temp->children[index])
            return false;
        temp = temp->children[index];
    }
    return (temp != NULL && temp->isEndOfWord);
}

int main()
{
    string input;
    cin>>input;

    Trie *root = getNode();

    for(int i = 0; i < input.length(); i++)
        for(int j = i; j < input.length(); j++)
        {
            cout<<"Substring : "<<input.substr(i,j - i + 1)<<endl;
            insert(root, input.substr(i,j - i + 1));
        }

    cout<<"DISPLAY"<<endl;
    display(root);

    compress(root);
    cout<<"AFTER COMPRESSION"<<endl;
    display(root);

    return 0;
}

My question, is how do I proceed to find the length of the LCP. I can get the LCP by getting the label field at the branching node, but how do I count the length of LCP's for all possible substrings ?
One way I thought of was to some how use the branching node, its label field which holds the LCP, and the branching node's children to find sum of all LCP's length (Lowest Common Ancestor ?). But I am still confused. How do I proceed further ?
Note: It is also possible that my approach to this problem is wrong, so please suggest other methods too for this problem (considering time and space complexity).
Link to similar unanswered questions:

*

*sum of LCP of all pairs of substrings of a given string

*Longest common prefix length of all substrings and a string
References for Code and Theory:

*

*LCP

*Trie

*Compressed Trie
Update1:
Based on @Adarsh Anurag's answer, I have come up with following implementation
with the help of trie data structure,
#include <iostream>
#include <cstring>
#include <stack>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::stack;

const int ALPHA_SIZE = 26;
int sum = 0;
stack <int> lcp;

struct TrieNode
{
    struct TrieNode *children[ALPHA_SIZE];
    string label;
    int count;
};
typedef struct TrieNode Trie;

Trie *getNode(void)
{
    Trie *parent = new Trie;
    parent->count = 0;
    parent->label = "";
    for(int i = 0; i <ALPHA_SIZE; i++)
        parent->children[i] = NULL;

    return parent;
}

void insert(Trie *root, string key)
{
    Trie *temp = root;

    for(int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';
        if(!temp->children[index])
        {
            temp->children[index] = getNode();
            temp->children[index]->label = key[i];
        }
        temp = temp->children[index];
    }
    temp->count++;
}

int countChildren(Trie *node, int *index)
{
    int count = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(node->children[i] != NULL)
        {
            count++;
            *index = i;
        }
    }
    return count;
}

void display(Trie *root)
{
    Trie *temp = root;
    int index = 0;
    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i] != NULL)
        {
            cout<<temp->label<<"->"<<temp->children[i]->label<<endl;
            cout<<"CountOfChildren:"<<countChildren(temp,&index)<<endl;
            cout<<"Counter:"<<temp->children[i]->count<<endl;

            display(temp->children[i]);
        }
    }
}

void lcp_sum(Trie *root,int counter,string lcp_label)
{
    Trie *temp = root;
    int index = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i])
        {
            Trie *child = temp->children[i];

            if(lcp.empty())
            {
                lcp_label = child->label;
                counter = 0;

                lcp.push(child->count*lcp_label.length());
                sum += lcp.top();
                counter += 1;
            }
            else
            {
                lcp_label = lcp_label + child->label;
                stack <int> temp = lcp;

                while(!temp.empty())
                {
                    sum = sum + 2 * temp.top() * child->count;
                    temp.pop();
                }

                lcp.push(child->count*lcp_label.length());
                sum += lcp.top();
                counter += 1;
            }

            if(countChildren(child,&index) > 1)
            {
                lcp_sum(child,0,lcp_label);
            }
            else if (countChildren(child,&index) == 1)
                lcp_sum(child,counter,lcp_label);
            else
            {
                while(counter-- && !lcp.empty())
                    lcp.pop();
            }
        }
    }
}

int main()
{
    string input;
    cin>>input;

    Trie *root = getNode();

    for(int i = 0; i < input.length(); i++)
        for(int j = i; j < input.length(); j++)
        {
            cout<<"Substring : "<<input.substr(i,j - i + 1)<<endl;
            insert(root, input.substr(i,j - i + 1));
            display(root);
        }

    cout<<"DISPLAY"<<endl;
    display(root);

    cout<<"COUNT"<<endl;
    lcp_sum(root,0,"");
    cout<<sum<<endl;

    return 0;
}

From the Trie structure, I have removed the variable isEndOfWordand instead replaced it with a counter. This variable keeps track of duplicate substrings which should help in counting LCP's for strings with duplicate characters. However, the above implementation works only for strings with distinct characters. I have tried implementing the method suggested by @Adarsh for duplicate characters but does not satisfy any test case.
Update2:
Based on further updated answer from @Adarsh and "trial and error" with different testcases, I seem to have progressed a bit for duplicate characters, however it still does not work as expected. Here is the implementation with comments,
// LCP : Longest Common Prefix
// DFS : Depth First Search

#include <iostream>
#include <cstring>
#include <stack>
#include <queue>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::stack;
using std::queue;

const int ALPHA_SIZE = 26;
int sum = 0;     // Global variable for LCP sum
stack <int> lcp; //Keeps track of current LCP

// Trie Data Structure Implementation (See References Section)
struct TrieNode
{
    struct TrieNode *children[ALPHA_SIZE]; // Search space can be further reduced by keeping track of required indicies
    string label;
    int count; // Keeps track of repeat substrings
};
typedef struct TrieNode Trie;

Trie *getNode(void)
{
    Trie *parent = new Trie;
    parent->count = 0;
    parent->label = ""; // Root Label at level 0 is an empty string
    for(int i = 0; i <ALPHA_SIZE; i++)
        parent->children[i] = NULL;

    return parent;
}

void insert(Trie *root, string key)
{
    Trie *temp = root;

    for(int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';   // Lowercase alphabets only
        if(!temp->children[index])
        {
            temp->children[index] = getNode();
            temp->children[index]->label = key[i]; // Label represents the character being inserted into the node
        }
        temp = temp->children[index];
    }
    temp->count++;
}

// Returns the count of child nodes for a given node
int countChildren(Trie *node, int *index)
{
    int count = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(node->children[i] != NULL)
        {
            count++;
            *index = i; //Not required for this problem, used in compressed trie implementation
        }
    }
    return count;
}

// Displays the Trie in DFS manner
void display(Trie *root)
{
    Trie *temp = root;
    int index = 0;
    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i] != NULL)
        {
            cout<<temp->label<<"->"<<temp->children[i]->label<<endl; // Display in this format : Root->Child
            cout<<"CountOfChildren:"<<countChildren(temp,&index)<<endl; // Count of Child nodes for Root
            cout<<"Counter:"<<temp->children[i]->count<<endl; // Count of repeat substrings for a given node
            display(temp->children[i]);
        }
    }
}

/* COMPRESSED TRIE IMPLEMENTATION
void compress(Trie *root)
{
    Trie *temp = root;
    int index = 0;

    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        if(temp->children[i])
        {
            Trie *child = temp->children[i];

            //if(!child->isEndOfWord)
            {
                if(countChildren(child,&index) >= 2)
                {
                    compress(child);
                }
                else if(countChildren(child,&index) == 1)
                {
                    while(countChildren(child,&index) < 2 and countChildren(child,&index) > 0)
                    {
                        Trie *sub_child = child->children[index];

                        child->label = child->label + sub_child->label;
                        //child->isEndOfWord = sub_child->isEndOfWord;
                        memcpy(child->children,sub_child->children,sizeof(sub_child->children));

                        delete(sub_child);
                    }
                    compress(child);
                }
            }
        }
    }
}
*/

// Calculate LCP Sum recursively
void lcp_sum(Trie *root,int *counter,string lcp_label,queue <int> *s_count)
{
    Trie *temp = root;
    int index = 0;

    // Traverse through this root's children array, to find child nodes
    for(int i = 0; i < ALPHA_SIZE; i++)
    {
        // If child nodes found, then ...
        if(temp->children[i] != NULL)
        {
            Trie *child = temp->children[i];

            // Check if LCP stack is empty
            if(lcp.empty())
            {
                lcp_label = child->label;   // Set LCP label as Child's label
                *counter = 0;               // To make sure counter is not -1 during recursion

                /*
                    * To include LCP of repeat substrings, multiply the count variable with current LCP Label's length
                    * Push this to a stack called lcp
                */
                lcp.push(child->count*lcp_label.length());

                // Add LCP for (a,a)
                sum += lcp.top() * child->count; // Formula to calculate sum for repeat substrings : (child->count) ^ 2 * LCP Label's Length
                *counter += 1; // Increment counter, this is used further to pop elements from the stack lcp, when a branching node is encountered
            }
            else
            {
                lcp_label = lcp_label + child->label; // If not empty, then add Child's label to LCP label
                stack <int> temp = lcp; // Temporary Stack

                /*
                    To calculate LCP for different combinations of substrings,
                    2 -> accounts for (a,b) and (b,a)
                    temp->top() -> For previous substrings and their combinations with the current substring
                    child->count() -> For any repeat substrings for current node/substring
                */
                while(!temp.empty())
                {
                    sum = sum + 2 * temp.top() * child->count;
                    temp.pop();
                }

                // Similar to above explanation for if block
                lcp.push(child->count*lcp_label.length());
                sum += lcp.top() * child->count;
                *counter += 1;
            }

            // If a branching node is encountered
            if(countChildren(child,&index) > 1)
            {
                int lc = 0; // dummy variable
                queue <int> ss_count; // queue to keep track of substrings (counter) from the child node of the branching node
                lcp_sum(child,&lc,lcp_label,&ss_count); // Recursively calculate LCP for child node

                // This part is experimental, does not work for all testcases
                // Used to calculate the LCP count for substrings between child nodes of the branching node
                if(countChildren(child,&index) == 2)
                {
                    int counter_queue = ss_count.front();
                    ss_count.pop();

                    while(counter_queue--)
                    {
                        sum = sum +  2 * ss_count.front() * lcp_label.length();
                        ss_count.pop();
                    }
                }
                else
                {
                    // Unclear, what happens if children is > 3
                    // Should one take combination of each child node with one another ?
                    while(!ss_count.empty())
                    {
                        sum = sum +  2 * ss_count.front() * lcp_label.length();
                        ss_count.pop();
                    }
                }

                lcp_label = temp->label; // Set LCP label back to Root's Label

                // Empty the stack till counter is 0, so as to restore it's state when it first entered the child node from the branching node
                while(*counter)
                {
                    lcp.pop();
                    *counter -=1;
                }
                continue; // Continue to next child of the branching node
            }
            else if (countChildren(child,&index) == 1)
            {
                // If count of children is 1, then recursively calculate LCP for further child node
                lcp_sum(child,counter,lcp_label,s_count);
            }
            else
            {
                // If count of child nodes is 0, then push the counter to the queue for that node
                s_count->push(*counter);
                // Empty the stack till counter is 0, so as to restore it's state when it first entered the child node from the branching node
                while(*counter)
                {
                    lcp.pop();
                    *counter -=1;
                }
                lcp_label = temp->label; // Set LCP label back to Root's Label

            }
        }
    }
}

/* SEARCHING A TRIE
bool search(Trie *root, string key)
{
    Trie *temp = root;

    for(int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';
        if(!temp->children[index])
            return false;
        temp = temp->children[index];
    }
    return (temp != NULL );//&& temp->isEndOfWord);
}
*/

int main()
{
    int t;
    cin>>t; // Number of testcases

    while(t--)
    {
        string input;
        int len;
        cin>>len>>input; // Get input length and input string

        Trie *root = getNode();

        for(int i = 0; i < len; i++)
            for(int j = i; j < len; j++)
                insert(root, input.substr(i,j - i + 1)); // Insert all possible substrings into Trie for the given input

        /*
          cout<<"DISPLAY"<<endl;
          display(root);
        */

        //LCP COUNT
        int counter = 0;    //dummy variable
        queue <int> q;      //dummy variable
        lcp_sum(root,&counter,"",&q);
        cout<<sum<<endl;

        sum = 0;

        /*
          compress(root);
          cout<<"AFTER COMPRESSION"<<endl;
          display(root);
        */
    }
    return 0;
}

Also, here are some sample test cases (expected outputs),
1. Input : 2 2 ab 3 zzz

   Output : 6 46

2. Input : 3 1 a 5 afhce 8 ahsfeaa

   Output : 1 105 592

3. Input : 2 15 aabbcceeddeeffa 3 bab

   Output : 7100 26

The above implementation fails for testcase 2 and 3 (partial output). Please suggest a way to solve this. Any other approach to this problem is also fine.

A: Your intuition is going into right direction.
Basically, whenever you see a problem with LCP of substrings, you should think about suffix data structures like suffix trees, suffix arrays, and suffix automata. Suffix trees are arguably the most powerful and the easiest to deal with, and they work perfectly on this problem.
Suffix tree is a trie containing all the suffices of a string, with every non-branching edge chain compressed into a single long edge. The problem with an ordinary trie with all suffices is that it has O(N^2) nodes, so it takes O(N^2) memory. Given that you can precompute LCP of all pairs of suffices in O(N^2) time and space with a trivial dynamic programming, suffix trees are no good without compression.
The compressed trie takes O(N) memory, but it is still useless if you build it with O(N^2) algorithm (as you do in your code). You should use Ukkonen's algorithm to construct suffix tree directly in compressed form in O(N) time. Learning and implementing this algorithm is no easy feat, maybe you will find web visualization helpful. As a last minor note, I'll assume for simplicity that a sentinel character (e.g. dollar $) is added to the end of the string, to ensure that all leaves are explicit nodes in the suffix tree.
Note that:

*

*Every suffix of the string is represented as a path from the root to a leaf in the tree (recall about sentinel). This is 1-1 correspondence.

*Every substring of the string is represented as a path from the root to a node in the tree (including implicit nodes "inside" long edges) and vice versa. Moreover, all substrings of equal value map into the same path. In order to learn how many equal substrings map into a particular root-node path, count how many leaves are there in the subtree below the node.

*In order to find LCP of two substrings, find their corresponding root-node paths, and take LCA of the nodes. LCP is then the depth of the LCA vertex. Of course, it would be a physical vertex, with several edges going down from it.

Here is the main idea. Consider all pairs of substrings, and classify them into groups with same LCA vertex. In other words, let's compute A[v] := the number of pairs of substrings with LCA vertex being exactly v. If you compute this number for every vertex v, then all that remains to solve the problem is: multiply every number by the depth of the node and get the sum. Also, the array A[*] takes only O(N) space, which means that we haven't yet lost the chance to solve the whole problem in linear time.
Recall that every substring is a root-node path. Consider two nodes (representing two arbitrary substrings) and a vertex v. Let's call the subtree with the root at vertex v a "v-subtree". Then:

*

*If both nodes are within v-subtree, then their LCA is also within v-subtree.

*Otherwise, their LCA is outside of v-subtree, so it works both ways.

Let's introduce another quantity B[v] := the number of pairs of substrings with LCA vertex being within v-subtree. The statement just above shows an efficient way to compute B[v]: it is simply the square of the number of nodes within v-subtree, because every pair of nodes in it fits the criterion. However, multiplicity should be taken into account here, so every node must be counted as many times as there are substrings corresponding to it.
Here are the formulas:
    B[v] = Q[v]^2
    Q[v] = sum_s( Q[s] + M[s] * len(vs) )    for s in sons(v)
    M[v] = sum_s( M[s] )                     for s in sons(v)

With M[v] being multiplicity of the vertex (i.e. how many leaves are present in v-subtree), and Q[v] being the number of nodes in the v-subtree with multiplicity taken into account. Of course, you can deduce the base case for the leaves yourself. Using these formulas, you can compute M[*], Q[*], B[*] during one traversal of the tree in O(N) time.
It only remains to compute A[*] array using the B[*] array. It can be done in O(N) by simple exclusion formula:
A[v] = B[v] - sum_s( B[s] )           for s in sons(v)

If you implement all of this, you will be able to solve the whole problem in perfect O(N) time and space. Or better to say: O(N C) time and space, where C is the size of the alphabet.

A: For solving the problem proceed as shown below.
If you look at the picture, I have made a trie for all substrings of abc.
Since, all the substrings are added, every node in the trie has endOfWord true.
Now start traversing the tree with me in a DFS fashion:

*

*sum = 0, stack = {empty}

*We encounter a first. Now for L(A,B) a can form 1 pair with itself.
Therefore do sum=sum+length and sum becomes 1 now. Now push length i.e 1 in stack. stack = {1}

*Move to b now. The substring is now ab. ab like a can form 1 pair with itself. Therefore do sum=sum+length and sum becomes 3 now.
Copy the stack contents to stack2. We get 1 as stack top . This means ab and a have LCP 1. But they can form L(a,ab) and L(ab,a). So add sum = sum + 2 * stack.top() . Sum becomes 3+2 = 5. Now copy back stack2 into stack and push length i.e 2.
stack becomes {2,1}.

*Move to c. Substring is abc. It will form 1 pair with itself, so add 3.
Sum becomes 5+3 = 8. Copy stack to stack2. At top we have 2. abc and ab will give LCP 2 and they will form 2 pairs. So sum = sum + 2*2. Sum becomes 12.
Pop out 2. Stack has 1 now. abc and a have LCP 1 and can form 2 pairs. So,
sum becomes 12+2 = 14. Copy back stack2 into stack and push length i.e 3 into stack.

*We reached end of trie. Clear the stack and start from b at length 1 and continue as above.
Sum becomes 14+1 = 15 here

*We reach c. Substring is bc here. Sum will become 15 + 2 + 2*1(top) =  19.

*We reached end of trie. Start from c at length 1. Sum = 19+1 = 20 now.
Time complexity: O(N^3). As it takes O(N^2) to generate substrings and O(N) time to insert them in trie. Node creation is constant time. As all substrings are not of length N, so it will take less than N^3 but T.C. will be O(N^3).
I have tested this method and it gives correct output for words with distinct characters only.
For words that allow repeat of characters it fails. In order to solve for words that allow character repeats, you will need to store the information about the number of times words occur at position A and B for L(A,B). In stack we will need to push pair of length and B_count. Then, you can find sum of LCP using length(in stack)*B_count(in stack)*A_count of current substring. I do not know any method to find A, B counts without using 4 loops.
See the below images for word abb

That's all. Thank you.


text:
Q: How to place a treeview item above ite root in wpf the question is I have a treeview with only one root(US).I am taking two treeviewitems(Dallas & NewYork), so that when I click on Root I get like this
US
-Dallas
-NewYork
now the requirement  I have is  to get one of the treeviewitems above the root(when I am clicking it) like this
-Dallas
US
-NewYork
Any idea how to do this??? please help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't sudo find a command after I added it to PATH? I want to add some command to PATH so that I can use them conveniently, such as:
export $PATH = "$PATH:/opt/storm/bin"

but sometimes storm need root authority, but when I use it with sudo, Ubuntu cannot find the command.
sudo storm nimbus

how can I find these command when I use sudo?

A: You have to add the path to the sudo path.
Run the command sudo visudo
you will see a line like this:
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:$

Now add the path of your command here and this should work.
For example:
$ sudo storm
sudo: storm: command not found

Now add the path as above:
$ sudo visudo

secure_path="......:/opt/storm/bin"

save and exit.
now sudo storm will just work normally.
Note You should also add the path to the default path in /etc/profile.

A: I think you have created the alias in the user level. That's why the shortcuts are available at the user level only.
You should add that alias command line to .bashrc file in /root folder and not in /home/user/.bashrc(this .bashrc file belongs to user account not root).
So that you can use your alias command directly in shell when logged in as root.

A: @Maythux explained what is the secure path where sudo searches for executables
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:$

you can add the path directly to the list as the answer suggests, but the better and right way is to create an symbolic link unde /usr/bin
sudo ln -s -f  /opt/storm/bin/storm /usr/bin/storm


text:
Q: Control DOIT ESP32 DevKit V1 using Blynk app I'm a beginner and I'm working on a project to light an LED using DOIT ESP32 devkit v1. I want to turn on and off the LED using a phone app via wifi (using Blynk application). I'm using the following code on Arduino IDE (version 1.8.13):
#define BLYNK_PRINT Serial
#define LED 2

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "...";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "...";
char pass[] = "...";

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(LED, HIGH);
  Serial.begin(115200);

  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("WiFi connected");

  Blynk.begin("Your auth token key", ssid, pass);

}

void loop(){
    Blynk.run();
}

The connection to the wifi succeeded, But when I press the serial monitor button I get an error saying "Invalid auth token"

I don't understand what am I doing wrong, I've check the auth key few times, that's the right one. In the Blynk project I've chose ESP32 Dev Kit and in the Arduino IDE I chose DOIT ESP32 Dev Kit V1 along with port COM4 (I've made sure that's the right one).  I think the problem is that I'm not using Blynk right, What do I need to do?
Thank you.

A: I did Have a problem in Blynk.begin("Your auth token key", ssid, pass); missed one letter in the auth token. (probably didn't copy correctly) I read it 100 times and still missed it, thank you everyone for your help.


text:
Q: Windows 10: run cmd at power-on WITH console window I have a batch file (which sets some stuff up and runs a Python script) that must be run at Windows 10 power-on; not log-on, power-on.  The Python script outputs useful diagnostics to the console and so the simplest thing I could do to see these diagnostics would be to have the console window visible so that, if I subsequently log-in to the Windows 10 machine, I can see what's been going on in the recent past.
Is there any way of doing this?  I've tried Task Scheduler but as soon as one selects "Run whether user is logged on or not" the console no longer appears.  I realise that I could log the output to a file but then I would need to find some way of tailing the log, or I could wrap it up in an app, etc., but this is all extra complication when having the console window visible is really all I need.


text:
Q: NHibernate serializing lazy-loaded entities with WCF I'm trying to send NH entities through the wire using WCF. I've got a complex graph of lazy-loaded objects..
I tried to implement a custom DataContractSurrogate to force initialization when serializing.
Here is the code :
public class HibernateDataContractSurrogate : IDataContractSurrogate
{
    public HibernateDataContractSurrogate()
    {
    }

    public Type GetDataContractType(Type type)
    {
        // Serialize proxies as the base type
        if (typeof(INHibernateProxy).IsAssignableFrom(type))
        {
            type = type.GetType().BaseType;
        }

        // Serialize persistent collections as the collection interface type
        if (typeof(IPersistentCollection).IsAssignableFrom(type))
        {
            foreach (Type collInterface in type.GetInterfaces())
            {
                if (collInterface.IsGenericType)
                {
                    type = collInterface;
                    break;
                }
                else if (!collInterface.Equals(typeof(IPersistentCollection)))
                {
                    type = collInterface;
                }
            }
        }

        return type;
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        if (obj is INHibernateProxy)
        {
            obj = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation();
        }

        // Serialize persistent collections as the collection interface type
        if (obj is IPersistentCollection)
        {
            IPersistentCollection persistentCollection = (IPersistentCollection)obj;
            persistentCollection.ForceInitialization();
            obj = persistentCollection.Entries(null); // This returns the "wrapped" collection
        }

        return obj;
    }

    public object GetDeserializedObject(object obj, Type targetType)
    {
        return obj;
    }

    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
    {
        return null;
    }

    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        return null;
    }

    public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
    {
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        return null;
    }

    public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
    {
        return typeDeclaration;
    }
}

However, I keep getting exceptions :
NHibernate.Exceptions.GenericADOException: could not initialize a collection [SQL trace] ---> System.ObjectDisposedException: Session is closed!

Looking at the stacktrace, it appears that this line persistentCollection.ForceInitialization();
is throwing the exception.
What can I do?
PS: I'd like to use DTO instead of serializing complex NH entities, however it's not possible here.

A: You can't lazy-load a collection after you've closed the NHibernate.ISession object from which it was loaded. The only options you have are:

*

*Keep the ISession open until you've serialized the data.

*Turn off lazy loading.

*make sure you fetch all the lazy loaded collections before closing the session.

A: Check out the answer here: What are the problems associated with sending a Hibernate Proxy class to clients


text:
Q: Copy one folder into another directory in commend prompt I want to copy one folder into another directory with all content on Windows 10. I used :
xcopy "C:\Users\X\Desktop\projects\XX\XXX\folder1" "C:\Users\X\Desktop\projects\XX\XXX\folder2"  /E /C /I /Y

this :
xcopy "C:\Users\X\Desktop\projects\XX\XXX\folder1" "C:\Users\X\Desktop\projects\XX\XXX\folder2\"  /E /C /I /Y

and :
robocopy"C:\Users\X\Desktop\projects\XX\XXX\folder1" "C:\Users\X\Desktop\projects\XX\XXX\folder2" /COPYALL /E`

but it only copy files which are in this directory and move it to another.
My goal is like we could right-click on mouse on folder and "copy" then "paste" it into another dir.
What is an issue into my commend?

A: Ok, so what you want is folder1 to be created in folder2 (was not clear to me reading the question)
So try:
xcopy "...\XX\XXX\folder1" "..\XX\XXX\folder2\folder1" /cheirky

No need to create folder2\folder1, /I flag makes it for you

A: I found two solutions about this.
1) create new folder in destination directory:
md "C:\Users\X\Desktop\projects\XX\XXX\folder2\folder1"

then, copy files from folder1 into new directory folder:
xcopy "C:\Users\X\Desktop\projects\XX\XXX\folder1" "C:\Users\X\Desktop\projects\XX\XXX\folder2\folder1"  /E /C /I /Y

2) use PowerShell on Windows 10:
Copy-Item -Path "C:\Users\X\Desktop\projects\XX\XXX\folder1" -Destination "C:\Users\X\Desktop\projects\XX\XXX\folder2" -recurse -Force


text:
Q: Discord.js: How to find server member (to assign roles in Discord) by Discord User-ID? I am building a web-application that authenticates users with discords oauth. When a user is registered in the laravel app, the given data from discords oauth is saved into an sql database. In this data is the Username, discriminator and the unique discord user ID. I now have a seperate node.js server that runs discord.js and forms a bot. I want this bot to assign a "registered" role to the authenticated user on a discord server. At the moment I am only able to assign roles to a user that messages the bot on the server via accessing the discord.js message object like below.
bot.on("messageCreate", (message) => {
    if (message.content.toLowerCase().startsWith("!role add")) {
        let member = message.mentions.members.first();
        let role = message.mentions.roles.first()
        member.roles.add(role)
    }
}) //this works. But how can a member be found only using the Discord User ID?

Here is the question: Is there a way in Discord.js to find the member by giving the discord user ID (Given by OAuth and saved into my DB) instead of retrieving it from a message, that the user has to send?
I hope my question is clear and does not confuse. I am not asking about anything regarding http / server-server communication or the Operations with Laravel/Oauth/DB because this works already. I just cant find a function like
let member = bot.findGuildMemberByID("USER-ID HERE");

Here is a visualisation of the general architecture to make it more clear.

A: You in fact only need ids to add a role to a member. Discord API has an endpoint for that.
discord.js doesn't currently have a "built-in" method for this, but I've made a pull request for this, but it's not ready yet
Instead, you can use rest, which is used there too, internally
const { REST } = require("discord.js") // will need to use @discordjs/rest if not using v14

// ...

const rest = new REST({ version: "9" }).setToken(client.token)
await rest.put(Routes.guildMemberRole(guildId, userId, roleId), {
  reason // optional - reason for adding the role
})

A: Simply get the guild where you want to find the member:
const guild = client.guilds.cache.get("GUILD-ID HERE"); // or message.guild

then you can get a member by their ID by:
Using get:
const member = guild.members.cache.get("USER-ID HERE");

Filtering all the guild's members
const member = guild.members.cache.find(member => member.id === "USER-ID HERE");

Fetching the member:
const member = guild.members.fetch("USER-ID HERE");


text:
Q: PostgreSQL 8.4 replication of more than 100 tables I am facing a problem with PostgreSQL version 8.4.
I need to create an slave machine but when I look to all tutorials of slony or londsite its saying I will need to specify the tables that I want to replicate with some details and sequences separately..... Now imagine a database with more than 100 tables, that is my case, what should I do?
If I upgrade PostgreSQL to version 9X the database links with Oracle stop working, so I need to stay with 8.4 but I can't find a tutorial to replicate the entire database like I do in the mysql instances.
I will be more specific in the end of this tutorial learning how to use slony suggests:
set add table (id=1, set id=1, origin = @PRIMARY, fully qualified name = 'schema.tablename', comment = 'table');
set add sequence (id=1, set id=1, origin = @PRIMARY, fully qualified name = 'schema.sequencename', comment = 'seq');

(Link for the full tutorial: https://www.howtoforge.com/configuring-slony-i-cascading-replication-on-postgresql-8.3)
For each table i want, and don't say nothing about replicating the entire database, another tutorials says the same.
Please somebody know a good way to solve that? Maybe I will need some Shell Script?

A: The solution was to use Postgres version 9.1 and Oracle Version 11.2.0.1.0.
I am running oracle in Debian Wheezy all do i need is to do some upgrades in certain libraries and now it works good:
Version of ODBC:
ii  odbc-postgresql:amd64              1:09.01.0100-1+deb7u1         amd64        ODBC driver for PostgreSQL

Version of Libssl required by ODBC:
ii  libssl1.0.0:amd64                  1.0.1e-2+deb7u13              amd64        SSL shared libraries

Postgres version in the another server:
ii  postgresql-9.1                     9.1.15-0+deb7u1               amd64        object-relational SQL database, version 9.1 server

This is how do i install Oracle with PostgreSQL 9.1 datalink and its working very fine now, also with Mysql 5.5.
Think now i will be able with this new version to do easy replication just like i do in the Mysql instances!


text:
Q: How to force the opening of UNetBootin? I'm trying to install UNetBootin for a MacBook Pro (13-inch, Mid 2012). However, I got this message when I tried to open it. Could anyone be able to tell me what I can do to force its opening?

A: Try right clicking on it in Finder and then clicking "Open".


text:
Q: Replace / Edit host file with windows BAT I wish to add and remove some lines in host file within a period of time (Time setting will be done via task schedule job)
I can create two BAT file, one for adding new lines and one for removing existing lines.
After some research in Google, i could only find something related to ADD new lines, but not remove it. (replace) and mostly were subject to one line. As i had a huge chunk of lines need to insert and remove.
Any ideas or suggestion?
(not sure will it be better to replace the HOST file physically.)
some findings related.
Is it possible to automatically run a batch file as administrator
https://stackoverflow.com/questions/3666740/windows-batch-how-to-add-host-entries
https://stackoverflow.com/questions/16208429/how-to-replace-a-string-in-the-host-file-using-batch
http://www.dslreports.com/forum/r26962139-Other-Adding-entries-to-HOSTS-file-by-batch-script


text:
Q: How to show custom failure message in Specs2 (Scala)? For example, for code like this:
myNum must beEqualTo("SOME INTERESTING TEXT")

The message will be like the following:
java.lang.Exception: ArrayBuffer() doesn't have size 1 but size 0

Is there an elegant way to get customised message displayed here?

A: First you can name value you're testing.
myNum aka "meaningful name" must_== expectedValue

You can also overwrite the full message.
(myNum must_== expectedValue).setMessage("Full failure message")


text:
Q: Ruby on Rails - Ruby, How to add the values from two hashes with same key, without overwriting the values? first of all thank you for helping me with my SQL question, at this point.
Now I'm struggling with another thing, makes me think if I should quit being a programmer to be honest.
Anyway, my problem is : I have an array of hashes( and inside that hash another ) like this:
[
 {"A1"=>{:month=>1.0, :balance=>"0.0000", :price=>"9.0000"}},
 {"A1"=>{:month=>7.0, :balance=>"34030.0000", :price=>"34030.0000"}},
 {"A3"=>{:month=>4.0, :balance=>"34030.0000", :price=>"34030.0000"}},
 ...
]

What I'm trying to accomplish is that, if there are two values with the same key, ie "A1" add those values into one whole hash, without overwriting the old values and having the month as a key desired output:
[
 {"A1"=> { 1 => { :balance=> "0.0000", :price=>"9.0000"} },
         { 7 => { :balance => "34030.0000", :price => "34030.0000" } }},
  and so on...
]

Is this posible?

A: Due the current format of the data you have, you'll need more than a couple of transformations. Most of them based on transforming the values of the resulting hash, after grouping the hashes in the array by their only key:
data
  .group_by { |hash| hash.keys.first }                                     # (1)
  .transform_values { |value| value.flat_map(&:values) }                   # (2)
  .transform_values { |values| values.index_by { |value| value[:month] } } # (3)

The first transformation is to group the current object, holding an array of hashes, by its only hash key, hence the keys.first, resulting in:
{
  "A1"=>[
    {"A1"=>{:month=>1.0, :balance=>"0.0000", :price=>"9.0000"}},
    {"A1"=>{:month=>7.0, :balance=>"34030.0000", :price=>"34030.0000"}}
  ],
  "A3"=>[{"A3"=>{:month=>4.0, :balance=>"34030.0000", :price=>"34030.0000"}}]
}

The second, is to extract only the values from each hash, in the resulting hash, with arrays of hashes:
{
  "A1"=>[
    {:month=>1.0, :balance=>"0.0000", :price=>"9.0000"},
    {:month=>7.0, :balance=>"34030.0000", :price=>"34030.0000"}
  ],
  "A3"=>[{:month=>4.0, :balance=>"34030.0000", :price=>"34030.0000"}]
}

Then, it just lacks to transform the array of hashes, to simply an hash, whose keys are the value of month:
{
  "A1"=>{
    1.0=>{:month=>1.0, :balance=>"0.0000", :price=>"9.0000"},
    7.0=>{:month=>7.0, :balance=>"34030.0000", :price=>"34030.0000"}
  },
  "A3"=>{4.0=>{:month=>4.0, :balance=>"34030.0000", :price=>"34030.0000"}}
}

A: @Sebastian's answer is excellent. For variety, let's also consider an iterative approach. Not sure if it's more efficient or easier to understand, but it's always good to understand multiple perspectives.
Setting up the input data you gave us:
arr = [
 {"A1"=>{:month=>1.0, :balance=>"0.0000", :price=>"9.0000"}},
 {"A1"=>{:month=>7.0, :balance=>"34030.0000", :price=>"34030.0000"}},
 {"A3"=>{:month=>4.0, :balance=>"34030.0000", :price=>"34030.0000"}}]

We create a new empty hash for our results.
new_hash = {}

And now iterating over the original data. We're going to make some assumptions about the form of the data.
# We know each thing is going to be a hash.
arr.each do |hsh|
    # Set up some convenient variables for keys and
    # values we'll need later.
    key = hsh.keys.first
    value = hsh.values.first
    month = value[:month]

    # If the output hash doesn't yet have the key,
    # give it the key and assign an empty hash to it.
    new_hash[key] ||= {}
    # Assign the value to the hash, keyed to the current month.
    new_hash[key][month] = value
    # ... and get rid of the month key that's now redundant.
    new_hash[key][month].delete(:month)
end

And the result is:
{"A1"=>{1.0=>{:balance=>"0.0000", :price=>"9.0000"},
        7.0=>{:balance=>"34030.0000", :price=>"34030.0000"}},
 "A3"=>{4.0=>{:balance=>"34030.0000", :price=>"34030.0000"}}}

A: Arguably it would be more useful for the desired return value to be a hash:
h = {"A1"=>{1=>{:balance=>    "0.0000", :price=>    "9.0000"},
            7=>{:balance=>"34030.0000", :price=>"34030.0000"}},
     "A3"=>{4=>{:balance=>"34030.0000", :price=>"34030.0000"}}}

That way you could write, for example:
require 'bigdecimal'

BigDecimal(h['A1'][7][:price])
  #=> 0.3403e5

See BigDecimal. BigDecimal is generally used in financial calculations because it avoids round-off errors.
This result can be obtained by changing the values of :month to integers in arr:
arr = [
  {"A1"=>{:month=>1, :balance=>    "0.0000", :price=>    "9.0000"}},
  {"A1"=>{:month=>7, :balance=>"34030.0000", :price=>"34030.0000"}},
  {"A3"=>{:month=>4, :balance=>"34030.0000", :price=>"34030.0000"}}
]

and by computing:
h = arr.each_with_object({}) do |g,h|
  k,v = g.flatten
  (h[k] ||= {}).update(v[:month]=>v.reject { |k,_| k == :month })
end

See Hash#flatten, Hash#update (aka merge!) and Hash#reject.
One could alternatively write:
h = arr.each_with_object(Hash.new { |h,k| h[k] = {} }) do |g,h|
  k,v = g.flatten
  h[k].update(v[:month]=>v.reject { |k,_| k == :month })
end

See the form of Hash::new that takes a block.


text:
Q: copy windowsform chart to clipboard VB I need to copy a chart (System.Windows.Forms.DataVisualization.Charting.Chart) to clipboard in order to paste it in other application. I use below code but it gives error on the last line for "img" says "Value of Type Bitmap cannot be converted to Bitmapsource"
Any help to rectify the error is highly appreciated.
Private Sub CopyChartBtn_Click(sender As Object, e As RoutedEventArgs) Handles CopyChartBtn.Click

    Dim main = DirectCast(Application.Current.MainWindow, MainWindow)
    Dim SET_H = DirectCast(main.Frame1.Content, SET_Home)
    Dim chart1 = DirectCast(SET_H.Benchchart.Child, System.Windows.Forms.DataVisualization.Charting.Chart)

    'save image
    Dim img As New System.Drawing.Bitmap(chart1.Width, chart1.Height)
    Dim gr As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(img)
    chart1.Printing.PrintPaint(gr, New System.Drawing.Rectangle(System.Drawing.Point.Empty, chart1.Size))
    Clipboard.SetImage(img)

End Sub

My project is WPF and I am hosting windowsform chart in it. Maybe that is the problem because when I run it in a windows form project it works fine

A: I used System.Windows.Forms.Clipboard.SetImage(img) and it works.Originally when it is a WPF project it uses System.Windows.Clipboard.SetImage(img) when not using the namespace


text:
Q: CSS Animation (Appear from the side by clicking) I'm trying to make something apppear from the right side in a div when I'm click on it.
It's a Div (dish) that have 2 Div in it (infoDish) and (validation).
infoDish have a width of 100%, validation have a width of 20% but is hidden unless I click on Dish.
I can make validation appear and disappear but the thing is it's instantaneus and I want to create an animation that take 1 or 2 seconds to make it appear from the right side (like you open the window from the right to the left).

.plat {
  border: 1px solid black;
  height: 70px;
  width: 95%;
  display: flex;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  background-color: white;
  margin-bottom: 20px;
  margin-left: 3%;
  cursor: pointer;
}
.plat:hover .divValid {
  border: 1px solid purple;
  background-color: #99E2D0;
  border-radius: 0 20px 20px 0;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 20%;
}

.partRouge {
  border: 1px solid red;
  height: 100%;
  width: 100%;
}

.divTitlePlat {
  border: 1px solid orangered;
  height: 50%;
  width: 100%;
  padding-left: 2%;
}

.divTitlePlat h3 {
  font-size: 20px;
  margin-top: 0;
}

.divInfoPlat {
  border: 1px solid blue;
  height: 50%;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.divDescPlat {
  border: 1px solid green;
  height: 100%;
  width: 80%;
  padding-left: 2%;
}

.divPricePlat {
  border: 1px solid yellow;
  height: 100%;
  width: 20%;
}/*# sourceMappingURL=menuresto.css.map */

Tartare de poulpe acidulé

                                        Aux zests d'orange

                                        25€

A: I don't know if I understood what you really want to do...
But if you want to add a little delay, not to change instantly you can add the CSS property transition in the class with the hover. You can even precise for each property you want a delay and the delay. To do this, you have to write:
transition: 1s;

To have more informations about this property, you can read:
https://www.w3schools.com/css/css3_transitions.asp
With your code, it's not perfect but if it's what you were searching for, the changement on the hover is now not instantly, but with a delay of 1 second.

.plat {
  border: 1px solid black;
  height: 70px;
  width: 95%;
  display: flex;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  background-color: white;
  margin-bottom: 20px;
  margin-left: 3%;
  cursor: pointer;
}
.plat:hover .divValid {
  border: 1px solid purple;
  background-color: #99E2D0;
  border-radius: 0 20px 20px 0;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 20%;
  transition: 1s;
}

.partRouge {
  border: 1px solid red;
  height: 100%;
  width: 100%;
}

.divTitlePlat {
  border: 1px solid orangered;
  height: 50%;
  width: 100%;
  padding-left: 2%;
}

.divTitlePlat h3 {
  font-size: 20px;
  margin-top: 0;
}

.divInfoPlat {
  border: 1px solid blue;
  height: 50%;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.divDescPlat {
  border: 1px solid green;
  height: 100%;
  width: 80%;
  padding-left: 2%;
}

.divPricePlat {
  border: 1px solid yellow;
  height: 100%;
  width: 20%;
}/*# sourceMappingURL=menuresto.css.map */

Tartare de poulpe acidulé

            Aux zests d'orange

            25€


text:
Q: Always getting response match (200) and login even if i put wrong creditential in android login form? i'm trying to validate user with json using retrofit2 in android but it always giving access even if i put wrong password and phone no.
JSON
 {
  "code": 200,
  "content": {
    "parents_id": 13,
    "parents_name": "Rafaqat Ali",
    "parents_cellno": "03016138728",
    "parents_password": "1234",
    "branch": 41,
    "school_name": "The Scholars College of Sciences Commerce ZWL",
    "school_contact": "03012370304",
    "school_address": "Old Chawinda Road Zafarwal 03012370304",
    "school_logo": "https://apps.eduportal-pk.com/EduPortal/Production/img/10832thescholar.png",
    "school_youtube": "https://www.youtube.com/channel/UCfUZ6NIGwShecxprTrCLsAQ",
    "school_fb": "https://web.facebook.com/The-Scholars-College-Of-Sciences-and-Commerce-Zafarwal-391658255028642/"
  }
}

Model Class:
public class ResLogin {

@SerializedName("code")
@Expose
private Integer code;

public Integer getCode() {
    return code;
}

public void setCode(Integer code) {
    this.code = code;
}

}
API Interface:
public interface APIServices {
@FormUrlEncoded
@POST("EduPortal/Production/apis/services.php?call=parents_authen&cellno=03016138728&password=1234")
Call<ResLogin> doLogin(@Field("parents_cellno") String parents_cellno, @Field("parents_password") String parents_password);

}
MainActivity:
   private void sendLoginReqWithRetrofit(String parents_cellno, String parents_password) {
    // login_progress.setVisibility(View.VISIBLE);
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://apps.eduportal-pk.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    APIServices services = retrofit.create(APIServices.class);
    Call<ResLogin> loginCall = services.doLogin(parents_cellno, parents_password);
    loginCall.enqueue(new Callback<ResLogin>() {
        @Override
        public void onResponse(Call<ResLogin> call, Response<ResLogin> response) {
            //login_progress.setVisibility(View.GONE);
            if (response.isSuccessful()) {
                ResLogin resLogin = response.body();
                if (resLogin != null && resLogin.getCode() == 200) {

                    Toast.makeText(getApplicationContext(), "login successful", Toast.LENGTH_LONG).show();
                    //open your next screen
                } else {
                    Toast.makeText(getApplicationContext(), "login failed", Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onFailure(Call<ResLogin> call, Throwable t) {
            // login_progress.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

I'm new in android development and also with rest Api's so i shall be very thankful with your help!

A: check your api with post-man. If the server send always 200 then it will login always. And if you check status code 200 that might log in you always.


text:
Q: Java extends from class with  Can you explain what is the meaning of  in the below code snippet
public class NoteAdapter extends  ArrayAdapter<Note>{

}

In my example Note is java class.

A: It means Note adapter inherits from ArrayAdapter which is a generic class.The generic class ArrayAdapter accepts an argument of type Note.To understand more visit the topic Generics in java


text:
Q: Inserting data with pandas or psycopg with a serial key? I have a simple dimension table which is storing all of the unique dimensions from several files.
In postgres, I made the table:
CREATE TABLE dimension_purpose (
  purpose_key SERIAL PRIMARY KEY,
  purpose text NOT NULL UNIQUE
);

Now I am trying to add the new rows to this table efficiently. I am able to identify the new dimensions easily (using pandas), but I am having trouble inserting them into this table. I typically use
def load_to_database(table_name, file_object, header=True):
    fake_conn = sqlalchemy.create_engine(engine).raw_connection()
    fake_cur = fake_conn.cursor()
    sql = 'COPY {} FROM STDIN WITH CSV HEADER'.format(table_name)
    fake_cur.copy_expert(sql=sql, file=file_object)
    fake_conn.commit()
    fake_cur.close()

If I try to bulk copy, I get an error that 'purpose' is not an integer (it is trying to insert itself into the purpose_key field).
What is the best way to insert a single column of data into the purpose field and then have the SERIAL purpose_key update automatically?
Can I do this with df.to_sql if my df is just one column?

A: You can specify the columns in your COPY command, e.g.
COPY dimension_purpose (purpose) FROM STDIN WITH CSV HEADER

http://www.postgresql.org/docs/current/static/sql-copy.html


text:
Q: System.UnauthorizedAccessException while saving a file I published my website on the IIS6.
When saving a file by File.WriteAllText("C:\" + txtSaveExport.Text + ".CSV", b.ToString());. Its gives an error as:

em.UnauthorizedAccessException: Access to the path 'C:\hj.CSV' is denied. ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.``

How  can this be handled?

A: You need to give writing permissions to the Aspnet user in that folder.
See this:
http://devnet.logixml.com/rdPage.aspx?rdReport=Article&dnDocID=209
Best regards.

A: It's not a good idea to write to a variable directory under C: drive. I suggest you not to give permissions to write under C, rather, write to a directory under your web app's directory, which you can get by Server.MapPath("~"). Make sure you give write access to the application pool's user account to whatever folder under your app directory, and you'll be much safer.


text:
Q: plugin_action_links Filter Hook Deprecated? http://adambrown.info/p/wp_hooks/hook/plugin_action_links_%7B$plugin_file%7D
Says the hook is deprecated.  However, the {$prefix}plugin_action_hook_{$plugin_file} is not.  I poked around the wp-admin/includes/class-wp-plugins-list-table.php file for the hook, and found this:
$actions = apply_filters( $prefix . "plugin_action_links_$plugin_file", $actions, $plugin_file, $plugin_data, $context );

$prefix is defined a few lines above:
$prefix = $screen->is_network ? 'network_admin_' : '';

Since I was able to get my add_filter call to plugin_actions_row_{$plugin_file} to work, I'm assuming the filter hook is still there. Well, sort of: the filter is still available as it's not a network admin screen.  Correct? And one could use...
add_filter( 'network_admin_plugin_action_links_{$plugin_file}', 'do_something' )

...to put a link into the network's plugin screen?

A: Yes, both should work as expected:
"plugin_action_links_{$plugin_file}"
"network_admin_plugin_action_links_{$plugin_file}"
Note that I'm using " instead of '.
PS: The term is deprecated, not depreciated.

A: This should be backward compatible and error free
"{$prefix}plugin_action_links_{$plugin_file}"


text:
Q: Laravel - How to change app domain into to the test? I have used app domain on my laravel projects till today, but today mozilla starts open app domains with `https..
So I edited my laravel.app.conf file and changed Servername as laravel.test then restart my apache2
sudo service apache2 restart

But this time local website doesn't open, it says server not found..  Did I something wrong ? Or am I need to do something else ?
Edit: Also I changed /etc/hosts file too

A: I just restart pc and now it works (But I restarted apache ?)


text:
Q: RealmList as a JSON Schema - Mongo DB Realm I have a simple model class from which I need to generate the schema on Mongo DB Atlas. But I'm having troubles when it comes to defining RealmList<String> inside a JSON schema. If I insert "array" as a bsonType, I get an error. What should I write instead?
Model class:
class Note : RealmObject {
    @PrimaryKey
    var _id: ObjectId = ObjectId.create()
    var title: String = ""
    var description: String = ""
    var images: RealmList<String> = realmListOf()
    var date: RealmInstant = RealmInstant.from(System.currentTimeMillis(),0)
}

Current Schema:
{
  "bsonType": "object",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "title": {
      "bsonType": "string"
    },
    "description": {
      "bsonType": "string"
    },
    "images": {
      "bsonType": "array"
    },
    "date": {
      "bsonType": "date"
    }
  },
  "required": [
    "_id",
    "title",
    "description",
    "images",
    "date"
  ],
  "title": "Note"
}

A: I am not sure which mode you're using but if you're in development mode, when you add an object in the SDK, the server will automatically generate a matching object, as long as the changes are additive, like adding a new object or property
In the queston, the 'images' bson definition looks incomplete
"images": {
   "bsonType": "array"
},

While it is an array, it's an array of strings so I believe it should look more like this
"images": {
   "bsonType": "array",
   "items": {
      "bsonType": "string"
   }
}

Where the type of items is defined as a string


text:
Q: Подскажите пожалуйста как доделать задачу по процедуре. Ассемблер Код на масм32. Задача состоит в том чтобы прибавить первый и последний элемент массива используя процедуру(чтобы потом добавить этот код вставкой в си).
Я написал код который суммирует все элементы массива. Помогите пожалуйста как сделать в процедуре чтоб прибавить первый к последнему....
Мой код (в ax сейчас выводит 94, а должно 8):
.data
a DW 6, 3, 3, 50, 8, 6, 2, 6, 8, 2
n DB 10
nsd DD ?
.code

start:
    xor edi,edi
    xor ecx,ecx
    mov ax,[a]
    mov cl,[n]
    dec cl
cykl:
    push ax
    inc edi
    inc edi
    mov ax,[a+edi]
    push ax

call Search
    dec cl
    test cl,cl
jnz cykl

Search PROC
    pop esi
    pop ax
    pop bx

    push esi
    push ebp
    mov ebp,esp

    add ax,bx

    pop ebp
    ret
Search ENDP
END START


text:
Q: HTTPUrlConnection 500 error only on android I've been trying to call the server from my Android App but I keep getting 500 ERROR

java.io.FileNotFoundException: https:// VALID URL

But when i use the same code block and run as Java application, it returns 200 response and works fine.
URL url = new URL("https://VALID URL");
HttpURLConnection conn = null;
conn =  (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("http.protocol.version", "HTTP/1.1");
conn.setRequestProperty("http.socket.timeout", "30");
conn.setRequestProperty("http.protocol.content-charset", "UTF-8");
conn.setRequestProperty("apiKey","90c67a05-7613-48c5-a986-4d4ba5649cb7");
conn.setRequestProperty("authId",authID);
conn.setRequestProperty("connectionTicket",connTicket);
conn.setRequestProperty("State", "Open,Pending,Canceled,Rejected,Completed");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
int httpresponse = conn.getResponseCode();
System.out.println(httpresponse);
System.out.println(conn.getErrorStream());

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

The above is the code I used in both of my applications. Using HTTPClient might solve the problem but I haven't tried yet. But since I've been using HTTPURLConnection throughout, I would like to know if there is a possible solution to this.
This is the trace
06-29 11:35:00.438: W/System.err(5000): java.io.FileNotFoundException: https://VALID URL (edited)
06-29 11:35:00.438: W/System.err(5000):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
06-29 11:35:00.478: W/System.err(5000):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
06-29 11:35:00.488: W/System.err(5000):     at com.Tabs.List$Populate_List.doInBackground(List.java:126)
06-29 11:35:00.488: W/System.err(5000):     at com.Tabs.List$Populate_List.doInBackground(List.java:1)
06-29 11:35:00.548: W/System.err(5000):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-29 11:35:00.598: W/System.err(5000):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-29 11:35:00.648: W/System.err(5000):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-29 11:35:00.648: W/System.err(5000):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-29 11:35:00.678: W/System.err(5000):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-29 11:35:00.698: W/System.err(5000):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-29 11:35:00.708: W/System.err(5000):     at java.lang.Thread.run(Thread.java:856)

I am btw running this as a background thread. That explains the AsyncTask part. I am not sure if that has got something to do here.
there are similar threads

*

*java.io.FileNotFoundException for valid URL

*FileNotFoundException while getting the InputStream object from HttpURLConnection


text:
Q: Android - Check if a row within the DB exists I've created a method where the app checks if a number exists in the DB:
    Cursor player = playerDatabase.rawQuery("select * from playerTable where playerNumber ="+number,null);
  try {
      if (player.getCount() >= 0) {
          player.close();
          return true;
      }
      else{
          return false;
      }
  }finally {
      if(player != null){
          player.close();
      }
  }

But the problem is, this always returns true? The reason I am using it this way, is from the previous answers on Stack Overflow.
What is the optimal way of being able to check if a search query returns a row/check if this number exits?

A: This is the most efficient way to find if a row exists or not.
SELECT EXISTS(SELECT 1 FROM playerTable WHERE playerNumber="Here comes the player number");

It will return 1 if there is a row with playerNumber in the table or will return 0 if there is no row in the table.


text:
Q: file upload control problem i am using file upload control in server side when iam trying to get the file it is showing no file present
<asp:FileUpload ID="upldDocument" runat="server" />
string fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
if (upldDocument.HasFile)
{
}

i am getting a empty string as file extension and upldDocument.HasFile is returning false even after selecting a file.
what could be the reason??

A: Based on the posted code, I can only offer a best guess.  There's not enough code posted to be sure what the problem is, but here's my best guess:
If you're not already, you need to check the HasFile property.
See here for a full example:
Edit - added
Using HasFile AFTER the bad code won't help.  You need to put the code to get the extention inside an if statement so that it only attempts to read the extension if there IS a file.
string fileExtension = "";
if (upldDocument.HasFile)
{
  fileExtension  = System.IO.Path.GetExtension(upldDocument.FileName);

}
else
{
   //No file selected by user, which is why you can't get the extension.
   // handle this eventuality here even if it means just returning from the function and not doing anything.
}

A: How are you checking the values? (in what event)
Did you set the enctype attribute of the form to "multipart/form-data" ?


text:
Q: Checking room type and player state before entering room in Inform 7 In this game rooms are private or public, and the player has two states, A or B. Th player can only enter a public room while in state A, but not state B. This is what the desired effect is, but after typing this:
A person can be A or B. A person is usually A.

A room can be private or public. A room is usually public.

Check entering public room:
     if player is B:
            say "You can't do that." instead.

Inform acts like the last block of text doesn't even exist. What am I doing wrong?

A: The entering action applies only to entering containers or supporters. Moving around the map is the going action.
Check going to public room when the player is B:
    say "You can't do that." instead.


text:
Q: How to work around the invalid byte sequence in UTF-8 ArgumentError? I am trying to run the following code where I use nokogiri to parse an xml file. I want to eliminate new line characters from text
contained between  tags. The code I have here, used to work, but for some reason, now it doesn't. Possibly because I
upgraded to ruby-1.9.1.
titles = node.search('b')
titles.each do |e|
  unless e.parent.name == "h4"
    if e.children.children.first.nil? == false
      puts e.children.children.first.text.gsub("\n","")
    end
  end
end

When I run the code I get this error:
HI.  You're using libxml2 version 2.6.16 which is over 4 years old and has
plenty of bugs.  We suggest that for maximum HTML/XML parsing pleasure, you
upgrade your version of libxml2 and re-install nokogiri.  If you like using
libxml2 version 2.6.16, but don't like this warning, please define the constant
I_KNOW_I_AM_USING_AN_OLD_AND_BUGGY_VERSION_OF_LIBXML2 before requring nokogiri.

test.rb:35:in `gsub': invalid byte sequence in UTF-8 (ArgumentError)

A: You could try installing 1.9.2 via RVM.
curl -L https://get.rvm.io | bash
rvm install 1.9.2

If you want ruby to default to your rvm 1.9.2 install, then
rvm use 1.9.2 --default

NOTE: The above are equivalent to:
curl -L https://get.rvm.io | bash -s -- --ruby=1.9.2


text:
Q: If $a$, $b$ and $c$ are sides of a triangle, then prove that $a^\text{2}(b+c-a) + b^\text{2}(c+a-b) + c^\text{2}(a+b-c)$ $\leqslant$ $3abc$
Let $a$, $b$ and $c$ be the sides of a triangle. Prove that $$a^\text{2}(b+c-a) + b^\text{2}(c+a-b) + c^\text{2}(a+b-c) \leqslant 3abc$$

SOURCE: BANGLADESH MATH OLYMPIAD (Preparatory Question.)
I am very new and novice at this problem. I did a little try but couldn't succeed because I was unable to substitute the left term of the inequality into formula. I know a formula that
$a^\text{3} + b^\text{3} + c^\text{3} - 3abc$ = $(a+b+c)(a^\text{2} + b^\text{2} + c^\text{2} - ab -bc - ca)$. But how to use this formula in that case isn't known to me. And how to show the relation of the both side and when they will become equal?
A small help will be enough for me. Thanks in advance.

A: Using the Ravi substitution $$a=y+z,b=x+z,c=x+y$$ we have to prove that
$$x^2y+x^2z+xy^2+xz^2+y^2z+yz^2-6xyz\geq 0$$ But this is AM-GM:
$$x^2y+x^2z+xy^2+xz^2+y^2z+yz^2\geq 6\sqrt[6]{x^6y^6z^6}=6xyz$$

A: It's true for all non-negatives $a$, $b$ and $c$.
Indeed, since our inequality is symmetric, we can assume that $a\geq b\geq c$ and we obtain:
$$3abc-\sum_{cyc}a^2(b+c-a)=\sum_{cyc}(a^3-a^2b-a^2c+abc)=\sum_{cyc}a(a-b)(a-c)\geq$$
$$\geq a(a-b)(a-c)+b(b-a)(b-c)=(a-b)^2(a+b-c)\geq0.$$


text:
Q: Azure Cosmos what happens if partition key value is null In Azure Cosmos I have selected partition key as City. But it is possible that this key can have a null also. In such a case. Will all the City with null be in one partition.
How will the partition be distributed in this case?

A: Fairly certain there is a hidden partition and all the documents without a partition key would go to that partition.
I recall reading this somewhere on SO answers\comments.

A: You can create. Null, Undefined, and empty string are treated as different values in Cosmos DB.
new RequestOptions { PartitionKey = new PartitionKey(null) }

As 4c74356b41 mentioned There will be a separate partition and these values will go under that.


text:
Q: (reactjs) useEffect didn't run in background I'm new to reactjs and and trying to make this simple stopwatch. this code is work in my browser, however when I minimize the browser the time paused, and only continue when I open the browser, do you found something I must be missed? Thanks in advance!
import { useState, useEffect } from "react";

export const SW = () => {
  const [mSec, setMSec] = useState(0);
  const [sec, setSec] = useState(0);
  const [min, setMin] = useState(0);
  const [isOn, setIsOn] = useState(false);
  const start = () => setIsOn(true);
  const stop = () => setIsOn(false);
  const reset = () => {
    setIsOn(false);
    setMin(0);
    setSec(0);
    setMSec(0);
  };

  useEffect(() => {
    let ms;
    if (isOn) {
      ms = setInterval(() => setMSec((mSec) => mSec + 1), 10);
      if (sec === 59) {
        setSec(0);
        setMin((min) => min + 1);
      }
      if (mSec === 99) {
        setMSec(0);
        setSec((sec) => sec + 1);
      }
    }
    return () => {
      clearInterval(ms);
    };
  }, [mSec, sec, isOn]);

  return (

        {min.toString().padStart(2, "0")}:{sec.toString().padStart(2, "0")}:
        {mSec.toString().padStart(2, "0")}

      {!isOn && <button onClick={start}>{!mSec ? "start" : "resume"}</button>}
      {isOn && <button onClick={stop}>stop</button>}
      <button disabled={!mSec} onClick={reset}>
        reset
      </button>

  );
};

A: It's not an issue on useEffect or your code, simply it's how browsers work, they execute JavaScript on the active tabs.
The solution is to use Web Workers API to execute JavaScript in the background.
For more details:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
https://www.w3schools.com/html/html5_webworkers.asp


text:
Q: Why chrome use a temporary file and then rename it when downloading files? I'm now impelmenting a simple download utility. I don't know why chrome need a temporary file when downloading from the Internet and then rename it, instead of downloading the file directly with its name. For file consistency? Or other reasons?
Thanks and best regards.

A: Many downloading programs create temporary files that they rename to the final name after the download is complete. That way nobody can mistake a partially downloaded file with the final results.


text:
Q: How to Set Text Inside the Responsive Table - Aspect Ratio of Cell and Table Should be 1:1 I Designed one Table using Responsive Design. It maintains the width and height as same in all the devices. All Cell should be in same width and height.
Cell Height = Responsive Cell Width

+---------+
|   CSS   |
|  Table  |
|   1:1   |
+---------+

I want to place the Text within the Cell without collapsing the aspect ratio of the Cell as well as Table and the Text should be formatted.

Note: Kindly give solution using CSS. Don't use the Javascript or any
  other raw value feeding. All Cell should be in same width and height.

My HTML Source Code:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Bootstrap Table</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

       as;dfjdj f;s f;sj f;sjdf

       as;dfjdj f;s f;sj f;sjdf

       as;dfjdj f;s f;sj f;sjdf

       as;dfjdj f;s f;sj f;sjdf  k kljsf sdf;ljsd fjsd f;lkjsd f;k jsad;lfkjas d;kk ;fjsadf

        asdfsadf

       as;dfjdj f;s f;sj f;sjdf

A: The only method that I am aware of, using only CSS, is to abandon tables (which do not react well to positioning) is to use viewport units to create squares.
Note, this limits the size of the 'cells' and the cells will not affect the size of other cells...that requires javascript.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.parent {
  width: 50vw;
  height: 50vw;
  margin: auto;
}
.child {
  width: 12.5vw;
  height: 12.5vw;
  float: left;
  border: 1px solid green;
}


text:
Q: Web service php tengo este web service POST que trae datos json como hago para mostrarlo en una lista ordenada?
class CurlRequest
    {
        public function sendPost()
        {
            //datos a enviar
            $data = array("a" => "a");
            //url contra la que atacamos
            $ch = curl_init("URL");
            //a true, obtendremos una respuesta de la url, en otro caso,
            //true si es correcto, false si no lo es
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //establecemos el verbo http que queremos utilizar para la petición
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            //enviamos el array data
            curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
            //obtenemos la respuesta
            $response = curl_exec($ch);
            // Se cierra el recurso CURL y se liberan los recursos del sistema
            curl_close($ch);
            if(!$response) {
                return false;
            }else{
                return $response;
            }
        }}
         $new = new CurlRequest();

    $resultado = $new ->sendPost();
    var_dump($resultado);

    $data = file_get_contents($resultado);
$products = json_decode($data, true);

foreach ($products as $product) {
    print_r($product);
}


text:
Q: onfocus onblur issue javascript multiple instace of same field <input type="text" rel="Credit card number" class="defaultColor" name="cc_num" id="txtCardNumber" runat="server" maxlength="20" onblur="cc_number_saved = this.value; this.value = this.value.replace(/[^\d]/g, '');" onfocus="if(this.value != cc_number_saved) this.value = cc_number_saved;"/>

I am saving the value of credit card and replacing the non numeric characters onblur and placing them again onfocus (basically space and dashes). This field will get created multiple time if there are more rooms(I mean if user select more than one room, we are populating credit card field for each room in different container.
Curently if i type different credit card information in other room it is replacing the value with the first room, how do I create a different instance for each room for this credit card field.
I have declare the variable in gloabal scope so it is causing issue I beilive. but not sure how do I make it private for each generated input credit card field with current approch.
var cc_number_saved = "";

Please let me know if it is not clear.

A: Use jQuery to attach values to the DOM element representing the relevant input.
With an id on the input:
<input id = 'input1' >

Then you can assign a value to a data-field attached to the input like this:
$('#input1').on('blur', function(){
    $(this).data('temp', $(this).val();
}

...retaining that value regardless of what you do with the input's value.
And later retrieve it again like this:
var originalVal = $('#input1').data('temp');

Then apply manipulated value back into the input like this:
var newVal = someFunction(originalVal);
$('#input1').val(newVal);

...or whatever.


text:
Q: Não consigo fazer desaparecer cards não pedidos Olá, possuo uma serie de cards que já coloquei os respectivos ids, porém quando clico na opção do menu que desejo ele apenas rola até o card com o id, mas na verdade gostaria que todos os outros desaparecessem e só os do id chamado ficassem. Podem me ajudar? :)

            Varejo
            Indústria
            Marketing
            Seguro
            Educação
            Saúde
            Finanças
            Telecom

E-commerce

Texto

            Saiba mais

Lojas Físicas

Texto

            Saiba mais

Serviços de Consumo

Texto

            Saiba mais

A: É só usar :target tipo o href tem que ser igual ao id.
Ai no CSS só o id:target {display:block}

#varejo,
#industria,
#marketing {
    display: none;
}
#varejo:target ,
#industria:target ,
#marketing:target {
    display: block;
}

    Varejo
    Indústria
    Marketing

E-commerce

Texto

    Saiba mais

Lojas Físicas

Texto

    Saiba mais

Serviços de Consumo

Texto

    Saiba mais


text:
Q: Pretashop get new order details in a custom module I am creating a custom module in Prestashop. In that module I want to get
the order details when a new order has been made on the store. So I want
to know which hook should I use and how to get new order details along with
customer details when a new order has been made. Any help and suggestions will be really appreciable.

A: Use a hook actionValidateOrder. Hook gives you params array which includes Order, Cart, Customer, Currency and OrderState objects associated with it.
With them you can now get customer and order details.
public function hookActionValidateOrder($params) {
    $order = $params['order'];
    $customer = $params['customer'];

    $order_details = $order->getOrderDetailList();
}

Hook needs to be registered in module install.
public function install() {
    return parent::install && $this->registerHook('actionValidateOrder');
}

A: You can use displayOrderConfirmation hook in your main controller to get details of any order.
Following code can help you:
 public function hookDisplayOrderConfirmation($params = null)
{
    $id_customer = $params['objOrder']->id_customer;
            //Get all other details using the $params['objOrder'] order object
}


text: Q: Firefox fixed element lost width I have a problem with fixed element width in Firefox. Element is search bar. Under search bar is a scrollable part of page. Search bar was scrolling with the rest of the page so I added class with position fixed. Now search bar is fixed and the rest of the page is scrolling under the bar. In Chrome and Opera everything works fine but in Firefox search bar lost it's width. Why?


text:
Q: PyQt - Create QLabels at runtime and change text afterwards i want to create QLabels dynamically at runtime, and change the Text afterwards.
I did it like that:
def __init__(self, *args, **kwargs):
    QWidget.__init__(self, *args, **kwargs)
    self.counter = 0
    self.items = self.read_hosts()
    self.layout = QGridLayout()
    for item in self.items:
        self.item = QLabel(item, self)

        self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.item.setAlignment(Qt.AlignCenter)
        self.item.setStyleSheet("QLabel {background-color: green;}")
        self.layout.addWidget(self.item,self.counter, 0)
        self.counter += 1
    self.setLayout(self.layout)
    self.startWorker()
    self.show()

def change_txt(self, lb, i):
     self.item.setText("{}".format(i))

It won't work.
I understand why it would change just the text of the last label. I'm doing something wrong during assignment.
How can I create all labels completely variably and subsequently change the texts?
I am using:
PyQT5
on Windows 10
Thanks!
Here is my whole code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import os

class Worker(QObject):
    update = pyqtSignal(str,int)
    exception = pyqtSignal(str)

    def read_hosts(self):
        #try:
            file = open("hosts.ini", "r")
            return file.readlines()
        #except Exception as ex:
            #self.exception.emit(str(ex))

    def check_ping(self):
        #try:
            hosts = self.read_hosts()
            while True:
                for host in hosts:
                    print(host)
                    params = " -l 1000"
                    response = os.system("ping  " + host + params)
                    print("weiter")
                    self.update.emit(host, response)

        #except Exception as ex:
            #self.exception.emit(str(ex))

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.counter = 0
        self.items = self.read_hosts()
        self.layout = QGridLayout()
        for item in self.items:
            self.item = QLabel(item, self)
            self.item.setObjectName("label" + str(self.counter))
            print("label" + str(self.counter))
            self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            self.item.setAlignment(Qt.AlignCenter)
            self.item.setStyleSheet("QLabel {background-color: green;}")
            self.layout.addWidget(self.item,self.counter, 0)
            self.counter += 1
        self.setLayout(self.layout)
        self.startWorker()
        self.show()

    def startWorker(self):
        self.thread = QThread()
        self.obj = Worker()
        self.thread = QThread()
        self.obj.moveToThread(self.thread)
        self.obj.update.connect(self.onUpdate)
        self.obj.exception.connect(self.onException)
        self.thread.started.connect(self.obj.check_ping)
        self.thread.start()

    def read_hosts(self):
        #try:
            file = open("hosts.ini", "r")
            return file.readlines()
        #except Exception as ex:
            #self.exception.emit(str(ex))

    def onException(self, msg):
        QMessageBox.warning(self, "Eine Exception im Worker wurde geworfen: ", msg)

    def onUpdate(self, lb, i):
        label = lb
        self.label0.setText("{}".format(i))

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

hosts.ini:
192.168.1.1
192.168.1.2
192.168.1.30

A: I have improved your code in the following aspects:

*

*If your layout has a column it is not necessary to use QGridLayout, just QVBoxLayout.

*Having a read_hosts() method for each class is a waste, so I've created a unique function.

*self.item is an attribute of the class that is continually being overwritten so it is not necessary to create them.

*The objectName should be the name of the host, that is, the IP, since that is the information that the thread has.

*To find the label through the objectName you can use findChild().

import sys
import os

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def read_hosts():
    file = open("hosts.ini", "r")
    return file.readlines()

class Worker(QObject):
    update = pyqtSignal(str, int)
    exception = pyqtSignal(str)

    def check_ping(self):
        hosts = read_hosts()
        while True:
            for host in hosts:
                params = "-l 1000"
                response = os.system("ping  {} {}".format(host, params))
                print("weiter")
                self.update.emit(host, response)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.layout = QVBoxLayout(self)

        hosts = read_hosts()
        for host in hosts:
            label = QLabel(host)
            label.setObjectName(host)
            label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            label.setAlignment(Qt.AlignCenter)
            label.setStyleSheet("QLabel {background-color: green;}")
            self.layout.addWidget(label)
        self.startWorker()

    def startWorker(self):
        self.thread = QThread()
        self.obj = Worker()
        self.thread = QThread()
        self.obj.moveToThread(self.thread)
        self.obj.update.connect(self.onUpdate)
        self.obj.exception.connect(self.onException)
        self.thread.started.connect(self.obj.check_ping)
        self.thread.start()

    def onException(self, msg):
        QMessageBox.warning(self, "Eine Exception im Worker wurde geworfen: ", msg)

    def onUpdate(self, host, value):
        label = self.findChild(QLabel, host)
        label.setText("{}".format(value))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())


text:
Q: Can the lithium test be applied to differentiate brown dwarfs from other substellar objects? The lithium test is often used to differentiate brown dwarfs from low-mass M-type dwarfs (see e.g. Martin et al. (1994)), because brown dwarfs (at least the lower-mass ones) do not burn lithium, whereas M-type dwarfs can and do.
Can the lithium test be applied to distinguish brown dwarfs from other substellar objects, such as massive gas giants or sub-brown dwarfs? I don't know what the lithium abundances are in those objects, though I expect it would depend on the exact type. Such a test could work if brown dwarfs have comparatively higher lithium abundances, though these other objects would not fuse lithium, either.

A: The lithium test has an ambiguity because it also depends on the age of the objects.
Li is depleted once the cores of fully convective objects reach temperatures of about $3\times 10^{6}$ K. The time at which this occurs depends on the contraction timescale of newly formed objects. This timescale is longer for lower mass objects.
Thus we can say that objects with $M<0.06 M_{\odot}$ will never burn their lithium. However, lithium will also survive in younger objects with higher masses.
For instance, in the Pleiades, with an age of 125 Myr, Li is expected to survive in all objects with $M<0.075M_{\odot}$, hence it is an ideal test to determine whether an object is a brown dwarf or not in clusters at that age.
In younger clusters, the mass limit is even higher. For instance at 35 Myr, objects with $M<0.12M_{\odot}$ will keep their lithium (Chabrier & Baraffe 1997).
In fact, this dependence is now used to estimate the age of young clusters by finding the lowest luminosity (mass) stars which still retain all their lithium - known as the "lithium depletion boundary" age (Jeffries & Oliveira 2005).
The lithium test was successfully applied to identify brown dwarfs in the Pleiades by Basri et al. (1996) and Stauffer et al. (1998), and establish the cluster age as 125 Myr, older than previously thought (the older age is why earlier efforts to find Li failed in what turned out to be low-mass stars rather than brown dwarfs).
The Li-test cannot be used to discriminate between brown dwarfs and even lower mass objects. We expect such objects to retain their cosmic Li abundance (currently $A(Li) = 3.3$ on a logarithmic number density scale where the hydrogen abundance $A(H)=12$), so that all objects with $M<0.06M_{\odot}$ should have their full complement. A further problem with using Li is that it will start to form molecules in the atmospheres of very cool, low-mass objects (e.g. LiH) making interpretation extremely difficult.
However, an exciting avenue for research is the "deuterium test". Deuterium behaves like Li, but at lower masses. In other words, D-burning takes place at temperatures below $10^{6}$ K and occurs at the centres of extremely low mass brown dwarfs ($\geq 0.013M_{\odot}$) on mass-dependent timescales of a few to 50 Myr. The detection of D in the atmosphere of an object would give you an upper limit to its mass, which depended on its age. i.e If it were an old object, then D-detection would tell you it had $M<0.013M_{\odot}$. The mass limit would be higher at younger ages (Chabrier et al. 2000).
The detection of deuterium will require the detection of HDO or CrD molecules in the mid-IR part of the spectrum, but will possibly be feasible with the James Webb space telescope. More importantly than merely identifying objects below a certain mass, the "deuterium depletion boundary" might offer them means to get the absolute ages of young clusters in the crucial range 2-20 Myr, when planetary systems are forming (Soderblom et al. 2014).


text:
Q: Imprecisão do resultado de soma de coluna Ambiente: Excel 2013
Exemplo: Ao somar os valores de uma coluna com 1110 linhas, o resultado obtido é 302.204.548,38
Se acrescentar o valor de 249.998,78 da linha 1111 da mesma coluna, deveria obter 302.454.547,16 mas em vez deste valor o resultado é 302.454.547,159999
Alguém me pode ajudar a ultrapassar esta imprecisão?
Obrigado desde já pela ajuda.
António Jesus

A: Olha, isso na verdade não é um bug, mas uma característica de como os números em ponto flutuante (com casas decimais) são armazenados e operados na memória dos computadores.
Como os números são codificados em binário e tem uma precisão limitada, há números fracionários que não tem um correspondente exato em binário. Quando o valor resultante de uma operação matemática resulta em um desses números, aparece uma diferença que não existiria na matemática "lápis e papel" em base 10.
Um exemplo bem mais simples que o seu seria:
   =1*(0,5-0,4-0,1)

Digite isso em qualquer célula do Excel e você vai receber um valor bem pequeno, mas diferente de 0, que seria o esperado.
A Microsoft tem dois artigos explicando isso e sugerindo correções:

*

*KB78113

*KB214118


text:
Q: Elastic search Average time difference Aggregate Query I have documents in elasticsearch in which each document looks something like as follows:
{
  "id": "T12890ADSA12",
  "status": "ENDED",
  "type": "SAMPLE",
  "updatedAt": "2020-05-29T18:18:08.483Z",
  "events": [
    {
      "event": "STARTED",
      "version": 1,
      "timestamp": "2020-04-30T13:41:25.862Z"
    },
    {
      "event": "INPROGRESS",
      "version": 2,
      "timestamp": "2020-05-14T17:03:09.137Z"
    },
    {
      "event": "INPROGRESS",
      "version": 3,
      "timestamp": "2020-05-17T17:03:09.137Z"
    },
    {
      "event": "ENDED",
      "version": 4,
      "timestamp": "2020-05-29T18:18:08.483Z"
    }
  ],
  "createdAt": "2020-04-30T13:41:25.862Z"
}

Now, I wanted to write a query in elasticsearch to get all the documents which are of type "SAMPLE" and I can get the average time between STARTED and ENDED of all those documents. Eg. Avg of (2020-05-29T18:18:08.483Z - 2020-04-30T13:41:25.862Z, ....). Assume that STARTED and ENDED event is present only once in events array. Is there any way I can do that?

A: You can do something like this. The query selects the events of type SAMPLE and status ENDED (to make sure there is a ENDED event). Then the avg aggregation uses scripting to gather the STARTED and ENDED timestamps and subtracts them to return the number of days:
POST test/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "status.keyword": "ENDED"
          }
        },
        {
          "term": {
            "type.keyword": "SAMPLE"
          }
        }
      ]
    }
  },
  "aggs": {
    "duration": {
      "avg": {
        "script": "Map findEvent(List events, String type) {return events.find(it -> it.event == type);} def started = Instant.parse(findEvent(params._source.events, 'STARTED').timestamp); def ended = Instant.parse(findEvent(params._source.events, 'ENDED').timestamp); return ChronoUnit.DAYS.between(started, ended);"
      }
    }
  }
}

The script looks like this:
Map findEvent(List events, String type) {
  return events.find(it -> it.event == type);
}
def started = Instant.parse(findEvent(params._source.events, 'STARTED').timestamp);
def ended = Instant.parse(findEvent(params._source.events, 'ENDED').timestamp);
return ChronoUnit.DAYS.between(started, ended);


text:
Q: Phalcon, Send mail in background process I using phalcon framework,
I need send email (in background process) after submit contact form
Everyone help me with the demo code.
thanks all.

A: No can't help you with demo code. But can help you with the steps:

*

*Prepare mail message

*Put into into queue

*In cli task(which will be fired by cron) get messages from queue and send it

A: You don't need any Phalcon CLI tasks or any cron job. You can just send your mail directly. You can use the phalcon incubator or this extension to easily add the mailer feature into your Phalcon project.
Based on your level, I suggest you to use the default operating system mailer which is supposed to be able to handle queuing in a native way so you don't have to bother developing your own cli task queue manager within your application.
The basic sendmail service will automatically queue the messages and try to send it again later if something went wrong.
$config = [
    'driver'     => 'sendmail',
    'sendmail'   => '/usr/sbin/sendmail -bs',
    'from'       => [
        'email' => 'example@gmail.com',
        'name'  => 'YOUR FROM NAME'
    ]
];