text:
Q: Why is the Gaussian-Legendre Quadrature so effective? I understand how it works, how its derived, etc. The proof of it has been shown to me. That is to say, I know how Legendre polynomials are derived, I know they are orthogonal, I know we sample a function at the roots of the polynomial, I know how the weights are calculated, and I see that it is basically a Riemann sum in that we are approximating the area with rectangles.
But the Riemann left sum, midpoint, right sum, simpsons rule, etc., have all been shown to me too. But they are not as impressive. What I dont understand is what makes the G-L Q so effective.  Where does it derive its stellar accuracy? And why should it be so accurate anyway?  The derivation is an interesting proof of concept that a numeric approximation can be done this way and is interesting in its own right... but to see that it is drastically so much more accurate than a Riemann sum is a completely different matter.
I dont see why the orthogonality of the Legendre polynomials is so important and how it plays such a key role in the accuracy.  I dont see why we choose the roots of the polynomials as the sampling points of a function, as opposed to any other set of points with appropriate weights derived.  Is the norm used in deriving the Legendre polynomials unique or can other norms and polynomials prove equally (or more) effective? Does the G-L Q work by approximating an arbitrary function by a polynomial? And if so, wouldnt we get more accuracy making those polynomials generic rather than by restricting them to linear combinations of Legendre?

A: I find it natural. We approximate an integral of function $f(x)$ over interval $[-1,1]$:
\begin{align}
\int_{-1}^1f(x)\,\text{d}x\approx\sum_{i=1}^nw_if(x_i),~~~~~~~(1)
\end{align}
where $x_i,~i=1,\dots,n$ are points and $w_i,~i=1,\dots,n$ are weights. Other quadrature rules (Newton-Cottes quadrature, Clenshaw-Curtis quadrature etc.) see Eq.(1) as an optimization problem
\begin{align}
\min_{w_1,\dots,w_n}\left[\max_{f(x) \in \left\{1,x,\dots,x^{2n-1}\right\}}\Bigg(\int_{-1}^1f(x)\,\text{d}x-\sum_{i=1}^nw_if(x_i)\Bigg)^2\right],
\end{align}
where $x_i$ are given and only $w_i$ are free. The Gauss quadrature sees Eq.(1) as an optimization problem, where both $x_i$ and $w_i$ are free:
\begin{align}
\min_{x_1,\dots,x_n,~w_1,\dots,w_n}\left[\max_{f(x) \in \left\{1,x,\dots,x^{2n-1}\right\}}\Bigg(\int_{-1}^1f(x)\,\text{d}x-\sum_{i=1}^nw_if(x_i)\Bigg)^2\right],
\end{align}
so you can find in general a better optimum (=satisfy Eq.(1) for more polynomials exactly). The fact, that $x_i$ are root's of the Legendre polynomial, can be seen as an interesting coincidence.

A: There is a key estimate which is commonly used in the analysis of quadrature rules for relatively nice functions:
$$|I(f)-Q(f)| \leq |I(f)-I(p)| + |I(p)-Q(p)| + |Q(p)-Q(f)|$$
where $I$ is the exact integral, $Q$ is the quadrature rule, $f$ is your integrand of interest, and $p$ can be any reasonable function, but for this bound to be useful it should be close to $f$ in some suitable sense. Generally we consider the case where $p$ is some polynomial.
Now on a bounded domain with an integrable weight function, Weierstrass's theorem lets you make the first term small as long as you're allowed to choose $p$ to be a polynomial with a large degree. If $Q$ is exact for polynomials of degree all the way up to the degree of $p$, then the second term is just zero. Thus many different rules behave nicely in the first two terms.
If you proceed this way, then the issue is the third term. In general, you can do this computation:
$$|Q(p)-Q(f)|=|Q(p-f)|=\left | \sum_{i=1}^n w_i (p(x_i)-f(x_i)) \right | \leq \left ( \max_i |p(x_i)-f(x_i)| \right ) \sum_{i=1}^n |w_i|.$$
Again Weierstrass's theorem lets you make that maximum as small as you want. But what about the sum? In general there is no reason to expect that sum to be bounded. But it is bounded if the weights have all the same sign, because $I(1)=Q(1)=\sum_{i=1}^n w_i$. For Gauss quadrature these weights are in fact positive, as you can show by noting that
$$0<I \left ( \prod_{j \neq i} (x-x_j)^2 \right ) = Q \left ( \prod_{j \neq i} (x-x_j)^2 \right )=w_i \prod_{j \neq i} (x_i-x_j)^2$$
which is because these polynomials all have degree $2n-2$, are everywhere nonnegative, and vanish at all but one of the nodes.
Note that from this point of view, the theory of orthogonal polynomials doesn't really come into play; the good behavior of Gauss quadrature is driven solely by its exactness behavior. Orthogonal polynomials only really come into play when you ask for the nodes.
There is a subtlety that I glossed over. What if you have some other method and instead of using Weierstrass's theorem to select $p$ so that the first term is small, you select $p$ to just interpolate $f$, so that the third term is zero? In this case the second term can again be made to be zero. But does the first term necessarily go to zero? The answer is no, which is closely related to Runge's phenomenon, which you can read more about on Wikipedia.


text:
Q: How to Interactive Sort by Calculated Columns in SSRS 2008 I have a calculate field Total Pts which is the sum of the values of report items
=ReportItems!Textbox28.Value + ReportItems!Textbox30.Value + ReportItems!Textbox32.Value
Now I want to put a interactive sort here and I am not able to do so . Any ideas? I can't do it in  a query because the reportitems that I am adding are from a two different datasets which are of diff. types eg: sql server & sharepoint

A: There should be no issue with doing this because SSRS allows you to use an expression to determine the sort order. Just right click on your header textbox for the column and go to the interactive sort tab. Here you can turn interactive sort on, then in the sort by field click the function icon next to the drop down. Use the same expression that you used for your calculated field, and it will sort according to the results of this expression. If there is some reason you can't do this that I'm missing, let me know and I'll try to help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node with Google Spreadsheet shows error when the node application runs When I run the node application it shows the following logs in a terminal,
(node:6929) UnhandledPromiseRejectionWarning: Error: HTTP error 400 (Bad Request) - <!DOCTYPE html><meta name="description" content="Web word processing, spreadsheets and presentations"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"><link rel="shortcut icon" href="//ssl.gstatic.com/docs/common/drive_favicon1.ico"><title>Page not found</title><link href="//fonts.googleapis.com/css?family=Product+Sans" rel="stylesheet" type="text/css">

Sorry, unable to open the file at present.

 Please check the address and try again.

Get stuff done with Google Drive

Apps in Google Drive make it easy to create, store and share online documents, spreadsheets, presentations and more.

Learn more at drive.google.com/start/apps.

(node:6929) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6929) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My application code is as follows,
const GoogleSpreadsheet = require('google-spreadsheet');
const {promisify} = require('util');

const creds = require('./client_secret.json');

async function accessSpreadsheet(){
    const doc = new GoogleSpreadsheet ('1I-hvqJjO0Gkm0awS38Wz9JhilXV1JyWN');
    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[0];
    console.log(`Title: ${sheet.title}, Rows: ${sheet.rowCount}`);
}

accessSpreadsheet();


text:
Q: Google Python API: httplib2 SSL certificate verify failed on mac OSX (10.8.4) I am trying to use Google Custom Search python API on mac OSX (10.8.4). In particular I am trying to replicate this sample code:
from googleapiclient.discovery import build

def main():
  service = build("customsearch", "v1",
            developerKey="some_key")

  res = service.cse().list(
      q='lectures',
      cx='some_num:some_lfve',
    ).execute()
  pprint.pprint(res)

if __name__ == '__main__':
  main()

However, while calling the build method, I keep getting the following httplib2 SSL error (full traceback):
1 service = build("customsearch", "v1", developerKey="some_key")

anaconda/lib/python2.7/site-packages/oauth2client/util.pyc in positional_wrapper(*args, **kwargs)
    135         else: # IGNORE
    136           pass
--> 137       return wrapped(*args, **kwargs)
    138     return positional_wrapper
    139

anaconda/lib/python2.7/site-packages/googleapiclient/discovery.pyc in build(serviceName, version, http, discoveryServiceUrl, developerKey, model, requestBuilder, credentials)
    194   logger.info('URL being requested: GET %s' % requested_url)
    195
--> 196   resp, content = http.request(requested_url)
    197
    198   if resp.status == 404:

anaconda/lib/python2.7/site-packages/httplib2/__init__.pyc in request(self, uri, method, body, headers, redirections, connection_type)
   1606                     content = ""
   1607                 else:
-> 1608                     (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
   1609         except Exception, e:
   1610             if self.force_exception_to_status_code:

anaconda/lib/python2.7/site-packages/httplib2/__init__.pyc in _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey)
   1348             auth.request(method, request_uri, headers, body)
   1349
-> 1350         (response, content) = self._conn_request(conn, request_uri, method, body, headers)
   1351
   1352         if auth:

anaconda/lib/python2.7/site-packages/httplib2/__init__.pyc in _conn_request(self, conn, request_uri, method, body, headers)
   1270             try:
   1271                 if hasattr(conn, 'sock') and conn.sock is None:
-> 1272                     conn.connect()
   1273                 conn.request(method, request_uri, body, headers)
   1274             except socket.timeout:

anaconda/lib/python2.7/site-packages/httplib2/__init__.pyc in connect(self)
   1057                 # something else (such as SSL protocol mismatch).
   1058                 if e.errno == ssl.SSL_ERROR_SSL:
-> 1059                     raise SSLHandshakeError(e)
   1060                 else:
   1061                     raise

SSLHandshakeError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Any idea how I can fix this certificate issue?


text:
Q: Account dropdown menu on mobile is not showing when logged in It works fine on desktop Site URL https://www.coastdailydeals.net
After logged in on mobil, top right click the button Greg two and a dropdown should show with my account, my favorite deals and sign out buttons.
Been working on it for hours can't figure out why.


text:
Q: Rank an unsorted list of integers in an array in C I'm doing an assignment where I have an array of integers in an unsorted form and my task is to rank each integer according to its value where the largest value will get 1st rank and the smallest values will get n-rank (in an array of 20 integers the lowest value will have rank 20). I cannot use 2D arrays as we haven't learned them yet. So I can only use <stdio.h> library. I'm struggling to write an algorithm that will solve the problem.
I'm not asking for a solution here so please don't post a code but rather some hints on how to build the algorithm or how to think here. Thank you in advance for any ideas and suggestions!

A: Start by setting the rank to zero. To find the rank of th i'th element you can iterate all element of the array. If an element is greater than the i'th element, increment the rank. If an element is equal to the i'th element, increment rank if-and-only-if that element is before the i'th element.
Here is some pseudo code to find the rank of the i'th element
* i = "index of element to rank"
* j = 0
* rank = 0
* while j < array-size do:
      * if array[j] > array[i] do: rank = rank + 1
      * if array[j] == array[i] and j < i do: rank = rank + 1
      * j = j + 1
