text:
Q: Woocommerce - Remove add to cart button functionality and change button text In WooCommerce I would like to replace add to cart button and change it to "Read More" but only for certain product categories.
I've tried using quite a few different code snippets for this but nothing seems to give me the results I'm wanting.
The reason is that I want to use certain sections of my shop as a product catalog displaying items and their prices but not allowing users to purchase them.
Does anyone know how/if this would be possible?
Any help at all would be much appreciated.

A: Here are some functions that will replace for some defined product categories only:

*

*In Shop and archives pages: The button add to cart by a link to the product

*In Single product pages: add to cart button and quantities by your custom button

You will have to define in that fuctions:

*

*The product categories in the arrays (2 times)

*The  "Read more" button product link (for simple product pages)

Here is the code:
// Replacing the button add to cart by a link to the product in Shop and archives pages
add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_conditionally_loop_add_to_cart_button', 10, 2 );
function replacing_conditionally_loop_add_to_cart_button( $button, $product  ) {
    // Set HERE your product categories in the array
    $categories = array( 't-shirts', 'gloves' );

    if( has_term( $categories, 'product_cat', $product->get_id() ) ){
        $button_text = __( "View product", "woocommerce" );
        $button = 'get_permalink() . '">' . $button_text . '';
    }
    return $button;
}

// Button replacement function for Single product pages (SET the link below)
function custom_button_read_more( $product_link ){
    global $product;

    // Set HERE your product link
    $product_link = home_url( '/some-link-to-define/' );

    $button_text = __('Read more', 'woocommerce');
    echo ''.$button_text.'';
}

// replacing add to cart button and quantities by your custom button in Single product pages
add_action( 'woocommerce_single_product_summary', 'replacing_conditionally_template_single_add_to_cart', 1, 0 );
function replacing_conditionally_template_single_add_to_cart() {
    global $product;

    // Set HERE your product categories in the array
    $categories = array( 't-shirts', 'gloves' );

    if( has_term( $categories, 'product_cat', $product->get_id()) ){

        // For variable product types
        if( $product->is_type( 'variable' ) ){
            // Removing add to cart button and quantities
            remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );

            // The button replacement
            add_action( 'woocommerce_single_variation', 'custom_button_read_more', 20 );
        }
        else // For all other product types
        {
            // Removing add to cart button and quantities
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

            // The button replacement
            add_action( 'woocommerce_single_product_summary', 'custom_button_read_more', 30 );
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
All code is tested on Woocommerce 3+ and works.

Similar answer: Customize "Add to cart" button for a specific product category in WooCommerce


text:
Q: Pandas dataframe has regex keywords I have a df with list of keywords and its corresponding columns
   Column 1         Column2  Column3
    Processing        Test     CPI
    WCR               Key      Comp
    DD|FF         Interp   Set ( If both keywords are present then
                                     select this row)

Folder path : C:\WCR basic\testing\dual, it should match with column1 WCR row value and return value of column2 and column3. Output : Key, Comp
When i loop through the list of filepath, if file path contains any of the keyword present in column1 then it should retrun the values from column2 and 3. I am not sure if using regex in this situation would give better result?

A: IIUC, you might have an easier time using a list comprehension, and searching whether each value of Column 1 is a substring of your folder path:
folder_path = 'C:\\WCR basic\\testing\\dual'

>>> df.loc[[i in folder_path for i in df['Column 1']], ['Column2','Column3']]
  Column2 Column3
1     Key    Comp

redpajama_set_name: RedPajamaStackExchange


text:
Q: Order in a list of adjectives Is this the correct order in a list of adjectives in a sentence?:
1.Quantity or number
2.Quality or opinion
3.Size
4.Age
5.Shape
6.Color
7.Proper adjective (often nationality, other place of origin, or material)
8.Purpose or qualifier
Example: I have 1 cheap little old white american sleeping mattress.
Is it the same thing if we use adjectival nouns(nouns which occupy the function of an adjective when there are 2 nouns in a row)?. Here are some examples:

a race horse is a horse that runs in races
  a horse race is a race for horses
  a boat race is a race for boats
  a love story is a story about love
  a war story is a story about war
  a tennis ball is a ball for playing tennis
  tennis shoes are shoes for playing tennis
  a computer exhibition is an exhibition of computers


text:
Q: Prism RegisterTypeForNavigation() in Module.Initialize() not working I am using Prism 6.3.0 with Autofac.
When I register a type for navigation inside the Initialize() method of a IModule like this:
 public class TestModule : IModule
 {
    public TestModule (ContainerBuilder builder)
    {
        this.Builder = builder;
    }

    private ContainerBuilder Builder { get; set; }

    public void Initialize()
    {
        ...
        this.Builder.RegisterTypeForNavigation<ViewTest>();
    }
}

And then try to navigate from another Module like this:
  private void NavigateTest()
        =>
            this.RegionManager.RequestNavigate("MainContentRegion", new Uri("ViewTest", UriKind.Relative), this.Result);

    private void Result(NavigationResult obj)
    { // Breakpoint here
    }

It fails with the following error:

The requested service 'ViewTest (System.Object)' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

And StackTrace:

en Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
  en Prism.Autofac.AutofacServiceLocatorAdapter.DoGetInstance(Type serviceType, String key)
  en Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) en c:\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:línea 49

But if I register the type in ConfigureContainerBuilder(ContainerBuilder builder), it works fine and I can navigate without problems:
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
    {
        builder.RegisterTypeForNavigation<ViewTest >();

        base.ConfigureContainerBuilder(builder);
    }

Is it possible to do the registration in the Module's Initialize() method or does it have to be in ConfigureContainerBuilder()?
Thanks

A: Autofac does not support modules as it is a immutable container.  The Builder you are passing in is not the builder the bootstrapper is using, but rather a new instance. For now, you could work around it by updating the Container with the new builder, but Autofac has marked the Update method as obsolete and it will be removed.  Due to this change, going forward I would not recommend Autofac for apps that require modules, because in v7 Prism will no longer allow modules to be loaded at all if using Autofac for this reason.
If you feel strongly about this, you could post an issue to the Autofac project asking them not to make the container immutable.


text:
Q: Cs50 member reference base type 'candidate [9]' is not a structure or union I am trying to solve the runoff problem of pset3 in cs50. We have to find the result of a election when the voters input the choice of first 3 preference of candidates.If their isn't a winner with more than 50% of 1st preference of votes then the candidate with the least number of votes is eliminated and looped until there is a winner.
#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max voters and candidates
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9

// preferences[i][j] is jth preference for voter i
int preferences[MAX_VOTERS][MAX_CANDIDATES];

// Candidates have name, vote count, eliminated status
typedef struct
{
    string name;
    int votes;
    bool eliminated;
}
candidate;

// Array of candidates
candidate candidates[MAX_CANDIDATES];

// Numbers of voters and candidates
int voter_count;
int candidate_count;

// Function prototypes
bool vote(int voter, int rank, string name);
void tabulate(void);
bool print_winner(void);
int find_min(void);
bool is_tie(int min);
void eliminate(int min);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: runoff [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX_CANDIDATES)
    {
        printf("Maximum number of candidates is %i\n", MAX_CANDIDATES);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
        candidates[i].eliminated = false;
    }

    voter_count = get_int("Number of voters: ");
    if (voter_count > MAX_VOTERS)
    {
        printf("Maximum number of voters is %i\n", MAX_VOTERS);
        return 3;
    }

    // Keep querying for votes
    for (int i = 0; i < voter_count; i++)
    {

        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            // Record vote, unless it's invalid
            if (!vote(i, j, name))
            {
                printf("Invalid vote.\n");
                return 4;
            }
        }

        printf("\n");
    }

    // Keep holding runoffs until winner exists
    while (true)
    {
        // Calculate votes given remaining candidates
        tabulate();

        // Check if election has been won
        bool won = print_winner();
        if (won)
        {
            break;
        }

        // Eliminate last-place candidates
        int min = find_min();
        bool tie = is_tie(min);

        // If tie, everyone wins
        if (tie)
        {
            for (int i = 0; i < candidate_count; i++)
            {
                if (!candidates[i].eliminated)
                {
                    printf("%s\n", candidates[i].name);
                }
            }
            break;
        }

        // Eliminate anyone with minimum number of votes
        eliminate(min);

        // Reset vote counts back to zero
        for (int i = 0; i < candidate_count; i++)
        {
            candidates[i].votes = 0;
        }
    }
    return 0;
}

// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    for (int k = 0; k < candidate_count; k++)
    {
        if (strcmp(name, candidates[k].name) == 0)
        {
            preferences[voter][rank] = k;
            return true;
        }
    }
    return false;
}

// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    for (int i = 0; i < voter_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (!candidates[j].eliminated)
            {
                candidates.votes[preferences[i][j]]++;
                break;
            }
        }
    }
    return;
}

// Print the winner of the election, if there is one
bool print_winner(void)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (candidates.votes[i] > (voter_count * 0.5))
            {
                printf("%s", candidates.name[i]);
                return true;
            }
        }
    }
    return false;
}

// Return the minimum number of votes any remaining candidate has
int find_min(void)
{
    int k = candidates[1].votes;
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (k > candidates[i].votes)
            {
                k = candidates[i].votes;
            }
        }
    }
    return k;
}

// Return true if the election is tied between all candidates, false otherwise
bool is_tie(int min)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (candidates[i].votes != min)
            return false;
        }
    }
    return true;
}

// Eliminate the candidate (or candidates) in last place
void eliminate(int min)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!candidates[i].eliminated)
        {
            if (candidates[i].votes == min)
            {
                candidates[i].eliminated = true;
            }
        }
    }
    return;
}

When compiled it shows these errors
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    runoff.c  -lcrypt -lcs50 -lm -o runoff
runoff.c:151:27: error: member reference base type 'candidate [9]' is not a structure or union
                candidates.votes[preferences[i][j]]++;
                ~~~~~~~~~~^~~~~~
