text:
Q: C: pass a 2D array as a function argument and get the results stored in the argument address Short: How can I pass a 2D array as a function argument and get the results stored in the argument address?
Longer: I have code (below) which calls, from main() an initialization function and then prints the content. However, I would expect that after storing the pointers given by malloc into the variable A the results would be saved in the argument but it does not. When doing similar things with 1D arrays it works smoothly but not for 2D arrays.
For simplicity, in this case I make it 3x3, but I want to have a non-fixed amount of GB of data. Then, I must use malloc and I cannot declare the matrix size at compilation time.
#include <stdio.h>
#include <stdlib.h>

void print_matrix(int n, double **A) {
    int i, j;
    for(i=0; i<n; i++) {
        for(j=0;j<n;j++) {
            printf("%0.2f ",A[i][j]);
        }
        printf("\n");
    }
}

void init(int n, double **A) {
    int i;
    A = (double **)malloc(n * n * sizeof(double *));
    for(i=0; i<n; i++) {
         A[i] = (double *)malloc(n * sizeof(double));
    }
    A[0][0] = 9.0;
    A[0][1] = 6.0;
    A[0][2] = -3.0;
    A[1][0] = 6.0;
    A[1][1] = 13.0;
    A[1][2] = -5.0;
    A[2][0] = -3.0;
    A[2][1] = -5.0;
    A[2][2] = 18.0;
    print_matrix(n, A);
}

int main() {
    int i;
    int n=3;
    double **A;
    init(n, A);
    print_matrix(n, A);
    for(i=0; i<n; i++)
        free(A[i]);
    free(A);
    return 0;
}

After compiling I can print the content of the matrix inside the init() function but not from main() without getting a segmentation fault, which of course means that A is pointing to unassigned memory and that not even A[0][0] is pointing to the root of the matrix. I am using GCC and standard C99.
$ gcc --version
gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
$ gcc main.c -o main -std=c99
$ ./main
9.00 6.00 -3.00
6.00 13.00 -5.00
-3.00 -5.00 18.00
Segmentation fault (core dumped)

There are other useful questions about passing 2D arrays but they do not solve my point because they do not tackle the issue of getting the results back in the argument.

*

*C — passing a 2d array as a function argument?

*how to define a 2d array using malloc and pass it to a function
fr

Edit: This is a simple case, but I would need to pass several matrices as function arguments. Therefore, I cannot simply return the address of the matrix A, because I would need to save the addresses of several matrices.

A: I'd do it like
#include <stdio.h>
#include <stdlib.h>

void print_matrix(int n, double **A) {
    int i, j;
    for(i=0; i<n; i++) {
        for(j=0;j<n;j++) {
            printf("%0.2f ",A[i][j]);
        }
        printf("\n");
    }
}

double ** init(int n) {
    int i;
    double **A;
    A = (double **)malloc(n * n * sizeof(double *));
    for(i=0; i<n; i++) {
         A[i] = (double *)malloc(n * sizeof(double));
    }
    A[0][0] = 9.0;
    A[0][1] = 6.0;
    A[0][2] = -3.0;
    A[1][0] = 6.0;
    A[1][1] = 13.0;
    A[1][2] = -5.0;
    A[2][0] = -3.0;
    A[2][1] = -5.0;
    A[2][2] = 18.0;
    print_matrix(n, A);
    return A;
}

int main() {
    int i;
    int n=3;
    double **A;
    A = init(n);
    print_matrix(n, A);
    for(i=0; i<n; i++)
        free(A[i]);
    free(A);
    return 0;
}

Allocate memory within your init() function and return the pointer.
[ronald@ocelot tmp]$ ./x
9.00 6.00 -3.00
6.00 13.00 -5.00
-3.00 -5.00 18.00
9.00 6.00 -3.00
6.00 13.00 -5.00
-3.00 -5.00 18.00

An answer to the original question would be (only the changed code)
void init(int n, double ***A) {
    int i;
    *A = (double **)malloc(n * n * sizeof(double *));
    for(i=0; i<n; i++) {
         (*A)[i] = (double *)malloc(n * sizeof(double));
    }
    (*A)[0][0] = 9.0;
    (*A)[0][1] = 6.0;
    (*A)[0][2] = -3.0;
    (*A)[1][0] = 6.0;
    (*A)[1][1] = 13.0;
    (*A)[1][2] = -5.0;
    (*A)[2][0] = -3.0;
    (*A)[2][1] = -5.0;
    (*A)[2][2] = 18.0;
    print_matrix(n, *A);
}

int main() {
    int i;
    int n=3;
    double **A;
    init(n, &A);
    print_matrix(n, A);
    for(i=0; i<n; i++)
        free(A[i]);
    free(A);
    return 0;
}

A: Pass the matrix by a pointer. Because no one wants to be a three star programmer, create a structure for your data and pass a pointer to the structure. Remember that readability of the code, proper encapsulation and readable object-oriented programing will take you further. Remember about error handling, which I hope you omitted in your question for brevity. Do not cast result of malloc. Use size_t type to represent count of elements in an array.
That said, I would do:
// Represents a n x n dynamically allocated matrix.
struct matrix_s {
   double **a;
   size_t n;
};

// Forward declaration for `matrix_init`.
void matrix_free(struct matrix_s *m);

int matrix_init(struct matrix_s *m, size_t n) {
    assert(n > 2); // as you seem to access indices at least 2
    m->a = calloc(n * n, sizeof(*m->a));
    if (m->a == NULL) {
        goto ERROR;
    }
    m->n = 0;
    for(size_t i = 0; i < n; i++) {
         m->a[i] = calloc(n, sizeof(*A[i]));
         m->n++;
         if (m->a[i] == NULL) {
            goto ERROR;
         }
    }

    // fill the array

    // SUCCESS
    return 0;

    ERROR:
    matrix_free(m);
    return ENOMEM;
}

void matrix_print(struct matrix_s *m) {
   for (size_t i = 0; i < m->n; ++i) {
       printf(....);
   }
}

void matrix_free(struct matrix_s *m) {
   for (size_t i = 0; i < m->n; ++i) {
      free(m->a[i]);
   }
   free(m->a);
   m->a = NULL;
   m->n = 0;
}

int main() {
    struct matrix_s m;
    if (matrix_init(&m, 3) != 0) {
       abort();
    }
    matrix_print(&m);
    matrix_free(&m);
    return 0;
}

Still, if you want to, you can be a 3-star programmer and pass the pointer A from main by a pointer with almost virtually no changes:
void init(int n, double ***A0) {
    double **A = malloc(n * n * sizeof(*A));

    // same your code without any modification

    *A0 = A; // asing the outer pointer to A
}

int main() {
    double **A;
    init(3, &A); // pass `A` by a pointer
    // ...
}

Because your matrix seems to have equal row size for each row, with proper encapsulation you could think about just allocating a single memory block for n * n doubles and calculate the indices yourself to navigate to. You could also use a variable length array like double (*array)[n] to access your data with array-like seamless fashion. But resizing the array could get significantly harder.
struct matrix_s {
    double *a;
    size_t n;
};

double *matrix_getp(struct matrix_s *m, size_t i, size_t j) {
     return &m->a[i * m->n + j];
}

int matrix_init(struct matrix_s *m, size_t n) {
     m->a = malloc(n * n * sizeof(*m->a)); // only a single allocation
     // ...

     // access to matrix at A[0][0]
     *matrix_getp(m, 0, 0) = 1;
     // or the same using a VLA variable:
     double (*a)[n] = (void*)m->a;
     a[0][0] = 1;

     // ...
}


text:
Q: game Loop performance issue I am making a bomberman game in Java, the game seems to be slowing the PC overloading the processors and CPU. I have used the loop in another game and it worked fine without causing any performance problem. However I did notice that by simply commenting out the gameloop() will cause major performance issue
The game loop I'm using:
public void start() {
    window.setVisible(true);
    running = true;
    int fps = 60;
    double timePerTick = 1e9 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();

    while (running) {
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        lastTime = now;
        if (delta >= 1) {
            gameLoop(); /* commenting this out will cause major performance
                         * problem to the PC */
            delta--;
        }
    }
}

@Override
public void gameLoop() {
    if(!gameover){
        run();
        gui.repaint();
    }
}

Is there any problem with this loop which could be causing problem, or is there a better method which will reduce the performance issues
[EDIT]
I changed the loop to do a similar task with timer, it works fine and does not cause any performance issues, anything still wrong with this method (long term issue)??
public void start(int fps){
   window.setVisible(true);
   running = true;
   gameTimer.scheduleAtFixedRate(new GameTimer(), 0, 1000/fps);
}

private class GameTimer extends TimerTask{

   @Override
   public void run(){
      gameLoop();
   }
}

A: Your are making an infinite loop without any pauses which consumes 100% of your CPU, in your case according to your needs, you should define your frame rate and set the length of time to sleep accordingly as next:
    run();
    gui.repaint();
    // Make the current thread sleeps 1 000 milliseconds which means 1 frame per sec
    Thread.sleep(1000L);

A: You are busy looping, which will keep one thread permanently busy. This inevitably takes away CPU resources, making less available for anything else.
Instead of constantly taking the nanoTime() and calling gameloop() when enough time has elapsed, you should predict at which time the next call to gameloop() shall take place and call Thread.sleep() to pause the thread until that time arrives. For many purposes its accurate enough to just calculate the millisecond timestamp when the next tick is due, subtract the current time and sleep that amount:
long lastTick = System.currentTimeMillis();
long ticksPerFrame = 1000 / fps;
while (true) {
    long nextTick = lastTick + ticksPerFrame;
    long sleep = nextTick - System.currentTimeMillis();
    if (sleep > 0) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    lastTick = nextTick;
    gameloop();
}

(Code not tested, only meant to demonstrate the general approach)
This will be only be as accurate as the system timer resolution plus/minus sleep variation. For most systems that means an average few ms of variation, acceptable for many scenarios, especially if you use AWT/Swing for rendering anyway. A repaint may be skipped by Swing if you place repaint() calls faster than the EDT can handle them, this is in most cases desirable as it allows the repaint queue to catch up when delayed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CLIENT_MISSING_INTENTS' enter image description here
i need help with that error when first coding discord bot
here code
const client = new Discord.Client()

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("message", msg => {
  if (msg.content === "ping") {
    msg.reply("pong");
  }
})

