text:
Q: Performance Impacts of Cordova/PhoneGap? Recently, I have got to know about Apache Cordova and PhoneGap and how beautifully then can package native Android and Ios Apps from HTML5 Apps.
However, I am trying to understand, How does this impact performance, security or any other concerns. I am sure, that using Cordova and PhoneGap, won't provide the security and performance of Native Apps, as they may be using Callback hooks to the OS over packaged apps ?
Am I correct, if yes, then how exactly Cordova/Phonegap bridges the gap ?

A: Cordova puts the entire HTML5 app in a webview, so performance depends mainly on the underlying javascript and CSS performance. There are clever tricks (e.g. using -webkit-translate and -webkit animations) to improve performance but definitely not everything can run as smooth as in a native app. Depending on the type of application this may or may not be an issue. A big role lies with the javascript/css library you use for generating the UI (or your own JS coding skills if you don't use any). There are no standard UI components you can use besides what HTML/CSS offers (<a>, <img>, css: border-radius etcetera). What is of course nice is that the webviews run on WebKit so you can use the latest & greatest CSS3 features.
As for security: imho there are no major impacts on security, everything is still packaged inside a native app which can be unzipped just the same as a native app. Only thing is that your JS code is visible instead of the native compiled code, but hey: security by obscurity was never a good security measure anyways.


text:
Q: Highlight date in Chart.js line graph I would like to add a marker to highlight a particular date using Chart.js, which I can currently do using a particular index number. In the code below I can highlight the points at 2020-11-17 but only by using the index of 300, rather than referring to the specific date.
Using the customRadius function I can interact with the chart data but unfortunately date information seems to have been stripped at this stage. Nevertheless the Chart itself keeps a record of the dates through use of labels (specifically the X-axis)
How do I corelate index number to the label value?
console.log(context.data.labels);

Returns an error

const but = document.getElementById('myButton');

function customRadius(context)
  {
    let index = context.dataIndex;
    let value = context.dataset.data[ index ];
    return index === 300 || value >= 1000000 ?
           10 :
           2;
  }

but.addEventListener('click',function() {
    let dates = [];
    let confirmed = [];
    let recovered = [];
    let deaths = [];

    fetch("https://pomber.github.io/covid19/timeseries.json")
    .then(response => response.json())
    .then(data=> {
        data["South Africa"].forEach(o => {
        dates.push(o.date);
        confirmed.push(o.confirmed);
        recovered.push(o.recovered);
        deaths.push(o.deaths);
        })
        new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
            labels: dates,
            datasets: [{
                label: 'Confirmed',
                borderColor: 'orange',
                backgroundColor: 'orange',
                fill: 'false',
                data: confirmed
            },
            {
                label: 'Recovered',
                borderColor: 'green',
                backgroundColor: 'green',
                fill: 'false',
                data: recovered
            },
            {
                label: 'Deaths',
                borderColor: 'red',
                backgroundColor: 'red',
                fill: 'false',
                data: deaths
            }
            ]
        },
        options: {
            responsive: true,
                animation: {
                duration:0
                },
            elements: {
                point: {
                    radius : customRadius,
                    display: true
                }
            },
            title: {
            display: true,
            text: 'Covid-19 / South Africa'
            }
        }
        });
    });

});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>
<body>
<button type="button" id="myButton">Click me</button>

<canvas id="myChart" height="100"></canvas>
</body>
</html>

A: You can access the chart instance itself on which the labels live, changing your function to this will let you access the dates:
function customRadius(context) {
  let index = context.dataIndex;
  let value = context.dataset.data[index];
  const label = context.chart.data.labels[index]
  console.log(label)
  return index === 300 || value >= 1000000 ?
    10 :
    2;
}

Live sample:

const but = document.getElementById('myButton');

function customRadius(context) {
  let index = context.dataIndex;
  let value = context.dataset.data[index];
  const label = context.chart.data.labels[index]
  // console.log(label)
  return label === '2020-11-17' ?
    10 :
    2;
}

but.addEventListener('click', function() {
  let dates = [];
  let confirmed = [];
  let recovered = [];
  let deaths = [];

  fetch("https://pomber.github.io/covid19/timeseries.json")
    .then(response => response.json())
    .then(data => {
      data["South Africa"].forEach(o => {
        dates.push(o.date);
        confirmed.push(o.confirmed);
        recovered.push(o.recovered);
        deaths.push(o.deaths);
      })
      new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
              label: 'Confirmed',
              borderColor: 'orange',
              backgroundColor: 'orange',
              fill: 'false',
              data: confirmed
            },
            {
              label: 'Recovered',
              borderColor: 'green',
              backgroundColor: 'green',
              fill: 'false',
              data: recovered
            },
            {
              label: 'Deaths',
              borderColor: 'red',
              backgroundColor: 'red',
              fill: 'false',
              data: deaths
            }
          ]
        },
        options: {
          responsive: true,
          animation: {
            duration: 0
          },
          elements: {
            point: {
              radius: customRadius,
              display: true
            }
          },
          title: {
            display: true,
            text: 'Covid-19 / South Africa'
          }
        }
      });
    });

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>

<body>
  <button type="button" id="myButton">Click me</button>

  <canvas id="myChart" height="100"></canvas>
</body>

</html>

redpajama_set_name: RedPajamaStackExchange


text:
Q: spa.UseAngularCliServer(npmScript: "start"); I created a .NET core project with an Angular template and deployed it to my local IIS, and it's working fine.
I want to know the back-end process of
spa.UseAngularCliServer(npmScript: "start")

after I deployed to IIS, the angular project the (html/js/css) files are bundled . how angular server started?

A: When you publish your solution into production mode angular will run ng build --prod command to generate production code and output everything into dist folder.
Then when we deploy to server like Azure the server will boost your index.html inside your dist folder to run your angular app.
Let me know if you still not clear


text:
Q: Is this impossible to install XP using BootCamp on Lion? I want to install XP with bootcamp on my Mac running Lion. The only choice that it gives me is to install Win7. Is there a way to install XP on Lion ?

A: *

*In Bootcamp: You can bypass it by putting in a Windows7 disk and format the drive for the Windows installation.

*After that you just restart, press alt to bring up the boot menu and put in your Windows XP CD to install.
One way that should work aswell(havent tested) is if you just create a new empty FAT-partition and then go to step 2.


text:
Q: Print the json data passed from node JS to EJS in string format rather than JSON sytax This is my document schema:
{
    "_id" : ObjectId("59b96cf0137127b27c5cd7fb"),
    "theatreid" : 10,
    "name" : "inox raghuleela ",
    "location" : "vashi",
    "address" : "sec 2,vashi, Mumbai, Maharashtra 410234",
    "shows" : [
            {
                    "mname" : "shubh mangal savdhan",
                    "timings" : [
                            6,
                            7,
                            9,
                            11,
                            15,
                            18
                    ]
            },
            {
                    "mname" : "Toilet:ek prem katha",
                    "timings" : [
                            11,
                            12,
                            13,
                            14,
                            15
                    ]
            }
    ]
}

I am using nodejs ,and passing the values of the retrieved query(displaying the timing array where value is greater than 10) to EJS. This works fine!
The output  is as follows:EJS output in browser
My index.ejs is as follows:

    <% include ../partials/header %>

This is great

Welcome to templating using EJS

Loop

     <% result.forEach(function(r) { %>

<%= r.name %> <%- JSON.stringify(r.shows)%>

       <% }); %>

But, i dont want to display the output in JSON format,I want the timings to displayed in normal string formatted way.
     What needs to be done.
 Please help ?

A: JSON.stringify() used to convert a JavaScript object into a string, thus on your webpage you have output like: [{"timings": [21]}, {"timings": [20, 21]}].
You need to use Array.prototype.toString() instead of JSON.stringify():
<% result.forEach(function(r) { %>

<%= r.name %>

        <% r.shows.forEach(function(s) { %>

<%= s.mname %> - <%= s.timings.toString() %>

        <% }) %>

<% }) %>

or Array.prototype.join():
...
<% r.shows.forEach(function(s) { %>

<%= s.mname %> - <%= s.timings.join(', ') %>

<% }) %>
...

If you need only output values greater than 10 you can use filter:
<% result.forEach(function(r) { %>

<%= r.name %>

        <% r.shows.forEach(function(s) { %>

<%= s.mname %> - <%= s.timings.filter(function(item) { return item >= 10 }).join(', ') %>

        <% }) %>

<% }) %>

A: Just call .toString() on your object:
var j = {"a":["b","c"]}

j.a.toString() //-> "b,c"


text:
Q: Не приходят данные о покупках в GA-4 ecomerce При подключении ecomerce через google tag manadger стоимость конверсии фиксируется в аналитике, а в совершенных покупках стоимости нет
'''
{
event: "purchase",
gtm: {uniqueEventId: 133, start: 1676870640445},
eventModel: {
transaction_id: "698",
affiliation: "Ветер Времени",
value: 29,
currency: "BYN",
shipping: 0,
items: [
{
id: "VQ92J006Y",
name: "VQ92J006Y",
category: "ЖЕНСКИЕ ЧАСЫ/ВСЕ БРЕНДЫ/Наручные часы/Q&Q",
variant: "",
quantity: 1,
price: 0.000029
}
]
}
}
''''


text:
Q: How do I condense a pandas data frame where the rows are the months and I'm trying to condense them into years? So I have a dataframe
https://docs.google.com/spreadsheets/d/19ssG8bvkZKVDR6V5yU9fZVRJbJNfTTEYmWqLwmDwBa0/edit#gid=0
This is the out put that my code gives.
Here is the code:
from yahoofinancials import YahooFinancials
import pandas as pd
import datetime as datetime

df = pd.read_excel('C:/Users/User/Downloads/Div Tickers.xlsx', sheet_name='Sheet1')

tickers_list = df['Ticker'].tolist()
data = pd.DataFrame(columns=tickers_list)

yahoo_financials_ecommerce = YahooFinancials(data)

ecommerce_income_statement_data = yahoo_financials_ecommerce.get_financial_stmts('annual', 'income')

data = ecommerce_income_statement_data['incomeStatementHistory']

df_dict = dict()

for ticker in tickers_list:

    df_dict[ticker] = pd.concat([pd.DataFrame(data[ticker][x]) for x in range(len(data[ticker]))],
               sort=False, join='outer', axis=1)

df = pd.concat(df_dict, sort=True)

df_l = pd.DataFrame(df.stack())
df_l.reset_index(inplace=True)
df_l.columns = ['ticker', 'financials', 'date', 'value']

df_w = df_l.pivot_table(index=['date.year', 'financials'], columns='ticker', values='value')

export_excel = df_w.to_excel(r'C:/Users/User/Downloads/Income Statement Histories.xlsx', sheet_name="Sheet1", index= True)

How would I go about condensing the months into years so that the data is comparable Year-over-Year?

A: Not sure since you didn't give us any data, but you can change a datetime column to year with the following code. The first bit is just generating some smaple data:
from datetime import datetime, timedelta
from random import randint

df = pd.DataFrame({
    'dates': [datetime.today() - timedelta(randint(0, 1000)) for _ in range(50)]
})

print(df.head())

                       dates
0 2019-09-02 21:01:46.702300
1 2019-11-03 21:01:46.702329
2 2019-04-01 21:01:46.702338
3 2019-03-04 21:01:46.702345
4 2019-03-28 21:01:46.702351