* print rank

A: So this is part of the code with 2 x for loops where I go through an array of results and compare each result with all other results and then calculate how many values are less than or equal to the value. I do this for each value. Then I record number of points for each value in another array and the highest points go the lowest value. Thank you everybody for your inputs! Apologies I couldn't post complete question as it would have been bad praxis.
> for(l=0; l<no_students; l++){
>         points=0;
>         for(i=0; i<no_students; i++){
>             if(array[l]<=array[i]){
>                 points++;
>             }
>             rank[l]=points;
>         }
>                     j++;
>     }


text:
Q: I am using https://github.com/scaperot/the-BPM-detector-python/blob/master/bpm_detection/bpm_detection.py, how to input the audio file? I'm using the following code to get the BPMS of a WAV file, but how do i input the audio file?
I tried to run
    bpm_detection.py --filename

but got IO error
The main function is as follows:
    if __name__ == '__main__':
        parser = argparse.ArgumentParser(description='Process .wav file to
    determine the Beats Per Minute.')
        parser.add_argument('--filename', required=True,
               help='.wav file for processing')
        parser.add_argument('--window', type=float, default=3,
               help='size of the the window (seconds) that will be scanned to determine the bpm.  Typically less than 10 seconds. [3]')

        args = parser.parse_args()
        samps,fs = read_wav(args.filename)

A: use
python file.py --filename file.wav

or
python file.py --filename C:\path\path\test.wav

or
python file.py --filename C:\\path\\path\\test.wav

or
python file.py --filename ./test.wav


text:
Q: Can't update Konva rect I built a grid of rectangles and cached them by calling group.children.cache();
After that on mousemove i have set
rect.fillPatternOffsetX(Math.max(newScaleWidth, 0));
rect.fillPatternOffsetY(Math.max(newScaleHeight, 0));

and I have called
layer.draw().
without calling group.clearCache() I can't see updates.
it's the right way to update Rect?
with clearCache() it works on Chrome and Safari, but on Firefox on Mac I have a lot of performance problems.
can someone help me?

A: this when i create the rects
  const rect = new Konva.Rect({
      x: coor.x * this.widthObject,
      y: coor.y * this.heightObject,
      width: this.widthObject,
      height: this.heightObject,
      fillPatternImage: imageObj,
      fillPatternOffsetX: this.scaleWidth,
      fillPatternOffsetY: this.scaleHeight,
      fillPatternScale: {
        x: this.patternScaleX,
        y: this.patternScaleY,
      },
      trick,
  });

    rect.on('click tap', this.handleClickRect);

    this.group.add(rect);

    this.layer.add(this.group);
    this.stage.add(this.layer);
    this.group.children.cache();

on mouse move
   rects.map((rect) => {
      rect.fillPatternScaleX(Math.min(
        this.patternScaleX,
        this.ratioImageWidthOnRect + incrementScaleRectsX,
      ));
      rect.fillPatternScaleY(Math.min(
        this.patternScaleY,
        this.ratioImageHeightOnRect + incrementScaleRectsY,
      ));
      rect.fillPatternOffsetX(Math.max(newScaleWidth, 0));
      rect.fillPatternOffsetY(Math.max(newScaleHeight, 0));
      return rect;
  });

  // this.group.children.clearCache()
  this.layer.draw();


text:
Q: MobaXterm ssh keeps getting disconnected although "SSH keepalive" is set Environment:
Ubuntu 18.04 / MobaXterm personal edition v20.2 build 4296
While connecting with ssh, even though I submitted jobs with nohup and let it work in background, it always gives me "Network error: Software caused connection abort".
Is there any other setup that helps prevent this kind of situation?
My network is unstable. Even though I did not put my laptop to sleep. Usually it just disconnected so my jobs are terminated.


text:
Q: How to make sure a string is in the correct format I need to make sure the inputed string is in the correct format. It must be in the format:
'#### #### #### ####' like a credit card number. How do I make sure my code will not accept something like '1234 5678 12345678' but accept '1234 5678 1234 5678'. I am not sure how to go about this. I have tried using the the len function, but that would accept anything with a len of 19, no matter how it is formatted. My guess is I would need to break it up into 4 strings and make sure they are all 4 characters long, but I don't know how to do that, or even if that is the correct way to go about it.

A: s='1234 5678 1234 5678'

all([len(x) == 4 for x in s.split()])
True

s='1234 5678 12345678'
all([len(x) == 4 for x in s.split()])
False

To check all are also numeric:
s='1234 5678 1234 t578'
   all([len(x) == 4 and x.isdigit() for x in s.split()])
   False

Using split, splits the string at the whitespace.
So if s = '1234 5678 1234 5678'
using list comprehension [x for x in s.split()] where x.split() creates a list ['1234', '5678', '1234', '5578'].
Checking all([len(x) == 4 for x in s.split()]) makes sure all   elements  are four characters long and x.isdigit() makes sure they are numbers.
You could have an initial check like if len(s.split())==4 as there have to be four elements in the list to match your needed input. So even if a user added input like "1234 5678 1234" you would catch that error also.
s='1234 5678 1234 5568'
if len(s.split())==4 and all([len(x) == 4 and x.isdigit() for x in s.split()]):
    print "all good"
all good

A: Use regular expression:
import re
p=re.compile('[0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4}')

p.match('1234 5678 1234 5678')

should return a match object, whereas
p.match('ABCD EFGH IJKL MNOP') will return None

A: Try using the re library (regex). There is a good starter in this book (as well as tons of other good stuff).
import re

pattern = re.compile(r'''
    ^          # match the beginning of the string
    (\d{4})    # match a group of 4 numbers and remember that group
    \D*        # optional separator of any number of non-digit characters
    (\d{4})    # match second group of 4 numbers
    \D*
    (\d{4})    # third group
    \D*
    (\d{4})    # fourth group
    $          # end of string
    ''', re.VERBOSE)

pattern.search(input_string).groups()    # returns the saved groups of 4 digits each in a list
pattern.match(input_string) is not None  # returns true or false (match or no match)

Note that this solution only matches four groups of four numbers each. This means that entries like '1234 5678 1234 5678' will get parsed into a list like ('1234', '5678', '1234', '5678'), and so will entries like '1234567812345678', or even '1234 regex = cool 56781234 wewt regex 5678'. There is some flexibility there. Note that the ^ at the beginning and the $ at the end mean that the beginning of the string has to lie right before the first number group and the end must be right after the last one for it to match. You could make it more flexible by omitting these.
For an exact match on only what you want, try pattern = re.compile(r'^(\d{4}) (\d{4}) (\d{4}) (\d{4})$') instead.
And if you do not care about returning the numbers in a list, just whether the input string matches your format, then @caoy has it right, leave out the parenthesis (they store the match as a group), and use the pattern.match(string) command.
EDIT: udpated the verbose regex to include separators. Previously it failed if there were spaces or anything else between the groups of digits. Now the first pattern is very general, and the last pattern is very specific.
EDIT 2: added just checking whether a string matches the pattern.


text:
Q: I'm stuck on my assignment, can I get some feedback? java /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;
 import java.io.*;
/**
 *
 * @author simon
 */
public class Main {

    /**
     * @param args the command line arguments
     */
       public static void main(String[] args) throws IOException {
            NotSimple[] objArray;
               BufferedReader stdin = new BufferedReader(
                                   new InputStreamReader( System.in ) );
            System.out.println( "Enter a number of objects:" );

            int size;
            size = Integer.parseInt( stdin.readLine() );

            //Initialize objArray
            objArray = new NotSimple[size];

            //TODO: Implement following functions

            initializeObj(objArray);
            increaseData(objArray);
            printObjData(objArray);

            //TODO: Explain all outputs of the below function
            explainOutputs();
            return;

                                                                 }

      //TODO
      //initialize every Notsimple object in the array 'a'
      //to NotSimple()
      //Hint: using the for loop, assign a[i] = new NotSimple();
      static void   initializeObj(NotSimple[] a){
      //TODO: FILL ME

          for (int i = 0; i < a.length; i++)
          {
          a[i] = new NotSimple();
          }

  }

  //TODO:
  //Increase the 'data' member of every NotSimple object
  //in the array 'a' by 1
  static void increaseData(NotSimple[] a) {
       //TODO: FILL ME

      for (int i = 0; i < a.length; i++)
      {
           a[i].setData(a[i].getData()+1);

      }

  }

  //TODO:
  //Print the data of every NotSimple object in the array 'a'
  static void printObjData(NotSimple[] a) {
       //TODO: FILL ME
       for (int i = 0; i < a.length; i++)
          {
          System.out.println (a[i].getData());
          }

  }

  //TODO explain all the outputs 1a-1f
  static void explainOutputs() {
    NotSimple nsObj1 = new NotSimple();
    //1a
    System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
    System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );

    NotSimple nsObj2 = new NotSimple( 50,
                         "Another immutable string!" );
    //1b
    System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
    System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );

    nsObj2 = nsObj1;

    nsObj2.setData(10);
    nsObj1.setData(100);
    //1c
    System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
    System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );

    nsObj1 = new NotSimple();
    //1d
    System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
    System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
    System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
    System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );

    nsObj2 = new NotSimple();
    //1e
    System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
    System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );

    nsObj2.setData(10);
    //1f
    System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
    System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
    System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
    System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
  }

}

class NotSimple
{
  NotSimple()
  {
    data = 5;
    str = new String( "Initialized!" );
  }

  NotSimple( int i, String str1 )
  {
    data = i;
    str = str1;
  }

  void setData( int i )
  {
    data = i;

    return;
  }

  int getData()
  {
   return data;
  }

  void setStr( String str1)
  {
    str = str1;

    return;
  }

  String getStr()
  {
    return str;
  }

  private int data;
  private String str;
}

The instructor wants me to "Increase the 'data' member of every NotSimple object in the array 'a' by 1" When I run the program it only increases the first data. For example when I enter 3 I get this:
run:
Enter a number of objects:
3
6
6
6
nsObj1.data is        5
nsObj1.str is         Initialized!
nsObj2.data is        50
nsObj2.str is         Another immutable string!
nsObj2.data is        100
nsObj2.str is         Initialized!
nsObj1.data is        5
nsObj1.str is         Initialized!
nsObj2.data is        100
nsObj2.str is         Initialized!
nsObj2.data is        5
nsObj2.str is         Initialized!
nsObj1.data is        5
nsObj1.str is         Initialized!
nsObj2.data is        10

My question is shouldn't all the data be increased by 1? i.e. 101, 6, 101, 6, 6, 11

A: You have two main operations here. The first is the creation of an array containing x elements, each of this element is initialized with the value 5 and get incremented by one. This give you this result :

3
  6
  6
  6

3 elements, with the value 5, incremented.
The second part of your code (the explainOutputs()) doesn't increment anything. Two objects are declared (nsObj1 and nsObj2), and they're modified manually before you print them. No incrementation. It just print what you've set.
Here is what you've done :

*

*NotSimple nsObj1 = new NotSimple();
 prints 5.