runoff.c:166:27: error: member reference base type 'candidate [9]' is not a structure or union
            if (candidates.votes[i] > (voter_count * 0.5))
                ~~~~~~~~~~^~~~~~
runoff.c:168:40: error: member reference base type 'candidate [9]' is not a structure or union
                printf("%s", candidates.name[i]);

I am not able to figure what's wrong.

A: In tabulate function, try changing this:
candidates.votes[preferences[i][j]]++;

to this:
candidates[preferences[i][j]].votes++;

In print_winner function, try changing this:
candidates.votes[i]

to this:
candidates[i].votes

and this:
printf("%s", candidates.name[i]);

to this:
printf("%s", candidates[i].name);


text:
Q: How to share Git aliases across multiple workstations? When using Git on multiple workstations, and for different Git repositories, it is convenient to have the same set of aliases available.
So, to synchronize the Git aliases across different workstations, and across different repositories, I consider putting the aliases in a shared Git repository on GitHub, but I am now certain how that can be done, or if that is the best way.
How to share Git aliases across multiple workstations?
Note: The answer at "Git aliases that are stored in origin" has some good input, but it does not directly address the question of how to share Git aliases across different Git repositories.

A: Its possible with just maintaining shared global .gitconfig across multiple workstations!!
It can be done easily by setting up alias4git on target workstations.

*

*Clone alias4git
git clone https://github.com/pipelineinc/alias4git.git

*Update paths in file alias.gitconfig to appropriate path of cloned alias4git repository

*Use git cfg command to add new aliases instead of standard git config command
for example,
git cfg --add alias.st "status"

git cfg --add alias.cm "commit -m"

(Note that git cfg command modifies alias4git/alias.gitconfig instead of actually modifying global .gitconfig file !!)

*Commit and push your changes in alias4git/alias.gitconfig to alias4git repository

*Update alias4git/alias.gitconfig on all other workstations by syncing alias4git repository
cd alias4git
git pull

As alias4git/alias.gitconfig file now works as replacement for global .gitconfig, it works for all the git repositories, across multiple workstations and across multiple git users.
Hope this answers your question!


text:
Q: How to best follow a function to understand what it is doing? This question is general but I am going to give a specific example.
The specific problem that needs to be solved is explained here. The description is long so I will not cut and paste but the basic idea is for input strings S and T (as they are called in the code below), find the minimum number of changes that needs to be done to S to produce T. One change can be :

*

*Insert one letter to any end of the string.

*Delete one letter from any end of the string.

*Change one letter into any other one.