The part that matters
df.dates.dt.to_period('Y')

0     2018
1     2018
2     2019
3     2018
4     2019
5     2020

A: IIUC, you need to melt, then use groupby on your date column to group by year.
#df['date'] = pd.to_datetime(df['date'])

df = pd.melt(df,id_vars=['date','financials'],var_name='ticker')

df.groupby([df['date'].dt.year,df['financials'],df['ticker']])['value'].sum().unstack()

ticker                                      AEM          AGI           ALB  \
date financials
2016 costOfRevenue                 1.030000e+09  309000000.0  1.710000e+09
     discontinuedOperations        0.000000e+00          0.0  2.020000e+08
     ebit                          3.360000e+08   21300000.0  5.370000e+08
     grossProfit                   1.110000e+09  173000000.0  9.700000e+08
     incomeBeforeTax               2.680000e+08   -7600000.0  5.750000e+08
...                                         ...          ...           ...
2019 researchDevelopment           0.000000e+00          0.0  5.828700e+07
     sellingGeneralAdministrative  1.210000e+08   19800000.0  4.390000e+08
     totalOperatingExpenses        1.650000e+09  557000000.0  2.830000e+09
     totalOtherIncomeExpenseNet   -1.000000e+08    2900000.0 -6.900000e+07
     totalRevenue                  2.490000e+09  683000000.0  3.590000e+09


text:
Q: Knockout JS - if data binding inside foreach data binding I am trying to get a if condition inside a foreach binding but it is not working for me. Below is the code that I tried:
View

            @{Html.RenderPartial("~/Views/Home/ServicePlan/_Priority1.cshtml");}

The Function that Is called
function IsValidServicePlan(priority, checkDetailFlag) {
var upActivityTempArr = ko.observableArray([]);

ko.utils.arrayForEach(priority.UpcomingActivities(), function (activity) {
    if (activity != undefined)
        if (!IsValidActivity(activity))
            upActivityTempArr.push(activity); // push valid Activity
});
ko.utils.arrayForEach(upActivityTempArr(), function (activity) {
    if (activity != undefined)
        priority.UpcomingActivities.remove(activity); // push valid Activity
});

if (hasValue(priority.Detail())
|| hasValue(priority.TimeFrames())
|| hasValue(priority.Feedback.SatisfactionLevel()) && priority.Feedback.SatisfactionLevel() != Satisfaction_Level
|| hasValue(priority.Feedback.FeedbackComment()) && priority.Feedback.FeedbackComment() != "Add Comment"
    ) {
    return true;
}}

When The function is called from the if condition, the priority parameter comes out as undefined. My requirement is that when the foreach loop is run, it will check and render the partial view only for those whose value is not empty. How will i resolve this to get this resolved?
Many thanks in advance.

A: Scope Issue as you are trying to access applicationView.ViewModel.AllPersonal[0] in child level where it doesn't exists , tough it exists at $parent & root level .
You can cut short you binding in view using $data which refers to current context rather going with a broader way ($parent.applicationView.ViewModel.AllPersonal[0]) in view
view:

 @{Html.RenderPartial("~/Views/Home/ServicePlan/_Priority1.cshtml");}

As a proper altenative you use .bind or function syntax in your view (as mentioned in comments)


text:
Q: Docker build not working with NextJS on node:alpine with SWC I have a NextJS App that I want to build into a docker image and run as a container later. I'm using the Dockerfile from https://nextjs.org/docs/deployment#docker-image.
When I run docker build . Everything works fine until Step 10/23:
yarn run v1.22.15
$ next build

info  - Checking validity of types...
info  - Creating an optimized production build...

Error: Error loading shared library ld-linux-x86-64.so.2: No such file or directory (needed by /app/node_modules/@next/swc-linux-x64-gnu/next-swc.linux-x64-gnu.node)

I found out that this is caused by SWC and alpine, but does anyone know how to solve this?
Maybe this can help: https://github.com/vercel/next.js/issues/30713

A: RUN rm -r node_modules/@next/swc-linux-x64-gnu
adding that und yarn install actually fixes that bug

A: For us, some of the team members had the older versions of the npm, and that created the problem in package-lock.json.
The solution to this is to delete the node_modules and package-lock.json from the project and run npm install
Note: If are building a docker image and your dockerfile has COPY package*.json ./ line then the new package-lock.json has to be updated to the repository from where the build will happen


text:
Q: React-admin additional item in dataProvider returned Object dataProvider on GET_LIST
return {
  data: someData,
  total: total,
}

I want something like this:
return {
  data,
  total,
  myCustomParam: 'param'
}

When i add myCustomParam it's just disappears
I can't find it out


text:
Q: Successive calls to MPI_IScatterv with same communicator I am trying to scatter two different, independent arrays from rank 0 to all others, over the same communicator, using non-blocking version of communication.
Something along these lines:
//do some stuff with arrays here...
MPI_IScatterv(array1, partial_size1, displs1,
             MPI_DOUBLE, local1, partial_size1,
             MPI_DOUBLE, 0, some_communicator, &request);
MPI_IScatterv(array2, partial_size2, displs2,
             MPI_DOUBLE, local2, partial_size2,
             MPI_DOUBLE, 0, some_communicator, &request);
//do some stuff where none of the arrays is needed...
MPI_Wait(&request, &status);
//do stuff with the arrays...

So... is it possible (or rather if it is guaranteed to always be error-free) to use two successive calls to MPI_IScatterv using the same communicator, or might that affect the result - mess up the messages from both scatters, since there are no tags?

A: Yes, it is possible to perform multiple non-blocking collective operations at once according to the MPI standard. In particular, on page 197, in section 5.12. NONBLOCKING COLLECTIVE OPERATIONS:

Multiple nonblocking collective operations can be outstanding on a single communicator. If the nonblocking call causes some system resource to be exhausted, then it will fail and generate an MPI exception. Quality implementations of MPI should ensure that
  this happens only in pathological cases. That is, an MPI implementation should be able to
  support a large number of pending nonblocking operations.

Nevertheless, make sure that different request are used for the successive calls to MPI_Iscatterv(). The function MPI_Waitall() is useful to check the completion of multiple non blocking operations.
MPI_Request requests[2];
MPI_Iscatterv(...,&requests[0]);
MPI_Iscatterv(...,&requests[1]);
MPI_Waitall(2,requests,...);

A sample code showing how it can be done:
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>

int main(int argc, char *argv[]) {

    MPI_Request requests[42];

    MPI_Init(&argc,&argv);

    int size,rank;
    MPI_Comm_size(MPI_COMM_WORLD,&size);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);

    int version,subversion;
    MPI_Get_version( &version, &subversion );

    if(rank==0){printf("MPI version %d.%d\n",version,subversion);}

    //dimensions
    int nbscatter=5;
    int nlocal=2;
    double* array=NULL;
    int i,j,k;
    //build a 2D array of nbscatter lines and nlocal*size columns on root process
    if(rank==0){
        array=malloc(nlocal*nbscatter*size*sizeof(double));
        if(array==NULL){printf("malloc failure\n");}

        for(i=0;i<nbscatter;i++){
            for(j=0;j<size*nlocal;j++){
                array[i*size*nlocal+j]=j+0.01*i;
                printf("%lf ",array[i*size*nlocal+j]);
            }
            printf("\n");
        }

    }

    //on each process, a 2D array of nbscatter lines and nlocal columns
    double* arrayloc=malloc(nlocal*nbscatter*sizeof(double));
    if(arrayloc==NULL){printf("malloc failure2\n");}

    //counts and displacements
    int* displs;
    int* scounts;
    displs = malloc(nbscatter*size*sizeof(int));
    if(displs==NULL){printf("malloc failure\n");}
    scounts = malloc(nbscatter*size*sizeof(int));
    if(scounts==NULL){printf("malloc failure\n");}

    for(i=0;i<nbscatter;i++){
        for(j=0;j<size;j++){
            displs[i*size+j]=j*nlocal;
            scounts[i*size+j]=nlocal;
        }

        // scatter the lines
        if(rank==0){
            MPI_Iscatterv(&array[i*nlocal*size], &scounts[i*size], &displs[i*size],MPI_DOUBLE,&arrayloc[i*nlocal], nlocal,MPI_DOUBLE, 0, MPI_COMM_WORLD, &requests[i]);
        }else{
            MPI_Iscatterv(NULL,  &scounts[i*size], &displs[i*size],MPI_DOUBLE,&arrayloc[i*nlocal], nlocal,MPI_DOUBLE, 0, MPI_COMM_WORLD, &requests[i]);
        }
    }

    MPI_Status status[nbscatter];
    if(MPI_Waitall(nbscatter,requests,status)!=MPI_SUCCESS){
        printf("MPI_Waitall() failed\n");
    }

    if(rank==0){
        free(array);
    }
    free(displs);
    free(scounts);

    //print the local array, containing the scattered columns
    for(k=0;k<size;k++){
        if(rank==k){
            printf("on rank %d\n",k);
            for(i=0;i<nbscatter;i++){
                for(j=0;j<nlocal;j++){
                    printf("%lf ",arrayloc[i*nlocal+j]);
                }
                printf("\n");
            }

        }

        MPI_Barrier(MPI_COMM_WORLD);
    }

    free(arrayloc);

    MPI_Finalize();

    return 0;
}

To be compiled by mpicc main.c -o main -Wall and ran by mpirun -np 4 main


text:
Q: How does std::variant becomes valueless_by_exception in this example? this is example inspired by example from cppreference
struct S {
    operator int() { throw 42; }
};

int main(){
    variant<float, int> v{12.f}; // OK
    cout << std::boolalpha << v.valueless_by_exception() << "\n";
    try{
        v.emplace<1>(S()); // v may be valueless
    }
    catch(...){
    }
    cout << std::boolalpha << v.valueless_by_exception() << "\n";
}

For one compiler I tried it outputs

false, true

meaning that emplace caused the variant to become valueless
What I do not understand is how this happened.
In particular I do not understand why emplace is called at all, I would expect the program to not even call it since conversion from S to int argument throws.

A: Note the signature for the relevant std::variant::emplace overload:
template <size_t I, class... Args>
std::variant_alternative_t<I, variant>& emplace(Args&&... args);

It takes a pack of forwarding references. This means that the conversion operator from S to int is not called when evaluating the function arguments; it's called inside the body of emplace. Since trying to construct the int in place would then fail, the variant is made valueless by exception.
It could perhaps be possible to implement variant such that for trivially movable types, the old value is saved before in place construction is attempted, and then restored if it failed, but I'm not sure if it fits in with the various restrictions on the type's implementation given by the standard.


text:
Q: How to calculate the probability of rolling 6 at least 5 times in a row, out of 50 tries? If I roll the dice 50 times, how do I calculate the chance that I will roll 6 at least 5 times in a row?
Why this problem is hard

*

*With 5 tries this would be easy: take $(1/6)$ to fifth power.

*With 6 tries this is manageable; take the probability of rolling 6 the first five times, add the probability of rolling 6 the last five times, then subtract the overlap (all six results are 6).

*Given two overlapping sets of 5 rolls, the probability that one is all 6's is not independent from the probability that the other is all 6's.

*In principle this could be continued, but inclusion-exclusion gets out of hand. There has to be a better way; what is it?