*NotSimple nsObj2 = new NotSimple(50, "Another immutable string!");
 prints 50

*nsObj2 = nsObj1; nsObj2.setData(10); nsObj1.setData(100);
 Basically you just said that nsObj2 value is 100 and it prints 100

*nsObj1 = new NotSimple();
nsObj1 will print 5 (as it's a reference to a new Object)
nsObj2 will still print 100

*nsObj2 = new NotSimple();
nsObj2 is a reference to a new Object, it will print 5

*nsObj2.setData(10);
nsObj1 still prints 5
nsObj2 will print 10 for because only the object referenced by nsObj2 will have a value changed

Result :
5 50 100 5 100 5 5 10

A: The increaseData method which increments the member field data of objects in its argument array is called only on the objArray.
In the method explainOutputs you don't increment anywhere. You set data field to different values and print them.
To fix this you can write another overloaded increaseData method that takes a NotSimple as:
static void increaseData(NotSimple a) {
    a.setData(a.getData()+1);
}

And call this method before you print in any object in the explainOutputs method as:
NotSimple nsObj1 = new NotSimple();
//1a
increaseData(obj1); // ADD THIS.
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );

With the above method in the class your existing increaseData method can make use of it as:
static void increaseData(NotSimple[] a) {
   for (int i = 0; i < a.length; i++) {
        increaseData(a[i]); // call increaseData for each object in the array.
   }
}


text:
Q: behaviour of \paragraphfootnotes in memoir.cls The switch \paragraphfootnotes in memoir has one odd, at least unusual feature: whenever a footnote starts a new line, it is indented. The idea of the para-feature is to have one paragraph with all the footnotes of a page. Is it possible to turn this off?
Is is possible to allow paragraph-footnotes to run onto the next page?
This is a minimal example. Footnote 10 is within the block and indented. There are surely scenarios where this is what you want, but normally not.
\documentclass{memoir}
\paragraphfootnotes
\usepackage{lipsum}

\begin{document}
\lipsum[1]\footnote{} test\footnote{test test test testtesttesttest test testtest}
test\footnote{test test test testtesttesttest test testtest}test\footnote{test test test
  testtesttesttest test testtest} test\footnote{test test test testtesttesttest test
  testtest}test\footnote{test test test testtesttesttest test testtest} test\footnote{test
}test\footnote{test}test\footnote{test }test\footnote{test}test\footnote{test
}test\footnote{test}test\footnote{test }test\footnote{test}test\footnote{test }test\footnote{test}
\end{document}


text:
Q: How to paste text at prompt's position with a Visual Studio Add-In? I'm trying to develop a Visual Studio 2013 Add-In (now called Extension Package?) that inserts some text at the prompt's position in the currently opened file when it's key shortcut is pressed, but I'm not being able to find any documentation on this.
Does anyone know how to access this?
Thanks
PS: further information on how to access this kind of data would be nice also, since I need to get the selected text for other functions too.


text:
Q: Is $\pi_2 (X_i)$ a free $\mathbb{Z}\pi_1 (X_i)$-module for $i=1,2$? Let $X_1$ be the suspension of $\mathbb{R}P^2$ and $X_2=\bigvee_{1\leq i\leq n} (\vee_{r_i} \mathbb{S}^i)$.
Is $\pi_2 (X_i)$ a projective (or a free) $\mathbb{Z}\pi_1 (X_i)$-module for $i=1,2$?
I was wondering if someone could help me about my question. I don't have much information about $\pi_n (X)$ as a $\mathbb{Z}\pi_1 (X)$.

A: No and yes, respectively.
For $X_1$, the suspension is simply connected, so $\pi_2(X_1) = H_2(X_1) = H_1(\mathbb{R}P^2) = \mathbb{Z}/2$ which is not a free $\mathbb{Z}$ module.
For the other one, $\pi_2(X_2) = H_2(\tilde{X}_2)$ where $\tilde{X}_2$ is the universal cover. Since $\pi_1(X_2)$ is a free group on $r_1$ letters (if I've understood your notation correctly),  $\tilde{X}_2$ is an infinite tree with a wedge of spheres (of dimension at least $2$) at each lift of the vertex of $X_2$.  Those spheres are permuted by the covering group action of $\pi_1(X_2)$, and so the homology of $\tilde{X}_2$ is free as a $\mathbb{Z}[\pi_1(X_2)]$-module, with a fixed lift of each of the spheres (of dimension at least 2) as basis. In particular, $\pi_2(X_2)$ is a free $\mathbb{Z}[\pi_1(X_2)]$-module on $r_2$ generators.
Because you can compute $\pi_2$ as $H_2$ of the universal cover, it's a lot easier than the higher homotopy groups.


text:
Q: Prove that $-x^2 \leq x^n \leq x^2$ for $-1Prove that $-x^2 \leq x^n \leq x^2$ for $-1<x<1, n\in \mathbb N, n \geq3$
I have no idea how to do this, I don't even know how to begin. Please help!

A: If $x<1$ is positive we have
$$
x^2>\underbrace{x\cdot x^2}_{x^3}>\underbrace{x\cdot x\cdot x^2}_{x^4}>...
$$
The negative bound is only relevant when $n$ is odd and $x$ is negative.

A: HINT: You have to prove $|x^n|\leq x^2$ for $|x|<1$. You know that for any $a>0$ and $0<b<1$, $ab<a$. Then, for $n=3$, we have that
$$
|x^3|=x^2\cdot |x|.
$$
Now set $b=|x|$, $a=x^2$, and see what you get.


text:
Q: Выбор специализации шаблона на основе значения перечислений проблема возникает при попытке реализовать CRTP похожий данный упрощенный пример:
#include <type_traits>
#include <iostream>

enum  ActionTypes {
    eInit      = 2 << 0,
    eUpdate    = 2 << 1,
    eMultUpdate = 2 << 2
};

template <class Data,
          unsigned  Actions = eInit|eUpdate|eMultUpdate>
class ActionData
{
    template<ActionTypes As /*???*/>
    struct action {
        static void exec(Data*) { std::cout << "ActionData:: /*dummy*/ exec()\n"; };
        static void exec(Data*,int) { std::cout << "ActionData::/*dummy*/ exec(int)\n"; };
    };

    template<>
    struct action < /*???*/ >
    {
        static void exec(Data*) { /*...*/ };
    };

    template< >
    struct action < /*???*/ >
    {
        static void exec(Data*, int) {  /*...*/  };
    };

    Data* derived() { return static_cast<Data*>(this); }
protected:
    void init()          { action<eInit>::exec(derived()); }
    void update()        { action<eUpdate>::exec(derived()); }
    void update(int key) { action<eMultUpdate>::exec(derived()); }
public:
    enum Keys { DEFAULT_KEY = -1 };

    void call(ActionTypes a, int key = DEFAULT_KEY)
    {
        switch (a) {
        case eInit:
            init(); break;
        case eUpdate:
            if (key == DEFAULT_KEY)
                update();
            else
        case eMultUpdate:
                update(key);
        }
    }

};

class Test : public ActionData<Test, eUpdate>
{
public:
    void update() { std::cout << "Test :: update()\n";  }
};

int main()
{
    Test actor;
    ActionTypes a = eInit;
    actor.call(a, 0); // useless here but must be possible.
    actor.call(eUpdate, 0);
    actor.call(eUpdate);
}

Не все наследуемые классы реализуют необходимые методы, если соответсвующий бит в маске не установлен,  action должен выбрать реализацию по умолчанию. На практике выбрать другую специализацию на основе параметра не являющегося типом невозможно, а решение, позволящие заменить его на класс, ускользает от меня.
ПС. Оригинальное решение наследует интерфейс от большого проекта написанного на Си и переведенного на Си++.  ActionData Допустимыми возможностями являются возможности С++98/03 и tr1 С++11 (без вариадических шаблонов, без if constexpr, но enable_if  и пр. присутствуют).

A: Весь секрет был в использовании частичных специализаций и учете возможности нулевого результата операции И
#include <type_traits>
#include <iostream>

enum  ActionTypes {
    eInit      = 2 << 0,
    eUpdate    = 2 << 1,
    eMultUpdate = 2 << 2
};

template <class Data,
          unsigned  Actions = eInit|eUpdate|eMultUpdate>
class ActionData
{
    template<ActionTypes A, typename Enable = void > struct action {};

    template< ActionTypes A >
    struct action<A, typename std::enable_if<(A & Actions) == 0>::type >
    {
        static void exec(Data*) { std::cout << "ActionData:: /*dummy*/ exec()\n"; };
        static void exec(Data*,int) { std::cout << "ActionData::/*dummy*/ exec(int)\n"; };
    };

    template< ActionTypes A >
    struct action < A, typename std::enable_if<(A & Actions) == eInit>::type  >
    {
        static void exec(Data* o) { o->Data::init(); };
    };

    template< ActionTypes A >
    struct action < A, typename std::enable_if<(A & Actions) == eUpdate>::type  >
    {
        static void exec(Data* o) { o->Data::update(); };
    };

    template< ActionTypes A >
    struct action  <  A, typename std::enable_if<(A & Actions) == eMultUpdate>::type >
    {
        static void exec(Data* o, int key) { o->Data::update(key); };
    };

    Data* derived() { return static_cast<Data*>(this); }
protected:
    void init()          { action<eInit>::exec(derived()); }
    void update()        { action<eUpdate>::exec(derived()); }
    void update(int key) { action<eMultUpdate>::exec(derived(), key); }
public:
    enum Keys { DEFAULT_KEY };

    void call(ActionTypes a, int key = DEFAULT_KEY)
    {
        switch (a) {
        case eInit:
            init(); break;
        case eUpdate:
            if (key == DEFAULT_KEY) {
                update();
                break;
            } else {
        case eMultUpdate:
                update(key);
                break;
            };
        }
    }

};

class Test : public ActionData<Test, eUpdate>
{
public:
    void update() { std::cout << "Test :: update()\n";  }
};

int main()
{
    Test actor;
    ActionTypes a = eInit;

    actor.call(a, 0);
    actor.call(eUpdate);
    actor.call(eMultUpdate, 0);
}


text:
Q: Can I emulate svn:externals using mercurial? We are considering a move from SVN to Mercurial, and have encountered a stumbling block.
We currently use svn:externals to automatically pull a common set of libraries into the working directory. I can't find support for anything like this in Mercurial.
Is there a way to do this automatically with Mercurial, or do I need to fake it as part of my build process?

A: Have you tried Deps Extension ?
It's not part of Mercurial, but seems to mimic svn:externals feature

A: It appears that the functionality of the Forest Extension is being implemented into core Mercurial (as of 1.3):
https://www.mercurial-scm.org/wiki/Subrepository.
Currently marked as "experimental" but perhaps will be the route to handle svn:external -type functionality as of v1.4.

A: There's no good way to do it using mercurial only. The Forest Extension mentioned elsewhere causes more problems that in fixes nowadays.  Most folks just use a large repo and include all their components in the repo and then have their build scripts download and use 3rd party libraries -- using maven if they're Java-heads.
Short answer "fake it in your build process".
Update:
In Mercurial 1.3 a new sub repos feature was added.  it's like the old forest extension, but started as all new code.
Subrepos are considered a "feature of last resort".

A: Try Mercurial's Forest Extension.


text:
Q: Flutter bluetooth.It doesn't give me real devices Hi everybody I'm trying to use flutter_blue in my app.For this ı use this github project.https://github.com/pauldemarco/flutter_blue/blob/master/example/lib/widgets.dart. However when ı run this in my emulator it gives me 2 devices which are gDevice-beacon it didn't give me real devices.How can ı solve this.

A: You must run your app in your real phone.How can you think your emulator can show real device when your turn on bluetooth :).