Below is a solution I am trying to track. What I am looking for are tips on how to best grok the solution. What are some methods I can use to read and understand the code (let's discard stepping through a debugger).
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
char S[2010];
char T[2010];
int lens,lent;
int main()
{
    int i,j,ma,p;

    while(scanf("%s%s",S,T)!=EOF)
    {
        lens=strlen(S);
        lent=strlen(T);
        ma=0;p=0;
        for(i=0;i<lens;i++)
        {
            p=0;
            for(j=0;j<lent;j++)
            {
                if(i+j>=lens)
                    break;
                if(S[i+j]==T[j]){p++;}
            }
            if(ma<p)
                ma=p;
            if(ma==lent)
                break;
        }
        for(i=0;i<lent;i++)
        {
            p=0;
            for(j=0;j<lens;j++)
            {
                if(i+j>=lent)
                    break;
                if(T[i+j]==S[j]){p++;}
            }
            if(ma<p)
                ma=p;
            if(ma==lent)
                break;
        }
        printf("%d\n",lent-ma);
    }
    return 0;
}

A: Step 1: Explain to yourself what the variables represent:
S: the string from which we want to extract a substring
T: the string which we want to achieve in the end, after having modified the extracted substring with as few operations as possible
lens: length of string S
lent: length of string T
i: the index in S from which the extracted substring starts
j: the index in string T of a character which we want to match with a corresponding character in the substring
p: the amount of matching chars found for the currently investigated substring
ma : the maximum amount of matching chars for any of the substrings

Step 2: Having established these meanings, it's rather simple to translate the first loop into words:
for loop 1 :    selects a start position of the substring

    set the match counter to 0, since we start investigation of a new substring

    for loop 2 :    loops through the substring

        if 1 :      if there is no char left to read string S, stop looping

        if 2 :      if the current character in the extracted substring matches
                a character in the "goal" string, increment the match counter (p)

    if 3 :      now, we finished looping through a substring,
            if the count of matching characters in the substring and the goal
            string was higher than for any of the previous counts,
            then store this value as the max count

    if 4 :      if the max count of matching characters is equal to the
            length of the "goal string", dr Moriatry can receive the goal string
            with 0 substring changes, and hence, we can stop looping

The next loop is similar. The roles of S and T have kind of been reversed. Notice though, that the roles of S and T have not been fully reversed (as some people have said). The end condition for the outer for loop uses the length of T in both cases, which makes sense.
Here we extract substrings from string T (the "goal" string) and try to match them against string S. Why are we doing this?
I expect that the person who wrote the code wanted to account for cases like the following, e.g.:
S = "b"     T = "abc"

If we'd only extract substrings from S and match them against the whole T string, starting at the first index (like the first loop does), we'd only compare "does b (in S) match a (the first char in T) and then we'd go on and say: "Since no substring matches, we need 3 string change operations to receive string T" (which is obviously wrong, as we can achieve it by choosing "b" as the substring to extract, and making 2 change operations to end up with T)

A: The best solution will be to rewrite the code as you are understanding it. There are few things :

*

*Watch for duplicate code. He does the same thing with S and T, and the roles are reversed. You can create a function foo() with both strings as parameter and use
foo(S,T) and foo(T,S)

*Try to break too much depth. When you see lot of nested loops most of the time some of the inner loops can be seen as a function doing something specific.

*rename progressively the variables as you are understanding more what is happening

*Last but not least, don't discard stepping through the debugger

A: The key to understanding the code is to understand the meaning of the variables that change least, in this case, ma and p and to recognize coding idioms.
The two code snippets
if(ma<p)
    ma=p;
if(ma==lent)
    break;

are a "high water mark" idiom for the variable p (with a break condition on the maximum possible value). p is incremented whenever there is match in the character at the j position of the LHS substring starting at i with the j position character of the RHS. So for the loops indexed by j (the inner loops), p is the number of identical characters that are at the same j positions. So I would rename p (in my head at least!) to "number_of_identical_chars_in_same_pos".
The loops indexed by i find the highest p (saved in ma) for each substring in the LHS that ends with the last character of the LHS (or earlier if the substring is lent long). So ma should be renamed "max_common_chars_in_a_span". Together the two loops find the maximum number of common characters in the same position of any substring ending with the last character of either side.
The final step (left to the serious student) is to understand how this solves the problem and that's mathematics, not programming.

A: I'd start by first doing some string manipulation on the program. First step would be to try to give better names to the variables.
I'd replace 'i' with sPos for the position in string S. Well, at least that applies for the first loop, for the second loop 'i' changes meaning to be the position in T, so I'd actually then decide to get rid of i and instead have two variables, so each variable has one purpose which matches its name.
Then try the same for j, ma and p.
Once that's done, I would consider trying to work out what the two 'for' loops do. They seem virtually identical. Maybe they could be split out into one function that gets called twice. Again, try to work out what this function does and name it very carefully so the name explains its purpose.
Repeat steps like this until you've got some code that makes some human sense.

A: *

*Extract the two outer loops into their own functions.

*Find the commonality (hint: they are only modifying ma).

*Extract that commonality.

*Extract the inner loops to their own function (hint: the code is identical).

*Write unit tests for each function to test your understanding.


text:
Q: Differentiation as Rotation I am trying to make a connection between linear algebra and the Fourier transform. Functions form a vector space and differentiation is an operator.
Fourier transforming a function from what i understand is writing the function in the basis of complex exponentials. Differentiation in the Fourier domain is multiplication by the imaginary unit which is also the eigenvalue of the 90 degree rotation matrix of the 2x2 rotational matrix.
Is it possible to say that the the differential operator is diagonalised in the Fourier domain?
and
Is the differential operator the equivalent of the rotation matrix in finite dimensional matrices?

A: Suppose you have a selfadjoint matrix $A$ on $\mathbb{C}^N$. The spectral theorem in projection form gives you orthogonal projections such that
$$
                      P_k^2 = P_k^{\star} = P_k \\
                      P_j P_k = 0,\;\;\; j\ne k \\
                      I = P_1+P_2+\cdots+P_n \\
                      AP_j = \lambda_j P_j.
$$
Therefore,
$$
                            A = \lambda_1 P_1 + \cdots +\lambda_n P_n.
$$
Any power of $A$ can be computed
$$
                      A^{m} = \lambda_1^m P_1 + \cdots + \lambda_n^m P_n
$$
Other functions of $A$ can be computed such as
$$
                   e^{A} = e^{\lambda_1}P_1 + \cdots e^{\lambda_n}P_n
$$
This abstraction using orthogonal projections is a useful one for transitioning to the general case.
The Fourier transform is a continuous diagonalization of $A=\frac{1}{i}\frac{d}{dt}$. One orthogonal projection is
$$
                   P_{S}f = \mathcal{F}^{-1}(\chi_{S}\mathcal{F}f),
$$
where $\chi_{S}$ is the characteristic function of a measurable subset $S$ of $\mathbb{R}$. You can see that $P_{S}^2f=P_{S}f$ because $\chi_{S}^2 =\chi_{S}$. And, it's not hard to check that $(P_Sf,g)=(f,P_Sg)$. And $P_{\mathbb{R}}=I$ because $P_{\mathbb{R}}f=\mathcal{F}^{-1}\mathcal{F}f$. As a starting point for comparing the matrix case, consider
$$
               I = \sum_{n=-\infty}^{\infty}P_{[\frac{n}{N},\frac{n+1}{N}]}
$$
Using Parseval's identity,
$$
        Af =\frac{1}{i}\frac{d}{dx}P_{[\frac{n}{N},\frac{n+1}{N}]}f \approx \frac{n}{N}P_{[\frac{n}{N},\frac{n+1}{N}]}f
$$
More precisely, using Parseval's identity,
\begin{align}
            \left\|\left(A-\frac{n}{N}I\right)P_{[\frac{n}{N},\frac{n+1}{N}]}f\right\|^2 &=\int_{\frac{n}{N}}^{\frac{n+1}{N}}|s-\frac{n}{N}|^2|\hat{f}(s)|^{2}ds \\
  & \le \frac{1}{N^2}\int_{\frac{n}{N}}^{\frac{n+1}{N}}|\hat{f}(s)|^2ds \\
  & \le \frac{1}{N^2}\|P_{[\frac{n}{N},\frac{n+1}{N}]}f\|^2.
\end{align}
Therefore,
$$
                   AP_{\frac{n}{N},\frac{n+1}{N}}f \approx \frac{n}{N}P_{[\frac{n}{N},\frac{n+1}{N}]}f
$$
So you have an approximate decomposition
$$
               I = \sum_{n=-\infty}^{\infty}P_{[\frac{n}{N},\frac{n+1}{N}]}
 \\
              A \approx \sum_{n=-\infty}^{\infty}\frac{n}{N}P_{[\frac{n}{N},\frac{n+1}{N}]}
$$
You can't quite make everything exact, because $e^{isx}$ is not in the space $L^2$, but you can make the operator approximation as close as you like by taking $N$ large enough, which is the granularity of the decomposition of the real axis. The reason you can't make it exact is because $\int_{n/N}^{(n+1)N}e^{isx}ds$ is in the space and is an approximate eigenvector with approximate eigenvalue $n/N$, but the function $e^{i(n/N)x}$ is not in $L^2$. The sum gives way to an integral in the limit as $N\rightarrow\infty$. The Spectral Theorem for selfadjoint operators makes this exact. If $P(t)f=\mathcal{F}^{-1}(\chi_{(-\infty,t]}\mathcal{F}f)$, then the following is made precise in a Hilbert space sense:
$$
    \frac{1}{i}\frac{d}{dx} = \int_{-\infty}^{\infty}\lambda dP(\lambda).
$$
And, you have
$$
     \|f\|^2 = \int_{-\infty}^{\infty}d_{\lambda}\|P(\lambda)f\|^2.
$$


text:
Q: Talend Open Studio Big Data - Iterate and load multiple files in DB I am new to talend and need guidance on below scenario:
We have set of 10 Json files with different structure/schema and needs to be loaded into 10 different tables in Redshift db.
Is there a way we can write generic script/job which can iterate through each file and load it into database?
For e.g.:

*

*File Name: abc_< date >.json
Table Name: t_abc

*File Name: xyz< date >.json
Table Name: t_xyz
and so on..
Thanks in advance

A: With Talend Enterprise version one can benefit of dynamic schema. However based on my experiences with json-s they are somewhat nested structures usually. So you'd have to figure out how to flatten them, once thats done it becomes a 1:1 load. However with open studio this will not work due to the missing dynamic schema.
Basically what you could do is: write some java code that transforms your JSON into CSV. Use either psql from commandline or if your Talend contains new enough PostgreSQL JDBC driver then invoke the client side \COPY from it to load the data. If your file and the database table column order matches it should work without needing to specify how many columns you have, so its dynamic, but the data newer "flows" through talend.
Really not cool but also theoretically possible solution: If Redshift supports JSON (Postgres does) then one can create a staging table, with 2 columns: filename, content. Once the whole content is in this staging table, INSERT-SELECT SQL could be created that transforms the JSON into tabular format that can be inserted into the final table.
However, with your toolset you probably have no other choice than to load these files with 1 job per file. And I'd suggest 1 dedicated job to each file. They would each look for their own files and triggered / scheduled individually or be part of a bigger job where you scan the folders and trigger the right job for the right file.


text:
Q: why do I get this Out Of Memory Exception? I have this C# segment code:
  string fileName = Path.GetTempPath() + "\\temp.bmp";
        image.Save(fileName);
        bmp = (Bitmap)Image.FromFile(fileName);

On this row:
  bmp = (Bitmap)Image.FromFile(fileName);
I get this exception:
**System.OutOfMemoryException was unhandled
Message=Out of memory.
Source=System.Drawing
StackTrace:
   at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromFile(String filename)
   at WindowsFormsApplication1.ShowContoursForm..ctor(Templates samples, IImage image) in C:\Michael work\MyContourAnalysis\WindowsFormsApplication1\ShowContoursForm.cs:line 40
   at WindowsFormsApplication1.Form1.tsbDislpayContours_Click(Object sender, EventArgs e) in C:\Michael work\MyContourAnalysis\WindowsFormsApplication1\MainForm.cs:line 170
   at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
   at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
   at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ToolStrip.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at WindowsFormsApplication1.Program.Main() in C:\Michael work\MyContourAnalysis\WindowsFormsApplication1\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

InnerException:
**
Any Idea why do I get this exception and how can I fix it?

A: Looks like it's a format issue with your image file. See here on the FromFile method exceptions.


text:
Q: Is my model any good, based on the diagnostic metric ($R^2$/ AUC/ accuracy/ RMSE etc.) value? I've fitted my model and am trying to understand whether it's any good. I've calculated the recommended metrics to assess it ($R^2$/ AUC / accuracy / prediction error / etc) but do not know how to interpret them. In short, how do I tell if my model is any good based on the metric? Is an $R^2$ of 0.6 (for example) sufficient to let me proceed to draw inferences or base scientific/business decisions?

This question is intentionally broad, to cover a wide variety of situations that members frequently encounter; such questions could be closed as duplicates of this one. Edits to broaden the scope beyond the metrics mentioned here are welcome, as are additional answers - particularly those that offer insight about other classes of metrics.

A: This answer will mostly focus on $R^2$, but most of this logic extends to other metrics such as AUC and so on.
This question can almost certainly not be answered well for you by readers at CrossValidated. There is no context-free way to decide whether model metrics such as $R^2$ are good or not. At the extremes, it is usually possible to get a consensus from a wide variety of experts: an $R^2$ of almost 1 generally indicates a good model, and of close to 0 indicates a terrible one. In between lies a range where assessments are inherently subjective. In this range, it takes more than just statistical expertise to answer whether your model metric is any good. It takes additional expertise in your area, which CrossValidated readers probably do not have.
Why is this? Let me illustrate with an example from my own experience (minor details changed).
I used to do microbiology lab experiments. I would set up flasks of cells at different levels of nutrient concentration, and measure the growth in cell density (i.e. slope of cell density against time, though this detail is not important). When I then modelled this growth/nutrient relationship, it was common to achieve $R^2$ values of >0.90.
I am now an environmental scientist. I work with datasets containing measurements from nature. If I try to fit the exact same model described above to these 'field' datasets, I'd be surprised if I the $R^2$ was as high as 0.4.
These two cases involve exactly the same parameters, with very similar measurement methods, models written and fitted using the same procedures - and even the same person doing the fitting! But in one case, an $R^2$ of 0.7 would be worryingly low, and in the other it would be suspiciously high.
Furthermore, we would take some chemistry measurements alongside the biological measurements. Models for the chemistry standard curves would have $R^2$ around 0.99, and a value of 0.90 would be worryingly low.

What leads to these big differences in expectations? Context. That vague term covers a vast area, so let me try to separate it into some more specific factors (this is likely incomplete):
1. What is the payoff / consequence / application?
This is where the nature of your field are likely to be most important. However valuable I think my work is, bumping up my model $R^2$s by 0.1 or 0.2 is not going to revolutionize the world. But there are applications where that magnitude of change would be a huge deal! A much smaller improvement in a stock forecast model could mean tens of millions of dollars to the firm that develops it.
This is even easier to illustrate for classifiers, so I'm going to switch my discussion of metrics from $R^2$ to accuracy for the following example (ignoring the weakness of the accuracy metric for the moment). Consider the strange and lucrative world of chicken sexing. After years of training, a human can rapidly tell the difference between a male and female chick when they are just 1 day old. Males and females are fed differently to optimize meat & egg production, so high accuracy saves huge amounts in misallocated investment in billions of birds. Till a few decades ago, accuracies of about 85% were considered high in the US. Nowadays, the value of achieving the very highest accuracy, of around 99%? A salary that can apparently range as high as 60,000 to possibly 180,000 dollars per year (based on some quick googling). Since humans are still limited in the speed at which they work, machine learning algorithms that can achieve similar accuracy but allow sorting to take place faster could be worth millions.
(I hope you enjoyed the example – the alternative was a depressing one about very questionable algorithmic identification of terrorists).
2. How strong is the influence of unmodelled factors in your system?
In many experiments, you have the luxury of isolating the system from all other factors that may influence it (that's partly the goal of experimentation, after all). Nature is messier. To continue with the earlier microbiology example: cells grow when nutrients are available but other things affect them too – how hot it is, how many predators there are to eat them, whether there are toxins in the water. All of those covary with nutrients and with each other in complex ways. Each of those other factors drives variation in the data that is not being captured by your model. Nutrients may be unimportant in driving variation relative to the other factors, and so if I exclude those other factors, my model of my field data will necessarily have a lower $R^2$.
3. How precise and accurate are your measurements?
Measuring the concentration of cells and chemicals can be extremely precise and accurate. Measuring (for example) the emotional state of a community based on trending twitter hashtags is likely to be…less so. If you cannot be precise in your measurements, it is unlikely that your model can ever achieve a high $R^2$. How precise are measurements in your field? We probably do not know.
4. Model complexity and generalizability
If you add more factors to your model, even random ones, you will on average increase the model $R^2$ (adjusted $R^2$ partly addresses this). This is overfitting. An overfit model will not generalize well to new data i.e. will have higher prediction error than expected based on the fit to the original (training) dataset. This is because it has fit the noise in the original dataset. This is partly why models are penalized for complexity in model selection procedures, or subjected to regularization.
If overfitting is ignored or not successfully prevented, the estimated $R^2$ will be biased upward i.e. higher than it ought to be. In other words, your $R^2$ value can give you a misleading impression of your model's performance if it is overfit.
IMO, overfitting is surprisingly common in many fields. How best to avoid this is a complex topic, and I recommend reading about regularization procedures and model selection on this site if you are interested in this.
5. Data range and extrapolation
Does your dataset extend across a substantial portion of the range of X values you are interested in? Adding new data points outside the existing data range can have a large effect on estimated $R^2$, since it is a metric based on the variance in X and Y.
Aside from this, if you fit a model to a dataset and need to predict a value outside the X range of that dataset (i.e. extrapolate), you might find that its performance is lower than you expect. This is because the relationship you have estimated might well change outside the data range you fitted. In the figure below, if you took measurements only in the range indicated by the green box, you might imagine that a straight line (in red) described the data well. But if you attempted to predict a value outside that range with that red line, you would be quite incorrect.

[The figure is an edited version of this one, found via a quick google search for 'Monod curve'.]
6. Metrics only give you a piece of the picture
This is not really a criticism of the metrics – they are summaries, which means that they also throw away information by design. But it does mean that any single metric leaves out information that can be crucial to its interpretation. A good analysis takes into consideration more than a single metric.

Suggestions, corrections and other feedback welcome. And other answers too, of course.

A: This problem comes up in my field of hydrology when assessing how well models predict streamflow from rainfall and climate data.  Some researchers (Chiew and McMahon, 1993) surveyed 93 hydrologists, (63 responded ) to find out what diagnostic plots and goodness of fit statistics they used, which were the most important, and how they were used to classify the quality of a model fit.  The results are now dated but the approach may still be of interest.  They presented the results of model fits of various qualities and asked hydrologists to classify them into 4 categories (1) perfectly acceptable result; (2) acceptable but use with reservation; (3) unacceptable, use only if there is no other alternative; and (4) never use under any condition.
The most important diagnostic graphs were timeseries plots and scatter plots of simulated and recorded flows from the data used for calibration.  R-squared and Nash-Sutcliffe model efficiency coefficient (E) were the favoured goodness of fit statistics.  For example, results were considered acceptable if E => 0.8
There are other examples in the literature.   When assessing an ecosystem model in the North Sea, the following categorisation was used E > 0.65 excelled, 0.5 to 0.65 very good, 0.2 to 0.5 as good, and <0.2 as poor (Allen et al., 2007).
Moriasi et al., (2015) provides tables of acceptable values for metrics for various types of models.
I've summarised this information and references in a blog post.
Allen, J., P. Somerfield, and F. Gilbert (2007), Quantifying uncertainty in high‐resolution coupled hydrodynamic‐ecosystem models, J. Mar. Syst.,64(1–4), 3–14, doi:10.1016/j.jmarsys.2006.02.010.
Moriasi, D., Gitau, M. Pai, N. and Daggupati, P. (2015) Hydrologic and Water Quality Models: Performance Measures and Evaluation Criteria Transactions of the ASABE (American Society of Agricultural and Biological Engineers) 58(6):1763-1785

A: Just to add to the great answers above - in my experience, evaluation metrics and diagnostic tools are as good and honest as the person using them. That is, if you understand the mathematics behind them, then you can likely artificially increase them to make your model appear better without increasing its actual utility.
For example, like mentioned in one of the comments, in some applications $R^2=0.03 \to R^2 = 0.05$ can be a great performance boost. However, if this increase was obtained artificially (i.e., by arbitrarily removing some observations), then this performance increase is not sincere and arguably provides little utility.
I'll keep this answer short since the above do a great job providing explanations/references. I just wanted to add some perspective on the section on 6. Metrics only give you a piece of the picture by mkt's answer.
Hope this helps.


text:
Q: Android Notification tap cause crashes the app due to Activity intent I have MainActivity and UserAcitivity, I have passed some values to UserActivity through intent.
from the UserActivity, I call Notification then notification appeared, I made notification tap to
start the UserActivity by Pending Intent. When the Notification tap the App crashes because the values passed from MainAcitvity become null.
I can't Use SharedPreferences because the Value conflict for another UserAcitivity(the passed value was unique for every user)
example code is here:-
This is MainAcitvity
public void buttonClick(View view){
    Intent intent = new Intent(this,SecondActivity.class);
    intent.putExtra("myname","ashiqueHira");
    startActivity(intent);
}

This is SecondAcivity Oncreate method;
String heading= "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Intent intent = getIntent();
    heading = intent.getStringExtra("myname");
    Toast.makeText(this, heading, Toast.LENGTH_SHORT).show();
}

This is my Notification method
public void notificationPops(){

    Intent intent = new Intent(this, SecondActivity.class);
    createNotificationChannel();
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(intent);
    Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_vibration_black_24dp)
            .setContentTitle("Token Reminder")
            .setContentText("Dismiss the Alarm by Clicking this")
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setVibrate(new long[] { 100, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 })
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(0, builder.build());
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                "myChannel",
                NotificationManager.IMPORTANCE_HIGH
        );
        serviceChannel.enableVibration(true);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}