client.login(process.env.TOKEN)

i try many way on internet but it still not sold ;.;
pls help me
this is error
 throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (E:\bot\node_modules\discord.js\src\client\Client.js:544:13)
    at new Client (E:\bot\node_modules\discord.js\src\client\Client.js:73:10)
    at Object.<anonymous> (E:\bot\src\bot.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47 {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'

A:
To specify which events you want your bot to receive, first think about which events your bot needs to operate. Then select the required intents and add them to your client constructor, as shown below.
All gateway intents, and the events belonging to each, are listed on the Discord API documentation. If you need your bot to receive messages (MESSAGE_CREATE - "messageCreate" in discord.js), you need the GUILD_MESSAGES intent. If you want your bot to post welcome messages for new members (GUILD_MEMBER_ADD - "guildMemberAdd" in discord.js), you need the GUILD_MEMBERS intent, and so on.

Example:
const client = new Discord.Client({
    intents: [
        Discord.Intents.FLAGS.GUILDS,
        Discord.Intents.FLAGS.GUILD_MESSAGES
    ]
});

A: The issue is exactly what the error says it is; your client is missing intents. You need to specify what events and data your bot intends to work with (e.g. guild member presences, messages, etc).

i try many way on internet but it still not sold

I don't know what tutorials or guides you're looking at, but only discord.js v11 and under can work without intents. Discord.js v12 and the latest version (v13) require intents to be specified. What intents you need to specify depends on what you want your bot to do. Does your bot need to detect messages and respond to them? Then enable the GUILD_MESSAGES intent. If your bot does not need to, for example, track guild member presences, you do not need to enable a GUILD_PRESENCES intent.
Before continuing, I would highly suggest you check out the official discord.js guide on how to create a bot on the latest version, which should have been the first place you looked for this information.
Here is a simple way to solve your issue based on the code on that guide, if you are using discord.js v13:
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

Here is another way of doing it, if you are on discord.js v12 (this may also work in v13):
// Require the necessary discord.js classes
const { Client } = require('discord.js');

// Create a new client instance
const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES"], ws: {intents: ["GUILDS", "GUILD_MESSAGES"]} });

Note that the intents I specified in the above examples may not be enough for you, depending on what your bot is supposed to do in the future. But I believe those examples will be enough to get your current code working without the error you are experiencing.
For a full list of intents, check the discord developer docs here.


text:
Q: How do I test a schedulable email sending? I have a schedulable apex class for the email sending. I tested a schedule, but I can't to coverage sending logic. Is there a some way to test good and bad scenarios for it?
My class:
public class EmailSchedule implements Schedulable {
    public void execute(System.SchedulableContext ctx){
        List<Tool__c> toolsForEmail = [SELECT Email__c, Email_content__c FROM Tool__c LIMIT 10];
        List<Tool__c> toolsToUpdateEmail = new List<Tool__c>();

        if(!toolsForEmail.isEmpty()){
            Messaging.SingleEmailMessage[] messages = new Messaging.SingleEmailMessage[0];
            for(Tool__c toolEmail : toolsForEmail){
                 if(toolEmail.Email__c != null && toolEmail.Email_content__c != null){
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    String[] toAddresses = new String[] {toolEmail.Email__c};
                    mail.setToAddresses(toAddresses);
                    mail.setReplyTo('tool@gmail.com');
                    mail.setPlainTextBody(toolEmail.Email_content__c);
                    messages.add(mail);
                    toolsToUpdateEmailStatus.add(toolEmail);
                }
            }
            Messaging.sendEmail(messages);
            if(!toolsToUpdateEmailStatus.isEmpty()){
                update toolsToUpdateEmail;
            }
        }
    }
}

My test:
@isTest
public class EmailScheduleTest {
    @isTest static void testSchedule(){
        test.starttest();
            EmailCheckInSchedule myClass = new EmailCheckInSchedule();
            String chron = '0 0 10 * * ?';
            System.schedule('Test Sched', chron, myClass);
        test.stopTest();
    }

    @isTest static void sendEmail(){
        Tool__c tool = new Tool__c(
            Name = 'Test',
            Email__c = 'test@test.com',
            Email_content__c = 'Test email content'
        );

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {tool.Email__c, 'test2@test.com'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('tool@gmail.com');
        mail.setPlainTextBody(tool.Email_content__c);
        Messaging.sendEmail(new List<Messaging.Email>{mail});
    }
}

A: Refer below Test class. I've modified a bit and invoked Schedular:
@isTest
public class EmailScheduleTest {

    @isTest static void sendEmail(){
        List<Tool__c> lstTool = new List <Tool__c> ();
        Tool__c tool = new Tool__c(
            Name = 'Test',
            Email__c = 'test@test.com',
            Email_content__c = 'Test email content'
        );
        lstTool.add (tool);
        tool = new Tool__c(
            Name = 'Test_2',
            Email__c = 'test@best.com',
            Email_content__c = 'Best email content'
        );
        lstTool.add (tool);
        insert lstTool;

        test.startTest ();
        EmailSchedule myClass = new EmailSchedule();
        String chron = '0 0 10 * * ?';
        System.schedule('Test Sched', chron, myClass);
        test.stopTest ();
    }
}


text:
Q: Using gulp-livereload with gulp-sass Gulp-livereload is giving me an error when I save a change to my .scss files. My gulpfile.js has been working fine for years and just started giving me trouble a little while ago. The scss gets compiled to css and livereload tries to reload the page, but I get the following error (photo attached: https://i.stack.imgur.com/o57el.png). When I manually reload the page the error goes away and the style changes are reflected. Also, if I make changes to other files (i.e. HTML or JavaScript) everything works just fine.
It may also be worth mentioning, I am using MAMP to create a local Apache server, so I don't think I can make use of something else like browsersync. Any help would be much appreciated, thank you!
Here is what my gulpfile.js looks like.
'use strict';

var gulp = require('gulp');

var sourcemaps = require('gulp-sourcemaps');

var sass = require('gulp-sass');

var livereload = require('gulp-livereload');

gulp.task('sass', function () {
  return gulp.src('./styles/sass/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./styles/css'))
    .pipe(livereload());
});

gulp.task('html', function() {
  return gulp.src('./**/*.html')
    .pipe(livereload());
});

gulp.task('js', function() {
  return gulp.src('./js/*.js')
    .pipe(livereload());
});

gulp.task('watch', function () {
  livereload.listen();
  gulp.watch('./styles/sass/**/*.scss', gulp.series('sass'));
  gulp.watch('./*.html', gulp.series('html'));
  gulp.watch('./js/*.js', gulp.series('js'));
});


text:
Q: Printing Selected Row in Gridview Is there a way to print only the information from selected rows in a GridView? I know how to print an ENTIRE GridView, by giving its div an ID...but I can't seem to figure out how I could extract just the information from each selected row.

A: I imagine you can do this by adding a style to row the user has selected (ie class="printMe"). Your print style sheet can have a style with display none for all the rows in the gridview, except for the style which you have added to the row.
#MyGrid TR {display:none;}
#MyGrid TR.printMe {display:block; }


text:
Q: Properties not loading for single project I have a Winforms project and checked in both VS 2015 and VS 2019. Properties for controls are not loading for just a single project in both versions. I have tried to re-create the solution but it remains the same.

Edit:
Hi, I found the problem, I used this control which cause lag. https://www.codeproject.com/Articles/91387/Painting-Your-Own-Tabs-Second-Edition-2
When I opened the form that was using this control, it was flickering in VS designer and lagged the whole VS interface. If anybody can help to fix this?


text:
Q: Gaussian sufficient statistic calculation Consider the Gaussian model
$$
Y_i = \beta + \epsilon_i,\, i = 1, \cdots, n,\; \mbox{where}\; \epsilon_i
\stackrel{i.i.d.}{\sim} \mathcal{N}(0, \sigma^2),
$$
parametrized by $\beta$, with known $\sigma$.
The likelihood function admits the factorization
\begin{align*}
L(Y) &= \frac{1}{ (\sqrt{2\pi \sigma^2}) ^n } e^{-\frac{1}{2\sigma^2} (\sum_{i = 1}^n (Y_i - \beta)^2)} \\\\
     &= \frac{1}{ (\sqrt{2\pi \sigma^2}) ^n } e^{-\frac{1}{2\sigma^2} ( \sum_{i = 1}^n (Y_i - \bar{Y})^2 + n ( \bar{Y} - \beta)^2)}.
\end{align*}
Evidently, by the Halmos-Savage factorization criterion, the sample mean $\bar{Y}$ is a sufficient statistic. (In fact, it is a minimal sufficient statistic.)
The decomposition
\begin{align*}
L(Y) &= \frac{1}{ (\sqrt{2\pi \sigma^2}) ^n } e^{-\frac{1}{2\sigma^2}  \sum_{i = 1}^n (Y_i - \bar{Y})^2} e^{-\frac{1}{2 \frac{\sigma^2}{n} } (\bar{Y} - \beta)^2 }\\\\
     &\equiv h(Y | \bar{Y}) \; g(\bar{Y}|\beta)
\end{align*}
suggests that $\bar{Y}$ is normally distributed with mean $\beta$ and variance $\frac{\sigma^2}{n}$, as it should be. So putting
$$
g(\bar{Y}|\beta) = \frac{1}{ (\sqrt{2\pi \frac{ \sigma^2}{n} })  } e^{-\frac{1}{2 \frac{\sigma^2}{n} } (\bar{Y} - \beta)^2}
$$
leads to
$$
h(Y | \bar{Y}) = \frac{1}{ (\sqrt{ \color{red}{ n }  \cdot 2\pi \sigma^2  }) ^{n-1} } e^{-\frac{1}{2\sigma^2} \sum_{i = 1}^n (Y_i - \bar{Y})^2}.
$$
Question
What is the explanation for the extra factor of $n$ in $\sqrt{ \color{red}{ n }  \cdot 2\pi \sigma^2  }$? One would expect the conditional density $h(Y | \bar{Y})$ to be a degenerate Gaussian---the joint density of $n-1$ i.i.d. Gaussians with variance $\sigma^2$---supported on a $(n-1)$-dimensional affine subspace of $\mathbb{R}^n$. So the normalization factor ought to be $(\sqrt{ 2\pi \sigma^2  })^{n-1}$, at first glance.

A: $$\left(\sqrt{2\pi\sigma^2}\right)^n = \sqrt{2\pi\sigma^2/n} \left(\sqrt{2\pi\sigma^2}\right)^{n-1}\sqrt{n}$$
So, $$h(Y | \bar{Y}) = \frac{1}{ \sqrt{ \color{red}{ n }} \cdot (\sqrt{2\pi \sigma^2  }) ^{n-1} } e^{-\frac{1}{2\sigma^2} \sum_{i = 1}^n (Y_i - \bar{Y})^2}.$$
The common pdf of degenerated normal distribution is
$$\displaystyle f(\mathbf {x} )=\left(\det \nolimits ^{*}(2\pi {\boldsymbol {\Sigma }})\right)^{-{\frac {1}{2}}}\,e^{-{\frac {1}{2}}(\mathbf {x} -{\boldsymbol {\mu }})'{\boldsymbol {\Sigma }}^{+}(\mathbf {x} -{\boldsymbol {\mu }})}$$
where $\displaystyle {\boldsymbol {\Sigma }}^{+}$ is the generalized inverse and det* is the pseudo-determinant.


text:
Q: How do you assign one series to another or merge where index does not intersect and retain values from one of the series for the interesting indices I have
S1 = pd.Series([1,2,3,4], index = ['A', 'B', 'C', 'D'])
S2 = pd.Series([5,6,7,8], index = ['C', 'D', 'E', 'F'])

I want to get
S3 = pd.Series([1,2,5,6,7,8], index = ['A', 'B', 'C', 'D', 'E', 'F'])

If an index is in S1 but not S2 keep value in S1. If index is not in S1 but is in S2 keep value in S2. if index in in both S1 and S2 keep value in S2.
It can also be viewed as a merge of S1 and S2 but for the values where the index interests keep the values in S2.

A: I think you need combine_first with astype if all output values are integers:
S3 = S2.combine_first(S1).astype(int)
print (S3)
A    1
B    2
C    5
D    6
E    7
F    8
dtype: int32


text:
Q: Pressing tab while editing a comment If you go to edit a comment, the tab order takes you to the "Save Edits" button, but then it skips the "Cancel" link and jumps down to "Active" (the answer sort method).
This wasn't expected.  I would expect TabTab would take you to "Cancel" next.  Should this be considered a bug?

A: Tab order will be fixed on the edit comment form after the next build.

A: This is because they are merely text, not links. Neither the "cancel" nor "help" anchors have a href attribute, so the browser doesn't consider them in tab order because they don't go anywhere. Could be easily fixed by adding a href="#" like the rest of the links (flag uses this).


text:
Q: Android widget - Where to register for explicit broadcasts Working on an Android widget that needs to be able to receive a broadcast from my application installed on the device itself. Basically want to be able to to notify the widget/s when certain events occur so they can update rather than wait the full 30 minutes.
Custom action: "com.example.UPDATE"
It looks like static register isn't an option anymore for my widget to receive custom intent broadcasts from my main application since they are separate entities and from the documentation it looks like Google locked down what is possible with static registers.  I wouldn't want to specific a single receiver anyways as I would like to be able to support multiple widgets and each receive the broadcast if they need to.
What would be the right way to dynamically register a broadcast receiver for a widget's context?
Would I register it in the onUpdate function of my AppWidgetProvider and just make sure its registered each time the onUpdate gets called?  That provides a context I could register it to.

A:
Working on an Android widget that needs to be able to receive a broadcast from my application installed on the device itself.

You act as though there are two separate apps: the "real" app and a separate app for the app widget. I strongly encourage you not to go that route, and instead have a single app. In that case, your app can simply use AppWidgetManager when it wishes to update the app widget's UI.
If you are convinced that having two separate apps is the right approach, read on.

It looks like static register isn't an option anymore for my widget to receive custom intent broadcasts from my main application since they are separate entities and from the documentation it looks like Google locked down what is possible with static registers

Only for implicit broadcasts. In your case, you can use an explicit broadcast, where you identify the specific app or component to receive the broadcast. setPackage() on the Intent should be sufficient.

What would be the right way to dynamically register a broadcast receiver for a widget's context?

Implement a foreground service and have it register for the broadcasts. It can then use AppWidgetManager to update your app widget. Since users will not like this, I recommend that you not go this route.

Would I register it in the onUpdate function of my AppWidgetProvider and just make sure its registered each time the onUpdate gets called?

No, because your process will go away shortly after onUpdate() returns, if there is nothing keeping that process around, such as a foreground service. This is why using a manifest-registered receiver and an explicit broadcast is a better solution.


text:
Q: Azure S2S vpn connection without IPSec I have azure subscription and have a home router (with no IPSec support) and I want to create a VPN tunnel. Need suggestion if I can still make a vpn tunnel to access on prem environment without IPSec configuration?

A: For site-to-site VPN it's IPSec only.  If you are ok to establish a client VPN on your device instead then you have more options (OpenVPN, SSTP or IPSec) - https://learn.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-about-vpngateways#planningtable


text:
Q: Reused MCU unit does not work I had a board with ATMEGA16 (SMD package) micro controller and I had to program through ICSP and it was working fine. Later I needed to make some changes on the board. So I designed a new board and transferred all the components to the new board. Now I am using the same ICSP programming technique but it does not read micro controller.
Could soldering and desoldering the IC with Hot blower be the problem? I soldered, de-soldered, soldered again.

A: I suspect you still have a continuity problem, even though you checked it.  Heat it up with your heat gun, and gently tap it with your tweezers, or something similar, after the solder reflows.  If no luck, try redoing it as shown on the instruction site SolderGuy.com


text:
Q: What does Instruction.Offset represent in mono.cecil? Can I interpret this as the line number in the source file?

A: No, Offset is the position of the instruction inside the method IL. It's used to implement branches.
To get line numbers you must use either Mono.Cecil.[Pdb|Mdb].dll (MS or Mono debugging symbols) and the SequencePoint. If that's what you're after then look at Gendarme source code for symbols.

A: This is the number of bytes into the IL-body of the method.


text:
Q: How we can 1 MONTH in a DateType variable in Oracle Stored Procedure I want to add 1 Month in v_TempEffectiveDate. What will be the correct statement?
  WHILE v_TempEffectiveDate <= v_EndDate LOOP
           v_TempEffectiveDate := ADD_MONTHS('v_TempEffectiveDate' + 1); --v_TempEffectiveDate + 1 MONTH
           v_MonthsElapsed := v_MonthsElapsed + 1;
        END LOOP; --WHILE v_TempEffectiveDate <= v_EndDate
        v_MonthsElapsed := v_MonthsElapsed - 1;

I got the following error:

PL/SQL : statement is ignored PLS-00306: worng number or type of argument in call to "ADD_Months()


text:
Q: .htaccess password protection with ip block I'm just trying to figure out the way trying to block user ip if they enter password 3 times wrong when prompted via .htaccess. I'm using this code to ask user user name and password. When they enter correct username password it allow user to view the webpage.Actually want to prevent brute force attack.
AuthType Basic
AuthName "wp-admin"
AuthUserFile "/home/isportal/.htpasswds/public_html/wp-admin/passwd"
require valid-user

Any help would be appreciated.

A: If you want to check password 3 times wrong then follow the tutorial. It is not possible by using .htaccess . You need php for this kind of task.
Block IP .htaccess Code:
Order Allow,Deny
Deny from 66.249.74.0/24
Allow from all


text:
Q: Expandable Listview Group Indicator half off screen? I am using a custom Group indicator as shown in the code below. Now if I leave the default I can use setBounds perfectly, but when using my custom image which is the same dimensions and setup as the same .9 patch file it is always half off screen. No matter what values I use for setBounds()
            Drawable plus = (Drawable) getResources().getDrawable(R.drawable.expander_group);
            getExpandableListView().setGroupIndicator(plus);
            Display newDisplay = getWindowManager().getDefaultDisplay();
            int width = newDisplay.getWidth();
            getExpandableListView().setIndicatorBounds(0,0);

XML expander_group
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_expanded="true"
        android:drawable="@drawable/minus" />
    <item
        android:drawable="@drawable/plus" />
</selector>

EDIT:
Interestingly. I have copied the exact xml and image files from the standard Android files. And when I use the above method to define it the exact same thing happens! So it is not the xml or image files that are causing the issue I think.


text:
Q: Routeconstraint with Ninject and dbcontext I'm trying to build a constraint that checks against database. And I'm using Ninject, but for some reason it doesnt create a new instance of my repository when it fires.
global.asax.cs
// Content
routes.MapRoute(
        "Content Language Route",
        "{languageID}/List",
             new { controller = "Content", action = "Index",
             new { languageID = new LanguageRouteConstraint() },
             new string[] { "MyProj.MVC.Controllers" }
         );
.....
kernel.Bind<IContentRepository>().To<ContentRepository>();

Constraint
public class LanguageRouteConstraint : IRouteConstraint
{
#region IRouteConstraint Members

private readonly IContentRepository _contentRepository;

public LanguageRouteConstraint(IContentRepository contentRepository)
{
     this._contentRepository = contentRepository;
}

public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
 if (routeDirection == RouteDirection.IncomingRequest)
 {
   string languageID = values["languageID"].ToString();

   if (String.IsNullOrEmpty(languageID))
     return false;

   MyProj.MVC.Models.Language language = _contentRepository.GetLanguage(languageID);

   return (language != null);
   }
  return false;
  }
#endregion
}

Using Ninject for the repository works in the controller, but do I need to modify the route in gobal asa for it to make it work?

A: Solved it like this:
 // Content
 routes.MapRoute("Content Language Route",
      "{languageID}/List",
      new { controller = "Content", action = "Index",
      new
      {
      languageID = new LanguageRouteConstraint(
            DependencyResolver.Current.GetService<IContentRepository>())
      },
     new string[] { "MyProj.MVC.Controllers" }
 );


text:
Q: Can't connect to Linksys E2000 router admin interface: Connection refused I am trying to connect to our router on 192.168.1.1 (correct IP) directly plugged in via Ethernet cable.
Connection via Firefox simply gives the can't establish a connection to the server error.
When I try a WGET command from our CentOS machine, I recieve the error ...failed: Connection refused.
Can anyone tell me why the router might be refusing connections to it's web interface?
Cheers

A: It is possible the router has been configured to disable the web interface. This can be done in a number of ways, some of which may not apply to your particular model.

*

*Switch to only allow admin via HTTPS.

*Restrict the ip addresses of the computers that are allowed to access the admin page.

*Disable admin page altogether.

For systems that do allow option 3 there must be another way of configuring the router. This could be via some special software program (which quite often is windows only) or by using telnet or by connecting the computer directly to a machine using a serial lead and using hyperterminal.
Of course you should always check that your browser isn't just blocking a popup that is asking for the username and password.

A:
Reset – There are two (2) ways to reset the Linksys E2000 to its
  factory defaults.  Either press and hold the Reset button for
  approximately five (5) seconds, or restore the defaults from the
  Administration > Factory Defaults screen in the Linksys E2000
  web-based setup page.
NOTE:  After resetting the router, your Internet and wireless
  configuration will be erased.  To know how to reinstall the router,
  click here.
QUICK TIP:  To log in to the router's web-based setup page, just leave
  the User name blank then enter the default Password "admin".

Cisco Knowledgebase: Getting to know your...


text:
Q: Picker Title show top position while click cancel in popup using xamarin forms We are using visual material picker control in our app. If I select anything from the picker popup title shows the top and selected value below. If I click cancel from the picker popup title also shows top. It should be in the default state. How to resolve this xamarin forms android and ios?
Screenshoot below:

Xaml Code:
<local:CustomPicker ItemsSource="{Binding CommentList, Mode=TwoWay}" SelectedItem="{Binding SelectedComment, Mode=TwoWay}" Grid.Row="0" TextColor="Black" ItemDisplayBinding="{Binding Text, Mode=TwoWay}"  SelectedIndex="{Binding CommentIndex, Mode=TwoWay}"
                                        Image="downarrow" Title="Picker" BackgroundColor="White" TitleColor="Gray">
                    </local:CustomPicker>

Renderer Code:
using Xamarin.Forms.Material.Android;

[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer), new[] { typeof(VisualMarker.MaterialVisual) })]
namespace MyApp.Android
{
    public class CustomPickerRenderer: MaterialPickerRenderer
    {
        //...
    }
}


text:
Q: NETSDK1152 Multiple output files error for _ViewImports.cshtml files when publishing ASP.NET Core 6 Recently I migrated my asp.net core 3.1 web app to NET6. Before migration, I didn't have this kind of problems. My web app has several projects (DLL) and some of them have Views and Controllers due to requirements. I marked those projects as Skd.Razor as shown below:
<Project Sdk="Microsoft.NET.Sdk.Razor">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
  </PropertyGroup>

I configured Startup to recognize those controllers and views by using application parts:

Each project has its own _ViewImports.cshtml including Main Project SicotX:

The problem comes out when I'm trying to publish the application, compilation is generating the following error

_ViewImports.cshtml is causing conflicts in the output path in both projects except the main SiotX project.
I need to use _ViewImports into those projects so I need your help or guide how to overcome this issue is blocking me, or maybe is it possible to use a unique _ViewImports.cshtml and share with all projects?
Thanks

A: In .NET SDK 6.0.100, the .NET SDK generates a new error (NETSDK1152) in cases where files from different source paths would be copied to the same file path in the publish output. This can happen when a project and its project references include a file with the same name that's included in the publish output.
Please visit Generate error for duplicate files in publish output to get detailed information.
I found some suggestions that could help you fix this issue.

*

*Add code below in *.csproj files to all of your projects.

<ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles>

*Exclude the problematic files from copying to the output folder.

Add the following lines to your common.props (located in the root directory of your solution):

<Content Remove="file_name"/>
<None Include="file_name">
  <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
  <CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>

References:

*

*Publish error: Found multiple publish output files with the same relative path

*NETSDK1152 Error for _ViewImports.cshtml files


text:
Q: GLSL performance issue in fragment shader on vec4 add I have a fairly simple fragment shader used to handle a situation with multiple lights  (code below trimmed down for clarity, only two lights shown).
The broad idea is to sum the various lighting contributions for each fragment, and it work fine, however I have found that it is unstably so on my hardware (Android HTX Desire X).
Measuring FPS, it becomes apparent that there is a single vec4 addition line which is causing the FPS to drop by 10.
What could be causing this performance hit on such an apparently simple operation?
void main (void)
{
    vec4 v = u_ViewModelMatrix * vec4(v_Vertex, 1.0);
    vec3 nv = normalize(-v.xyz);
    vec3 normalVector = normalize((u_ViewModelTransposeMatrix * vec4(normalize(v_Normal), 0.0)).xyz);

    vec4 finalColour = vec4(0.0, 0.0, 0.0, 1.0);

    // LIGHT 0
    lightPosition = vec4(u_LightData[2], u_LightData[3], u_LightData[4], 1);
    lightColour = vec4(u_LightData[5], u_LightData[6], u_LightData[7], 1.0) * u_LightData[0];

    lightVector = normalize((u_ViewMatrix * lightPosition).xyz - v.xyz);
    halfwayVector = normalize(lightVector + nv);

    facing = dot(normalVector, lightVector);
    if (facing >= 0.0) {
        finalColour = finalColour + diffuseColour * facing * lightColour;
    }

    // LIGHT 1
    lightPosition = vec4(u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+2],
                         u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+3],
                         u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+4],
                         1);
    lightColour = vec4(u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+5],
                       u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+6],
                       u_LightData[LIGHTS_FLOATS_PER_LIGHT*1+7],
                       1.0) * u_LightData[LIGHTS_FLOATS_PER_LIGHT*1];

    lightVector = normalize((u_ViewMatrix * lightPosition).xyz - v.xyz);
    halfwayVector = normalize(lightVector + nv);

    facing = dot(normalVector, lightVector);
    if (facing >= 0.01) {
        vec4 qwe = diffuseColour * facing * lightColour;
// HERE .............
        finalColour = finalColour + qwe;  // takes 10 fps
// HERE ^^^^^^^^^^^^^
    }

    gl_FragColor = finalColour;
}