A: To expand on Jack's solution, you can write a matrix equation
$$ \left[ \begin{matrix}
L_n \\
L_{n-1} \\
L_{n-2} \\
L_{n-3} \\
L_{n-4} \end{matrix} \right]
= \left[ \begin{matrix}
5 & 5 & 5 & 5 & 5 \\
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
\end{matrix}\right] \left[ \begin{matrix}
L_{n-1} \\
L_{n-2} \\
L_{n-3} \\
L_{n-4} \\
L_{n-5} \end{matrix} \right]
$$
and thus
$$ \left[ \begin{matrix}
L_{n+4} \\
L_{n+3} \\
L_{n+2} \\
L_{n+1} \\
L_{n} \end{matrix} \right]
= \left[ \begin{matrix}
5 & 5 & 5 & 5 & 5 \\
1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
\end{matrix}\right]^n \left[ \begin{matrix}
L_{4} \\
L_{3} \\
L_{2} \\
L_{1} \\
L_{0} \end{matrix} \right]
$$
By diagonalizing the matrix, we can obtain an exact formula for the matrix exponential, and thus an exact formula for $L_n$.
However, if you just want the exact value of $L_{50}$, it's probably better to do it by exponentiating the matrix directly (using a square-and-multiply method: e.g. to obtain $A^{25}$, you first find $A^{12}$, then square it, and finally multiply the result by $A$).

A: There is no straightforward formula for this probability. However it can be computed exactly (within numerical error). You can keep track of the vector of probabilities $\mathbf{p}_t$ that at time $t$ you are in state:

*

*you haven't already rolled 5 6s and at the present time have rolled 0 6s,

*you haven't already rolled 5 6s and at the present time have rolled 1 6s,

*you haven't already rolled 5 6s and at the present time have rolled 2 6s,

*you haven't already rolled 5 6s and at the present time have rolled 3 6s,

*you haven't already rolled 5 6s and at the present time have rolled 4 6s, or

*you have already rolled 5 6s.

There are thus 6 probabilities in the vector. And initially $\mathbf{p}_0 = [1, 0, 0, 0, 0, 0]^T$. The chance of transitioning from state 1 to state 2 is $1/6$ and similarly for other states upto state 5 to state 6. From states 1 to 5 the chance of transitioning back to state 1 is $5/6$. However once you have already rolled 5 6s you have always already rolled 5 6s so if you get to state 6 you stay in state 6. These probabilities can be specified in a transition matrix $X$:
$$ X = \left\{
\begin{array}{c|cccccc}
& S_1 & S_2 & S_3 & S_4 & S_5 & S_6  \\
\hline
S_1 & \frac56 & \frac56 & \frac56 & \frac56 &\frac56  & 0 \\
S_2 &  \frac16 &0 & 0 &0 & 0 & 0 \\
S_3 & 0 & \frac16 &0 &0 & 0 & 0 \\
S_4 & 0 & 0 &\frac16 &0 & 0 & 0 \\
S_5 & 0 & 0 &0 &\frac16 & 0 & 0 \\
S_6 & 0 & 0 & 0&0 &\frac16 & 1
\end{array}\right\}
$$
Probabilities for time $t+1$ can be computed from probabilities for time $t$ by applying the transition matrix:
$$ \mathbf{p}_{t+1} = X\mathbf{p}_t $$
Computing $\mathbf{p}_{50} = X^{50}\mathbf{p}_0$ gives the probability of observing at least 5 6s within 50 rolls to be 0.00494 (simulation gave 0.00493). As Hurkyl points out, for large numbers of rolls it can be worth using the square and multiply method for matrix exponentiation to maintain accuracy.

A: This problem can also be approached using a generating function as in this related answer.

Using A Generating Function
As Jack D'Aurizio notes, we can build up all possible strings where $6$ does not appear at least $5$ times with the $5$ atoms
$$
\underbrace{\square\vphantom{6}}_{\large 5x^{\vphantom{1}}},\underbrace{6\square}_{\large 5x^2},\underbrace{66\square}_{\large 5x^3},\underbrace{666\square}_{\large 5x^4},\underbrace{6666\square}_{\large 5x^5}
$$
The coefficient of $5$ represents the number of ways to fill the $\square$. Note that any sequence of length $50$ can be made in a unique way by putting together such atoms to a length of $51$ and removing the last $\square$. Therefore, in the sum
$$
\begin{align}
\sum_{k=0}^\infty5^k(x+x^2+x^3+x^4+x^5)^k
&=\frac1{1-5\frac{x-x^6}{1-x}}\\
&=\frac{1-x}{1-6x+5x^6}\tag{1}
\end{align}
$$
the coefficient of $x^{n+1}$ is $5$ times the number of ways to arrange $n$ numbers with no subsequence of $5$ sixes in a row.
The coefficient of $x^{51}$ is $4021435247555066377711342806458789062500$ and $6^{50}$ is $808281277464764060643139600456536293376$. Dividing their quotient by $5$ and subtracting from $1$, we get a probability of
$$
\frac{4109288018262124589373497083105433}{831565100272391008892118930510839808}\doteq0.0049416311686434034927\tag{2}
$$

Computing The Coefficients By Recursion
Computing the coefficients of generating function in $(1)$ can be tedious. I used Mathematica to compute $(2)$. However, there is a more manual-friendly way to compute the coefficients using recursion.
The denominator in $(1)$ tells us that the coefficients of the series should satisfy
$$
a_n=6a_{n-1}-5a_{n-6}\tag{3}
$$
where we compute the first $6$ terms by series division
$$
a_0=1,a_1=5,a_2=30,a_3=180,a_4=1080,a_5=6480\tag{4}
$$
Using this recursion, it is easier to compute
$$
a_{51}=4021435247555066377711342806458789062500\tag{5}
$$

A: This is equivalent to counting the number of strings with length $50$ over the alphabet $\Sigma=\{1,2,3,4,5,6\}$ that avoid $66666$ as a substring of five consecutive characters. Let $S_n$ be the set of such strings with length $n$ and $L_n=|S_n|$. The prefix of an element in $S_n$ can be only:
$$ x,\quad 6x,\quad 66x,\quad 666x,\quad 6666x$$
where $x$ differs from $6$. This gives the recursive formula:
$$ L_n = 5(L_{n-1}+L_{n-2}+L_{n-3}+L_{n-4}+L_{n-5})\tag{1}$$
with the initial conditions:
$$ L_0=1,\quad L_1=6,\quad L_2=36,\quad L_3=216,\quad L_4=1296,\quad L_5=7775.\tag{2}$$
So we have that:
$$ L_n = A_1\sigma_{1}^n + A_2\sigma_2^n + A_3\sigma_3^n+A_4\sigma_4^n + A_5\sigma_5^n \tag{3}$$
where $\sigma_i$ is a root of the characteristic polynomial $f(x)=x^5-5(x^4+x^3+x^2+x+1)$ and the $A_i$s are constants given by the initial conditions. $f(x)$ has only one real root, very close to $6$, namely:
$$\sigma_1 = 5.999356651043833111223\ldots $$
and all the other roots satisfy $|\sigma_i|<1$, hence our probability is close to:
$$1-\left(\frac{\sigma_1}{6}\right)^{50}=0.0053471814\ldots\sim\frac{1}{187}.$$
An explicit computation of the coefficients in $(3)$ gives:
$$ A_1 = 1.00040773044846\ldots,$$
$$ A_2 = A_3 = -0.006863339\ldots,$$
$$ A_4 = A_5 = 0.0066594738\ldots,$$
hence the true probability is:

$$ 0.0049416311686434\ldots\sim\frac{3}{607}.$$

A: This is a hard kind of question to answer, because you might roll 5 6's in a row more than once with separation in between, and/or you may roll more than 5 6's in a row. There are 46 places where a run of 5 6's might start, and although these events can overlap, if we consider them all separate then we get that the expected number of times you get 5 6's in a row is less than $46/6^5 = 46/7776$ which is pretty small. By the Markov inequality, the probability that you get 5 6's in a row at least once is thus less than $46/7776$.


text:
Q: 2D array vs 1D array I have read the question for Performance of 2-dimensional array vs 1-dimensional array
But in conclusion it says could be the same (depending the map own map function, C does this automatically)?...
I have a matrix wich has 1,000 columns and  440,000,000 rows where each element is a double in C#...
If I am doing some computations in memory, which one could be better to use in performance aspect? (note that I have the memory needed to hold such a monstruos quantity of information)...

A: If what you're asking is which is better, a 2D array of size 1000x44000 or a 1D array of size 44000000, well what's the difference as far as memory goes?  You still have the same number of elements!  In the case of performance and understandability, the 2D is probably better.  Imagine having to manually find each column or row in a 1D array, when you know exactly where they are in a 2D array.

A: It depends on how many operations you are performing. In the below example, I'm setting the values of the array 2500 times. Size of the array is (1000 * 1000 * 3). The 1D array took 40 seconds and the 3D array took 1:39 mins.
var startTime = DateTime.Now;
Test1D(new byte[1000 * 1000 * 3]);
Console.WriteLine("Total Time taken 1d = " + (DateTime.Now - startTime));

startTime = DateTime.Now;
Test3D(new byte[1000,1000,3], 1000, 1000);
Console.WriteLine("Total Time taken 3D = " + (DateTime.Now - startTime));

public static void Test1D(byte[] array)
{
    for (int c = 0; c < 2500; c++)
    {
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = 10;
        }
    }
}

public static void Test3D(byte[,,] array, int w, int h)
{
    for (int c = 0; c < 2500; c++)
    {
        for (int i = 0; i < h; i++)
        {
            for (int j = 0; j < w; j++)
            {
                array[i, j, 0] = 10;
                array[i, j, 1] = 10;
                array[i, j, 2] = 10;
            }
         }
     }
}

A: The difference between double[1000,44000] and double[44000000] will not be significant.
You're probably better of with the [,] version (letting the compiler(s) figure out the addressing. But the pattern of your calculations is likely to have more impact (locality and cache use).
Also consider the array-of-array variant,  double[1000][]. It is a known 'feature' of the Jitter that it cannot eliminate range-checking in the [,] arrays.


text:
Q: Why do logs that are run by schedule:run on Laravel Vapor not saving in Cloudwatch? So I have this in my Kernel.php $schedule->command('command:name')->hourly()->withoutOverlapping(); but it never stores the logs in Cloudwatch. However, if I run it manually using vapor command staging --command="php artisan command:name", they do get stored in Cloudwatch.
I am assuming it has to do with cron based commands in Laravel Vapor storing their output to /dev/null but I might be wrong. My goal is to capture these logs, any help? To add further, my command basically fetches data from an API for 50 records.

A: This is from the official Laravel Vapor documentation:

Log Messages
Due to Vapor limitations, log messages from scheduled tasks will not
appear in AWS CloudWatch or Vapor UI. As a workaround, you should
dispatch a queued job from your scheduled tasks and write log messages
from your queued job.

When you execute vapor command staging --command="php artisan command:name you are using the CLI. This mode generates logs and that's the reason you can see them.

A: Solved this by doing a symbolic link between the screen output and a log file. All thanks to @koalaok. See his answere here https://stackoverflow.com/a/46767123/4296706
ln -sf /proc/1/fd/1 /var/log/laravel-scheduler.log

and in my Kernel.php
$filePath = '/var/log/laravel-scheduler.log';;
$schedule->command('my sample command')->daily()->appendOutputTo($filePath);