This is a similar condition that I have. The difference is I have many usages for the getIntent value
and that value is unique for every Activity.
Thanks in Advance

A: So, basically you get NullPointerException. For reducing this problem change youe SecondActivity code like this:
String heading= "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Intent intent = getIntent();
    if(intent.getStringExtra("myname")!= null){
       heading = intent.getStringExtra("myname");
       Toast.makeText(this, heading, Toast.LENGTH_SHORT).show();
    }
}

This will reduce your nullException error and your app cannot crash.
Another thing If you always need heading value pass through intent. Then pass the value also from notification pendingIntent and get it from SecondActivity

A: I found a way to solve this problem by adding and replacing the following code
in the notificationPops() method
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("yourName",heading);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);

this will get you the value to the activity when the activity stats by notification taps.
Please post if other best practices to solve the problem above


text:
Q: Project only required shapefiles in folder - update I have updated the script from my previous question;
Project only required shapefiles in folder
I can't get the if fcspatialRef != spatialRef: to work. The script won't filter the shapefiles in ArcGIS, any advice/suggestions?
import arcpy

# Set Workspace
arcpy.env.workspace = arcpy.GetParameterAsText(0)

#Access shapefiles
fcList = arcpy.ListFeatureClasses()

try:
# Projection template
  template = arcpy.GetParameterAsText(1)
# Output folder
  outFolder = arcpy.GetParameterAsText(2)

# Get the spatial reference
 spatialRef = arcpy.Describe(template).SpatialReference

 #Loop through shapfiles in folder and reproject
 for fc in fcList:
    fcspatialRef = arcpy.Describe(fc).SpatialReference
    if fcspatialRef != spatialRef:
        arcpy.Project_management(fc, outFolder + "\\" + fc, spatialRef)

# Return any errors
except:
    arcpy.AddMessage(arcpy.GetMessages ())

# Print shapefile list
for fc in fcList:
    print fc

A: Using the spatial reference name method will likely work for you.
 # Get the spatial reference
 spatialRef = arcpy.Describe(template).SpatialReference.name

 #Loop through shapfiles in folder and reproject
 for fc in fcList:
    fcspatialRef = arcpy.Describe(fc).SpatialReference.name
    if fcspatialRef != spatialRef:
         arcpy.Project_management(fc, outFolder + "\\" + fc, spatialRef)


text:
Q: How to close gvim from command prompt Usually, we open gvim from the command line like this:
gvim someFile.txt

But how are we going to close it from command line too? Instead of closing it from gvim itself?
I wanted to do some automation, hence, will need to close it from command line.

A: gVIM has the ability to act in client/server manner. That means you can send commands to a running vim.
Do the following

*

*Start GVIM, open a document, do whatever

*Run the following command to close GVIM
vim --servername GVIM --remote-send '<C-\><C-N>:wq<CR>'

That will save the file in GVIM and close GVIM.

A: First, why are you automating using a gui application?
But you can close it by sending it either <ESC>ZZ or :q!


text:
Q: Download progress with a logging callback? I have a headscratcher of a challenge here.
I have a web application running in Azure, that at some point will expose a SAS URI (download link) for users to download files from our Azure Storage.
The problem with this is that I cannot keep track of an exact count of the content downloaded.
I can only assume that when I produce a download link for a certain user, the file was completely downloaded. Which perhaps wasn't.
I've looked at Azure logs and I don't think I could find what I want in there.
Is there any way I could have the user download the file from a controller method, and have a callback being executed every once in a while that would hold the transfer progress so I could log it somewhere and know which user download that much.
I'm thinking SignalR too. Could this be used for this purpose ?
Thanks.

A:
The problem with this is that I cannot keep track of an exact count of the content downloaded.

If Azure storage diagnostics feature is turned on, the read/write/delete operations on blob will be logged, you can get download (getblob operation) count for the specified blob from diagnostics logs.
Besides, if users are only enabled to download blobs from your MVC application, you can update & save download count in an external storage in your controller action, and this SO thread discussed a similar issue. If you expose SAS URI directly, user who has a valid and not-expired SAS URI can enter that SAS URI in browser and download the blob, it will be difficult to trace the download count of blobs that is downloaded in this way.


text:
Q: Reply address does not match the reply address provided when requesting authorization I'm getting frustrated by an error which occurs on a .netcore3.1 app I'm working on.
Here's my setup:
In Startup.cs
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftWebApp(options =>
    {
        Configuration.Bind("AzureAd", options);
        options.Events ??= new OpenIdConnectEvents();
        options.Events.OnRedirectToIdentityProvider = async ctx =>
        {
            ctx.ProtocolMessage.RedirectUri = Configuration["AzureAd:RedirectUri"];
            await Task.CompletedTask;
        };
    })
    .AddMicrosoftWebAppCallsWebApi(Configuration, new[] { "user.read" })
    .AddDistributedTokenCaches();

In my appsettings
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "ClientId",
    "TenantId": "TenantId",
    "RedirectUri": "https://mywebsite.com/signin-oidc",
    "ClientSecret": "ClientSecret"
  },