A: Branching causes this. Avoid using ifs and for loops.
Replace
if (facing >= 0.0) {
    finalColour = finalColour + diffuseColour * facing * lightColour;
}

with
finalColour += max(0.0, facing) * diffuseColour * lightColour;

and
if (facing >= 0.01) {
    vec4 qwe = diffuseColour * facing * lightColour;
    // HERE .............
    finalColour = finalColour + qwe;  // takes 10 fps
    // HERE ^^^^^^^^^^^^^
}

with
finalColour += step(0.01, facing) * facing * diffuseColour * lightColour;

Don't worry if you will be calculating some values even when you don't need it. Since shaders are executed in parallel you can't get much faster than the slowest instance.
Also you should move as many things as possible to the vertex shader since it'll be executed just once for every vertex vs for every pixel in the fragment shader; basically you calculate everything that (tri)interpolates well in vertex shader and pass it as varyings:

*

*Position and color of the lights

*Vectors L, V and H (in this example at least)


text:
Q: JavaScript Closures: Add the numbers of an array by calling the inner function I have an array with random numbers. I want to add the sum of these numbers by using calling the inner function using the outer function. Basically, using closures.

let arr = [93, 95, 88, 0, 55, 91];

let addMany = function(arr){
    let addTwo = function (numbers) {
        console.log('array', arr)
        console.log('numbers', numbers)

        return numbers.reduce((acc,cur) => acc+cur,0)
    }
    return addTwo(arr);
}
let sum = new addMany(arr);
console.log('final sum', sum)