A: Try this in build.gradle file in app:
 buildTypes {
        release {
            signingConfig signingConfigs.release
            shrinkResources false    // this line
            minifyEnabled false       // this line
        }
    }

You can also try building the apk by :
flutter build apk --no-shrink


text:
Q: Stuck on Hotel Salesperson Java Program Here is the problem: A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a program that reads such a file and displays the total amount for each service category. Display an error if the file does not exist of the format is incorrect.
Here is what I have:
package practice;

import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
import java.io.PrintWriter;

public class practice1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    System.out.println("Please enter input file name: ");
    String inputFileName = console.next();
    System.out.println("Please enter desired output file name: ");
    String outputFileName = console.next();
    console.useDelimiter(";");

    //Construct Scanner and PrintWriter objects for reading and writing

    File inputFile = new File(inputFileName);
    Scanner in = new Scanner(inputFile);
    PrintWriter out = new PrintWriter(outputFileName);
    double dinnerTotal = 0;
    double conferenceTotal = 0;
    double lodgingTotal = 0;
    double total = dinnerTotal + conferenceTotal + lodgingTotal;

    //Read the input and write the output

    while (in.hasNext())
    {
        String line = in.nextLine();
        String[] parts = line.split(";");
        if(parts[2].equals("Conference")){
            conferenceTotal = conferenceTotal+ Double.parseDouble(parts[3]);
        } else if(parts[2].equals("Dinner")){
            dinnerTotal += Double.parseDouble(parts[3]);
        } else if(parts[2].equals("Lodging")){
            lodgingTotal += Double.parseDouble(parts[3]);

        }
    }

    out.printf("Dinner Total:", dinnerTotal);
    out.println();
    out.printf("Conference Total:", conferenceTotal);
    out.println();
    out.printf("Lodging Total", lodgingTotal);
    out.println();
    out.printf("Total", total);

    in.close();
    out.close();
    }

}

This program creates a new file that looks like this:
Dinner Total
Conference Total
Lodging Total
Total
It doesn't print the actual totals though. How do I print the totals?

A: double total = dinnerTotal + conferenceTotal + lodgingTotal; line needs to go below the while loop.

A: printf requires a converter to work properly.
You should change:
out.printf("Dinner Total:", dinnerTotal);

to:
out.printf("Dinner Total: %f", dinnerTotal);

which will print the value you want. The other lines work similarly.
And, as @Atri pointed out,
double total = dinnerTotal + conferenceTotal + lodgingTotal;

should go after the loop so it gets calculated properly.

A: Also to add to the replies: Your array index is wrong. Java arrays start at 0 so you need to shift all values with -1.
I got the code working with changing:

*

*Array index

*error in output code

*move line that calculate total below the loop.


text:
Q: Android Studio FATAL EXCEPTION: main I am newbie at developing android. And this is my first app I want to create. But I get some problem on this and don't know how to resolve it. Please help me.
This error I got:
03-19 14:30:44.502 22661-22661/com.don.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.don.test, PID: 22661
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.don.test/com.don.test.MainActivity}: java.lang.NullPointerException
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
  at android.app.ActivityThread.access$800(ActivityThread.java:144)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5158)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
  at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
  at com.don.test.MainActivity.onCreate(MainActivity.java:29)
  at android.app.Activity.performCreate(Activity.java:5998)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
  at android.app.ActivityThread.access$800(ActivityThread.java:144)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5158)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
  at dalvik.system.NativeStart.main(Native Method)

This is my MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

Button bLogout;
EditText etId, etNama, etUsername;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    etId = (EditText) findViewById(R.id.etId);
    etNama = (EditText) findViewById(R.id.etNama);
    etUsername = (EditText) findViewById(R.id.etUsername);
    bLogout = (Button) findViewById(R.id.bLogout);

    bLogout.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.bLogout:

            break;
    }
}
}

I use my Samsung Galaxy SIII Mini as emulator. Can you help me with this error, thanks before

A: You need to set the content view for your Activity before using it's views:
Add
setContentView(R.layout.activity_main); // activity_main is an example, here you need to put the name of your layout

Right after
super.onCreate(savedInstanceState);


text:
Q: Nonresponsive black screen after left idle for I am running Ubuntu (20.04 LTS) on my laptop (Asus ZenBook 13 OLED UX325) and I enjoy it for the most part. However, there I have one issue that is driving my crazy. If the laptop is left idle for a period of time, the screen turns black and it is impossible to undo it after it enters some sort of hibernation or sleep (or suspend?) mode. In other words, it enters some sort of sleep mode, and will not wake up when any buttons are pushed. The only solution forcibly turn off the laptop using the power button. This only occurs if it is left idle for a sufficient amount of time -- if I am quick enough after the screen turns black, I am able to press any key and log in normally.
Do anyone have an idea how to fix this for my specific laptop? I tried adding nouveau.modeset=0 to GRUB_CMDLINE_LINUX="" from this answer without any luck.

Edit (added /var/log/syslog as requested by @matigo in the comments):
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA avahi-daemon[743]: Interface wlp1s0.IPv4 no longer relevant for mDNS.
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA NetworkManager[752]: <info>  [1641480035.2654] device (wlp1s0): state change: disconnected -> unmanaged (reason 'sleeping', sys-iface-state: 'managed')
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA wpa_supplicant[787]: wlp1s0: CTRL-EVENT-SCAN-FAILED ret=-100
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA nm-dispatcher[4283]: run-parts: failed to stat component /etc/network/if-post-down.d/avahi-daemon: No such file or directory
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA wpa_supplicant[787]: nl80211: deinit ifname=p2p-dev-wlp1s0 disabled_11b_rates=0
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA systemd[1]: Reached target Sleep.
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA systemd[1]: Starting Record successful boot for GRUB...
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA systemd[1]: Starting Suspend...
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA kernel: [ 2959.035172] PM: suspend entry (s2idle)
Jan  6 15:40:35 abc-ZenBook-UX325UA-UM325UA systemd-sleep[4290]: Suspending system...
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@Jan  6 16:01:53 abc-ZenBook-UX325UA-UM325UA systemd-modules-load[382]: Inserted module 'lp'
Jan  6 16:01:53 abc-ZenBook-UX325UA-UM325UA systemd-modules-load[382]: Inserted module 'ppdev'
Jan  6 16:01:53 abc-ZenBook-UX325UA-UM325UA systemd-modules-load[382]: Inserted module 'parport_pc'
Jan  6 16:01:53 abc-ZenBook-UX325UA-UM325UA systemd-modules-load[382]: Inserted module 'msr'
Jan  6 16:01:53 abc-ZenBook-UX325UA-UM325UA systemd-sysctl[399]: Not setting net/ipv4/conf/all/promote_secondaries (explicit setting exists).

NB! I pushed many buttons for it to be easier to locate in the vast /var/log/syslog file.


text:
Q: Cloning/Multiple reading an Input Stream from an HttpResponse I have an HttpResponse containing some data (json/xml, which can contain a large amount of data).
I am using a function that reads and uses an input stream with this data (which is closed, and cannot be changed either than maybe accepting a string instead of an inputstream), and a different function that validates the data (general validation, not related to the actual usage which is a part I can't touch).
I would like to do something like this:
HttpResponse response = getTheResponse();
InputStream in = response.getEntity().getContent();
boolean isVaid = validateData(in);
if(!isValid){
    throw new Exception("Something is wrong");
} else {
    useData(in);
}

Since validateData needs to read the data from the InputStream (written by me so this can be manipulated), the useData will get an empty stream.
What is the best way to implement this?  I thought about copying the inputstream but for a large response that could be very wasteful. Converting from InputStream to string can have the same effect
Any Thoughts?
Thanks

A: Basically, you have two options

*

*Keep the result in memory

*Perform the HTTP Get request twice

Performing the HTTP request twice will produce some additional network traffic and requires the endpoint to be indempotent. So you move the additional "load" to the network and the remote server. I wouldn't do that.
Keeping the result is probably the better way to go but may require some amount of memory as you pointed out. You could read everything into a byte-array and read from that byte array using ByteArrayInputStream.
If you improve your design, you could use a fixed buffer and perform both operations on the content of the buffer - if partial content is acceptable. Some input streams have the capability to rewind, which in the end boils down to an internal buffer that is used. However, when reading from a Network socket - which is required for reading a http response - won't be possible to rewind to the beginning of the stream as the socket buffer might already be flushed.


text:
Q: Import OpenCV in Google Cloud Datalab How to import OpenCV in GCP? I'm using Google Datalab here.
It looks like I can install the package:
!pip install opencv-python

Collecting opencv-python
Downloading opencv_python-3.2.0.7-cp27-cp27mu-manylinux1_x86_64.whl (6.7MB)
100% |################################| 6.7MB 98kB/s
Requirement already satisfied: numpy>=1.11.1 in
/usr/local/lib/python2.7/dist-packages (from opencv-python)
Installing collected packages: opencv-python
Successfully installed opencv-python-3.2.0.7

But after I import cv2, I get an error
import cv2

ImportErrorTraceback (most recent call last)
<ipython-input-17-72fbbcfe2587> in <module>()
----> 1 import cv2

/usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>()
  5 os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__))
  6
----> 7 from . import cv2
  8 sys.modules['cv2'] = cv2

ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

A: i succeeded in the next step.
let's try this ♥
!apt-get update
!apt-get -y upgrade
!pip install opencv-python
!apt-get install libgtk2.0-dev -y

A: It worked for me with:
!apt-get install python-opencv -y --allow-unauthenticated


text:
Q: Issue with tag open-source I asked two open-source tagged questions that were closed. I've had some discussion this morning, and I'm told anything legal is closed on open-source. I was not proposing any legal action in my questions, just seeking to understand mine and others rights with the common open source licencing agreements.
I need to know what the rules of the open source licences I choose so I can communicate with other coders who want to join with my code. This falls in "practical, answerable problems that are unique to the programming profession" from the FAQ. Operating under an open source licence of some sort is a problem unique to the programming profession in open source hobby software projects. I did a search of the FAQ for the word 'legal', and it was not in the FAQ except at bottom of the page as a link to the Stack Exchange user agreement.
I have edited all four of my last four questions which includes these two tag open-source ones and my two iOS HIG guideline questions.
I'd like some support in being able to ask questions again as I'm question banned for four closed questions in a row. I also would like tag open-source to be more clear as to what is a good question for that tag as many seem closed that seem to meet the FAQ element I mentioned above.
The first paragraph of the tag wiki as it stands now is particularly misleading:
"Open source software is software distributed under an open source license. Such a license specifically allows anyone to copy, modify, extend and redistribute the source code without paying royalties or fees to the original authors. Many open source licenses require that the source code is released for software that includes (modified) portions of the original open source software."