text:
Q: passing query params for aws lambda function I am trying to set up a Lambda function that will pull query params that are passed into the API Gateway URL that is created. (Sidebar: I am still pretty green when it comes to programming, so please forgive any unintentional confusion regarding how to name things on my part). I've wrapped a few REST calls within a fiber using Synchronize.JS, and it works great when I hard code the variables that I want to pass into the various REST urls, but our goal is to be able to pass different parameters that will act as global variables for the different REST calls being made. This is what I currently have...
// Dependendies
var request = require('superagent');
var sync = require('synchronize');

exports.handler = function(event, context) {

    sync.fiber(function() {
        var followingArray = [];
        var followersArray = [];
        var postsCountArray = [];
        var allSqorCountArray = [];
        var trendingPostAuthorArray = [];
        var hashtagCountArray = [];
        var notificationCountArray = [];

        var getParam = function(query){
                var SearchString = window.location.search.substring(1);
                var VariableArray = SearchString.split('&');
                for(var i = 0; i < VariableArray.length; i++){
                var KeyValuePair = VariableArray[i].split('=');
                if(KeyValuePair[0] == query){
                    return KeyValuePair[1];
                }
                };
        };

        var userId = getParam('userId');
        var limit = getParam('limit');
        var offset = getParam('offset');

        var restCallOne = function() {
            request('https://someurl.com/etc/' + userId + '/follows?limit=' + limit + '&offset=' + offset)
            .end(function(err, res) {
                if (err) {
                    console.log('Request 1');
                    context.fail("Danger Will Robinson!!! Follows Count Does Not Like You!!");
                } else {
                    var followsCount = res.body.total_count;
                    followingArray.push(followsCount);
                }
            });
        };

        var restCallTwo = function() {
            request
            .get('https://someurl.com/etc/etc/etc?limit=' + limit + '&offset=' + offset)
            .set({'access-token': 'someAccessToken'})
            .end(function(err, res) {
                if(err) {
                    console.log('Request 4');
                    context.fail("Danger Will Robinson!!  The All Sqor Feed is moody");
                } else {
                    var allSqorCount = res.body.total_count;
                    allSqorCountArray.push(allSqorCount);
                }
            });
        };

        var restCallThree = function() {
            request
            .get('https://someUrl.com/etc/' + userId + '/followers?limit=' + limit + '&offset=' + offset)
            .end(function(err, res) {
                if (err) {
                    console.log('Request 3');
                    context.fail("Danger Will Robinson!!! Following Count Done Smacked You Upside The Head!!");
                } else {
                    var count = res.body.total_count;
                    followersArray.push(count);
                    context.done(null, 'The total number of people that follow Andy is ' + followersArray[0] +
                                       ', and the number of people that Andy follows is ' + followingArray[0] +
                                       ', and the number of posts in his feed is ' + allSqorCountArray[0]);
                }
            });
        };

        try {
            restCallOne(userId, limit, offset);
        } catch(errOne) {
            console.log("Error on call 1!!");
        }

        try {
            restCallTwo(limit, offset);
        } catch(errTwo) {
            console.log("Error on call 2!!");
        }

        try {
            restCallThree(userId, limit, offset);
        } catch(errThree) {
            console.log("Error on call 3!!");
        }
    });
};

The API Gateway URL that was generated when I linked it with this function is as such: https://someID.execute-api.us-east-1.amazonaws.com/syncFunctionalParams
but I'd like to be able to pass something like this in, and use the params within my Lambda function to return the correct information from the rest calls:
https://someID.execute-api.us-east-1.amazonaws.com/syncFunctionalParams?userId=212733&limit=25&offset=0
Is this possible?? Am I way off track with this?

A: You need to setup a mapping template in API Gateway. If you know the name of your parameters ahead of time your template could look like this:
{
  "userId": "$input.params('userId')",
  "limit": "$input.params('limit')",
  "offset": "$input.params('offset')"
}

Where each $input.params('...') will get evaluated and the value in your query string will be put in its place when the event is passed to Lambda.
If you don't know the parameter names ahead of time you will have to do some parsing in Lambda. Your mapping template would look like this:
{
  "querystring": "$input.params().querystring"
}

Which will end up looking like this in the event that is passed to Lambda:
{
  "querystring": "{limit=25, offset=0, userId=212733}"
}

And then you would parse event.querystring instead of window.location.search in your getParam(). Obviously you would need to change some of the logic since you'll be splitting on commas instead of ampersands and you'd need to get rid of the curly brackets. Which by the way, since you are on the server at this point you don't have a window object.


text:
Q: Document is not ready in DocumentReady event? I am using Awesomium 1.7.0.5 in order to load a page, fill some textboxes and click a button. I am trying to fill a textbox using an example from this thread: http://answers.awesomium.com/questions/857/webcontrol-type-in-webbrowser.html
Here is my code (I am using WPF control):
        private void WbAwsOnDocumentReady(object sender, UrlEventArgs urlEventArgs)
        {
            if (wbAws == null || !wbAws.IsLive)
              return;

            //Thread.Sleep(555);

            dynamic document = (JSObject)wbAws.ExecuteJavascriptWithResult("document");

            if (document == null)
              return;

            using (document)
            {
                dynamic textbox = document.getElementById("email");

                if (textbox == null)
                  return;

                using (textbox)
                {
                    textbox.value = "gaaffa";
                }

            }
        }

It works but only with Thread.Sleep for 0.1-0.5 sec. Otherwise document is empty (not null) and/or textbox is null.
What should I do? Why it is not ready in DocumentReadyEvent?

A: Here is how I solved it:
     WbAws.LoadingFrameCompleted += OnLoadingFrameCompleted;
     WbAws.Source = new Uri("http://google.com");

private void OnLoadingFrameCompleted(...)
{
   if (webView == null || !webView.IsLive ||
         webView.ParentView != null || !e.IsMainFrame)
     return;

    LoadingFrameCompleted -= OnLoadingFrameCompleted;

    // do something
}

LoadingFrameCompleted instead of DocumentReady and because it fires not only when I need it but also on app startup I subscribe to it just before navigating and unsubscribe after it. Also checking that it IsMainFrame.
edit: but with this solution it sometimes throws exception that document is not ready. So I am also waiting for it using Thread.Sleep.

A: Very old question. but for someone like me, who is facing this problem-
use LoadingFrameCompleted event with WebControl.IsNavigating == false and e.IsMainFrame == true condition.
if these conditions are true in this event then page is finished loading and you are ready to get HTML content.


text:
Q: fedora : install package from local, with no internet access Is there a way to install a downloaded package on a fresh install of fedora 33 without triggering cache update, as the server does not have internet access (vm guest) ?
I tried the --cacheonly option, set the metadata value to -1 for the set-opt option (dnf) : neither seems to function.
Thank

A: Given that your system doesn't have Internet access (which I assume means no access to the package repositories), you could forgo dnf entirely:
rpm -i yourpackage.rpm

dnf would resolve missing dependencies for you, but that's not going to work anyway if the system can't access the necessary repositories. If other packages are needed, you'll have to download them yourself and add them to the rpm -i command.


text:
Q: how to create Array of Arrays in angular I need a array of arrays and I can't get it and I cant understand what am I doing wrong..this is my code..
c.push({ id: data[0]["id"], title:data[v]["title"], date:data[v]["date"],
         text:data[v]["text"], favorit:"true" });
$scope.favoriti.push({c});
c=[];

I'm trying to access the array with this, but it write undefined
alert( $scope.favoriti[0]["id"] );

What I must write, to get that kind of a array where can I access with that alert. I really need help, I try everything. Thank you.

A: check this code.