let res = sum.addTwo();

console.log(res);

I also think I am passing array 'arr' bit too many times. I could be wrong.
I have already tried it using IIFE and modular approach. That one worked fine. I am trying to achieve the same this way.

A: With return addTwo(arr) you are already returning the result directly. I assume you rather want to return addTwo itself, and use arr inside addTwo:
let addMany = function(arr){
  let addTwo = function () {
    console.log('array', arr)
    return arr.reduce((acc,cur) => acc+cur,0)
  };
  return addTwo;
}

The  you'd call it as:
 const closured = addMany(1, 2, 3);
 console.log(closured()); // call addTwo

In your example you are calling it as (new addMany(...)).addTwo() ... to achieve that behaviour, remove the return as constructors do not return anything, amd assign addTwo as a method to this (which is the returned object):
let addMany = function(arr){
  this.addTwo = function () {
    console.log('array', arr);

    return arr.reduce((acc,cur) => acc+cur,0)
  };
}

A: You could take a instanciable function and a prototype for adding the values.

function Numbers(array) {
    this.numbers = array;
}

Numbers.prototype.add = function () {
    return this.numbers.reduce((a, b) => a + b, 0);
};

var array = [93, 95, 88, 0, 55, 91],
    numbers = new Numbers(array),
    result = numbers.add();

console.log(result);

An other possibillity is to use a fluent interface, where you return an object with some functions, where you can chain the functions.

function take(array) {
    var object = {
            add: () => array.reduce((a, b) => a + b, 0),
            update: cb => take(array.map(cb)),
            valueOf: () => array
        };
    return object;
}

var array = [93, 95, 88, 0, 55, 91],
    numbers = take(array),
    result = numbers.add();

console.log(result);
console.log(numbers.valueOf());
console.log(numbers.update(x => 2 * x).valueOf());


text:
Q: Variables not updating in C Here is the full code. The printf shows that the max and min are changing but the random number doesnt reflect this. it still exceeds the boundries. Im new to C and have only used Java until now. I have a feeling pointers have something to do with this. Any help is appreciated. Thanks
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void){
  //initalised the max and min values for the random number
  int max = 100;
  int min = 1;
  int randomNumber;
  int endGame = 0; //set to 0 as game has not been won yet

  //asking your for their number which the program will guess
  char input[3];
  printf("Please enter a number between 1-100 and I will try to guess it: ");
  scanf(" %c \n", input);

  srand(time(NULL));

  while(endGame == 0){
    //generates random number and prints it. asks for users input
    randomNumber = (rand()%max)+min;

    printf("My guess is: %d \n", randomNumber);
    printf("Max: %d  \n", max);
    printf("Min: %d  \n", min);
    //printf("Press 'l' if your number is lower or 'h' if your number is higher$
    char c;
    scanf(" %c", &c);

    if(c == 'l'){
      max = randomNumber;
    }
    if(c == 'h'){
      min = randomNumber;
    }
    if(c == 'c'){
      endGame = 1;
    }
  }
}