A: SO is about strictly programming problems. For not programming-related but program/programmer-related questions is Programmers.SE.
They have quite a plenty of Open Source questions there:
https://softwareengineering.stackexchange.com/questions/tagged/open-source
so yours can be a good fit on that site.

A: There is a proposal for a Q&A site regarding Open Source licensing on area51: http://area51.stackexchange.com/proposals/58715/open-source-licensing?referrer=8PFLrZ3ydnhFtbu7jPSDPA2


text:
Q: Openshift: build never ends I'm facing with a problem.
I'm performing:
mvn -Dfabric8.namespace=t-devhub-dev \
  -Dfabric8.openshift.trimImageInContainerSpec=true \
  -Dmaven.test.skip=true \
  clean package fabric8:resource fabric8:build

This process is hanging on waiting for fabric8:build ends:
[INFO] --- fabric8-maven-plugin:3.5.38:build (default-cli) @ tdev-forum-service ---
[INFO] F8: Using OpenShift build with strategy Docker
[INFO] Copying files to /home/jcabre/projects/tdevhub/application-src/t-devhub/tdev-forum-service/target/docker/forum/0.0.1-SNAPSHOT/build/maven
[INFO] Building tar: /home/jcabre/projects/tdevhub/application-src/t-devhub/tdev-forum-service/target/docker/forum/0.0.1-SNAPSHOT/tmp/docker-build.tar
[INFO] F8: [forum:0.0.1-SNAPSHOT]: Created docker source tar /home/jcabre/projects/tdevhub/application-src/t-devhub/tdev-forum-service/target/docker/forum/0.0.1-SNAPSHOT/tmp/docker-build.tar
[INFO] F8: Updating BuildServiceConfig forum-s2i for Docker strategy
[INFO] F8: Adding to ImageStream forum
[INFO] F8: Starting Build forum-s2i

docker-build.tar is really straigforward:
├── Dockerfile
├── maven
│   └── tdev-forum-service-0.0.1-SNAPSHOT.jar
└── .s2i
    └── environment

where Dockerfile is:
FROM docker.io/fabric8/java-jboss-openjdk8-jdk:1.2
ENV JAVA_APP_JAR=tdev-forum-service-0.0.1-SNAPSHOT.jar
COPY maven /deployments/

and .s2i/environment:
JAVA_APP_JAR=tdev-forum-service-0.0.1-SNAPSHOT.jar

Also, I've tried using oc client:
cat docker-build.tar | oc start-build --from-dir=- --loglevel=10 forum-s2i --follow

It's also handing on:
I0723 12:17:06.770656    3403 loader.go:357] Config loaded from file /home/jcabre/.kube/config
Uploading archive file from STDIN as binary input for the build ...
round_trippers.go:417] curl -k -v -XPOST  -H "Accept: application/json, */*" -H "User-Agent: oc/v1.9.1+a0ce1bc657 (linux/amd64) kubernetes/a0ce1bc" -H "Authorization: Bearer cQFjgh_mjoAkbjYRhyz0sYCr8SaeauIpi4cjYL2UzDY" https://<cluster-url>/v1/namespaces/t-devhub-dev/buildconfigs/forum-s2i/instantiatebinary?name=forum-s2i&namespace=t-devhub-dev

Any ideas?


text:
Q: Compare difference between two dates using JPA Criteria Query I am using MySQL as a backend for my application.
I want to execute query below using JPA Criteria Query.
SELECT *
FROM table1 t1
WHERE datediff(now(), t1.created) >= 20;

Note: Type of created is TIMESTAMP
I want Criteria Query like:
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

// select
CriteriaQuery<Table1> query = cb.createQuery(Table1.class);

// from
Root<Table1> root = query.from(Table1.class);

// where
List<Predicate> predicates = new ArrayList<Predicate>();

// TODO: add expression for datediff(now(), t1.created) >= 20

query.where(cb.and(predicates.toArray(new Predicate[0])));

Can any one help?
Thanks in advance.

A: Supposing that created is a java.util.Date, you have to perform the DATEDIFF in java and compare the property with the resulting date:
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, -20);
Date myDate = c.getTime();

predicates.add(cb.lessThanOrEqualTo(root.<Date>get("created"), myDate));


text:
Q: Using a Derived class of a Java Swing control to create listener for self At the outset: I know that what I am doing is bad design. I am trying this to get a better feel of Java - what is possible, what is not and why?
I have written the following code:
    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

    public class ButtonTest
    {
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    ButtonFrame frame = new ButtonFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                }
            });
        }
    }

    @SuppressWarnings("serial")
    class ButtonFrame extends JFrame
    {
        private final static int DEFAULT_WIDTH = 300;
        private final static int DEFAULT_HEIGHT = 200;
        private final JPanel buttonPanel;

        public ButtonFrame()
        {
            this.setTitle("Button Frame");
            this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

            PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, this);
            PanelButton redButton = new PanelButton("Red", Color.RED, this);
            PanelButton blueButton = new PanelButton("Blue", Color.BLUE, this);

            this.buttonPanel = new JPanel();
            this.buttonPanel.add(yellowButton);
            this.buttonPanel.add(redButton);
            this.buttonPanel.add(blueButton);

            // add panel to frame
            this.add(this.buttonPanel);
        }
    }

    @SuppressWarnings("serial")
    class PanelButton extends JButton implements ActionListener
    {
        private final Color buttonColor;
        private final ButtonFrame containingFrame;

        public PanelButton(String title, Color buttonColor,
                ButtonFrame containingFrame)
        {
            super(title);
            this.buttonColor = buttonColor;
            this.containingFrame = containingFrame;
            this.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent event)
        {
            this.containingFrame.setBackground(this.buttonColor);
        }
    }

But this is not working. I see from the debugger that actionPerformed() is being invoked and it has the expected values. I am not able to understand what is happening here. Can someone please help me?

A: You are setting the background color of the JFrame, but the JPanel that is contained by the JFrame, which then holds your buttons, takes up all of the space of the JFrame, so you can't see the background color changing.
This works.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonTest
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                ButtonFrame frame = new ButtonFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

@SuppressWarnings("serial")
class ButtonFrame extends JFrame
{
    private final static int DEFAULT_WIDTH = 300;
    private final static int DEFAULT_HEIGHT = 200;
    private final JPanel buttonPanel;

    public ButtonFrame()
    {
        this.setTitle("Button Frame");
        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        this.buttonPanel = new JPanel();

        PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, buttonPanel);
        PanelButton redButton = new PanelButton("Red", Color.RED, buttonPanel);
        PanelButton blueButton = new PanelButton("Blue", Color.BLUE, buttonPanel);

        this.buttonPanel.add(yellowButton);
        this.buttonPanel.add(redButton);
        this.buttonPanel.add(blueButton);

        // add panel to frame
        this.add(this.buttonPanel);
    }
}

@SuppressWarnings("serial")
class PanelButton extends JButton implements ActionListener
{
    private final Color buttonColor;
    private final JPanel buttonPanel;

    public PanelButton(String title, Color buttonColor,
            JPanel buttonPanel)
    {
        super(title);
        this.buttonColor = buttonColor;
        this.buttonPanel = buttonPanel;
        this.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent event)
    {
        buttonPanel.setBackground(this.buttonColor);
    }
}

A: You can skip passing the container and just do
@Override
public void actionPerformed(ActionEvent event)
{
    this.getParent().setBackground(buttonColor);
}


text:
Q: How do I calculate cumulative sum for last 7 rows on a specific date in Postgresql? I have a table that has these columns: user_id, day, valueA, valueB.
I'd like to calculate the running sum of last 7 rows of valueA and valueB for each user that has data on a specific day, for example '2020-08-01'.
(Note: Users only have a row when their valueA and valueB is not zero so there are some dates not in the table.)
I tried this query:
select user_id, day,
          sum(valueA) over(partition by user_id rows between 7 preceding and current row) as last_7_A,
          sum(valueB) over(partition by user_id rows between 7 preceding and current row) as last_7_B
from table where day='2020-08-01'

But this query doesn't calculate the running sum and returns me the valueA and valueB on date 2020-08-01
I could just calculate on each day and select the date I want but that'll be really inefficient. Any ideas how to add the date constraint and let it just calculate on just one row's last 7 running sum for each user?

A: As per question:
sum of last 7 rows for each user for a particular date, this might work
select user_id, sum(valueA) "sum of valueA", sum(valueB) "sum of valueB"
from sample_table
where id in (
    select id
    from sample_table
    where day='2020-08-08'
    order by id desc limit 7)
group by user_id;