the azure app registration is configured correctly with https://mywebsite.com/signin-oidc as the redirect url.
I've also added the following to allow headers to be forwarded from the proxy:
services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});

// then in the Configure method

app.UseForwardedHeaders();

Yet I'm still getting this error which is baffling me. I thought by adding
ctx.ProtocolMessage.RedirectUri = Configuration["AzureAd:RedirectUri"];

I would overcome this but it seems to have no impact on this error.
An unhandled exception occurred","Properties":{"CorrelationId":"c3393560-6ebe-41ce-99fc-693c1a387474","Path":"/signin-oidc","Method":"POST","exceptionMessage":"An error was encountered while handling the remote login.","exception":"System.Exception: An error was encountered while handling the remote login.\n ---> MSAL.NetCore.4.16.1.0.MsalServiceException: \n\tErrorCode: invalid_client\nMicrosoft.Identity.Client.MsalServiceException: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details.  Original exception: AADSTS500112: The reply address 'http://mywebsite.com/signin-oidc' does not match the reply address 'https://mywebsite.com/signin-oidc' provided when requesting Authorization

A: Could it be that your proxy is also terminating HTTPS, so the traffic your application is getting is HTTP?

A: According to your error message:Reply address does not match the reply address provided when requesting authorization.  You must ensure that the redirect_uri configured in the Azure portal is exactly the same as the redirect_uri configured in the code.
When you visit the application url , you will be redirected to the login page. Decode the authorization request URL, you will find redirect_uri, copy the value of redirect_uri and paste it into the azure portal, and try again.

For the redirect URL, it should start with https, if you need to start with http, you must configure it as http://localhost.


text:
Q: Windows 10 drops IKEv2 VPN connection to Cisco router in exactly 60 seconds after last data exchange Update 3: 22 January 2017
I've narrowed down the update that causes this problem: KB3201845 OS Build 14393.479 from December 9 2016. I went through all these updates step by step.
Looking at the changes files manifest, these files have been changed:

*

*agilevpn.sys

*vpnike.dll

Other topics I've created:
Microsoft Technet Forums, 2 other people have confirmed the same problem there.
Reddit /r/networking
Microsoft Feedback Hub
Update

*

*Windows 10 pre-anniversary (version 10.0.10586) works fine

*Windows 10 post-anniversary (version 10.0.14393) drops, so the problem is with the anniversary update.

Update 2
I can connect using two pre-anniversary Windows hosts fine
If I connect 1 anniversary Windows host to the VPN and keep it alive artificially by pinging, I cannot connect a second host to the VPN. In the router's "debug crypto ikev2", this happens:
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Session present in ID PAIR TREE, but absent in TUPLE TREE
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):: Failed to add new SA into session DB
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Queuing IKE SA delete request reason: unknown
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Sending DELETE INFO message for IPsec SA [SPI: 0x3DA95352]
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Check for existing IPSEC SA
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Delete all IKE SAs
Jan 17 19:20:35.811: IKEv2:(SESSION ID = 25,SA ID = 2):Sending DELETE INFO message for IKEv2 SA [ISPI: 0x3B52B7EBA8A353B1 RSPI: 0x16F36D79AAE675A5]

I have a Cisco IOS router, 892 model, which I'm setting up IKEv2 with EAP-MSCHAPv2 as remote authentication (backed by a Windows 2012 Server Network Policy Server) and local certificate authentication. Everything works, I can connect to the VPN and ping a loopback address on the router. Windows 7 and 8.1 work fine, Android with Strongswan too.
However, on Windows 10 (10.0.14393 - fully up to date 16 jan 2017), exactly 60 seconds after the last data exchange (like a ping), Windows drops the connection. So:

*

*T+0 VPN connection opened

*T+60 VPN connection drops

*

*T+0 VPN connection opened

*T+20 1 Ping to 172.16.0.5, reply received

*T+80 VPN connection drops

The VPN is dropped with the following message in the System event log:
Source: RasClient
Event ID: 20226
CoId={43121588-861C-447A-A510-C44C2BA86639}: The user LAPTOP-GLENN\Glenn dialed a connection named ikev2-test which has terminated. The reason code returned on termination is 829.
So I started digging and enabled RAS debugging on the client:
netsh ras diagnostics * state=enabled

The only relevant stuff I could find was in C:\Windows\tracing\rasman.log (20:11:51 is when the disconnect happens - interesting bits prefixed with "***"):
[1384] 01-16 20:11:51:216: FreeInterfaceLuidIndex: Luid = 0
[1384] 01-16 20:11:51:216: RasUpdateVpnLuidCache: Luid: 17000000000000, fAddLuid:0
[1384] 01-16 20:11:51:216: RasUpdateVpnLuidCache: Removed Luid 17000000000000 from cache
[1384] 01-16 20:11:51:216: FreeInterfaceLuidIndex: done 0
[1384] 01-16 20:11:51:216: DeallocateRouteRequestCommon: pBundle=0xa50adde0, type=0x800
[1384] 01-16 20:11:51:232: DeActivated Route , bundlehandle 0x4, prottype = 2048
[1384] 01-16 20:11:51:232: DeAllocateRoute: PI_Type=0x800, PI_AdapterName=\DEVICE\{93A76D72-2010-45BB-9096-244B06735879}, PI_Allocated=-1
[3524] 01-16 20:11:51:248: SendProtocolResultToRasman: msgid=1, hPort: 6.
*** [3524] 01-16 20:11:51:248: Setting last error for port VPN2-1 to ppp error 0x3635
[3524] 01-16 20:11:51:248: SetProtocolResultAvailableEvent: Notification handle event for port 6 is not registered.
[2640] 01-16 20:11:51:248: WorkerThread: Disconnect event signaled on port: VPN2-1
[2640] 01-16 20:11:51:248: OVEVT_DEV_STATECHANGE. pOverlapped = 0xa4611940
[2640] 01-16 20:11:51:248: onecoreuap\net\rras\ras\rasman\rasman\worker.c, 2031: Disconnecting port 6, connection 0xa6af47e0, reason 1
[2640] 01-16 20:11:51:248: Disconnecting Port 0xVPN2-1, reason 1
[2640] 01-16 20:11:51:248: DisconnectPort: Saving Bundle stats for port VPN2-1
[2640] 01-16 20:11:51:263: RevertPostConnectionActions
[2640] 01-16 20:11:51:263: RasImpersonateUser. 0x0
[2640] 01-16 20:11:51:263: DeleteCredentialsFromCredMan
[2640] 01-16 20:11:51:263: DeleteCredentialsFromCredMan Done: 0
[2640] 01-16 20:11:51:263: RasRevertToSelf. 0x0
[2640] 01-16 20:11:51:263: QueueCloseConnections: no dependent connections
[2640] 01-16 20:11:51:263: 10. Throwing away handle 0x0!
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c, 2315:Setting port 6 for autoclosure...
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c 2327: Disconnected Port 6, reason 1. rc=0x0
[2640] 01-16 20:11:51:263: FreeBundle: freeing pBundle=0xa50adde0
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c: 2443: port 6 state chg: prev=2, new=3
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c: 2459: port 6 state chg: prev=3, new=4
[2640] 01-16 20:11:51:263: 5. Notifying of disconnect on port 6
[2640] 01-16 20:11:51:263: SignalPortDisconnect: Notification handle event for port 6 is not registered.
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c: 2573: port 6 async reqtype chg: prev=0, new=0
[2640] 01-16 20:11:51:263: ***** DisconnectType=1,DisconnectReason=4,pConn=0xa6af47e0,cbports=1,signaled=1,hEvent=0xffffffff,fRedial=0
[2640] 01-16 20:11:51:263: Calling DwQueueRedial
[2640] 01-16 20:11:51:263: DwQueueRedial
[2640] 01-16 20:11:51:263: DwQueueRedial returned 0x0
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\util.c, 2634: Autoclosing port 6
[2640] 01-16 20:11:51:263: PortClose: port (6). OpenInstances = 1
[2640] 01-16 20:11:51:263: Freeing the notifier list for port 6
[2640] 01-16 20:11:51:263: PortClose (6). OpenInstances = 0
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\request.c: 3845: port 6 async reqtype chg: prev=0, new=0
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\request.c: 3848: port 6 state chg: prev=4, new=4
[2640] 01-16 20:11:51:263: PortClose: Resetting PCB_OpenedUsage for port: 6.
[2640] 01-16 20:11:51:263: RemoveConnectionPort: port 6, fOwnerClose=0, pConn=0xa6af47e0, pConn->CB_Ports=0

*** [2640] 01-16 20:11:51:263: Completely disconnected connection: Reason: ERROR_LINK_FAILURE (829)
[2640] 01-16 20:11:51:263: SendSensNotification(_RAS_DISCONNECT) for 0x00040000 returns 0x00000000
[2640] 01-16 20:11:51:263: Successfully notified event(128, C:\Users\Glenn\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk, ikev2-test) to the caller.
[2640] 01-16 20:11:51:263: SignalNetman: IRasEventNotify::RasEvent returned S_FALSE
[2640] 01-16 20:11:51:263: DwSendNotificationInternal(ENTRY_DISCONNECTED) rc=0x1
[2640] 01-16 20:11:51:263: RemoveConnectionPort: FreeConnection hconn=0x40000, pconn=0xa6af47e0, AutoClose=1
[2640] 01-16 20:11:51:263: FreeConnection: pConn=0xa6af47e0, 1
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\request.c, 3918: Clearing the autoclose flag for port 6
[2640] 01-16 20:11:51:263: fAnyConnectedPorts: 0
[2640] 01-16 20:11:51:263: SetRasmanServiceStopControl: Enabled 1
[2640] 01-16 20:11:51:263: PortClose: DisableAutoWPPTracing failed with error 0x2
[2640] 01-16 20:11:51:263: DisconnectPort Complete
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\worker.c: 2077: port 6 state chg: prev=4, new=4
[2640] 01-16 20:11:51:263: onecoreuap\net\rras\ras\rasman\rasman\worker.c: 2081: port 6 async reqtype chg: prev=0, new=0
[1276] 01-16 20:11:51:263: The specified notification entry with cookie 2 found.
[1276] 01-16 20:11:51:263: Dequed notification entry: (128, C:\Users\Glenn\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk, ikev2-test) from the queue.