A: scanf() takes a format specifier and a pointer to a character as an argument. You can do what you did, but i would declare char * c instead of char c and pass that directly to the call to scanf, like this:
char * c = malloc (sizeof (char));
scanf (" %c", c);

Then in your if statements you will need to dereference your pointer to compare the value of c to your relevant constants. The dereference operator, '*' is used to do this. For example:
if (*c == 'l') {
  min = randomNumber;
}


text:
Q: "A 10 hour course" - Why not "hours" I came across this example written by a native English teacher: "The student followed a 10 hour English course."
I was curious to know if "hours" would also be valid here, and if there's a nuance etc.
Thanks.


text:
Q: Laravel PWA not installable on apache I create a plain laravel 8 project to test pwa by following https://infyom.com/blog/how-to-make-a-laravel-application-pwahttps://infyom.com/blog/how-to-make-a-laravel-application-pwa.
It works as expected When I run it via cmd with php artisan serve [ http://localhost/127.0.0.1:8000 ], showing Install btn in the right side of the URL but when I try to run it on apache [ http://localhost/projectname ] (I am using Xampp), The installation btn doesn't show. When i check it using Chrome Light House, it shows the following Two error messages

Web app manifest or service worker do not meet the installability requirements 1 reason
Service worker is the technology that enables your app to use many Progressive Web App features, such as offline, add to homescreen, and push notifications. With proper service worker and manifest implementations, browsers can proactively prompt users to add your app to their homescreen, which can lead to higher engagement. Learn more.
Failure reasonNo matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest.
&
Does not register a service worker that controls page and start_url

Can someone please explain why this happens or how can I fix this issue?
Thank U in advance.
Since it work correctly when running it on php artisan serve, hoping to see it run on apache servers as well.

A: When you use apache it's configure your project as a vhost and without port. In order to use service workers  need SSL cert on you domain. Also if you want work locale in Chrome you can enable your localhost adding by  insecure origin as secure domains list, easiest way to test pwa, in my opnion, was using ngrok. I use ngrok my all project when need test pwa in dev env.
Usefull links:
SO answer
Ngrok download


text:
Q: How to solve could not find or load main class error with spring boot? I created a Maven project for Spring Boot. I have a lot of Spring dependencies and one main class:
package com.vastserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyArtifactApplication {

    public static void main(String[] args) {

//      SpringApplication.run(MyArtifactApplication.class, args);
        System.out.println("hello!");
    }

}

The folder structure of src directory is:
.
└── main
    ├── java
    │   └── com
    │       └── vastserver
    │           └── MyArtifactApplication.java
    └── resources
        └── application.properties

In my pom.xml I use maven-assembly-plugin in order to build my project in a standalone .jar file. Even though I triple checked that the directory structure and main class file appear correctly in the pom.xml I keep getting the error: Error: Could not find or load main class com.vastserver.MyArtifactApplication when I run mvn package and then java -cp target/vast-ad-server-artifactId-1.0-SNAPSHOT-jar-with-dependencies.jar com.vastserver.MyArtifactApplication or mvn exec:exec. The main class does work if I run it from Intellij so I know the code is not the problem but rather Maven build settings. I lost at where my problem could be.
My pom.xml looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <maven.compiler.release>11</maven.compiler.release>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <mainClass>com.vastserver.MyArtifactApplication</mainClass>
        <descriptorRef>jar-with-dependencies</descriptorRef>
        <targetSnapshot>target/vast-ad-server-artifactId-1.0-SNAPSHOT</targetSnapshot>
        <targetWithDependencies>${targetSnapshot}-${descriptorRef}.jar</targetWithDependencies>
    </properties>

    <groupId>com.vastserver</groupId>
    <artifactId>vast-ad-server-artifactId</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>${mainClass}</mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>${descriptorRef}</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <arguments>
                        <argument>-cp</argument>
                        <argument>${targetWithDependencies}</argument>
                        <argument>${mainClass}</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: For me: Maven - Update Project worked.

A: I realized that the spring-boot-maven-plugin actually does the building, so other plugins are not needed. If the plugins section in maven is edited to:
<plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
</plugins>

Then running mvn package and java -jar target/vast-ad-server-artifactId-1.0-SNAPSHOT.jar works.

A: I think you should check the directory structure of the artifact that was built by maven.
Usually, spring boot artifacts are prepared by a special spring boot plugin and not by a maven assembly plugin.
Although it shares the "jar" suffix, it's not really a jar, it has special classloader to load classes from BOOT-INF/lib folder.
I've already provided a detailed answer on what happens exactly when the spring boot application starts here but bottom line if you use assembly plugin you'll have to prepare both manifest file and a fairly complicated structure of folders. Frankly, I think you should use spring boot plugin as a first resort to build spring boot applications.

A: maven --> update project
it works for me

A: Adding to all the above answers
right click on project-> Maven ->update project-> force update
This will download all missing dependencies.
Still if it doesn't work ?? right click on pom.xml and run as configuration. Check you are using correct JRE. Then set goal as install and run it.
Important check java version in pom.xml if it doesn't match with your installed JRE version then also you might get this error. So make sure its same.
Still doesn't work??  Delete the project from workspace and import it back.

A: Rightclickonproject->Maven->UpdateProject->Tick the checkbox Force update of Snapshots/Releases-OK
give time to update the project. Then simply run the application Rightclickonproject->Runas->Spring Boot App

A: try updating project in maven. Sometimes while adding new dependency it wants maven to be updated there Dev tools won't work
---Right click project
---go to maven
---Update project

A: Your source file is missing from classpath. For me it happened when I restarted STS.

*

*Go to Run -->Run Configurations- classpath , in user entries add your project.

*Go to source tab of Run configurations and add workspace folder and select your src file where your main method class is there.
Click on apply and execute. It will work.

A: It may be caused by JRE path. Change JRE path and clean project, it will work.


text:
Q: How to execute code on post_migrate signal in Django? I'm doing some kind of refactoring for my project, where I'm relying on the django django.contrib.auth.models.Permission model. So far I define the permissions for each new user using a post_save signal, so when the user is created, I assign their permissions using user.user_permissions.add(the_permission), this works perfectly.
Now I want to use the django.contrib.auth.models.Group model to clasify the permissions a user should have.
This is my code:
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.contrib.auth.models import Group, Permission

def create_group(name, permissions):
    group = Group.objects.create(name=name)
    [group.permissions.add(permission) for permission in permissions]

def define_company_groups(sender, **kwargs):
    permissions = [
        Permission.objects.get(codename='add_mymodel'),
        Permission.objects.get(codename='change_mymodel'),
    ]
    create_group('managers', permissions)

class MyAppConfig(AppConfig):
    name = 'players'
    verbose_name = 'The players app'

    def ready(self):
        post_migrate.connect(define_company_groups, sender=self)

After define this code, I'm expecting that after call ./manage.py migrate this handler should be fired. But it doesn't happen, all I got is:
Running post-migrate handlers for application players
Adding permission 'players | mymodel | Can add mymodel'
Adding permission 'companies | company | Can change mymodel'
Adding permission 'companies | company | Can delete company'

I found this https://groups.google.com/forum/#!topic/django-developers/8MdaWtJp4VQ article, they say I should define my post_migrate handler inside a file named management.py, but it does not work for me.
Finally, here's my question: Where should I put this code for my custom post_migrate signal?

A: I have had done a post_migrate example for another question before. I will write down its solution. Maybe it will be helpful for you.
# in apps.py

...
from django.conf import settings
from django.db.models.signals import post_migrate

def create_default_site_profile(sender, **kwargs):
    """after migrations"""
    from django.contrib.sites.models import Site
    from core.models import SiteProfile

    site = Site.objects.get(id=getattr(settings, 'SITE_ID', 1))

    if not SiteProfile.objects.exists():
        SiteProfile.objects.create(site=site)

class CoreConfig(AppConfig):
    name = 'core'

    def ready(self):
        post_migrate.connect(create_default_site_profile, sender=self)

        # if you have other signals e.g. post_save, you can include it
        # like the one below.
        from .signals import (create_site_profile)

A: Signal post_migrate is different from other signals.
'./manage.py' command will not execute the code from the apps.py files or the signals.py files
To execute this signal, place it in the models.py file.
Then you will get the desired result

A: The Django docs recommend connecting the post_migrate signal in your app config's ready method. The Google groups post you link to is out of date, from before the docs were updated.
You also need to specify the app config in your INSTALLED_APPS setting.
INSTALLED_APPS = [
    'myapp.apps.MyAppConfig',
    # ...
]

Another way to configure your app is to use default_app_config in __init__.py of your app. See Configuring Applications. But the other way (dotted path to AppConfig) is preferred.


text:
Q: Getting value from CheckBox in asp.net mvc 5 I am trying to get a CheckBox value from the view, however, even if i check the CheckBox it still returnse me "false".
What am i doing wrong?
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,ReaderId,BookId")] BookingViewModel bookingViewModel)
        {
            Booking booking = new Booking();
            if (ModelState.IsValid)
            {
                var userId = User.Identity.GetUserId();
                int readerId = db.Readers.Where(c => c.ApplicationUserId == userId).First().ReaderId;

                booking.ReaderId = readerId;
                booking.BookId = bookingViewModel.BookId;

                db.Bookings.Add(booking);

                bool value = bookingViewModel.IfWantEmail;
                db.SaveChanges();

                return RedirectToAction("ShowUserBookings");
            }

            ViewBag.BookId = new SelectList(db.Books, "BookId", "Title", booking.BookId);

            return View(booking);
        }

And this is the code from my view:

                @Html.DisplayNameFor(model => model.IfWantEmail)

                @Html.CheckBoxFor(model => model.IfWantEmail)

A: You're intentionally excluding IfWantEmail from binding the POST data to the model.
[Bind(Include = "Id,ReaderId,BookId")]


text:
Q: Python: dashboard with multiple filters on the same Data Table I have Dashboard which uses data from Pandas df. It is one table on which I want to provide 2 filters. One for COUNTRY, second for STATE. Below is a code (only problematic part shown) which I am using:
app.layout = html.Div(children=[
    html.H4(children='STATISTICS FOR COUNTRY AND STATE'),
    dcc.Dropdown(id='dropdown_country', options=[
        {'label': i, 'value': i} for i in stats_df.COUNTRY.unique()
    ], multi=True, placeholder='Filter by COUNTRY...'),
    dcc.Dropdown(id='dropdown_state', options=[
        {'label': i, 'value': i} for i in stats_df.STATE.unique()
    ], multi=True, placeholder='Filter by STATE...'),
    html.Div(id='table-container')
])

@app.callback(
    dash.dependencies.Output('table-container', 'children'),
    [dash.dependencies.Input('dropdown_country', 'value'), dash.dependencies.Input('dropdown_state', 'value')])

def display_table(dropdown_country, dropdown_state):
    if dropdown_country is None and dropdown_state is None:
        return generate_table(stats_df)

    stats_dff = stats_df.loc[(stats_df.COUNTRY.str.contains('|'.join(dropdown_country))) | (stats_df.STATE.str.contains('|'.join(dropdown_state)))]
    return generate_table(stats_dff)

With below code my Dashboard displays correctly but when I chose value for first filter i.e. COUNTRY it crashes with error:

Callback error updating table-container.children TypeError: can only
  join an iterable

Can anyone help to point where is an error? Wit just one filter (COUNTRY or STATE) all works OK.

A: I figured it out. Function display_table needs to be changed to this:
def display_table(dropdown_country, dropdown_state):
    if dropdown_country is None and dropdown_state is None:
        return generate_table(stats_df)
    if dropdown_country is not None and dropdown_state is not None:
        stats_dff = stats_df.loc[(stats_df.COUNTRY.str.contains('|'.join(dropdown_country))) & (stats_df.STATE.str.contains('|'.join(dropdown_state)))]
        return generate_table(stats_dff)
    if dropdown_country is not None:
        stats_dff = stats_df.loc[stats_df.COUNTRY.str.contains('|'.join(dropdown_country))]
        return generate_table(stats_dff)
    if dropdown_state is not None:
        stats_dff = stats_df.loc[stats_df.STATE.str.contains('|'.join(dropdown_state))]
        return generate_table(stats_dff)


text:
Q: how apt-get compares between two different version schemes how dose apt-get compares between two different version schemes of the same package?
for example: 1.3.8 ? 1.09
More detailed example:
Lets say i got package_a in my repository with version 1.08 (package-a_1.08.deb).
Then i upload a new version of the same package but I've changed then version scheme,
 and its now 1.2.0 (package-a_1.2.0.deb)
When i'll run apt-get install package_a what version will be installed and why?

A: The algorithm used by Debian tools to compare package versions is described in the Debian Policy Manual:
https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version
In short: within the upstream version of the package version (which is what you're describing here), each numeric "segment" of the version number is compared separately, and the first pair that differs is used for the comparison.
Given your example of comparing 1.08 vs 1.2.0, the segments end up being 1, 8 and 1, 2, 0. Because 8 is greater than 2, 1.08 would be treated as the newer version.
If your versioning scheme changes dramatically, use an epoch number to indicate the break. For instance, if 1.2.0 is part of a new version numbering scheme, use 1:1.2.0 as the Version field, and include that 1: in all future versions.


text:
Q: SQL "IN" as LINQ query using method syntax I have a set of related tables that I am trying to return a result set for and I just can't get the syntax quite right to get the results I want.
I am trying to return a list of countries (United States being the only one expected right now) with appropriate states.   The "appropriate" requirement is that I only want to return the states under the countries that are represented by one of our clients....ie....if we have 3 clients, 2 in Texas and 1 in OK, I need the query to return "United States (with only Texas and OK...not the other 48 states where we don't have clients).
I can get the query to return only the United States, but it returns ALL states, not just the ones I am after.  This is an example of the query that I "want" to run....NOTE:  FirstAdminDivision table = states table.
select * from Country c
    inner join FirstAdminDivision f on f.CountryId = c.CountryId
where f.FirstAdminDivisionId IN
(
    select f2.FirstAdminDivisionId from Company C
        inner join [Address] a on a.AddressId = c.AddressId
        inner join City cty on cty.CityId = a.CityId
        inner join FirstAdminDivision f2 on f2.FirstAdminDivisionId = cty.FirstAdminDivisionId
)

This is the code I currently have (which is as close as I have been able to get) that returns the US only with all states.   The "ids" list contains only Texas and OK like I would expect, so I think they issue lies in the where in the main select.
IQueryable<int> innerQ = base.Context.Set<FirstAdminDivision>().Where(x => x.Cities.Any(y => y.Addresses.Any(z => z.Companies.Any()))).Select(x => x.FirstAdminDivisionId);
            List<int> ids = innerQ.ToList();

            IQueryable<ICountryModel> q2 = base.Context.Set<Country>()
                .Include(x => x.FirstAdminDivisions)
                .Where(x => x.FirstAdminDivisions.Where(y => innerQ.Contains(y.FirstAdminDivisionId)).Any())
                .Select(x => new CountryModel
                {
                    Abbreviation = x.Abbreviation,
                    CountryId = x.CountryId,
                    Name = x.Name,
                    UrlDisplay = x.UrlDisplay,
                    FirstAdminDivisions = x.FirstAdminDivisions.Select(y => new FirstAdminDivisionModel
                    {
                        Abbreviation = y.Abbreviation,
                        Name = y.Name,
                        UrlDisplay = y.UrlDisplay
                    }).ToList()
                });

Any help pointing out what I am missing/doing wrong would be greatly appreciated.

A: Well basically i would use your first query as the base query instead of all the countries and instead of returning a list of ints i would want it to return a list of FirstAdminDivision objects.
So in this case you would have two objects in that list OK and Texas. And in this case you also should have the country available since you say that FirstAdminDivision has the country as a property
Then from that list i would include country object so you can group those two state objects by country. And from that build your model using the key, country, and then the list of states.
Something like this:
    IQueryable<ICountryModel> countriesWithStates = base.Context.Set<FirstAdminDivision>()
        .Where(x => x.Cities.Any(y => y.Addresses.Any(z => z.Companies.Any())))
        .Include(x => x.Country)
        .GroupBy(x => x.Country, y=>y, (countryKey, states) => new { Country = countryKey, States = states.ToList() })
        .Select(x => new CountryModel
        {
            Abbreviation = x.Country.Abbreviation,
            CountryId = x.Country.CountryId,
            Name = x.Country.Name,
            UrlDisplay = x.Country.UrlDisplay,
            FirstAdminDivisions = x.States.Select(y => new FirstAdminDivisionModel
            {
                Abbreviation = y.Abbreviation,
                Name = y.Name,
                UrlDisplay = y.UrlDisplay
            }).ToList()
        });


text:
Q: Calendar class not working as expected in Java Below is my demo program:
public class Demo {
    public static void main(String[] args){
        Demo d = new Demo();
        Calendar c = Calendar.getInstance();
        System.out.println("Initial : "+c.getTime());
        d.addDay1(c);
        System.out.println("After addDay1 call : "+c.getTime());

    }

    public void addDay1(Calendar d){
        d.add(Calendar.DATE, 1);
    }

}

The output I am getting is the following :
Initial : Thu Mar 21 05:20:53 IST 2013
After addDay1 call : Fri Mar 22 05:20:53 IST 2013

But I am expecting the output as :
Initial : Thu Mar 21 05:20:53 IST 2013
After addDay1 call : Thu Mar 21 05:20:53 IST 2013

Why after my method call addDay1, the calendar object c has the added day in the main method?
In java, the parameters are passes by value in java, so why it is behaving indifferently?
Can anyone help me understand this?

A: You are passing the reference of Calendar hence adding day to it is reflected in the calling method.


text:
Q: How to compare API request JSON with existing json document in MongoDb? The title of the question is self explanatory. I want to know what differences are there in JSON Document A which comes from API request and JSON Document B which is already in Mongo DB.how to get changes column name and data also.. i am creating log..that's why i want...
Below is the code of what I'm trying:
NodeJS APICode//
 function Updatejob(req, res) {
      return function (jobSchedule) {
        var obj = new Date();

        CompareJSON(req, mongodbjson);
        return Job.create(req.body).then(.....)
        }

Already Data in Mongodb before Update Record
{
    "_id" : ObjectId("586d1032aef194155028e9c7"),
  "history" : [
        {
            "_id" : ObjectId("586d1032aef194155028e9c4"),
            "updated_by" : "",
            "details" : "Job Created",
            "changetype" : "Created",
            "datetime" : ISODate("2017-01-04T15:09:38.465Z")
        }
    ],
 "current_status" : "Pending",
    "time" : 0
}

//REQUEST FOR UPDATE DATA
  {
        "_id" : ObjectId("586d1032aef194155028e9c7"),
      "history" : [
            {
                "_id" : ObjectId("586d1032aef194155028e9c4"),
                "updated_by" : "",
                "details" : "Job Completed",
                "changetype" : "Completed",
                "datetime" : ISODate("2017-01-04T15:09:38.465Z")
            }
        ],
     "current_status" : "Completed",
        "time" : 0
    }

A: You can use jsondiffpatch:
 var delta = jsondiffpatch.diff(object1, object2);

See:

*

*https://www.npmjs.com/package/jsondiffpatch


text:
Q: AttributeError: module 'pandas' has no attribute 'ewma' mte_exp_wighted_avg = pd.ewma(mte, halflife=12)
plt.plot(mte)
plt.plot(mte_exp_wighted_avg, color='red')
plt.xticks(fontsize = 25)
plt.yticks(fontsize = 25)
plt.xlabel('Years', fontsize = 25)
plt.ylabel('CO2 Emission', fontsize = 25)
plt.title('CO2 emission by coal power generation', fontsize = 25)
plt.show()

code is shown above, pandas are upgraded
error is shown below

A: Pandas' Exponential Moving Average function (ewma) has been renamed to ewm as of Pandas 0.19. It's just a matter of changing some names:
mte_exp_wighted_avg = pd.ewm(mte, halflife=12)
plt.plot(mte)
plt.plot(mte_exp_wighted_avg, color='red')
plt.xticks(fontsize = 25)
plt.yticks(fontsize = 25)
plt.xlabel('Years', fontsize = 25)
plt.ylabel('CO2 Emission', fontsize = 25)
plt.title('CO2 emission by coal power generation', fontsize = 25)
plt.show()

A: pd.ewma(mte, halflife=12) will not work anymore.
ewma has been changed to  ewm
mte_exp_wighted_avg = mte.ewm(halflife=12,min_periods=0,adjust=True,ignore_na=False).mean()


text:
Q: Relationship Many-To-One how to save I've searched on google and mostly of examples didn't helped or I'm doing wrong what I want. So I quite don't understand how GORM saves in this type of relationship, how I can save new event that is related on the user? the addToEvent doesn't work.
class User{
Long id
String name
Long codeUser
StatusType statusType
static hasMany = [event: Event]
static constraints = {
    statusType(nullable: true)
    name(nullable: true)
}
class Event{
Long id
String name
String startDate
String description
static belongsTo = [user:User]
static constraints = {
    name(nullable: true)
    startDate(nullable: true)
    description(nullable: true)
}

def createEvent(){
    def data = JSON.parse(params.data)
    def user = User.findByCodeUser(data.codeUser)
    def event = new Event(name: data.name, startDate: data.start_time, description: data.description)
    //removed the user: user
    user.addToEvent(event)
    user.save(flush: true)
}

The error is this: Message: No signature of method: java.util.ArrayList.addToEvent() is applicable for argument types: (project.web.Event) values: [project.web.Event : (unsaved)]

A: As outlined in the Grails documentation you need to use the addTo* method to save the relationship correctly through GORM.
class User{
    ...//attributes
    Long codeUser
    static hasMany = [event: Event]
}
class Event{
    ...//attributes
    Long codeEvent
    static belongsTo = [user:User]
}

def user = User.findByCodeUser(params.codeUser)

def event = new Event(codeEvent: params.codeEvent)
user.addToEvent(event)
user.save(flush: true)

Notice that you don't have to set the User property of the Event and saving the User will also save the Event.
Finally, as a style guide you typically want to name your collections in the plural form.
static hasMany = [events: Event]


text:
Q: How to store existing string secretly in ios swift app I am working on ios application,which contains some files which are AES-128 encrypted,so for decrypting these files, I am using some third party libraries like cryptoswift,right now in swift code only i am writing my own logic to decrypt data using keys,but i want to store these keys securely,for android i had written my logic in native library,here what is the best way to secure my secret key

A: You should use the iOS Keychain Services to store the keys securly.
There are several libraries implemented in Swift which provide easy access to the key chain. See here: https://github.com/vsouza/awesome-ios#keychain

A: For storing sensitive information you should use the Keychain always.You can use the following sample code posted by apple to know in detail Generic Keychain.Happy Coding!!!

A: EDIT: See the discussion under it. Wise conclusion: Perhaps the best answer is "don't bother, put the key in the code", there is a large work factor to obtain the key.
If you store a secret token within the app there's a risk it would be easily recoverable as simple string. You can read more about it at Reverse Engineering iOS Apps.
You can't prevent it totally, but you can obscure password data by splitting password into smaller chunks, keep them apart in the code, and use some dumb-decryption algorithm to retrieve final form, like this:
func crypt(string: String) -> [UInt32] {
    return string.unicodeScalars.enumerated().map { index, char in
        return char.value + UInt32(index)
    }
}

func decrypt(chars: [UInt32]) -> String {
    return chars.enumerated().map { (index, char) -> String in
        let s = UnicodeScalar(char - UInt32(index))!
        return "\(Character(s))"
    }.joined()
}

let clearPassword = "Acb,321"
let cryptedChars = crypt(string: clearPassword)
let decrypted = decrypt(chars: cryptedChars)

let c1: UInt32 = 65
let c2: UInt32 = 100
let c3: UInt32 = 100
let c4: UInt32 = 47
let c5: UInt32 = 55
let c6: UInt32 = 55
let c7: UInt32 = 55

let decryptedScattered = decrypt(chars: [c1, c2, c3, c4, c5, c6, c7])

Not perfect, but should be enough for simple attacks, and more advanced ones would be probably too expensive to proceed.


text:
Q: GCM notification not working (GoogleCloudMessaging) I have a strange problem with GCM using GoogleCloudMessaging, where the notifications work at the beginning but somehow stop working after some time (roughly an hour or so).
Another thing, whenever I register with GoogleCloudMessaging.getInstance(context).register(SENDER_ID); i get the call in the onReceive() of my 'WakefulBroadcastReceiver' which contains REGISTRATION_ID in bundle extras. Is this a common thing and should I just ignore this?
I have followed the tutorial from here Implementing GCM client.
EDIT: The problem was with a library called Localytics, which was also handling Push notifications. Nothing related to GCM setup.

A: Every GCM message has expired date, the message might have expired, or the device is not connected, and messages are not real time.
GCM uses broadcast receiver to deliver messages in following steps:
1. onClick() calls gcm.send()
2. onReceive() method in broadcast receiver triggered
3. the method handles GCM messages
A WakefulBroadcastReceiver is a special type of broadcast receiver that takes care of creating and managing a partial wake lock for your app. It passes off the work of processing the GCM message to a Service (typically an IntentService), while ensuring that the device does not go back to sleep in the transition. If you don't hold a wake lock while transitioning the work to a service, you are effectively allowing the device to go back to sleep before the work completes. The net result is that the app might not finish processing the GCM message until some arbitrary point in the future, which is not what you want.
However, using WakefulBroadcastReceiver is not a requirement. If your app does not require a service, you can use a regular BroadcastReceiver.
According to the GCM documentation, after registering, the app calls storeRegistrationId() to store the registration ID in shared preferences for future use. This is just one way of persisting a regID. So the registration_id is good for data persistence.

A: EDIT: The problem was with a library called Localytics, which was also handling Push notifications. Nothing related to GCM setup.


text:
Q: Finding commonly occurring words across multiple lists I have 5 lists of words. I need to find all words occurring in more than 2 lists. Any word can occur multiple times in a list.
I have used collections.Counter but it only returns the frequencies of all the words in individual lists.
a = ['wood', 'tree', 'bark', 'log']

b = ['branch', 'mill', 'boat', 'boat', 'house']

c = ['log', 'tree', 'water', 'boat']

d = ['water', 'log', 'branch', 'water']

e = ['branch', 'rock', 'log']

For example, the output from these lists should be ['log':4, 'branch':3] as 'log' is present in 4 lists and 'branch' in 3.

A: Without Counter:
a = ['wood', 'tree', 'bark', 'log']
b = ['branch', 'mill', 'boat', 'boat', 'house']
c = ['log', 'tree', 'water', 'boat']
d = ['water', 'log', 'branch', 'water']
e = ['branch', 'rock', 'log']

all_lists = [a, b, c, d, e]
all_words = set().union(w for l in all_lists for w in l)

out = {}
for word in all_words:
    s = sum(word in l for l in all_lists)
    if s > 2:
        out[word] = s

print(out)

Prints:
{'branch': 3, 'log': 4}

Edit (to print the names of lists):
a = ['wood', 'tree', 'bark', 'log']
b = ['branch', 'mill', 'boat', 'boat', 'house']
c = ['log', 'tree', 'water', 'boat']
d = ['water', 'log', 'branch', 'water']
e = ['branch', 'rock', 'log']

all_lists = {'a':a, 'b':b, 'c':c, 'd':d, 'e':e}
all_words = set().union(w for l in all_lists.values() for w in l)

out = {}
for word in all_words:
    s = sum(word in l for l in all_lists.values())
    if s > 2:
        out[word] = s

for k, v in out.items():
    print('Word : {}'.format(k))
    print('Count: {}'.format(v))
    print('Lists: {}'.format(', '.join(kk for kk, vv in all_lists.items() if k in vv )))
    print()

Prints:
Word : log
Count: 4
Lists: a, c, d, e

Word : branch
Count: 3
Lists: b, d, e

A: you can sum the counters - starting with an empty Counter():
from collections import Counter

lists = [a, b, c, d, e]
total = sum((Counter(set(lst)) for lst in lists), Counter())
# Counter({'log': 4, 'branch': 3, 'tree': 2, 'boat': 2, 'water': 2,
#          'wood': 1, 'bark': 1, 'house': 1, 'mill': 1, 'rock': 1})
res = {word: occ for word, occ in total.items() if occ > 2}
# {'log': 4, 'branch': 3}

note that i convert all the lists to a set first in order to avoid double-counts for the words that are more than once in the same list.

if you need to know what list the words were from you could try this:
lists = {"a": a, "b": b, "c": c, "d": d, "e": e}

total = sum((Counter(set(lst)) for lst in lists.values()), Counter())
# Counter({'log': 4, 'branch': 3, 'tree': 2, 'boat': 2, 'water': 2,
#          'wood': 1, 'bark': 1, 'house': 1, 'mill': 1, 'rock': 1})
res = {word: occ for word, occ in total.items() if occ > 2}
# {'log': 4, 'branch': 3}

word_appears_in = {
    word: [key for key, value in lists.items() if word in value] for word in res
}
# {'log': ['a', 'c', 'd', 'e'], 'branch': ['b', 'd', 'e']}


text:
Q: Bunch of Records displaying in Custom View android but Very Time Consuming I am developing Android Application which is Syncing data from Server.
Server has thousands of records that i have stored in SQLite Database.
But now i am displaying records in custom TableView Successfully, but its very time consuming and i got black screen for 10 to 20 seconds.
My code is:
/**** FILL ALL DATA OF PRODUCT WHICH IS AVAILABLE IN THIS COMPANY ****/
        dbHelper.open();

        productCursor = dbHelper.getProduct(companyid, isDistributor);

        if(productCursor.getCount() > 0)
        {
            productTable.setVisibility(View.VISIBLE);
            (view.findViewById(R.id.productIfNoAvailable)).setVisibility(View.GONE);

            TableRow row= null;

            com.salesman.library.ImageLoader mImageLoader = new com.salesman.library.ImageLoader(context);
            ImageView prodImage;
            TextView prodName;
            EditText prodRate = null;
            EditText prodQty = null;
            EditText prodDisc = null;

            /** For every time add new row in Table Layout **/
            productTable.removeAllViews();

            rowid = 0;
            int catid = 0;

            while (productCursor.moveToNext()) {
                final View childView = inflater.inflate(R.layout.list_product_view, null);

                row = new TableRow(context);
                catid = productCursor.getInt(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_CATEGORY_ID));

                int concatid = Integer.parseInt(catid+""+rowid++);

                row.setId(concatid);

                row.setLayoutParams(new LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));

                double productRateValue;
                double productDiscountValue;

                productRateValue = productCursor.getDouble(productCursor.getColumnIndex("rate"));
                productDiscountValue = productCursor.getDouble(productCursor.getColumnIndex("discount"));

                /*** Image ***/
                prodImage = (ImageView) childView.findViewById(R.id.productImage);
                String path = productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_IMAGES));
                mImageLoader.DisplayImage(path, prodImage);

                prodName = (TextView) childView.findViewById(R.id.productName);
                prodName.setText(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME)));

                prodQty = (EditText) childView.findViewById(R.id.productQuantityValue);
                prodQty.setText("");

                prodRate = (EditText) childView.findViewById(R.id.productRateValue);
                prodRate.setText(String.valueOf(productRateValue));

                prodDisc = (EditText) childView.findViewById(R.id.productDiscountValue);
                prodDisc.setText(String.valueOf(productDiscountValue));

                prodRate.setFocusable(isRateEditable);
                prodRate.setEnabled(isRateEditable);

                prodDisc.setFocusable(isDiscountEditable);
                prodDisc.setEnabled(isDiscountEditable);

                row.addView(childView);
                productTable.addView(row);

                if(productSharedPref.getBoolean("saved", false))
                {
                    View rowView = productTable.findViewById(concatid);
                    String prodRatePrefValue    = productSharedPref.getString("rate"+concatid, "");
                    String prodQtyPrefValue     = productSharedPref.getString("qty"+concatid, "");
                    String prodDiscPrefValue    = productSharedPref.getString("discount"+concatid, "");

                    if(!prodQtyPrefValue.equals("") || prodQtyPrefValue != null)
                        ((EditText)rowView.findViewById(R.id.productQuantityValue)).setText(prodQtyPrefValue);

                    if(!prodRatePrefValue.equals(""))
                        ((EditText)rowView.findViewById(R.id.productRateValue)).setText(prodRatePrefValue);

                    if(!prodDiscPrefValue.equals(""))
                        ((EditText)rowView.findViewById(R.id.productDiscountValue)).setText(prodDiscPrefValue);
                }
            }