var app = angular.module('app', []);
app.controller('controller', function($scope) {
  var c = [];
  $scope.favoriti = [];
  var v = 0;
  var data = [{
    id: 1,
    title: 't',
    date: 'd',
    text: 'text'
  }]
  c.push({
    id: data[0]["id"],
    title: data[v]["title"],
    date: data[v]["date"],
    text: data[v]["text"],
    favorit: "true"
  });
  $scope.favoriti.push(c);
  console.log($scope.favoriti);
  console.log("id : " + $scope.favoriti[0][0]["id"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
</div>


text:
Q: Debian boots into initramfs, but /sbin/init is present I was crossgrading Debian Stretch from i386 to amd64. The kernel is already 64-bit, so is dpkg/apt. I was going through the rest of the packages, and then I had to reboot the box.
Upon reboot, it goes into the recovery mode (initramfs). There are the following messages:
/scripts/local-premount/resume: line 34: /bin/resume: not found
/dev/sda1: recovering journal
/dev/sda1: clean
/init: line 267: run-init: not found
Target filesystem doesn't have requested /sbin/init
/init: line 267: run-init: not found
/init: line 267: run-init: not found
/init: line 267: run-init: not found
/init: line 267: run-init: not found
/init: line 272: run-init: not found
No init found. Try passing init= boot argument.

And then there's the busybox prompt.
The hard drive (/dev/sda1) is mounted into /root. fsck reports no issues. /sbin/init is present there, it's a symlink to /lib/systemd/systemd, which also exists (but remains 32-bit).
I can remount the hard drive as R/W and chroot into it. In that mode, I can get get some of the regular Debian stuff, like dpkg, to work. No network though, so no apt-get.
Please, what could be wrong with the boot environment? What else should I check? It's most likely something I did during the crossgrade process, not hardware or filesystem corruption.
EDIT: using another Debian box, found a tool called run-init. It's under /usr/lib/klibc/bin, comes in the klibc-tools package, and has to do with the initramfs operation. I'll try installing that. Now, if I could figure out a way to copy files to this box...

A: I'm still not sure where did I go wrong. But after running
update-initramfs -u

in a chroot-to-sda1 environment, things were back to normal.
By the way, installing klibc-utils didn't help.
Also, I got the wired network to work in initamfs. After remount/chroot, the ifup eth1 command stood up the network, and I could download packages again.


text:
Q: C miscalculating distances I wrote some code in C to convert your distance to other distance units but it seems to mix up the numbers and miscalculate the result.
I use a Windows 10 laptop, but, I don't think it matters because I used an online compiler (GDB) to write the code. I really don't even know where is the problem.
#include <stdio.h>

int main ()
{
    float distance;
    char in_unit[20];

    printf("Enter your distance:\n");
    scanf("%f", &distance);

    printf("Enter the length unit of your distance.(C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)\n");
    scanf("%s", in_unit);
    if (in_unit == "Cm");
    {
        printf("Your distance in feet is:%f", distance/30.48);
        printf("\nYour distance in kilometers is:%f", distance/100000);
        printf("\nYour distance in inches is:%f", distance/2.54);
        printf("\nYour distance in miles is:%f", distance/160934.4);
        printf("\nYour distance in meters is:%f", distance/100);
    }
    if (in_unit == "Ft")
    {
        printf("Your distance in centimeters is:%f", distance*30.48);
        printf("\nYour distance in kilometers is:%f", distance/3280.84);
        printf("\nYour distance in inches is:%f", distance*12);
        printf("\nYour distance in miles is:%f", distance/5280);
        printf("\nYour distance in meters is:%f", distance/3.281);
    }
    if (in_unit == "Kg")
    {
        printf("Your distance in centimeters is:%f", distance * 100000);
        printf("\nYour distance in feet is:%f", distance * 3280.84);
        printf("\nYour distance in inches is:%f", distance * 39370.079);
        printf("\nYour distance in miles is:%f", distance / 1.609);
        printf("\nYour distance in meters is:%f", distance * 1000);
    }
    if (in_unit == "In")
    {
        printf("Your distance in centimeters is:%f", distance*2.54);
        printf("\nYour distance in feet is:%f", distance/12);
        printf("\nYour distance in kilometers is:%f", distance/39370.079);
        printf("\nYour distance in miles is:%f", distance/63360);
        printf("\nYour distance in meters is:%f", distance/39.37);
    }
    if (in_unit == "M")
    {
       printf("Your distance in centimeters is:%f", distance*160934.4);
       printf("\nYour distance in feet is:%f", distance*5280);
       printf("\nYour distance in kilometers is:%f", distance*1.609);
       printf("\nYour distance in inches is:%f", distance*63360);
       printf("\nYour distance in meters is:%f", distance*1609.344);
    }
    if (in_unit == "Mtrs")
    {
       printf("Your distance in centimeters is:%f", distance*100);
       printf("\nYour distance in feet is:%f", distance*3.281);
       printf("\nYour distance in kilometers is:%f", distance/1000);
       printf("\nYour distance in inches is:%f", distance*39.37);
       printf("\nYour distance in miles is:%f", distance/1609.344);
    }
    return 0;
}

For example, this is one of the runs:
Enter your distance:
1
Enter the length unit of your distance. (C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)
Kg
Your distance in feet is:0.032808
Your distance in kilometers is:0.000010
Your distance in inches is:0.393701
Your distance in miles is:0.000006
Your distance in meters is:0.010000


text:
Q: Mechanize Ignore Javascript when Required by Page I understand a few people have asked about JS support in Mechanize. My question might be a little bit different, and/or posed differently. I am looking to ignore the Javascript check and log in to a page that requires Javascript. The web site itself does not really need JS, but the developers felt they needed to require it for the best appearance.
With that said, has anyone been able to circumvent the check for JS? I could use Watir, Watij, Selenium, or a surplus of other utilities but they open an actual browser which was not that desirable -- but if this is the only way I guess I'll go that route.
I'm running Mac OS X, Ruby 1.8.7, Mechanize/Hpricot (latest as of this post). Thanks.

A: Generally speaking, the simplest option is to work out what the server expects the user-agent to send to claim that it supports JS (either by monitoring the HTTP requests (perhaps with Charles Proxy) sent by a browser with JS enabled or by reverse engineering the JS) and then just having your script send that information.

A: You could try Webrat. Webrat doesn't understand JavaScript as far as I know.

*

*Webrat


text:
Q: add primary key to mapped super class inherited entity JPA I am trying to create my database with JPA and i have a mapped super class "user" from wich the entities "student" and "teacher" inherit (they extend from the mapped super class) and the "chief" entity extends from "teacher" but the primary key of "chief" has another column.
How can I add a column to the primary key using JPA annotations.


text:
Q: Data Warehouse - DB2 to SQL Server: how and what impacts on ETL? I'm working towards migrating an IBM DB2 database to SQL Server, however the DB2 database sits in a Data Warehouse environment.
As I am very new to Data Warehousing, DB2 and DB Migration between different types of databases, I would like to ask about how to best approach this and understand what components are involved (listing or linking elsewhere is fine - happy to read a bunch of things or learn something new).
The context:

*

*The ETL tool in use, and to be kept in use, is Informatica

*The only application that queries the DB is Cognos

*There are 4 DB2 DBs in use on 2 (non-windows) hosts, one of these is 'H1' which has a 'DB2-DW-PROD' DB used as part of the Data Warehouse

*I am interested in migrating the 'DB2-DW-PROD' DB to some space I have on an existing (Windows) SQL Server host, 'H2' under the name 'SQL-DW-PROD'. This host currently has several DBs on it for other purposes (in one instance) and can have SSRS/SSIS or other services/resources installed or configured if needed.

*I would like to clean up the poorly maintained DB a little bit during the migration, if possible, based off what has not been used/updated in the past couple of years.

What I would like to know, directly or indirectly:

*

*Should I create a new instance on H2 or is a single new database enough?

*Does the new instance/DB need particular resources? If so, where from?

*Should I use a particular Microsoft tool or use some type of import/export to get the data I need? (Is Informatica involved in this process?)

*Someone mentioned 'metadata tables' for Informatica and/or Cognos, should I be wary of something?

*Another mentioned maintaining sequence values -How is this best achieved; is it needed?

*Any changes on the Informatica side are not my personal concern but the work of another, as such, Is there anything I should provide this person (apart from the address of the new db)?


text:
Q: Python looping thru days to sum up total grouped by month I am trying to group the list of days according to month, for example day 1 to 31 is January, and so on. Here is some input data:
Day 1: -109.743833
Day 2: -59.743030
Day 3: -149.539798
Day 4: -134.004097
Day 5: -101.911757
Day 6: -64.655886
Day 7: 38.683420
Day 8: 14.493554
Day 9: -52.823889
Day 10: -16.754896
Day 11: 27.648000
Day 12: -8.978296
Day 13: 3.077756
Day 14: 8.925626
Day 15: -13.099969
Day 16: 36.508620
Day 17: -20.888302
Day 18: 2.014708
Day 19: 52.070549
Day 20: 14.389047
Day 21: 46.281278
Day 22: 6.589799
Day 23: 14.849905
Day 24: 21.924614
Day 25: -19.006338
Day 26: -16.249006
Day 27: 41.147836
Day 28: 25.397426
Day 29: 45.358489
Day 30: 129.366465
Day 31: 129.377892
Day 32: -16.628081
Day 33: 56.484472
Day 34: 73.509385
Day 35: 119.484387
Day 36: -21.506795
Day 37: -16.499800
Day 38: -17.491308
Day 39: 140.532548
Day 40: -8.470736
Day 41: 203.523499

I am tring to sum up its total grouped by month. This is the code where I printed out the above:
print('Day %d: %f' % (day, inverted))

I am thinking to manually do an if else statement to sum them up but I do not think that's a good idea. Is there any better way of doing this?
Thanks!
Edit
dataset = list()
for yhat in forecast
    print('Day %d: %f' % (day, inverted))
    temp = str(day) + ':' + str(inverted)
    dataset.append(temp)

A: Let's say your input is in a dictionary, with the integer day as the keys.
{1: -109.743833, 2: -59.743030, ...}

We can use those keys to build date strings, then use the datetime.strptime method to interpret them.  We can then extract the month from the datetime object
from collections import defaultdict
from datetime import datetime

month_groups = defaultdict(list)
year = 2018

for day, value in day_dict.items():
    month = datetime.strptime('{:0>3}-{}'.format(day, year), '%j-%Y').month
    month_groups[month].append(value)

I would not be surprised if there is some better way of doing this, so you might want to double check in the datetime and calendar modules to see if you can find something I missed

A: Convert day to month based on a given year, and then group by month using dictionary:
from datetime import datetime
from datetime import timedelta
from collections import defaultdict

year = 2018
data = [
    (32, -16.628081),
    (33, 56.484472),
    ...
]

base = datetime(year, 1, 1)
res = defaultdict(float)
for month, val in (((base + timedelta(day - 1)).month, inverted) for day, inverted in data):
    res[month] += val

print(res)


text:
Q: Find some $n, k$ such that: $\phi(kn) = k * \phi(n)$ This question might be a duplicate.

For what positive integers $n$, $k$ is $\phi(kn) = k \cdot \phi(n)$?

I read Wikipedia page but I did not find any identity to help me answer the question so I tried some examples that given identity works:
$$k = 1, n = 1\\
k = 2, n = 2\\
k = 3, n = 3\\
k = 4, n = 4\\
k = 5, n = 5\\
k = 6, n = 6\\
k = 7, n = 7\\
k = 9, n = 9\\
k = 10, n = 10$$
Any hint would be appreciated.

A: The condition is that every prime dividing $k$ divides $n$.
To see this, let $k = k_1 k_2$ and $n = n_1 n_2$ where $k_1$ and $n_1$ are divisible by the same set $S$ of primes, while $k_2$ and $n_2$ are coprime to each other and to $k_1$ and $n_1$.  Thus we have
$$ \frac{\varphi(k n)}{k \varphi(n)} = \frac{\varphi(k_1 n_1) \varphi(k_2) \varphi(n_2)}{k_1 k_2 \varphi(n_1) \varphi(n_2)} = \frac{\varphi(k_1 n_1) \varphi(k_2) }{k_1 k_2 \varphi(n_1) } $$
But if $k_1 = \prod_{p \in S} p^{d(p)}$ and $n_1 = \prod_{p \in S} p^{e(p)}$, where $d(p) \ge 1$ and $e(p) \ge 1$, we have
$$ \frac{\varphi(k_1 n_1)}{k_1 \varphi(n_1)} = \prod_{p \in S} \frac{(p-1) p^{e(p)+d(p)-1}}{p^{d(p)}(p-1)p^{e(p)-1}} = 1$$
So the condition reduces to
$ \varphi(k_2) = k_2$, and this is only true for $k_2 = 1$.


text:
Q: How to generate directory size recursively in python, like du . does? Lets say my structure is like this
/-- am here
/one/some/dir
/two
/three/has/many/leaves
/hello/world

and say /one/some/dir contains a big file, 500mb, and /three/has/many/leaves contains a 400mb file in each folder.
I want to generate the size for each directory, to have this output
/ - in total for all
/one/some/dir 500mb
/two 0
/three/has/many/leaved - 400mb
/three/has/many 800
/three/has/ 800+someotherbigfilehere

How would I go about this?

A: Have a look at os.walk.  Specifically, the documentation has an example to find the size of a directory:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

This should be easy enough to modify for your purposes.

Here's an untested version in response to your comment:
import os
from os.path import join, getsize
dirs_dict = {}

#We need to walk the tree from the bottom up so that a directory can have easy
# access to the size of its subdirectories.
for root, dirs, files in os.walk('python/Lib/email',topdown = False):

    # Loop through every non directory file in this directory and sum their sizes
    size = sum(getsize(join(root, name)) for name in files)

    # Look at all of the subdirectories and add up their sizes from the `dirs_dict`
    subdir_size = sum(dirs_dict[join(root,d)] for d in dirs)

    # store the size of this directory (plus subdirectories) in a dict so we
    # can access it later
    my_size = dirs_dict[root] = size + subdir_size

    print '%s: %d'%(root,my_size)

A: Actually @mgilson answer is not working if there are symbolic links in the directories. To allow that you have to do that instead :
dirs_dict = {}
for root, dirs, files in os.walk(directory, topdown=False):
    if os.path.islink(root):
        dirs_dict[root] = 0L
    else:
        dir_size = getsize(root)

        # Loop through every non directory file in this directory and sum their sizes
        for name in files:
             full_name = join(root, name)
             if os.path.islink(full_name):
                 nsize = 0L
             else:
                 nsize = getsize(full_name)
             dirs_dict[full_name] = nsize
             dir_size += nsize

        # Look at all of the subdirectories and add up their sizes from the `dirs_dict`
        subdir_size = 0L
        for d in dirs:
            full_d = join(root, d)
            if os.path.islink(full_d):
                dirs_dict[full_d] = 0L
            else:
                subdir_size += dirs_dict[full_d]

        dirs_dict[root] = dir_size + subdir_size

A: The following script prints directory size of all sub-directories for the specified directory. This script should be independent from the platform - Posix/Windows/etc.  It also tries to benefit (if possible) from caching the calls of a recursive functions. If an argument is omitted, the script will work in the current directory. The output is sorted by the directory size from biggest to smallest ones. So you can adapt it for your needs.
PS i've used recipe 578019 for showing directory size in human-friendly format
from __future__ import print_function
import os
import sys
import operator

def null_decorator(ob):
    return ob

if sys.version_info >= (3,2,0):
    import functools
    my_cache_decorator = functools.lru_cache(maxsize=4096)
else:
    my_cache_decorator = null_decorator

start_dir = os.path.normpath(os.path.abspath(sys.argv[1])) if len(sys.argv) > 1 else '.'

@my_cache_decorator
def get_dir_size(start_path = '.'):
    total_size = 0
    if 'scandir' in dir(os):
        # using fast 'os.scandir' method (new in version 3.5)
        for entry in os.scandir(start_path):
            if entry.is_dir(follow_symlinks = False):
                total_size += get_dir_size(entry.path)
            elif entry.is_file(follow_symlinks = False):
                total_size += entry.stat().st_size
    else:
        # using slow, but compatible 'os.listdir' method
        for entry in os.listdir(start_path):
            full_path = os.path.abspath(os.path.join(start_path, entry))
            if os.path.islink(full_path):
                continue
            if os.path.isdir(full_path):
                total_size += get_dir_size(full_path)
            elif os.path.isfile(full_path):
                total_size += os.path.getsize(full_path)
    return total_size

def get_dir_size_walk(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

def bytes2human(n, format='%(value).0f%(symbol)s', symbols='customary'):
    """
    (c) http://code.activestate.com/recipes/578019/

    Convert n bytes into a human readable string based on format.
    symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
    see: https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.2FIEC_80000

      >>> bytes2human(0)
      '0.0 B'
      >>> bytes2human(0.9)
      '0.0 B'
      >>> bytes2human(1)
      '1.0 B'
      >>> bytes2human(1.9)
      '1.0 B'
      >>> bytes2human(1024)
      '1.0 K'
      >>> bytes2human(1048576)
      '1.0 M'
      >>> bytes2human(1099511627776127398123789121)
      '909.5 Y'

      >>> bytes2human(9856, symbols="customary")
      '9.6 K'
      >>> bytes2human(9856, symbols="customary_ext")
      '9.6 kilo'
      >>> bytes2human(9856, symbols="iec")
      '9.6 Ki'
      >>> bytes2human(9856, symbols="iec_ext")
      '9.6 kibi'

      >>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
      '9.8 K/sec'

      >>> # precision can be adjusted by playing with %f operator
      >>> bytes2human(10000, format="%(value).5f %(symbol)s")
      '9.76562 K'
    """
    SYMBOLS = {
        'customary'     : ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
        'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa',
                           'zetta', 'iotta'),
        'iec'           : ('Bi', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'),
        'iec_ext'       : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi',
                           'zebi', 'yobi'),
    }
    n = int(n)
    if n < 0:
        raise ValueError("n < 0")
    symbols = SYMBOLS[symbols]
    prefix = {}
    for i, s in enumerate(symbols[1:]):
        prefix[s] = 1 << (i+1)*10
    for symbol in reversed(symbols[1:]):
        if n >= prefix[symbol]:
            value = float(n) / prefix[symbol]
            return format % locals()
    return format % dict(symbol=symbols[0], value=n)

############################################################
###
###  main ()
###
############################################################
if __name__ == '__main__':
    dir_tree = {}
    ### version, that uses 'slow' [os.walk method]
    #get_size = get_dir_size_walk
    ### this recursive version can benefit from caching the function calls (functools.lru_cache)
    get_size = get_dir_size

    for root, dirs, files in os.walk(start_dir):
        for d in dirs:
            dir_path = os.path.join(root, d)
            if os.path.isdir(dir_path):
                dir_tree[dir_path] = get_size(dir_path)

    for d, size in sorted(dir_tree.items(), key=operator.itemgetter(1), reverse=True):
        print('%s\t%s' %(bytes2human(size, format='%(value).2f%(symbol)s'), d))

    print('-' * 80)
    if sys.version_info >= (3,2,0):
        print(get_dir_size.cache_info())

Sample output:
37.61M  .\subdir_b
2.18M   .\subdir_a
2.17M   .\subdir_a\subdir_a_2
4.41K   .\subdir_a\subdir_a_1
----------------------------------------------------------
CacheInfo(hits=2, misses=4, maxsize=4096, currsize=4)

A: I achieved this with this code:
def get_dir_size(path=os.getcwd()):

    total_size = 0
    for dirpath, dirnames, filenames in os.walk(path):

        dirsize = 0
        for f in filenames:
            fp = os.path.join(dirpath, f)
            size = os.path.getsize(fp)
            #print('\t',size, f)
            #print(dirpath, dirnames, filenames,size)
            dirsize += size
            total_size += size
        print('\t',dirsize, dirpath)
    print(" {0:.2f} Kb".format(total_size/1024))

A: I achieved this using the pathlib module. The following code will calculate correct directory sizes for every sub-directory in a given directory tree.

Note: If you wish to calculate the total size of the given root directory only and not for all the individual sub-directories using this code, then you must get rid of the outer loop, i.e. - for sub in subdir: and replace ls = list(sub.rglob('*.*')) with ls = list(dir_path.rglob('*.*')) and correct the indentation accordingly.

So, here's the sample code generated using Python 3.7.6 on Windows.
import os
from pathlib import Path

# Set home/root path
dir_path = Path('//?/C:/Downloads/.../.../.../.../...')

# IMP_NOTE: If the path is 265 characters long, which exceeds the classic MAX_PATH - 1 (259) character
# limit for DOS paths. Use an extended (verbatim) path such as "\\\\?\\C:\\" in order
# to access the full length that's supported by the filesystem -- about 32,760 characters.
# Alternatively, use Windows 10 with Python 3.6+ and enable long DOS paths in the registry.

# pathlib normalizes Windows paths to use backslash, so we can use
# Path('//?/D:/') without having to worry about escaping backslashes.

# Generate a complete list of sub-directories
subdir = list(x for x in dir_path.rglob('*') if x.is_dir())

for sub in subdir:
    tot_dir_size = 0
    ls = list(sub.rglob('*.*'))
    # print(sub, '\n')
    # print(len(ls), '\n')
    for k in ls:
        tot_dir_size += os.path.getsize(k)
    # print(format(tot_dir_size, ',d'))
    print("For Sub-directory: " + sub.parts[-1] + "   ===>   " +
          "Size = " + str(format(tot_dir_size, ',d')) + "\n")

# path.parts ==> Provides a tuple giving access to the path's various components
# (Ref.: pathlib documentation)

Output:

For Sub-directory: DIR_1   ===>   Size = 5,600,621,618

For Sub-directory: DIR_2   ===>   Size = 9,113,492,347

For Sub-directory: DIR_3   ===>   Size = 928,986,489

For Sub-directory: DIR_4   ===>   Size = 2,125,250,470


text:
Q: meteor 0.9 "list" shows "new versions of these packages are available" but "update" doesn't $ meteor list
...
 * New versions of these packages are available! Run 'meteor update' to update.
$ meteor update
Figuring out the best package versions to use. This may take a moment.
This project is at the latest release which is compatible with your
current package constraints.

See the simplified version below:

It seems like there's a "conflict" between the list command which is saying there are updates available, and the update command which can not find any... how can this happen?

A: The problem seemed to be the mrt migrate-app script, which was a convenient way to upgrade... but apparently left some cruft around.
problems

*

*some of the packages were guessed a bit wrong... with cmather:iron-router when it should be iron:router and more like that... (wish there was some way to filter/vote/identify "good" packages)

*some of the packages were added with version suffixes like @2.0.0 and those were holding up the update... so list says "there are updates available" but update doesn't get them...  <-- answer
solution
remove all packages, update, add them all back, without the version suffix...
pretty easy to do now that they are all single lines in the .meteor/packages file:
sed -e 's/^[a-zA-Z0-9]/meteor remove &/' .meteor/packages | sed 's/\@[0-9\.]*//g' > packages-rm.sh
sed -e 's/ remove / add /' packages-rm.sh > packages-add.sh
bash packages-rm.sh
meteor list  # should be empty
meteor update
bash packages-add.sh
meteor list


text:
Q: javascript getting google-plus user avatar stackoverflow'ers!
So my job now is to work around social networks. I've made login for facebook, google and twitter. Now i need to retrieve user avatars. Site is very dynamic and pretty much everything are working through javascript and ajax. I have got facebook user avatar successfully. When user has avatar, it returns avatar, when user has no avatar, it returns facebook's default avatar. Now im working on google-plus and twitter. I found nice url, where i can get avatar from google-plus:
    https://plus.google.com/s2/photos/profile/{oauth_id}?sz=100

I am storing oauth_id in session, it is accessible.
When user has set avatar - everything works fine. Problem is, when users avatar is'nt set - that link returns 404 error.
How can i determine in jquery or just javascript, if that link returns 404 error or not?
And for some future work - i think twitter has the same problem.
Or may be you could provide some better options to achieve this.

A: Another way to do this is to request the plus.me scope, authenticate the user, then retrieve their profile which will have the image value set if they have an avatar. I created a live demo here: http://wheresgus.com/profile.html which shows profile retrieval using the Google+ public data API.
To set things up for your project, go to the Google APIs console - https://code.google.com/apis/console/ and create a project with the Google+ API enabled. You will need the Client ID for a web application from the API Access section of the Google APIs console.
The relevant code is as follows:
<html>
  <head>
    <script src="https://apis.google.com/js/plusone.js"></script>
    <script type="text/javascript">
    function onSignin(e){
      accessToken = e.access_token;
      var xhr = new XMLHttpRequest();
      xhr.open('GET', "https://www.googleapis.com/plus/v1/people/me/");
      xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
      xhr.send();

      xhr.onreadystatechange = function(){
        if (this.readyState == 4){
          var myProfile = JSON.parse(xhr.responseText);
          alert(myProfile.image.url);
        }
      }
    }
    </script>
  </head>
  <body>
    <g:plus action="connect" clientid="YOUR CLIENT ID" scope="https://www.googleapis.com/auth/plus.me" callback="onSignin">
    </g:plus>
  </body>
</html>

Create an HTML file with this code and replace YOUR CLIENT ID with the credentials you created in the Google APIs console.  When you click the sign in button, the client will give you a URL for the user.

A: If you are using the jquery.ajax() or jquery.get() method (or something similar), you should be able to check the jqXHR object that is returned as part of the callback. It has a "status" field which contains the status code for the HTTP call.
See the section The jqXHR Object under http://api.jquery.com/jQuery.ajax/

A: I tried to fiddle around with the above suggestions but found the following approach suitable. I used jquery get to fetch the image url. Following is the code snippet.
function getImageURL(_gplusid) {
                $.get("https://www.googleapis.com/plus/v1/people/"+_gplusid+"?fields=image"+"&key="+googlepluskey,
                function (data) {
                    console.log(data);
                });
        }

P.S : _gplusid is the google plus id of the user and googlepluskey is your google authentication key. The output is a json object containing the image url. You need to enable google plus api access via google api console.


text:
Q: CSS translate button on sibling hover I'm trying to create a stack of buttons that will slide out from underneath the top hovered button, but it's not working in my Codepen (http://codepen.io/dmoz/pen/xIsfL).
Here's the code:
HTML
<button class="one"></button>
<button class="two"></button>
<button class="three"></button>
<button class="four"></button>
<button class="five">^</button>

CSS
button {
  margin: 0;
  font-size: 12px;
  padding: 0;
  border: 0 none;
  cursor: pointer;
  color: #fff;
  width: 60px;
  height: 60px;
  display: block;
  text-transform: none;
  border-radius: 0;
  background-color: #0078E7;
  background-image: none;
  box-shadow: none;
  position: absolute;
  overflow: visible;
}
.one {
  background-color: #3b5997;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.two {
  background-color: #ba0f16;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.three {
  background-color: #d64937;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.four {
  background-color: #0073b2;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.five {
  background-color: #ffffff;
  border: 1px solid #888888;
  color: #888888;
  left: 10;
}
.five:hover ~ .one {
  left: 70px;
}
.five:hover ~ .two {
  left: 130px;
}
.five:hover ~ .three {
  left: 190px;
}
.five:hover ~ .four {
  left: 250px;
}

Anyone see why it's not working?

A: The CSS3 selector ~ only works for siblings that come AFTER the first element, regardless of how many siblings are between. The CSS2.1 selector + works only on the immediate NEXT element. Thus your code won't work since .five is the last element. There is no selector for previous siblings.
If you move the fifth button before the others and add z-index to it, it will work, see http://codepen.io/anon/pen/kEjwe
UPDATE: As requested, the CodePen example now has a wrapper div rendering the buttons child elements. Thus, the siblings selector is no longer required. This way, the individual buttons can be clicked when the wrapper is hovered.


text:
Q: MySQLDataTruncation: Out of range value for column I am inserting a row using ibatis and a java webapp. The POJO has a field which needs to store a number (like 3.0 or 2.34). I have tried using BigDecimal and Double on the java side. On the MySQL side, I am using a Decimal(5, 5) data type.
When I try to insert a row which has "4" as the value for this numeric field, MySQL and iBatis throw the following exception:
org.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation: encountered SQLException [
--- The error occurred in org/mySQL.xml.
--- The error occurred while applying a result map.
--- Check the mySQL.insertQuery.
--- The error happened while setting a property on the result object.
--- Cause: java.lang.RuntimeException: org.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation: encountered SQLException [
--- The error occurred while applying a parameter map.
--- Check the insertQuery-InlineParameterMap.
--- Check the statement (update failed).
--- Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Out of range value for column 'numericColumn' at row 316]; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException:
    at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithCallback(GeneralStatement.java:188)
    at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithRowHandler(GeneralStatement.java:133)
    at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryWithRowHandler(SqlMapExecutorDelegate.java:649)
    at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.queryWithRowHandler(SqlMapSessionImpl.java:156)
    at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.queryWithRowHandler(SqlMapClientImpl.java:133)
    at org.springframework.orm.ibatis.SqlMapClientTemplate$5.doInSqlMapClient(SqlMapClientTemplate.java:267)
    at org.springframework.orm.ibatis.SqlMapClientTemplate.execute(SqlMapClientTemplate.java:165)
    at org.springframework.orm.ibatis.SqlMapClientTemplate.queryWithRowHandler(SqlMapClientTemplate.java:265)
    at org.myClass(myClass.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:248)
    at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:165)
    at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:191)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:516)

Am I using the wrong java data type for the value to be inserted? If not, why won't MySQL let me insert the value?

A: You appear to have misunderstood how defining a DECIMAL (or potentially NUMERIC) column works in SQL -
Specifically, when defining the column as DECIMAL(x, y), x is the total number of digits the column will store, and y is the number of digits after the decimal point.  So, in your column definition, you specified a range of -1 < column < 1.  The datatype is correct, but you're attempting to specify a value outside the range the column was told to allow.
Fortunately, the fix is simple: change the column definition.  I'm assuming you want to have up to 5 digits before the decimal point, which would make the column definition DECIMAL(10, 5).


text: Q: How were the Potters so rich? It seems that Harry's parents left him a pretty sizable fortune. They were pretty young when they had Harry and when they died. I dont remember much talk about their professions. How did they manage to amass such a fortune at such a young age?


text:
Q: Unable to connect to Socket Server running on VPS! I Could need some help here...
I'm running a java socket server on a 64bit Linux VPS and listening on a port 5555 however my clients aren't able to connect to that port.
When I run a netstat -anp on the server it gives me local address of  ::ffff:127.0.0.1:5555and foreign address of :::* and the state is LISTEN.
Is the ::ffff:in the local address part causing the problem?

A: That address is your localhost interface, not an external interface. I assume your clients are connecting from "outside" the server, correct? If so, you'll need to set your java app to listen on whatever IP address is assigned to an outward-facing interface.


text:
Q: Symbolic series Mathematica realises, of course, how to deal with symbolic series:
Sum[g[x]^k, {k, 0, ∞}]
(*Out: 1/(1 - g[x]) *)

I.e. it does not worry about values of g[x] around 1. Next, when I write (don't ask me why I need this :-)) something like
Sum[Sum[Product[g[y], {y, xi}], {xi, {Table[x, k]}}], {k, 0, 10}]

I get the correct answer
1 + g[x] + g[x]^2 + g[x]^3 + g[x]^4 + g[x]^5 + g[x]^6 + g[x]^7 + g[x]^8 + g[x]^9 + g[x]^10

However,
Sum[Sum[Product[g[y], {y, xi}], {xi, {Table[x, k]}}], {k, 0, ∞}]

leads to the error

During evaluation of In[3]:= Table::iterb: Iterator {k} does not have appropriate bounds.

The same will happen if I write, say,
Limit[Sum[Sum[Product[g[y], {y, xi}], {xi, {Table[x, k]}}], {k, 0, r}], r -> ∞]

Is it possible to ask Mathematica to compute Sum with such 'variable' upper limit?


text:
Q: onCreate got invoked onClick of the imageview in android I have ScreenRecorder activity invoking RecorderService. RecorderService setting floating view with imageview. when i onclick on image view ScreenRecorder oncreate got called not able to invoke onclick action. But OnTouchListener working fine
      <ImageView
    android:id="@+id/sr_float_home"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_marginTop="8dp"
    android:src="@drawable/recorder"
    android:onClick="startRecord"
    tools:ignore="ContentDescription"/>

ScreenRecorder activity
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate " );
     mProjectionManager = (MediaProjectionManager)
            getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
    } else {
        recordeScreen();
    }
    Log.d(TAG,"onCreate end");
}
private void recordeScreen() {
    Log.d(TAG, "recordeScreen open " );
    if (mMediaProjection == null) {
        startService(new Intent(ScreenRecorder.this, RecorderService.class));
        finish();
        return;
    }
    Log.d(TAG, "recordeScreen open end " );
}

 public void startRecord(){
 Log.d(TAG, "startRecord start " );
 startActivityForResult(mProjectionManager.createScreenCaptureIntent(),
         PERMISSION_CODE_SR);
 Log.d(TAG, "startRecord end " );
 finish();
 return;}

RecorderService
    @Override
public void onCreate() {
    super.onCreate();
    mChatHeadView = LayoutInflater.from(this).inflate(R.layout.activity_screen_recorder, null);
    mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    mWindowManager.addView(mChatHeadView, params);
    final ImageView srFloatHome = (ImageView)
    mChatHeadView.findViewById(R.id.sr_float_home);
    srFloatHome.setOnTouchListener(new View.OnTouchListener() {
         @Override
        public boolean onTouch(View v, MotionEvent event) {
        }
        }
        }

i have also tried placing startRecord method like ontouch , but still not working. can someone please tell me why onclick call not received insteated it calling activity oncreate.

A: Seems like you're missing the parameter on your startRecord function. From Android documentation:

public static final int onClick
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity)

A: Maybe your code less a property in xml.
android:clickable="true"

if you want ImageView have the clicked method ,should add this,
this is demo code .xml:
<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="200dp"
    android:background="@android:color/background_dark"
    android:onClick="StartDoSomething"
    android:clickable="true"/>

and in .java is
public void ButtonClick(View v){
    System.out.println("Do something here!");
}

hope to help you.

A: I have used layout root element and used below code i am able to get onclick in recorderervices
 mChatHeadView.findViewById(R.id.sr_float_home);

form
    final View srFloatHome =  mChatHeadView.findViewById(R.id.sr_head_root);

    srFloatHome.setOnClickListener(this);

my onclick method in RecorderService
 public void startRecord(View v){}


text:
Q: Finding counterexample for topology question (NBHM 2017)
Which of the following statements are true? (NBHM 2017)

$a.$ Let $X$ be a set equipped with two topologies $\mathcal{T}_1$ and $\mathcal{T}_2$. Assume that any
given sequence in $X$ converges with respect to the topology $\mathcal{T}_1$ if, and only
if, it also converges with respect to the topology $\mathcal{T}_2$. Then $\mathcal{T}_1$ = $\mathcal{T}_2$.
$b.$ Let ($X$; $\mathcal{T}_1$) and ($Y$; $\mathcal{T}_2$) be two topological spaces and let $f$ : $X \to Y$ be a
given map. Then $f$ is continuous if, and only if, given any sequence {$x_n$}n$\epsilon_\Bbb{N}$
such that $x_n \to x$ in X, we have $f(x_n) \to f(x)$ in $Y$ .
$c.$ Let ($X$; $\mathcal{T}$) be a compact topological space and let {$x_n$}n$\epsilon_\Bbb{N}$ be a sequence
in $X$. Then, it has a convergent subsequence.

Answer: all of them are false.

I came up with counterexamples for ($b$) and ($c$), but I'm unable to find one for ($a$).
For ($b$) I assumed, $X=Y$ and $\mathcal{T}_1$ as discrete topology and $\mathcal{T}_2$ as indiscrete topology, and $f$ :$X\to$$Y$ as identity map.
Now because of topological properties of discrete and indiscrete topologies, $f$ is continuous. If we assume constant sequence in $X$ ( which converges). then its image under $f$ in $Y$ will be a constant sequence, but the constant sequence does not converge in indiscrete topology. Hence $(b)$ is false.
For $(c)$ assuming ($X$; $\mathcal{T}$) as indiscrete topology (Indiscrete topology is compact for any space $X$)  and {$x_n$}n$\epsilon_\Bbb{N}$ be constant sequence, whose any subsequence will be a contant sequence, and again we know that constant sequence does not converge in indiscrete topology. Hence $(c)$ is also false.
But I'm unable to find counterexample for $(a)$
Please help. Thanks in advance.
EDIT: As suggested by David Hartley, in indiscrete topology every sequence converges to each point of the space, my arguments for $(b)$ and $(c)$ will no longer hold true, so I'm also requesting for the counterexamples for ($b$) and ($c$). ( I'm also trying to find out)

A: Hint In the countable complement topology on an infinite set, a sequence is convergent if and only if it is eventually constant. The same is true about discrete.
Note that this gives counterexamples for (a) and (b)


text:
Q: Jest :No test found I am trying to have some integration tests on my project using npm test and my directory is like this:
Main_directory==>tests==>integration==>auth.test.js and bar.test.js
On my package.json, I've got this:
"scripts": {
    "test": "jest --watchAll --verbose"
  },

when I execute the code npm test , I run into this mind-boggling error on terminal:
No tests found

In G:\main_directory
  35 files checked.
  testMatch: **/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x) - 5 matches
  testPathIgnorePatterns: \\node_modules\\ - 35 matches