*

*Ran the same config on a Cisco CSR1000v router and the exact same thing happened.

*Created a REG_DWORD named "InactivityIdleSeconds" under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class{4d36e972-e325-11ce-bfc1-08002be10318}\0012 (WAN Miniport (IKEv2)) and played with its value but that didn't change anything (see here why I tried that)

*Played around with Dead Peer Detection but that didn't change anything either

I can't find what the criteria are for Windows 10 to consider an IKEv2 connection dead or what state changes cause Windows 10 to think the VPN has to be disconnected.
Soooo... any pointers?
Microsoft Technet: Error 829 means ERROR_LINK_FAILURE The modem (or other connecting device) was disconnected due to link failure.
Microsoft Technet: 0x3635 means 13877 ERROR_IPSEC_IKE_RPC_DELETE "Deleted via RPC call."
The Cisco IOS router configuration.
Cisco IOS router IKEv2 debug logs
Zipfile of the complete C:\Windows\tracing directory

A: I was able to work around this issue because I have setup the VPN server myself on my server. The StrongSwan VPN server allows to register updown script which is run whenever client connection changes.
conn %default
    ...
    leftupdown=/absolute/path/to/keepalive/script.sh
    ...

And the script.sh looks like this:
#!/bin/bash
/usr/lib/ipsec/_updown $* # call original updown script, just to be sure

# PLUTO_VERB - name of the event
# PLUTO_PEER_SOURCEIP - IP of the client

PLUTO_IPSTRING="${PLUTO_PEER_SOURCEIP//./}" # strip client IP of dots, to create unique name for pidfile
PID_PATH="/absolute/path/to/writable/location"

if [ "up-client" == "$PLUTO_VERB" ]; then # when new client connects
        ping $PLUTO_PEER_SOURCEIP -i 30 >/dev/null 2>/dev/null & echo $! > "$PID_PATH/pluto$PLUTO_IPSTRING.pid" # launch ping in background, send packets every 30 seconds. Store the PID in given file.
fi

if [ "down-client" == "$PLUTO_VERB" ]; then # when client disconnects
        kill -9 $(cat "$PID_PATH/pluto$PLUTO_IPSTRING.pid") # kill the ping process
        rm -rf "$PID_PATH/pluto$PLUTO_IPSTRING.pid" # remove the associated PID file
fi

You have to edit the paths to reflect you setup.
This approach is a bit of a hack, but works perfectly. Sadly it's only possible if you can create such a script. If you don't have access to the remote VPN server, this won't help you.

A: This looks like it's the peer that's the deleting the session..;
*Jan 16 20:12:10.655: IKEv2:(SESSION ID = 12,SA ID = 1):Received Packet [From 192.168.0.107:4500/To 192.168.0.200:4500/VRF i0:f0]
Initiator SPI : 598D998BFD1C9FFB - Responder SPI : 6ADF174B54D76AA1 Message id: 6
IKEv2 INFORMATIONAL Exchange REQUEST
Payload contents:
 DELETE
so you need to t/shoot the windows client (sorry if you are already there..)
also you're fan looks like it's playing up..
*Jan 16 20:11:24.243: %ENVMON-3-FAN_FAILED: Fan is malfunctioning


text:
Q: getting yesterday stopped working after few days jquery I am getting yesterday with a function in jquery which was working fine few days back but all of sudden its not giving me yesterday date.
getYesterdaysDate = ->
  date = new Date
  date.setDate date.getDate() - 1
  date.getFullYear() + '/' + date.getMonth() + 1 + '/' + date.getDate()

that was working fine but now its giving me totally different date, why is it so? any help will be appreciated thanks

A: Add some brackets -
date = new Date
date.setDate(date.getDate() - 1);
date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();


text:
Q: vb.net loop through textbox controls in containers My question may be simple but it's killing me...
I Have a windows user form with on it tabcontrols (about 10x).
On each tabcontrol i have some groupbox controls with in them some textboxes.
Tree structure would be something like this.
-Tab1
--Groupbox1
---Textbox name Alg_0
---Textbox name Alg_1
---Textbox name Alg_2
---Textbox name Alg_3
--Groupbox2
---Textbox name Alg_4
---Textbox name Alg_5
---Textbox name Alg_6
---Textbox name Alg_7
-Tab2
--Groupbox3
---Textbox name DD_0
---Textbox name DD_1
---Textbox name DD_2
---Textbox name DD_3
--Groupbox4
---Textbox name DD_4
---Textbox name DD_5
---Textbox name DD_6
---Textbox name DD_7
And many more (but in the same spirit)

What i want to do is loop through theses text boxes to create a comma seperated line and the write the values to a .txt file for saving. Later i will load these values and continue working with them.
Example (the names will be values ofcourse):
Alg_0,Alg_1,Alg_2,Alg_3,Alg_4,Alg_5,Alg_6,Alg_7,

I tried using the me.controls("String here") method. But this appears not to be working when the controls are in a container.
Example:
Private Sub main_save_Click(sender As Object, e As EventArgs) Handles main_save.Click

    Dim oID As Integer
    Dim oEnd As Integer
    Dim oAlg As String
    Dim oDD As String

    For oID = 0 To oEnd = 7
        oAlg = Me.Controls("Alg_" & oID).Text & ","
    Next

    For oID = 0 To oEnd = 7
        oDD = Me.Controls("DD_" & oID).Text & ","
    Next

End Sub

/At the end will be a writeline code which i will add later here./
For my Question
How do i access these textboxes in this order when they are in the containers as described?

A: You could try with something like this
for each tp in tabControl.Controls.OfType(Of TabPage)()
    for each gp in tp.Controls.OfType(Of GroupBox)()
        for each tx in gp.Controls.OfType(Of TextBox)()
            sb.Append(tx.Text & ",")
        Next
    Next
Next

This method takes the tabControl that contains the various tabPage and for each tabPage search the page ControlCollection for controls of type GroupBox then, for each groupbox search its controls collection for TextBoxes and prepare the output text
On the contrary you could take the string produced here to restore the textboxes with similar code
Dim texts = lineFromFile.Split(",")
Dim index as Integer = 0

for each tp in tabControl.Controls.OfType(Of TabPage)()
    for each gp in tp.Controls.OfType(Of GroupBox)()
        for each tx in gp.Controls.OfType(Of TextBox)()
            tx.Text = texts(index)
            index = index+1
        Next
    Next
Next

I should add that this approach is rather weak and you could face many problems to restore the values if you change in any way the layout of your form


text:
Q: How to inform parent control when UserControl perform method call? I have MainForm on which i've loaded UserControl. This UserControl has few textboxes and save button. Once i click save, information from textboxes is saved to file. I want to inform MainForm that information is updated to it can reload.
How can i do that ?

A: Use events.
Declare an event in your UserControl, for instance:
public event EventHandler SaveClicked;

then on save click, raise the event:
if (this.SaveClicked != null)
{
    this.SaveClicked(this, EventArgs.Empty);
}

and finally attach a handler in the main form to your event:
...
YourUserControl ctrl = new YourUserControl();
ctrl.SaveClicked += (sender, e) =>
{
    // Put logic of your main form here
};

A: You can use event - the userControl will send event to the parent - and the parent will register as event listener.


text:
Q: VUEX does not find a mutation but it is defined I'm working with VUEX and everything was fine until I registered a new mutation "shipping" since every time I commit it tells me: unknown mutation type: shipping. But I do not understand the reason since the previous mutations work correctly.
This is my code:
mutations:
export function removeAllProducts (state){
    state.cart = []
}

export function shipping(state, cost){
    state.cart.shipping = cost;
};

Component:
Template:
<input type="number" name="cost" :value="shippingCost" @input="updateCost">

Scripts:
computed: {
   ...mapState( 'cart', ['cart'] ),
   ...mapGetters('cart', ['totalItems', 'totalCost', 'shippingCost']),
    shippingCost:{
      get(){ return this.$store.getters.shippingCost; },
    }
},

     methods: {
     ...mapMutations('cart', ['addProductToCart', 'subtractProductToCart', 'removeProductFromCart', 'removeAllProducts', 'shipping' ]),
     ...mapMutations('routes', ['addRoute']),

      updateCost (e) {
        this.$store.commit('shipping', e.target.value)
      }
   }
}

A: You might call your mutation wrong. If this line is correct:
...mapMutations('cart', ['addProductToCart', 'subtractProductToCart', 'removeProductFromCart', 'removeAllProducts', 'shipping' ])

Then the function updateCost should be:
  updateCost (e) {
    this.$store.commit('cart/shipping', e.target.value)
  }

if in your module you did set namespacing to true. Or the function can be
  updateCost (e) {
    this.shipping(e.target.value)
  }

since you already use mapMutations to map shipping to your component.


text:
Q: How to sort this float list of numerical values in ascending order? I have been able to import 3 scores (or numbers) for each person in my CSV file
and have it work out the average of the three scores for each person but what I need to do next is sort the list of averages shown in the output from high to low. I have searched everywhere and have received 'Float' errors with everything I try.
from collections import defaultdict, deque
with open("highscores.csv", "r+")as file:
    file.seek(0)
    scores = file.readlines()
user_scores = defaultdict(lambda:deque(maxlen=3))
for line in scores:
    name, score = line.rstrip('\n').split(',')
    score = int(score)
    user_scores[name].append(score)

for name in user_scores:
    avg = (user_scores[name])
    x = sorted(avg)
    avg2 = sum(x) / float(len(x))
    print(name, avg2)

Output:
Odis 22.0
Vance 20.0
John 26.0
Marinda 25.0
Shenita 18.0
Marquitta 24.0
Concepcion 17.0
Robby 23.0
Valda 19.0
Ernesto 21.0
Jack 5.0