How to reduce this time.
Please Help.

A: You can use async task.....what it does is loads a few items and displays the screen...and then it will keep updating the list with the new items,when they are processed


text:
Q: Changing product name on checkout and order on WooCommerce with WPML I am using WooCommerce with WPML plugin. I want to implement a feature on checkout when a customer under certain conditions can have an upgrade of his product but keeping the old product price.
The products are variable with many variable attributes.
So, more specifically, what I want is if a customer has selected a specific product variation with x price on checkout (under a certain condition) I could change his cart item with another product's variation but keep the x price.
What I tried first is to change only the name of the product using woocommerce_order_item_name hook but the change doesn't follow on the order. This is important because some order data are then sent to an API.
Afterwards I used "Changing WooCommerce cart item names" answer code, which worked perfectly for my purpose until I installed WPML. For some reason the WC_Cart method set_name() doesn't work with WPML. I opened a support thread but they still can't find a solution.
Can anyone suggest any other solution?
Update
I have tried an approach where I remove the product item on cart and then I add the one I need. After I use set_price() to change the price of the newly added item. The removal/addition seems to be working but the price is not changed on one language and it is not applied on both languages after placing order.
This is the code I use:
function berrytaxiplon_change_product_name( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {

                $new_product = wc_get_product( 82 );
                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

                foreach ( WC()->cart->get_cart() as $new_item ) {

                    $new_item['data']->set_price( $cart_item['s-fare'] );
                }
            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {

                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( $cart_item['s-fare']);
                }

            }
        }

    }

}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