Pattern:  - 0 matches

Do you have any idea on how to bring everything back to normal and run some smooth integration tests?

A: You are matching for the folder __tests__ but you said that your tests are in the test folder. So either change the folder name where the tests are to __test__ or change the name in your jest config.


text:
Q: Semantic differences between commenting and answering According to the rules and various statements, comments are for clarification, while answers are...well...answers.
However, in various questions, I have seen answers given directly in comments. Sometimes, these answers are long, and sometimes they are short. I have also seen short answers as answers, so there is definitely a situational difference.
I looked into this thread, but I still do not understand the semantic difference between the two. Anyone can explain this?

A: I've seen this many times, especially on Meta.
(You'll have to trust me with this assertion, because I'm not going to go and trawl for examples or name names...) Usually these answers are left by high rep individuals. They are interested in helping someone but due to circumstances, i.e.:

*

*not looking for (more meaningless) rep

*too busy

*don't expect the question to survive

*haven't got time to dig out supporting references that a good answer should have

*haven't got the time (or inclination) to select the appropriate duplicate (from potentially 100's) in order to close the question

they tender the answer as a comment.
Are they throw-away answers? Not really, they are still perfectly valid and correct.
Do we want to encourage this habit? Probably not, but nor should we stomp on it.

A: I think it depends on the site, but on non-meta sites, I think "answers" as comments come in 2 different flavors.