My CSV file looks like this :
Jack    4
Jack    5
Jack    6
Concepcion  7
Shenita 8
Valda   9
Vance   10
Ernesto 11
Odis    12
Robby   13
Marquitta   14
Marinda 15
John    16
Concepcion  17
Shenita 18
Valda   19
Vance   20
Ernesto 21
Odis    22
Robby   23
Marquitta   24
Marinda 25
John    26
Concepcion  27
Shenita 28
Valda   29
Vance   30
Ernesto 31
Odis    32
Robby   33
Marquitta   34
Marinda 35
John    36

A: The line where you sort avg is unnecessary - after all these are the scores of a single person and it doesn't matter in which order you sum them. What you want to do is to sort all the entries once all the averages are calculated, so you need to collect those. If you want them to be sorted according to their averages, use a tuple with the average as the first field, that way sorted will do exactly what you want:
# The list that will hold the pairs of
# average score and name
avgs = []

# Your initial loop
for name in user_scores:
    x = user_scores[name]

    # Just collect the pair
    avgs.append((sum(x) / float(len(x)), name)

# Now sort it
avgs = sorted(avgs)

# Print it
for avg, name in avgs:
    print (name, avg)

However, a much more Pythonesque way of doing it is with list comprehensions:
# A function for the average
def average(lst):
    return sum(lst) / float(len(lst))

# The averages as list comprehension
avgs = sorted((average(scores), name)
              for name, scores in user_scores.items())

# Print it
for avg, name in avgs:
    print (name, avg)

This assumes that you are using Python 3, for Python 2 use iteritems() or viewitems()

A: Assuming Python 3…
In your second for loop, you can't possibly get them printed in the desired order if you're printing them while you're still calculating the averages.  You need to split it up into two phases.
Calculate the average scores:
avg_user_scores = {
    user: sum(map(float, scores))/len(scores)
    for user, scores in user_scores.items()
}

Then print them, sorted in descending order:
for name, score in sorted(avg_user_scores.items(), key=itemgetter(1), reverse=True):
    print(name, score)

operator.itemgetter(1) is a way to fetch the second element of a tuple (i.e. lambda t: t[1]) — which is the average score.

The entire program:
from collections import defaultdict, deque
from operator import itemgetter

user_scores = defaultdict(lambda: deque(maxlen=3))
with open('highscores.csv') as file:
    for line in file:
        name, score = line.split(',')
        user_scores[name].append(float(score))
avg_user_scores = {
    user: sum(scores) / len(scores)
    for user, scores in user_scores.items()
}
for name, score in sorted(avg_user_scores.items(), key=itemgetter(1), reverse=True):
    print(name, score)

A: Average the three scores for each person. Place the values into a dictionary (the key will be the person). Call the sorted() method.


text:
Q: Render a variable in React html const getTime = () => {
    const today = new Date();
    const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    return {time};
}

export default function UpdateButton() {
    const classes = useStyles();
    const today = new Date();
    const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    return (

            <Button variant="contained" className={classes.button}>
                Update
            </Button>
            <text>Last Updated: {getTime}</text>

    )
};

I am trying to render the time in the text tag but it keep throwing error. How do I resolve this issue. This is under react framework.

A: The getTime function should return a string and not an object, and you should call it in the JSX - getTime():

const getTime = () => {
  const today = new Date();
  const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  return time;
}

function UpdateButton() {
  return (

      <button variant="contained">
        Update
      </button>
      <text>Last Updated: {getTime()}</text>

  )
};

ReactDOM.render(
  <UpdateButton /> ,
  root
);

A: SInce you didn't share the error I'm going to guess it's because you return a function in your JSX:
const getTime = () => {
    const today = new Date();
    const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    return time;
}

export default function UpdateButton() {
    const classes = useStyles();
    const today = new Date();
    const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    return (

            <Button variant="contained" className={classes.button}>
                Update
            </Button>
            <text>Last Updated: {getTime()}</text>

    )
};


text:
Q: SSIS 2012 Send Mail Task with an attachment My SSIS package writes a log file during the execution. In the end it calls another package that sends that log file via email.
I'm not able to send it (the email without the attachment works fine) and I always get this error:
[Send Mail Task] Error: Either the file "F:\ etc..." does not exist or you do not have permissions to access the file.
I've already tried to:
- set DelayValidation property to True for the Send Mail Task;
- close the filestream of the log file before sending the email.
but nothing changes...

A: I added the file extension to the file path and now it works! I also left DelayValidation property set to True for the Send Mail Task.
I didn't think of it because I saw that Windows opened the file, even if without extension.


text:
Q: Typeset an author without affiliation with authblk I'm currently using authblk to typeset authors and corresponding affiliation(s) in a proceeding article, one of the authors has no affiliation.
Commands are the following:
\author[*]{Name1}
\author[**]{Name2}
\author{Name3}

\affil[*]{Dept #1}
\affil[**]{Dept #1}

However, the package does not recognize that Name3 has no affiliation, and it's typeset like it's affiliated with Dept #1.
How should I modify the autlblk package to overcome this?

A: Just put a single space as the marker for author 3 (you need the space, not just []).
\author[ ]{Name3}

A: I find a single way.
\author[1]{name 1}
\author[2]{name 2}

\affil[1]{...}
\affil[2]{...}

In the output, if you do not like the upper script in the affiliation, you add
\affil[**]{...}
where I use * to present the space.
I notice that one space is not enough, you need at least two space.
In my case, I use
\affil[  ]{Email:**@**}
then the upper script disappeared.


text:
Q: How do we include native library symbols for android app? in firebase crashlytics we see no stacktrace for native crash

How do we include symbol files?
Below is my guess on how to proceed..

*

*build NDK from source and generate *.so files. They are typically generated under obj or libs folder.

*find the path of the *.so files

*direct crashlytics to upload those symbols using firebaseCrashlytics directive in build.gradle (https://firebase.google.com/docs/crashlytics/ndk-reports)

I'm not sure if my assumption is correct, if it is.. How do I do #1? build NDK?
I can see that react-native can generate those *.so files when I build react-native from source files. (such as libc++_shared.so)
I guess we need to do the same thing as RN is doing.


text:
Q: Alert Volume slider sound file In ubuntu 12.10, when you go to Sound -> Sound Effects tab and slide the Alert Volume slider, it makes a "pop" sound. What is the name of that sound file? I'd like to set it as my terminal beep sound.
Hint: it's not in /usr/share/sounds/gnome/default/alerts/.

A: /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga

A: It is one of the files in /usr/share/sounds/gnome/default/alerts/.


text:
Q: Ajax request to controller error I am using ajax to perform a user register function. I use ajax to send the user information over to the controller which then passes the information to a model to insert the information into a database.
The insertion is done successfully as I saw the entry in my database. However for my ajax request it always returns an error.
Something I noted was that once I leave one of the fields empty, it returns a success.
my ajax script as below
var post_data =
    {
        'username':user_name,
        'password':user_password,
        'email':user_email,
        'role':user_role
    };

    $.ajax({
        type: "POST",
        dataType: "json",
        url:"login_register/register_data",
        data: post_data,
        success: function(data) {
                alert('Insertion of user ok');
        },
        error: function(data)
        {
            alert('Insertion of user error ' + data.responseText);
        }
    });

my controller code
public function register_data()
{
    $this->load->database();
    $this->load->model('login_model');

    $user_name=$this->input->post('username');
    $user_password=$this->input->post('password');
    $user_email=$this->input->post('email');
    $user_role=$this->input->post('role');

    $result = $this->login_model->register_data_model($user_name,$user_password,$user_email,$user_role);

    //if($result)
        echo "true";
    //else echo "false";
}

my model code
public function register_data_model($user_name,$user_password,$user_email,$user_role)
{
    $result = $this->db->query("INSERT INTO user_table (user_name,user_password,user_email,user_role) VALUES (".$this->db->escape($user_name).",".$this->db->escape($user_password).",".$this->db->escape($user_email).",".$this->db->escape($user_role).")");
}

even if I dont return anything from the model and the controller, it still behaves like this. Anyone has any idea what is going on?

A: I don't think the post_data is correct... Try this:
$.ajax({
    type: "POST",
    dataType: "json",
    url:"login_register/register_data",
    data: {user_name:'username', user_password:'password',user_email:'email',user_role:'role'},
    success: function(data) {
            alert('Insertion of user ok');
    },
    error: function(data)
    {
        alert('Insertion of user error ' + data.responseText);
    }
});

This would require you to get by the new key in the controller, i.e.
$user_name=$this->input->post('user_name');

A: Try this:
var post_data =
{
     username:user_name,
     password:user_password,
     email:user_email,
     role :user_role
};

A: id suggest returning actual json formatted data instead of just true.
something along the lines of:
[{"successfull":"yes" }]

and set your php headers to application type json.
then in your javascript you can test in the success function
if(data[0]["successfull"].indexOf("yes") != -1)
    {
    dosomething()
    }

A: Check the network headers to make sure you're site isn't throwing a 500 or something.


text:
Q: php build query username and password and check result i would like to ask you about my database query
i have this table admin_table in my data base
tag id       name           password       profession
xxxxxx     Jhon Begly         123            admin

i build a php page to insert a user name and password
i need to check the user name and password that i entered with its profession if its valid then proceed with a new page as bellow
$sql = "SELECT * FROM admin_table WHERE name='".$username."' AND password='".$password."'";
so how can i check profession in the same query above
any update will be highly appreciated

A: Where are you validating the profession?  If it is in another table... use
INNER JOIN profession_table as pt
ON pt.some_column

right after the from part of your query

A: You mean this?
$sql = "SELECT * FROM admin_table WHERE name='".$username."'
        AND password='".$password."' AND profession = 'admin'";

If you get a result row back, you matched all three columns. If zero rows, it failed to match at least one. Not really sure your use case.
I also agree with other commenters that this is far from best practices in several ways.


text:
Q: How can I mask a UIImageView? I am trying to mask an image with something like this:

Would you please help me?
I am using this code:
- (void) viewDidLoad {
    UIImage *OrigImage = [UIImage imageNamed:@"dogs.png"];
    UIImage *mask = [UIImage imageNamed:@"mask.png"];
    UIImage *maskedImage = [self maskImage:OrigImage withMask:mask];
    myUIIMage.image = maskedImage;
}

A: SWIFT 3 XCODE 8.1
func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

    let maskRef = maskImage.cgImage

    let mask = CGImage(
        maskWidth: maskRef!.width,
        height: maskRef!.height,
        bitsPerComponent: maskRef!.bitsPerComponent,
        bitsPerPixel: maskRef!.bitsPerPixel,
        bytesPerRow: maskRef!.bytesPerRow,
        provider: maskRef!.dataProvider!,
        decode: nil,
        shouldInterpolate: false)

    let masked = image.cgImage!.masking(mask!)
    let maskedImage = UIImage(cgImage: masked!)

    // No need to release. Core Foundation objects are automatically memory managed.

    return maskedImage

}

// for use
testImage.image = maskImage(image: UIImage(named: "OriginalImage")!, withMask: UIImage(named: "maskImage")!)

A: The tutorial uses this method with two parameters: image and maskImage, these you have to set when you call the method. An example call could look like this, assuming the method is in the same class and the pictures are in your bundle:
Note - amazingly the images do not even have to be the same size.
...
UIImage *image = [UIImage imageNamed:@"dogs.png"];
UIImage *mask = [UIImage imageNamed:@"mask.png"];

// result of the masking method
UIImage *maskedImage = [self maskImage:image withMask:mask];

...

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];

    CGImageRelease(mask);
    CGImageRelease(maskedImageRef);

    // returns new image with mask applied
    return maskedImage;
}

After you provided your code I have added some numbers as comments to it for reference. You still have two options. This whole thing is a method, which you are calling somewhere. You don't need to create the images inside it: this reduces the reusability of the method to zero.
To get your code working. Change the methods head (1.) to
- (UIImage *)maskImageMyImages {

Then change the name of the variable in 2. to
UIImage *maskImage = [UIImage imageNamed:@"mask.png"];

The method will return your masked images so you'll have to call this method in some place.
Can you show us the code where you are calling your method?

A: Swift version of the accepted solution:
func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

    let maskRef = maskImage.CGImage

    let mask = CGImageMaskCreate(
        CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef),
        nil,
        false)

    let masked = CGImageCreateWithMask(image.CGImage, mask)
    let maskedImage = UIImage(CGImage: masked)!

    // No need to release. Core Foundation objects are automatically memory managed.

    return maskedImage

}