Any idea why the set_price() method is not applied?
Update 2
WPMl uses 'woocommerce_before_calculate_totals' and overrides the action added on functions.php
WPML support provided a solution using 3 filters:
https://wpml.org/forums/topic/cant-use-set_name-method-for-the-product-object-on-checkout/#post-3977153

A: So this is a code that I am using in one of my projects to add a product variation to cart based off of some filters and the selected product:
$product = new WC_Product($product_id); //The main product whose variation has to be added
$product_name = $product->get_name(); //Name of the main product
$quantity = sanitize_text_field($cData['quantity']); //You can set this to 1
$variation_id = sanitize_text_field($cData['variation_id']); //I had the variation ID from filters
$variation = array(
    'pa_duration' => sanitize_text_field($cData['duration']) //The variation slug was also available for me.
);
$cart_item_data = array('custom_price' => sanitize_text_field($custom_price));
$cart = WC()->cart->add_to_cart( (int)$product_id, (int)$quantity, (int)$variation_id, $variation, $cart_item_data ); //This will add products to cart but with the actual price of the variation being added and meta data holding the custom price.
WC()->cart->calculate_totals();
WC()->cart->set_session();
WC()->cart->maybe_set_cart_cookies();

Then you need to do a check on before cart totals are calculated and set the price to custom price like this:
function woocommerce_custom_price_to_cart_item( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["custom_price"] ) ) {
                $value['data']->set_price($value["custom_price"]);
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 99 );