*

*Question that should be closed but someone wants to help out the OP before or after the question gets closed

*I don't know the answer and just have a guess, so I leave it as a comment instead.

For meta sites, it is usually just a short answer or link and not worth a full answer.

A: The main reason for me is because I don't want to be downvoted for feeding a help vampire. However, if you're referring to [meta] as well, it's probably because people don't understand that saying "-1 ..." in a comment could easily well be an a swer explaining why they don't want the proposal to succed.
Look at FEichinger's comment. That could very wel be an answer here IMHO.


text:
Q: XGboost gives me 100% prediction accuracy, for my binary classification problem. How can I solve it? XGBoost gives me 100% prediction accuracy, for a binary classification problem. This seems too good to be true. How can i solve it?
I am using a normalized dataset (max-min or z-score), already split it as training and validation set, and I am using training set values in order to predict the validation set. In both subsets, data is very alike obviously, but there is nothing i can do about it. I also avoid look-forward bias. What else can be the possible reason for 100% accuracy and how can i solve it? Thank you very much!
My code is:
train_x=data.matrix(tmp[,-40])
train_y=tmp[,40]
test_x=data.matrix(tmp2[,-40])
test_y=tmp2[,40]
test_y=as.factor(test_y)

xgb_train = xgb.DMatrix(data=train_x, label=train_y)
xgb_test = xgb.DMatrix(data=test_x, label=test_y)