Just in case someone need it.
It`s working for me flawlessly.

A: we found, that correct answer is not working now and implemented little drop-in class, which helps to mask any image in UIImageView.
It's available here: https://github.com/Werbary/WBMaskedImageView
Example:
WBMaskedImageView *imgView = [[WBMaskedImageView alloc] initWithFrame:frame];
imgView.originalImage = [UIImage imageNamed:@"original_image.png"];
imgView.maskImage = [UIImage imageNamed:@"mask_image.png"];

A: Swift 3 - Simplest Solution I Found
I created an @IBDesignable for this so you could see the effect right away on your storyboard.
import UIKit

@IBDesignable
class UIImageViewWithMask: UIImageView {
    var maskImageView = UIImageView()

    @IBInspectable
    var maskImage: UIImage? {
        didSet {
            maskImageView.image = maskImage
            updateView()
        }
    }

    // This updates mask size when changing device orientation (portrait/landscape)
    override func layoutSubviews() {
        super.layoutSubviews()
        updateView()
    }

    func updateView() {
        if maskImageView.image != nil {
            maskImageView.frame = bounds
            mask = maskImageView
        }
    }
}

How to use

*

*Create a new file and paste in that code above.

*Add UIImageView to your storyboard (assign an image if you want).

*On Identity Inspector: Change the custom class to "UIImageViewWithMask" (custom class name above).

*On Attributes Inspector: Select mask image you
want to use.

Example

Notes

*

*Your mask image should have a transparent background (PNG) for the non-black part.

A: There's an easier way.
#import <QuartzCore/QuartzCore.h>
// remember to include Framework as well

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
mask.frame = CGRectMake(0, 0, <img_width>, <img_height>);
yourImageView.layer.mask = mask;
yourImageView.layer.masksToBounds = YES;

For Swift 4 and plus follow code below
let mask = CALayer()
mask.contents =  UIImage(named: "right_challenge_bg")?.cgImage as Any
mask.frame = CGRect(x: 0, y: 0, width: leftBGImage.frame.size.width, height: leftBGImage.frame.size.height)
leftBGImage.layer.mask = mask
leftBGImage.layer.masksToBounds = true

A: I tried both code using either CALayer or CGImageCreateWithMask but none of them didn't work for me
But i found out that the problem is with png file format, NOT the code!!
so just to share my finding!
If you want to use
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage

you must use 24bit png without alpha channel
If you want to use CALayer mask, you must use (24bit or 8bit) png with alpha channel where transparent part of your png will mask the image (for smooth gradient alpha mask.. use 24bit png with alpha channel)

A: - (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGImageRef maskImageRef = [maskImage CGImage];

        // create a bitmap graphics context the size of the image
        CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(colorSpace);

        if (mainViewContentContext==NULL)
            return NULL;

        CGFloat ratio = 0;

        ratio = maskImage.size.width/ image.size.width;

        if(ratio * image.size.height < maskImage.size.height) {
            ratio = maskImage.size.height/ image.size.height;
        }

        CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
        CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};

        CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
        CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);

        // Create CGImageRef of the main view bitmap content, and then
        // release that bitmap context
        CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
        CGContextRelease(mainViewContentContext);

        UIImage *theImage = [UIImage imageWithCGImage:newImage];

        CGImageRelease(newImage);

        // return the image
        return theImage;
}

This works for me.


text:
Q: Python Google App Engine redirect not updating content I am using Python and Google App Engine to send a POST form to increase a likes counter. It updates the number of likes, but when redirect to home page it doesn't show the updated counter, but if I click refresh it does show the updated counter. This only happens on the first time I submit the form, the second, third and so on it shows the updated counter fine, but if I refresh again it won't show the updated counter on the first submission
if likePostId:
    if post.likes == None:
       post.likes = 1
    else:
       post.likes = int(post.likes) + 1
    post.put()
    self.redirect('/')


text:
Q: Saving UITextView Text to Parse I was wondering how to save the text inside UITextView to parse. Everytime I run my code below an error comes up saying it accidentally "found nil when unwrapping an optional" on the lines that save the information to parse.
Note: The functions "SaveNotesParse" and "SaveFrontScreenInfo" are where the errors occur. They are also both called in another class.
@IBOutlet weak var titleText: UITextView!

@IBOutlet weak var descriptionText: UITextView!

@IBOutlet weak var titleText2: UITextView!

@IBOutlet weak var contentText: UITextView!

let testObject = PFObject(className: "Notes")

func SaveNotesParse () {

    //parse stuff

    testObject["Title2"] = titleText2.text

    testObject["Content"] = contentText.text

    print("Saving")

    testObject.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in

        print("Object has been saved.")

    }

}

func SaveFrontScreenInfo () {

    testObject["Title"] = titleText.text

    testObject["Description"] = descriptionText.text

}

override func awakeFromNib() {

    foregroundView.layer.cornerRadius = 10

    foregroundView.layer.masksToBounds = true

    super.awakeFromNib()

}

override func animationDuration(itemIndex:NSInteger, type:AnimationType)-> NSTimeInterval {

    let durations = [0.26, 0.2, 0.2]

    return durations[itemIndex]

}

Image of the error and line that it appears:
Line that the error message appears
The actual error message as shown in the logs

A: Try using the setObject function like so:
testObject.setObject(titleText2.text, forKey: "Title2")

Otherwise, can you tell us what is nil? It will have to be either the testObject or the Text Fields. Try printing them to see which one is nil.


text:
Q: MvvmLight dynamic message token Is it possible to send register for a Message that is created with a dynamic token?
I have several user controls that are in a ItemsControl and I want each control to only listen for messages that target a certain Id.
Keeps throwing a un-handled exception.

A: Please see the video of Laurent Bugnion, who has developed the mvvm-light toolkit:
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
He is saying about a universal lambda converter in this discussion.


text:
Q: PLSQL, SQL*PLUS get current username? I know that the show user command return: USER is "SCOTT"
But is it possible in a sql query or in a plsql script to only get the username of the current user and store it in a variable?

A: SYS_CONTEXT( 'USERENV', 'CURRENT_USER' )

A: The USER built-in function may be used.
DECLARE
  v VARCHAR2(30);
BEGIN
  v := USER;
END;

A: fnd_profile.value('USERNAME')
fnd_profile.value('USER_ID')
fnd_flobal.user_id

these can be used to get the user details


text:
Q: Inaccurate intervals in setInterval and setTimeout I have built a Pomodoro clock in ReactJS, which involves using setInterval (or setTimeout), but when I ran it to follow the sessions/breaks patterns, I discovered that at the end of a 90 minutes session on my mobile clock, there was a lag of about 30 minutes in my Pomodoro app. That is, there was a delay of 30 minutes!!
After a little research I discovered that setInterval doesn't fire exactly at the specific interval you specify, and it tends to drift depending on the CPU load, and these drifts accumulate to make a significant delay in the long run.
A solution to this problem that I came across is the self-adjusting timers that use Date.now() method to account for the drift in the recursive setTimeout function.
However, in the process, I came to also know that when a tab in Google chrome is inactive, then even the self-adjusting timers drift because of the way processes are scheduled in the CPU (inactive tabs probably means nothing important to process).
For me this poses a problem, because I would like to run my Pomodoro clock in one tab, and go and work on another tab.
My question is: how can I solve this inactive browser's tab problem to create an accurate timer in JavaScript?