text:
Q: Nginx conf to invoke xslt script to generate php AND process with php-fpm in one request? Consider the following non-working nginx.conf fragment:
server {
    ...
    root    /var/www/html/example.com/www;

    location /dev/ {
        root    /var/www/html/example.com;

        location ~* \.(pdf|js|css|png|jpg|jpeg|gif|ico)$ {
        }

        fastcgi_split_path_info ^/dev/(.+)()$;
        fastcgi_intercept_errors on;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /var/www/html/example.com/xsltproc.php;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_pass php-fpm;

        location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(x)$;
            fastcgi_intercept_errors on;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_pass php-fpm;
        }
    }
    location / {
        index index.html;

        location ~ \.php$ {
            ...

The objective is to use XSLT to transform .xml into .php and instantaneously serve the generated .php file from the protected /dev/ location all in one step for a fast and easy edit / view cycle.
The xsltproc.php script looks up the resource by $fastcgi_script_name and checks to see if the corresponding .xml or .xsl files are newer than the .php file and, if yes, regenerates it using XSLTProcessor::transformToXML().
When development is complete, the .php files are copied to the www location where they are served in the typical non-xslt manner.
However, the above does not work because, even though location /dev/ matches, location ~ \.php$ is ultimately favored and used such that the .php file is not regenerated. If I temporarily remove the location ~ \.php$ section, the .php file is generated correctly. When the section is restored, the .php file is processed correctly.
How do I configure nginx to invoke xsltproc.php AND process the .php file with php-fpm in the same request?
Meaning I effectively want to invoke php-fpm twice in one request: once for xstlproc.php and once on the generated .php file.
Can an internal redirect be used even though the name of the resource is exactly the same (e.g. /dev/test.php)?
UPDATE:
I have not found a way to invoke php-fpm twice. Adding a rewrite immediately after the xsltproc.php fastcgi_pass call results in a jump for the rewrite without executing the script. No surprise there.
However, I did settle on a solution which was to add:
require($phpfile)

to the end of xsltproc.php to simply include the php file regardless of weather or not it was re-generated and then remove location ~ \.php$. The more I think about it, this is a satisfactory solution. It's only for dev anyway.


text:
Q: Auto start outlook using vbacript prompts password always I am running scheduled task with below VBScript but it always prompt password for Outlook. I tried to make it remember in Outlook but it does not affect in schedule task start and never asks for the password if I start Outlook manually. How can I fix this issue?
Code:
Set WShell = WScript.CreateObject("Wscript.Shell")
WShell.run("outlook")

Here's how I run the scheduled task:

[


text:
Q: How do I assign a cell array to multiple matrices? I am relatively new to matlab, and I was wondering if there was a simpler way to do the following:
Given mycellarray = {[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15 16]}, I would like to assign each matrix inside mycellarray to a separate variable. Is there any faster/better/shorter way to do it than this?
a = cell2mat(mycellarray(1,1))
b = cell2mat(mycellarray(1,2))
c = cell2mat(mycellarray(1,3))
d = cell2mat(mycellarray(1,4))

Thanks in advance!

A: [a,b,c,d]=mycellarray{:}
The {:} makes a comma seperated list of the cell array, which an be assigned to individual variables.
relevant documentation pages:

*

*colon operator

*comma seperated list

A: Here a short example on how to do what you want with the MATLAB function deal.
a = {[1 2 3] [4 5 6] [7 8 9]}
[aa bb cc] = deal(a{:})


text:
Q: Rmi for centralized database systems? I have to develop a java application with a centralized database. Is RMI suitable for it or should i use some other method.

A: Consider to use Java EE. The Java EE application will have the server side logic and manages access to the database via EJBs.
You can use either remote EJBs, which are based on RMI, but usually only work in a LAN. Or you can create SOAP or RESTful webservices using the easy to use JAX-WS and JAX-RS annotations.
You can find the Java EE tutorial here: http://docs.oracle.com/javaee/6/tutorial/doc/
You will need an application server. The reference implementation is GlassFish: http://glassfish.java.net/
The easiest way to get started is to download a NetBeans version with a bundled GlassFish: http://netbeans.org/downloads/
Then just create a WAR project.

A: Good answer by Puce, but you can also consider a different kind of application server (without EJBs or RMI) such as Vaadin (Java-based) or Real Studio Web Edition (not Java-based). The user interacts with a web browser on the client-side while your app's business logic executes on the server and connects to the database server.


text:
Q: How can I remove the unwanted part of sprite area How can we animate using this coin sprite image (suppose the background is not transparent, but white) http://blocksjs.com/demos/block/images/coin.png without getting the white parts? Suppose we want just the coin, not this white background, because, let's say, the background on canvas is black. How can we accomplish this?

A: The image provided is transparent so there's no need to eliminate the white background.  If you do have an image with a white background then you might try one of the globalCompositeOperations to draw only the dark pixels and ignore the white.
I've added a function to key out a color. You could key out the color of your image and save it before running the animation.

var ctx = document.getElementById("can").getContext('2d');
var sprite = document.getElementById("sprite");
var sprite_width = 100;
var sprite_height = 100;
var sprite_frames = 10;
var sprite_frame = -1;
var sprite_x = 100;
var sprite_y = 0;
var sprite_fps = 10;
var sprite_time = 0;

var spriteCan = document.getElementById('spriteCan');
var sprites = [];

function makeSpriteCan() {
  var can = spriteCan;
  var ctx = can.getContext('2d');
  ctx.fillStyle="#FF00FF";
  ctx.fillRect(0,0,can.width,can.height);
  ctx.textAlign = "center";
  ctx.textBaseline='middle';
  ctx.font = "30pt Sans-serif";
  ctx.fillStyle="#FFFFFF";
  for (var i = 0; i < 10; i++) {
    ctx.fillText(i, 50 + i * 100, 50);
  }

}

makeSpriteCan();
spriteCan = keyColor(spriteCan, 255,0,255);
sprites.push(spriteCan);
ani();

function spriteLoad() {
  sprites.unshift(sprite)
}

function ani() {
  var now_time = Date.now();
  if (now_time - sprite_time > 1000 / sprite_fps) {
    sprite_time = now_time;
    sprite_frame ++;
    sprite_frame %= sprite_frames;
  }

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  var frame_x = sprite_frame * sprite_width;
  var frame_y = 0;

  for (var i = 0; i < sprites.length; i++) {
    ctx.drawImage(sprites[i], frame_x, frame_y, sprite_width, sprite_height, sprite_x, sprite_y, sprite_width, sprite_height);
  }

  requestAnimationFrame(ani);
}

// key out a color in an image
function keyColor(img, r, g, b) {
  var can = document.createElement('canvas');
  var ctx = can.getContext('2d');
  can.width=img.width;
  can.height=img.height;
  ctx.drawImage(img, 0, 0);
  var imageData = ctx.getImageData(0,0,can.width,can.height);
  var d = imageData.data;
  var length = d.length;

  for (var i = 0; i < length; i+=4) {
     if (d[i] == r && d[i+1] == g && d[i+2] == b) {
         d[i+3] = 0;
     };
  }
  ctx.putImageData(imageData, 0, 0);
  return can;
}
#can {
  border:1px solid red;
  background-color:black;
}
<img src="http://blocksjs.com/demos/block/images/coin.png" id="sprite" onload="spriteLoad()"/>
<canvas id="spriteCan" width="1000" height="100"></canvas>
<canvas id="can" width="300" height="100"></canvas>


text:
Q: How to fill a textarea so it's submitted in a form after setting value with jQuery I was trying to automatically fill the form for ad report on mobile.de (Object to ad link). Filling fields (textarea for the description, inputs for email and phone number)  with jQuery and submitting the form doesn't work as the fields are reset on submit.
Filling them with jQuery works (you can see the change) but the field gets reset when a user focuses the field manually with the mouse.
I thought that some events were messing with the fields so I tried to block them but then I realized that not even jQuery triggers work on the fields (e.g. $().focus() doesn't work).
How can I fill the form with jQuery so the values stay in the fields (without manipulating the post request)?
Edit:
$('#complain-link-center').click(function() {

    setTimeout(function() {
        // first radio click
        $('#reasonName_CONTRADICTORY_VEHICLE_DATA').click();

        // second radio click
        $('#sourceOfDistrust_AD').click();

        // this doesn't work
        $('.cBox-body .g-col-4 textarea').focus();

        // this works but you have to manually focus the field (stays populated on submit)
        $('input#email').focus(function() {
            $(this).val('email@example.com');
        });

    }, 100);
});

Edit2: I figured out that this page is developed with ReactJS so that's why it doesn't work with jQuery. Is there any possibility to manipulate ReactJS components with jQuery?

A: Try this, i hope it'll help you out. Thanks

$('#complain-link-center').click(function() {

    setTimeout(function() {
        // first radio click
        $('#reasonName_CONTRADICTORY_VEHICLE_DATA').click();

        // second radio click
        $('#sourceOfDistrust_AD').click();

        // this doesn't work
        $('.cBox-body .g-col-4 textarea').focus();

        // this works but you have to manually focus the field (stays populated on submit)
        $('#email').focus(function() {
            $(this).val('email@example.com');
        });

    }, 2000);
});
<form>

  Radio 1
  <input type="radio" class="form-control" id="reasonName_CONTRADICTORY_VEHICLE_DATA">

  Radio 2
  <input type="radio" class="form-control" id="sourceOfDistrust_AD">

    Message
    <textarea id="message"></textarea>

  Email
  <input type="email" id="email" />

</form>

<button id="complain-link-center" class="btn">Complain</button>


text:
Q: This app is not allowed to query for scheme tel I just opened an old project onbjectif-c created in 2010, the application works correctly except an interface
is not working.The error is -canOpenURL: failed for URL: "tel: 0" - error: "This app is not allowed to query for scheme tel".
according to my research I find that the error is related to ios 9 but I do not find how to resolve it
thank you

A: I've got the same mistake! The thing is that using phone calls with URL schemes doesn't require a special key in Info.plist.
The answer is- in simulator, this will not work, you need to test in device. The simulator doesn't have carrier service.

A: This means you have to add the scheme 'tel' in your info.plist, i.e
    <key>LSApplicationQueriesSchemes</key>
            <array>
                    <string>tel</string>
            </array>

This will whitelist the scheme 'tel'

A: for me this error was shown on the simulator, in testing on a real device it wasn't shown


text:
Q: Yosemite Sleep Wake Failure I've got a MBA Mid 2013 and since installing Yosemite, I've had 3-4 sleep wake failures.  Generally I'll close the lid, head home and either when I open the laptop at home or back at work the next morning I get message (not sure of exact text) "Your computer failed to wake properly and has restarted".  It didn't happen with Mavericks nor ML before that.
2 Times it stated the process was Activity Monitor and this most recent time it was airportd.
I don't really lose anything since all my apps open pretty much where they left off it's just a big annoying.
Any ideas?
https://gist.github.com/dstarh/77180ee3382cdca03afb

A: I have had this happen a few times myself.  If I was to guess, at the time you closed you lid on your computer you had the power supply hookup and running. After the lid was closed you removed the power plug.  Later you open the lid, without the power plug and it was a blank screen.  If this is your case, you have two options,

*

*unplug first before closing the lid

*plug into power before you open the unit later.

I have found if I give my Mac a few seconds after closing the lid, before removing the power, it will not freeze later when I open the lid.
Still not sure of the problem, just a work around that I found after a little time with this type of problem.

A: I have a 2010 MacBook Air, and it was freezing on wake from sleep --- making the thing basically useless.  Had to power cycle every time I used it.
After much research and fix attempts, here's what worked:
- reset PRAM
- reset SCM
- Use time machine to make a complete backup
- Reformat the hard drive
- Restore from the latest backup (I did NOT reinstall a fresh Yosemite -- I only restored)
The restore ran overnight (over wifi).  And after logging in, I had to input my iCloud password and a few other things, but my MacBook Air has all the files (for two users) and programs installed, and works great again.  Wakes from sleep like a champ.
So, my vote is: go full-on thermonuclear and wipe/restore.


text:
Q: Search and Select box does not have a default value We have a report that requires users to be able to search from a field [Templates] and then select the 1 or more than 1 Templates to filter by.  However, the report spec. also calls to be able to return the set of all Templates.  I have done a lot of searching and attempts to get this kind of behavior all to no avail.  We have Cognos 10.2.  The main query is populated by a sql script.  The fields in the main query are Template, Attribute, and Gov Rule.  Every row will have a Template, but not nec. a Attribute or Gov Rule.  I have already tried:  http://www-01.ibm.com/support/docview.wss?uid=swg21341603
Any help would be most appreciated.

A: After several attempts; I came at the issue from another point of view.  I made a toggle to "show" or "hide" by setting box-type as none on one of two blocks based on a style-variable.  The first block was the "all" query and the second block was the "filtered" query.  When the toggle said all the filtered block box-type was none and thus did not show.  When the toggle said filter, the search and select would appear (based on the same style variable) then the SNS prompt could be used and the resulting filter block would display while the all display would be hidden.  I know it is kind of a work-around and would love a better solution than two seperate lists to be maintained; but for now I don't think Cognos 10.2 has a great way to have a SNS default to "all" or a filter.  If I'm wrong, I would love to see a working example.

A: You can just make the Select & Search an optional prompt and configure your filter to also be optional. In that configuration, if the user does not touch the Select & Search prompt nothing will be passed in and the optional filter will be ignored, effectively returning all values.
Consider a query that had a single data item [Sales]. If you filter by city with [City] = ?city?, Congnos will require you to supply a city and then it will only display that city's sales. If you then set that prompt to optional and then run the report or show the tabular data for the query, Cognos will again prompt you for city but you will be free to not enter anything in the city prompt. The results will show sales for all cities as the optional prompt is ignored since no value was supplied. Remember that the default behavior is to include all rows.


text:
Q: Ionic2-3 - Best way to save "game progress" I'm starting with Ionic and trying to figure it out, best practices and how the life cycle works, etc.
On a test project I'm working there's a small game capability, like a quiz or something.
Whats the correct way of saving the user progress and game settings? I don't have a backend to connect... Wondering if this Firebase is good to do this kind of stuff.
ps.: sorry for my english

A: Maybe you can use these:
http://couchdb.apache.org/
and
https://pouchdb.com/
I hope help you.


text:
Q: Compatible connection on the associated vector bundle Assume $E\rightarrow X$ is a holomorphic vector bundle of rank $n$ with a linear connection $\nabla=\nabla^{1, 0}+\bar\partial_E$ which is compatible with the complex (somewhere the literature says "holomorphic") structure of $E$. Let $P\rightarrow X$ be the associated principal $GL_n(\mathbb{C})$-bundle (say the frame bundle of $E$).
There is a theorem which states that $\nabla$ induces a unique connection 1-form $\omega$ on $P$.
Let further $V$ be a representation of
$GL_n(\mathbb{C})$ and let $P\times_{GL_n(\mathbb{C})}V$ be the associated vector bundle which should be in my opinion holomorphic as well. The principal connection $\omega$ induces always a linear connection $\tilde{\nabla}$ on the associated vector bundle $P\times_{GL_n(\mathbb{C})}V$. The question I want to pose is the following:
Is $\tilde{\nabla}$ compatible with the complex structure on $P\times_{GL_n(\mathbb{C})}V$?
P.S.:Thanks in advance for any clarifications, corrections and responses to that for me very interesting question.

A: According to your last comment, the holomorphic structure is irrelevant; you just have a $GL_n(\mathbb{C})$-bundle.
I presume that your representation is complex, i.e., merely a homomorphism $H:=GL_n(\mathbb{C})\to G:=GL_m(\mathbb{C})$. (Otherwise, there is nothing to speak about.) This gives you a map $P\to P\times_HG$ of principal bundles, which is called extension of the structure group. (Unlike reduction of the structure group, it is well defined and involves no choices.) In this situation, any $H$-connection extends uniquely to a $G$-connection (e.g., via translations in the fibers, see the definition of connections as $1$-forms and their properties; BTW, a $1$-form is not induced by a connection: it is the connection). Since this is a $G$-connection, it is compatible with the complex structure just by definition.


text:
Q: How to set IE11 default emulating Core how i can set default emulation IE to Edge? In F12 i have selected IE7 and i dont know how return Edge.

A: The easiest way to get your page to render in Edge mode is to include a DOCTYPE on the top of your HTML page:
<!DOCTYPE html>

If you are testing your page locally or on the intranet, you may have to change your Compatibility view settings. These can be found in:
"Tools" (Alt+T) -> "Compatibility View Settings" -> And uncheck "Display Intranet Sites in Compatibility View"

You can also include the X-UA-Compatible  tag, which will force the page to EDGE mode.

More information on X-UA-Compatible: http://modern.ie/en-us/performance/how-to-use-x-ua-compatible
If you have any more questions, you visit http://Modern.ie

A: As with MS and specifically IE habit, it's a little more complicated. Look at this article, which refers to here. In a result is thus several ways to achieve what you need.


text:
Q: Chaining commands with && after "start /b" in a batch file I'm trying to spawn multiple processes to recursively convert .doc files within a folder into .docx using Microsoft's wordconv.exe. I know this will spawn an unlimited number of them, so that is not the issue here.
Here is what I have:
@echo off

set "WCONV=C:\Program Files\Microsoft Office\root\Office16\Wordconv.exe"

FOR /D /r %%F in ("*") DO (
    pushd %CD%
    cd %%F
    FOR %%X in (*.doc) DO (

        echo "%%F\%%X"

        start /b "" %WCONV% -oice -nme "%%X" "%%Xx" && del "%%X"

    )
    popd
)

The problem is that del "%%X" seems to execute upon successful completion of start /b instead of upon completion of %WCONV% -oice -nme "%%X" "%%Xx", so the original .doc file gets deleted before wordconv gets to work on it.
How do I group %WCONV% -oice -nme "%%X" "%%Xx" && del "%%X" so that it works as one command for start /b to spawn?
EDIT to clarify:
If I run the script sequantially, without start /b, it all works fine, as in docs get converted and deleted only if the conversion is successful. This is what I mean:
@echo off

set "WCONV=C:\Program Files\Microsoft Office\root\Office16\Wordconv.exe"

FOR /D /r %%F in ("*") DO (
    pushd %CD%
    cd %%F
    FOR %%X in (*.doc) DO (

        echo "%%F\%%X"

        %WCONV% -oice -nme "%%X" "%%Xx" && del "%%X"

    )
    popd
)

A: In your code, && is indeed not part of the spawned subprocess. To force the parser to include them, escape them:
start /b "" "%WCONV%" -oice -nme "%%X" "%%Xx" ^&^& del "%%X"

(note: personally, I would use /min instead of /b, but ymmv)
Based on the comments, the following should work for you:
start /b "" cmd /c ""%WCONV%" -oice -nme "%%X" "%%Xx" && del "%%X""

A: Please give this a try, I've added an additional If statement to be sure that no files are cycled back into the For loop.
@Echo Off
Set "WCONV=C:\Program Files\Microsoft Office\root\Office16\Wordconv.exe"
For /D /R %%F In (*) Do (
    PushD "%%F"
    For %%X In (*.doc) Do (
        If /I "%%~xX"==".doc" (
            Echo "%%F\%%X"
            Start /B "" Cmd /C ""%WCONV%" -oice -nme "%%X" "%%Xx" && Del "%%X""
        )
    )
    PopD
)

However, using the Where command you can isolate only the .doc files. Also you probably don't even need to nest a For loop within another:
@Echo Off
Set "WCONV=C:\Program Files\Microsoft Office\root\Office16\Wordconv.exe"
For /F Delims^=^ EOL^= %%A In ('Where /R . *.doc 2^>Nul') Do (
    Echo "%%A"
    Start /B "" Cmd /C ""%WCONV%" -oice -nme "%%A" "%%~nxAx" && Del "%%A""
)

In the lower example, depending upon how Wordconv works, you may need to replace %%nxAx to %%Ax.

A: Wordconv.exe is buggy. I preferred to use libreoffice,
but you can replace it with any program in the variable "WCONV=anyprogram.exe"
First, set path on the command line:
set path=%path%;c:\your libreoffice location

Or
I preferred to include the libreoffice path directly on the windows system, windows+pause > advanced config system > path variables > path > edit > new > include path of libreoffice folder
@echo off
set "WCONV=soffice"

FOR /D /r %%F in ("*") DO (
    pushd %CD%
    cd %%F
    FOR %%X in (*.doc) DO (

        if not exist "%%X" echo Not exist ".doc" on the folder "%%F"

        %WCONV% --headless --convert-to docx "%%X" "%%Xx"

        if exist "%%Xx" echo convert and delete "%%F\%%X" && del "%%X"

    )
    popd
)


text:
Q: Trying to use ResourceBundle to fetch messages from external file Essentially I would like to have a messages.properties files external to the jar files in my application. So that users can add languages and edit the files easily if my translations are wrong
at the moment i use
ResourceBundle.getBundle("package.MessageBundle");

But i would like to do something like this
ResourceBundle.getBundle("lang/MessageBundle");

Where lang is a folder under my application installation directory.

*

*is this a good idea (if not, why not)?

*can someone point me in the right direction, or some sample code that does this

thanks
Alex

A: Just put it elsewhere in an existing path covered by the classpath, or add its path to the classpath. This way you can access it the same way, but instead maintain it externally.

A: The way ResourceBundle works is that the argument you pass to getBundle is the "basename". This basename will be suffixed with the locale that you're working with, e.g. MessageBundle_en.properties, MessageBundle_fr.properties. If you want a different Locale to your system default, then you pass the Locale is as an additional parameter to getBundle().
So what you end up with is multiple language files in one directory, rather than a directory for each language.
So rather than
ResourceBundle.getBundle("lang/MessageBundle");

you would do
ResourceBundle.getBundle("MessageBundle", locale); // locale corresponds to "lang"

I suppose you could do this by prefixing the basename with the language name, but you'd be losing much of the functionality that ResourceBundle does for you out of the box.
The "externalizing" part is largely irrelevant, since ResourceBundle operates off the classpath, it works regardless of whether it internal (e.g. a JAR file), or external (e.g. a directory).


text:
Q: How to do this box copy overlay effect in CSS? I want to create this dialog window in CSS:

The only way I managed to come close to this was to copy the dialog window several times, tilt it with transform: rotate(..) and play a bit with z-indexes.
Could this be achieved with borders or box shadows without having to copy the original dialog window? It doesn't have to literally be there three times, of course. It can just be an illusion.

A: I don't think you'd be able to do it with just borders, though you could use pseudo-elements to avoid actually having to copy the element and some Z transforms to achieve this:

#modal, #modal:before, #modal:after{
  width: 500px;
  height: 300px;
  background: whitesmoke;
  border-radius: 10px;
  box-shadow: 0 0 5px 5px #eee;
  content: " ";
  position: absolute;
}
#modal:before{
  transform: rotate(-3deg) translateZ(-1px);
}
#modal:after{
  transform: rotate(-6deg) translateZ(-2px);
}
#modal{
  transform-style: preserve-3d;
  position: relative;
  margin: 50px auto;
}