set.seed(12345)
xgbc=xgboost(data=xgb_train, max.depth=4, nrounds=200)
print(xgbc)

preds=predict(xgbc,test_x)
preds[preds>0.5] = "1"
pred_y = as.factor(test_y)
print(pred_y)

cm = confusionMatrix(test_y, pred_y)
print(cm)

Code output is:
> xgbc=xgboost(data=xgb_train,max.depth=4, nrounds=200, nthread=2, eta=1,
objective="binary:logistic")
[1] train-error:0.415888
[2] train-error:0.390654
[3] train-error:0.368692
[4] train-error:0.323832
[5] train-error:0.307944
[6] train-error:0.278037
[7] train-error:0.259346
[8] train-error:0.240187
[9] train-error:0.232710
[10]    train-error:0.224766
[11]    train-error:0.208879
[12]    train-error:0.192523
[13]    train-error:0.185981
[14]    train-error:0.177103
[15]    train-error:0.168224
[16]    train-error:0.157944
[17]    train-error:0.141121
[18]    train-error:0.132243
[19]    train-error:0.132243
[20]    train-error:0.121495
[21]    train-error:0.109346
[22]    train-error:0.101869
[23]    train-error:0.100000
[24]    train-error:0.090654
[25]    train-error:0.080374
[26]    train-error:0.078505
[27]    train-error:0.069626
[28]    train-error:0.063084
[29]    train-error:0.066822
[30]    train-error:0.056542
[31]    train-error:0.044860
[32]    train-error:0.042991
[33]    train-error:0.039252
[34]    train-error:0.037383
[35]    train-error:0.029439
[36]    train-error:0.023832
[37]    train-error:0.018692
[38]    train-error:0.011682
[39]    train-error:0.011215
[40]    train-error:0.010748
[41]    train-error:0.009346
[42]    train-error:0.007477
[43]    train-error:0.005140
[44]    train-error:0.005140
[45]    train-error:0.006075
[46]    train-error:0.003271
[47]    train-error:0.002804
[48]    train-error:0.003271
[49]    train-error:0.002804
[50]    train-error:0.002804
[51]    train-error:0.002336
[52]    train-error:0.002336
[53]    train-error:0.002336
[54]    train-error:0.002336
[55]    train-error:0.000935
[56]    train-error:0.000467
[57]    train-error:0.000000
[58]    train-error:0.000000
[59]    train-error:0.000000
[60]    train-error:0.000935
[61]    train-error:0.000467
[62]    train-error:0.000000
[63]    train-error:0.000000
[64]    train-error:0.000000
[65]    train-error:0.000000
[66]    train-error:0.000000
[67]    train-error:0.000000
[68]    train-error:0.000000
[69]    train-error:0.000000
[70]    train-error:0.000000
[71]    train-error:0.000000
[72]    train-error:0.000000
[73]    train-error:0.000000
[74]    train-error:0.000000
[75]    train-error:0.000000
[76]    train-error:0.000000
[77]    train-error:0.000000
[78]    train-error:0.000000
[79]    train-error:0.000000
[80]    train-error:0.000000
[81]    train-error:0.000000
[82]    train-error:0.000000
[83]    train-error:0.000000
[84]    train-error:0.000000
[85]    train-error:0.000000
[86]    train-error:0.000000
[87]    train-error:0.000000
[88]    train-error:0.000000
[89]    train-error:0.000000
[90]    train-error:0.000000
[91]    train-error:0.000000
[92]    train-error:0.000000
[93]    train-error:0.000000
[94]    train-error:0.000000
[95]    train-error:0.000000
[96]    train-error:0.000000
[97]    train-error:0.000000
[98]    train-error:0.000000
[99]    train-error:0.000000
[100]   train-error:0.000000

> print(xgbc)
##### xgb.Booster
raw: 186.6 Kb
call:
xgb.train(params = params, data = dtrain, nrounds = nrounds,
watchlist = watchlist, verbose = verbose, print_every_n = print_every_n,
early_stopping_rounds = early_stopping_rounds, maximize = maximize,
save_period = save_period, save_name = save_name, xgb_model = xgb_model,
callbacks = callbacks, max.depth = 4, nthread = 2, eta = 1,
objective = "binary:logistic")
params (as set within xgb.train):
max_depth = "4", nthread = "2", eta = "1", objective = "binary:logistic",
silent = "1"
xgb.attributes:
niter
callbacks:
cb.print.evaluation(period = print_every_n)
cb.evaluation.log()
# of features: 38
niter: 200
nfeatures : 38
evaluation_log:
iter train_error
   1    0.415888
   2    0.390654
---
 199    0.000000
 200    0.000000

preds=predict(xgbc,test_x)
> preds
[1] 7.273692e-01 1.643806e-02 3.032141e-04 9.764441e-01 9.691942e-02
5.343258e-01 9.090783e-01
[8] 5.609832e-01 4.061035e-01 1.105066e-01 4.406907e-03 9.946358e-01
7.929156e-01 4.119191e-03
[15] 3.098451e-01 2.945659e-04 3.966548e-03 7.829595e-01 1.698021e-01
9.574184e-01 7.132806e-01
[22] 1.044374e-01 9.024003e-01 5.769060e-01 5.096554e-02 1.751429e-01
9.982671e-01 9.993696e-01
[29] 6.521277e-01 5.780852e-03 4.867651e-01 9.707865e-01 8.398834e-01
1.825542e-01 1.134274e-01
[36] 7.154977e-02 5.450470e-01 1.047506e-01 3.099218e-03 2.268739e-01
9.023346e-01 8.026977e-01
[43] 3.844074e-01 4.463347e-01 8.543612e-01 9.998935e-01 8.699111e-01
6.243381e-02 1.137973e-01
[50] 9.385086e-01 9.994442e-01 8.376440e-01 8.492180e-01 3.362629e-04
4.316351e-02 9.234415e-01
[57] 8.924388e-01 9.977444e-01 6.618840e-02 2.186051e-04 1.647688e-03
8.050095e-03 6.535615e-01
[64] 4.707330e-01 9.138927e-01 5.177013e-02 3.349773e-04 9.392425e-01
4.979803e-02 2.934091e-01
[71] 8.948106e-01 9.854530e-01 9.795361e-02 9.275551e-01 5.865968e-01
9.746857e-01 3.859183e-01
[78] 1.194406e-01 3.267710e-01 6.294726e-01 9.250816e-01 6.118813e-02
3.394562e-01 7.257250e-04
[85] 8.491386e-01 7.081388e-03 3.268852e-01 8.931246e-01 2.204458e-01
8.818560e-01 9.923303e-01
[92] 9.845840e-01 7.688413e-01 9.803721e-01 9.958567e-01 9.500723e-01
7.733757e-01 9.368727e-01
[99] 3.276393e-01 9.952766e-01 2.130413e-01 8.992375e-02 8.594028e-02
8.160641e-01 9.915828e-01

> preds[preds>0.5] = "1"
> preds[preds<=0.5]= "0"
> pred_y = as.factor(test_y)
> print(pred_y)
[1] 1 1 0 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 1 1
1 0 1 1 1 0 1 0 1 1 1 1 0 0
[51] 1 1 0 1 0 1 1 0 1 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 1 1
1 1 0 0 1 0 0 0 1 1 1 1 0 1

> test_y=as.factor(test_y)
> cm = confusionMatrix(test_y, pred_y)
> print(cm)
Confusion Matrix and Statistics

      Reference

Prediction   0   1
         0 421   0
         1   0 497
           Accuracy : 1
             95% CI : (0.996, 1)
No Information Rate : 0.5414
P-Value [Acc > NIR] : < 2.2e-16

              Kappa : 1

Mcnemar's Test P-Value : NA
        Sensitivity : 1.0000
        Specificity : 1.0000
     Pos Pred Value : 1.0000
     Neg Pred Value : 1.0000
         Prevalence : 0.4586
     Detection Rate : 0.4586

Detection Prevalence : 0.4586
      Balanced Accuracy : 1.0000
   'Positive' Class : 0

A: It seems like you're seriously overfitting to your training data, and you should use cross validation instead of just a naive train-test split. There are a number of ways to do this. You can do it with xgb.cv inside of the xgboost package in R, for one. I prefer Tidymodels, but that's a different rabbit hole. My guess is that if you tune a parameter like gamma, you'll end up with non-zero loss because the gamma > 0 will help prevent overfitting by pruning your trees. You can also help prevent overfitting by growing fewer, shallower trees, subsampling features, etc. All of these options can be tuned with xgb.cv

A: Try checking the correlation of the predictor variables with the output. Try removing variables with high correlation because it introduces high bias. This solved my issue with 100% accuracy.