A: The code provided from Faham is very helpful but the page-template that leads to checkout is already over-complicated so I focused to use his logic on the 'woocommerce_before_calculate_totals' hook I am trying all along.
So instead of trying to change the name I remove the item and add the new one. Then calling a new loop I set the price to be of the item that was removed.
function berrytaxiplon_change_product_name( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {
            // SET THE NEW NAME
            $new_product = wc_get_product( 82 );

            $atrributes = $product->get_attributes('view');
            foreach ($atrributes as $atrribute_key => $atrribute_value) {
                $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
            }
            $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
            $cart->remove_cart_item( $cart_item_key );
            $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

            foreach ( WC()->cart->get_cart() as $new_item ) {
                $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
            }

            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {
                // SET THE NEW NAME
                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
                }

               }
        }

    }
}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

I use the function below to match the attributes taken from the question WooCommerce: Get Product Variation ID from Matching Attributes
function find_matching_product_variation_id($product_id, $attributes)
{
    return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new \WC_Product($product_id),
        $attributes
    );
}

I am a little skeptical using add_to_cart() and a second foreach() inside the $cart_item. But I tested and it seems to work without errors.
Update
Actually there is an issue with this code (or with WPML again). It seems that set_price() is not applied on the secondary language. Yet if I reload the checkout page an send the data again the new price is applied.


text:
Q: Hello World on Visual Studio 2010 with Intel ArBB? I'm trying to get started working with Intel's Array Building Blocks, and there seems to only be one tutorial on "Hello World", at http://www.hpc.lsu.edu/training/tutorials/sc10/tutorials/SC10Tutorials/docs/M07/M07.pdf . And I'm not really getting it.
I'm using Visual Studio 2010 and this is the code I got from the above link, kinda.
#include <C:/Program Files/intel/arbb/Beta6/include/arbb.hpp>
//What do I have to do to make just "#include <arbb.hpp>" work?

using namespace arbb;

void my_function(f32& result, f32 input){
    std::cout << "Hello, world!" << std::endl;
    result = input + 1.0f; //"Error: no operator "+" matches these operands
}

int main(){
    typedef closure<void (f32&, f32)> mfc;
    mfc a = capture(my_function);
    mfc b = call(my_function);
    mfc c = call(my_function);
}

What else do I need to do to get "Hello World" working?

A: There are many samples available in arbb installation path. You can use the visual studio solution files to start with any of the sample. That is the easiest way.
In order to compile and run your own application from scratch, you have to have the include and dependencies set.
On Linux, you can add the path ~/(whatever)/intel/arbb/Beta6/include in the compile option using -I
On Windows, you can do:
set INCLUDE=C:/Program Files/intel/arbb/Beta6/include/arbb.hpp;
Or have a batch script that will ensure all the environment variables are set by default.
--- contents of the batch file ---
SET ARBB_OPT_LEVEL=O3
SET PATH=%ARBB_ROOT%\bin\ia32;%ARBB_ROOT%\bin\ia32\vs%MSVS_VERSION%;%OPENCV_ROOT%\bin;%FFTW_ROOT%;%FREEGLUT_ROOT%;%PTHREADS_ROOT%\lib;%PATH%
---- here is hello world program in arbb ---
#include <arbb.hpp>

void arbb_hello_map(arbb::i32& val)
{
  val = val * 2;
}
void arbb_hello(arbb::dense<arbb::i32>& data)
{
  using namespace arbb;
  map(arbb_hello_map)(data);
}

int main()
{
  using namespace arbb;
  int size = 5;
  dense<i32> data = dense<i32>(size);
  range<i32> write_data = data.write_only_range();
  for (int i = 0; i < size; ++i)
    write_data[i] = i;

  arbb::call(arbb_hello)(data);
  std::cout << "hello: " << std::endl;
  const_range<i32> read_data = data.read_only_range();
  for (int i = 0; i < size; ++i)
    std::cout <<"data["<<i<<"] = " << read_data[i] <<"\n";
  return 0;
}

And compile it using
g++ -m64  -I/home/YOUR_NAME/arbb/install//include -Wall -Werror -O3 -W -Wshadow temp.cpp -o temp -L/home/YOUR_NAME/arbb/install/lib/intel64 -larbb_dev -ltbb -littnotify

Run it using
./temp


text:
Q: Como fazer um count no Mysql usando o case ou if? Estou precisando saber como posso fazer uma pesquisa no mysql para saber quantos documentos tenho para analizar com uma condição que se o processo anterior nao estiver liberado ele nao pode contar.
SELECT COUNT(`num`),
        CASE  WHEN (`pl_de_manutencao` = 'Liberado' || `pl_de_manutencao` = 'N/A'
            AND `ra_padrao` != 'Liberado' || `ra_padrao` != 'N/A')
        THEN COUNT(`num`) END AS `Count`
FROM `ind_master_view`

algo parecido com esse código.

A: Se é o que estou entendendo, você tem que usar o COUNT() antes do case com incremento de 1 caso a condição seja verdadeira .
SELECT COUNT(CASE  WHEN (pl_de_manutencao = 'Liberado' || pl_de_manutencao = 'N/A'
                        AND ra_padrao != 'Liberado' || ra_padrao != 'N/A')
                    THEN 1  -- caso a condição seja verdadeira .
            END) AS Total
FROM ind_master_view