This basically creates two pseudo-copies of your modal and pushes them behind the original with slightly different rotation.


text:
Q: Change flag tooltip for comment flags Given that the flag mechanism has been expanded and improved for both questions and answers and taking into consideration these two questions that ended up more or less with a 'you should flag more' answer.
I think comment flags should be revamped. I suggest changing the tooltip to remove the "hate speech" part of it:
"Flag this comment as noise, offensive or spam"
This because I think that having both offensive and hate speech as flag reasons bias people towards a stronger definition of offensive than they would otherwise have, as illustrated by the sample comments that follow.
Remember offensive is a superset of hate speech, so it's not really necessary (hate speech is by definition offensive.)
Some relevant quotes:

One concern I have is inundating you with nitpicky stuff. Send me a note if you
feel that's happening. I think -- based on the feedback here -- that I feel a
little more free to flag comments that are simply rude but not patently
offensive.
– tvanfosson Aug 18 at 15:39

I think I've avoided flagging because I assumed it was reserved for personal
attacks and specific malicious language (racist/sexist views, calling someone
stupid, or offensive language in excess). But now that I know that it's meant
to curb exactly what my email was about, I'll be sure to use the flag option
for those situations.
– Anthony 14 hours ago

I certainly cannot prove that these ideas are due to the biasing hate speech part of the tooltip provokes, but it certainly does give that impression to me. And there is nothing to lose from removing it. It's not as if our community needed a reminder to flag hate speech when it happens.

A: Noise was recently added as a reason to flag.
When you flag a comment, it doesn't bug a moderator, it just works on its own. Plus, when you read it with commas and the OR, it's like a menu, you decide what you want to be flagging the comment for:
noise | offensive | spam | hate speech

Is there a dilemma when you spot a pointless add-nothing comment like, "+1 Good answer", but because it's not offensive or spammy, you won't flag?
If you can't decide, order a burger and just don't flag.

A: I think it should be left alone. A moderator is not going to be reviewing the comment because you flagged it, that is not how comment flags work.
When you flag a comment, you are voting it to be deleted. Currently, I see "noise, offensive, spam or hate speech". I think that sums it up very well. This should not be taken lightly and I believe most of the people who use StackOverflow are capable of grokking logic like 'or'.


text:
Q: Use a Mayer-Vietoris sequence to calculate $S^3 - K$ where $K$ is an embedding of $S^1$. Use a Mayer-Vietoris sequence to calculate $H_i(S^3 - K)$ where $K$ is an embedding of $S^1$.
(hint: Let $S^3 = (S^3 - K) \cup O$ where $O$ is an open tubular neighborhood around $K$ that is homemorphic to the solid torus $D^2 \times S^1$.
This is what I have of the proof so far. Will somebody help me correct it, finish it, and just make it better in general? Thanks!
Proof:
Let $A = S^3 - K$ and $B = O \cong D^2 \times S^1$. Then $A \cap B \cong T^2$, the Torus and $A \cup B \cong S^3$.
Note that since $D^2$ is contractible, $B=O$ has the same homotopy type as $S^1$. Thus $H_i(B) = H_i(S^1)$
We thus have the following Mayer-Vietoris Sequence:
$$0 \rightarrow H_3(S^3-K) \oplus H_3(S^1) \rightarrow^z H_3(S^3) \rightarrow^x H_2(T^2) \rightarrow^a H_2(S^3 - K) \oplus H_2(S^1) \\ \rightarrow^b H_2(S^3) \rightarrow^c H_1(T^2) \rightarrow^d H_1(S^3 - K) \oplus H_1(S^1) \rightarrow^e H_1(S^3) \rightarrow^f H_0(T^2) \\ \rightarrow^g H_0(S^3-K) \oplus H_0(S^1) \rightarrow^h H_0(S^3) \rightarrow 0$$
We now make the following known substitutions:
$H_2(T^2) \cong \mathbb{Z}$
$H_2(S^1) \cong 0$
$H_2(S^3) \cong 0$
$H_1(T^2) \cong \mathbb{Z} \oplus \mathbb{Z}$
$H_1(S^1) \cong \mathbb{Z}$
$H_3(S^3) \cong \mathbb{Z}$
$H_1(S^3) \cong 0$
And all the zeroth homologies are $\mathbb{Z}$ as they are all path connected.
Thus our sequences becomes:
$$0 \rightarrow H_3(S^3-K) \oplus 0 \rightarrow^z \mathbb{Z} \rightarrow^x \mathbb{Z} \rightarrow^a H_2(S^3 - K) \oplus 0 \rightarrow^b 0 \rightarrow^c \mathbb{Z} \oplus \mathbb{Z} \\ \rightarrow^d H_1(S^3 - K) \oplus \mathbb{Z} \rightarrow^e 0 \rightarrow^f \mathbb{Z} \rightarrow^g \mathbb{Z} \oplus \mathbb{Z} \rightarrow^h \mathbb{Z} \rightarrow 0$$
And so by exactness of our sequence we have $H_1(S^3-K) = \mathbb{Z}$
I now turn my attention to proving that $H_3(S^3-K) = H_2(S^3-K) = 0$, so I zoom in on this part of our L.E.S.
$0 \rightarrow H_3(S^3-K) \oplus 0 \rightarrow^z \mathbb{Z} \rightarrow^x \mathbb{Z} \rightarrow^a H_2(S^3 - K) \oplus 0 \rightarrow^b 0 \rightarrow...$
or, simplified a bit:
$0 \rightarrow H_3(S^3-K) \rightarrow^z \mathbb{Z} \rightarrow^x \mathbb{Z} \rightarrow^a H_2(S^3 - K) \rightarrow^b 0 \rightarrow...$
note to reader: I can be pretty sloppy when analysing simple sections of a L.E.S. like this one; Here is my attempt. If somebody could show me the simpliest way to think about this that would be great!
Because of exactness, we know that $im(z) = ker(x)$, $ker(a) = im(x)$, and we know that $z$ is injective and $a$ is surjective.
Thus we know that:
$\frac{\mathbb{Z}}{im(x)} = \frac{\mathbb{Z}}{ker(a)} \cong H_2(S^3-K)$
Also, for some reason, perhaps because $\mathbb{Z}$ is free abelian, we know that $\mathbb{Z} = ker(x) \oplus im(x) = im(z) \oplus im(x)$
So if we can prove that something like $im(x)=\mathbb{Z}$ and this would instantly imply that $H_2(S^3-K)$ is trivial, and it would also imply that $im(z)=0$ and since $z$ is injective this means that $H_3(S_3-K)=0$.
Calculating $im(x)$ has to do with understanding the boundary map rather than falling out of the exactness of the sequence.
To understand the boundary map, here is Cheerful_Parsnip, where he use $U$ instead of $O$
"One way to see that is to trace through the definition of the boundary map. Basically, the fundamental class for S3 is a direct sum of simplices in a triangulation of S3. Subdivide these until all of them are contained either in S3∖K or U (or equivalently in S3∖K up to sign). Then look at the direct sum of those in U. The boundary of this is a torus around the knot, and is homologous to the fundamental class of T2. I'm sure there's some fancier way of seeing it."
Thus $x$ is an isomorphism and $H_3(S^3-K) \cong H_2(S^3-K)=0$


text:
Q: Replace part of string with '()' I need to replace some country names which has '()' or numbers in the 'Country' column of a dataframe.
For Example 'Bolivia (Plurinational State of)' should be 'Bolivia'. 'Switzerland17' should be 'Switzerland'.
I am using the below code
df3['Country'] = df3['Country'].str.replace(r'[^(][\w]*[)]','')
df3['Country'] = df3['Country'].str.replace(r'[\d]*','')

Where am i am going wrong here ,can you help

A: You can take a single pass replacing the text between parenthesis or digits:
\s*(?:\([^()]*\)|\d+)

Explanation

*

*\s* Match 0+ whitespace chars

*(?: Non capture group

*

*\([^()]*\)|\d+ Match either from (.. till ..) or match 1+ digits

*) Close non capture group

Regex demo
df3['Country'] = df3['Country'].str.replace(r'\s*(?:\([^()]*\)|\d+)', '')

Output
       Country
0      Bolivia
1  Switzerland

A: You should use
df3['Country'].str.replace(r"\s*(?:\d+|\([^()]*\))","").str.strip()

See the regex demo. Details:

*

*\s* - zero or more whitespaces

*(?:\d+|\([^()]*\)) - either one or more digits, or (, then zero or more chars other than ( and  ), then a )
The .str.strip() is necessary if the match happens to be at the start and is followed with whitespace.
See the Pandas test:
>>> import pandas as pd
>>> df3 = pd.DataFrame({'Country':['Bolivia (Plurinational State of)','Switzerland17','(Republic of) Korea']})
>>> df3['Country'].str.replace(r"\s*(?:\d+|\([^()]*\))","").str.strip()
0        Bolivia
1    Switzerland
2          Korea
Name: Country, dtype: object

A: I would using the following pattern: '([^)])|[\d.]' the | character let's you use multiple patterns in a single line.
df = pd.DataFrame({'Country':['Bolivia (Plurinational State of)','Switzerland17']})

Original df:
    Country
0   Bolivia (Plurinational State of)
1   Switzerland17

Suggested code:
df['Country'] = df['Country'].str.replace(r'\([^)]*\)|[\d.*]','',regex=True)

Outputs:
    Country
0   Bolivia
1   Switzerland


text:
Q: need to read a specific response header after sending "POST" information for login I have trouble reading the value of a specific response header. I'm posting login information and when ok, there is a token set in the response headers.
I'm able to list all the headers, but how do I read the value of that one specific header?
I searched and found the code which list all headers nicely howerver, those are lines / strings with name of header and the value. Still can't figure out how to read that one value.
$ch = curl_init('http://url');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:
application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
$response = curl_exec($ch);

curl_close($ch);
list($headers, $content) = explode("\r\n\r\n",$response,2);

// Print header
foreach (explode("\r\n",$headers) as $hdr)
    printf('
Header: %s
', $hdr);

there is a line "Header: x-token: xxxxxxx" as output
I now need the xxxxxx to go into a variable...


text:
Q: Php session in ajax call before link redirecting doesn't work I have a main page where you fill in some data. After you click on a link "create" it will call ajax to insert new record into mysql database (with data from main page). The mysql table where I'm inserting this new record has an auto_increment primary key and I need to know this key on page where the "create" link is redirecting. So to show it in a short simplified example I have something like this:
index.php has a link Create
index.php has also this jquery $("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... } }));
create.php inserts record into database and after that does this $_SESSION["id"] = mysql_insert_id();
new.php needs to get this id from $_SESSION["id"]
When I tried to call ajax (insert record) outside of click event (so immediately after the main page has loaded) before I actually clicked the link it worked perfectly. However this way it works kind of randomly. Sometimes it does sometimes it doesn't and it never ever worked in Google Chrome this way...
I'm using session_start() properly in the beginning of the documents so there's no problem in this.
Thank you very much for any help I'm struggling many days with this and at last I located that the problem comes from this ajax call position in click event but I have no idea how to fix it. I guess that I'm missing some knowledge about how exactly do page redirecting and click event work together with ajax.

A: First your session has to be started in the index.php page so new.php and create.php will receive the session ID in the session cookie. You could theoretically call $.ajax then change the window location right after it. However this doesn't guaranty you that create.php as finished execution (ie. created the line you want and insert the data you want into the session which should be stored in your database). This can result in a race condition which you are experiencing.
To fix this, you simply have to change your window URL in a function on Ajax call success like :
$("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... }, success: function() { window.location = 'new.php'; } }));