text:
Q: Formatting String I'm trying to format Strings as they arrive and meet certain criteria. However  if the tokens below are of different length things don't match up, How do I do this? I want all the "IP address"s to match up. I assume I use something like %20s?
if (tokens.length == 4 && (tokens[3].equals("up") || tokens[3].equals("down"))){
    String result = String.format("%s is %s. IP address: %s \n", tokens[0], tokens[2], tokens[1]);
    final String ReceivedText = mReceiveBox.getText().toString() + result;

    if(tokens[2].equals("up")){
        runOnUiThread(new Runnable() {
        public void run() {
            mReceiveBox.setText(ReceivedText);
            mReceiveBox.setSelection(ReceivedText.length());

         }
      });
   }
}

A: Here's an example of right padding a String with spaces:
System.out.println(String.format("%-40s", "SHORT TEXT") + "|");
System.out.println(String.format("%-40s", "SOME LONG TEXT") + "|");
System.out.println(String.format("%-40s", "SOME MUCH LONGER TEXT") + "|");

Which outputs:
SHORT TEXT                              |
SOME LONG TEXT                          |
SOME MUCH LONGER TEXT                   |

The - formatting flag will left justify your text. Without it, the output looks like:
                              SHORT TEXT|
                          SOME LONG TEXT|
                   SOME MUCH LONGER TEXT|

Also, as mentioned in another answer, you'll have to use a monospaced font if you want everything to align correctly.
Here are 2 lines of 10 characters each in a font which is not monospaced:
wwwwwwwwwwiiiiiiiiii
And those same 2 lines in a monospaced font:
wwwwwwwwww
iiiiiiiiii

A: Look into specifying a width in your format string, and include mReceiveBox.getText().toString() in your format (instead of appending result to it).
See: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
You want to end up with something like:
String result = String.format("%20s%s is %s. IP address: %s \n",
    mReceiveBox.getText().toString(), tokens[0], tokens[2], tokens[1]);

Where 20 is the maximum width for the receive box text. You'll need to do the same for the tokens preceding the IP as well.
EDIT: Also, from looking at your image, you're doing to need to used a fixed width font in your output. Otherwise you're going to need to start computing widths of rendered text in pixels. A much trickier problem.
EDIT 2: The font matters because if it's not fixed width, the width will actually depend on the content of your string. Consider the following (assuming you're using a standard font on a standard browser):
lllll that was five characters long
mmmmm that was five characters long
vs.
lllll that was five characters long
mmmmm that was five characters long

See the alignment issues?


text:
Q: How do I only get TOP-level child tags that match what I am looking for? For example, if I have:
<conversations>
  <status>1</status>
  <conversation>
    <status>0</status>
    <text>Hi</text>
  </conversation>
</conversations>

How do I go about getting < status > for < conversations > while ignoring < conversation >?

A: Use the child selector, >:
$('conversations > status')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way I can dynamically increment the number of items being showed on the html page using ajax, php and plain js This is what I have
The JS file:
var loadBtn = document.getElementById('loadButton');

loadBtn.addEventListener('click', fetchProducts);

let quantity = 3;

function fetchProducts() {

   quantity = quantity + 3;

   var xhr = new XMLHttpRequest;

   xhr.open('GET', `php/products.php?quantity=${quantity}`, true);

   xhr.onload = function () {
      if (this.status == 200) {
         var products = JSON.parse(this.responseText);

         var output, i;

         for (i = 0; i < products.length; i++) {
            output += `

${products[i].item_name}

${products[i].item_description}

                     `;
         }

         document.getElementById('products').innerHTML = output;
      }
   }

   xhr.send();
}

The PHP file:
include 'config.inc.php';

$quantity = $_GET['quantity'];

$sqlFetch = "SELECT id,item_name,item_description FROM items ORDER BY id ASC LIMIT $quantity";

$result = mysqli_query($connection, $sqlFetch);

$products = mysqli_fetch_all($result, MYSQLI_ASSOC);

echo json_encode($products);

I expected, after defining the quantity in the js file the fetchProducts function would increment the quantity of products and parse the quantity through GET to the php file.
Instead, this is what am getting from products.php:
Notice: Undefined index: quantity in C:\wamp64\www\simplesites\ss9_ajax\php\products.php on line 7


text:
Q: Android Socket download multiple files fired? I want to download multiple images from server. I open socket and download first image and when I want download second image in this socket, download not proceed, socket are closed. My code below...
public class ClientThread implements Runnable {
    public void run() {
        try {
            Log.d("ClientActivity", "C: Connecting...");
            SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
            socket = new Socket();
            socket.setKeepAlive(true);
            socket.connect(sockaddr, 5000);
            if (socket.isConnected()) {
                final DataInputStream input = new DataInputStream(socket.getInputStream());
                final PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                output.println("GET /way/images/profile/1231 HTTP/1.1");
                output.println("Host: 192.168.1.2");
                output.println("User-Agent: Java");
                output.println("Accept: */*");
                output.println("Connection: Keep-Alive");
                output.println("");
                output.flush();

                String line;
                File file = new File("/sdcard/aaa.png");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fileOut = new FileOutputStream(file);
                System.out.println("Getting first file");
                while ( (line = input.readLine()) != null ) {
                    System.out.println(line);
                    fileOut.write(line.getBytes());
                }
                System.out.println("First file finished");
                fileOut.flush();
                fileOut.close();

                output.println("GET /way/images/profile/1231 HTTP/1.1");
                output.println("Host: 192.168.1.2");
                output.println("User-Agent: Java");
                output.println("Accept: */*");
                output.println("Connection: Keep-Alive");
                output.println("");
                output.flush();

                file = new File("/sdcard/aaa1.png");
                if (!file.exists()) {
                    file.createNewFile();
                }
                fileOut = new FileOutputStream(file);
                System.out.println("Getting second file");
                while ( (line = input.readLine()) != null ) {
                    System.out.println(line);
                    fileOut.write(line.getBytes());
                }
                System.out.println("Second file finished");

                fileOut.flush();
                fileOut.close();
                input.close();
                output.close();
                socket.close();
            }
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

A: You seem to be downloading image files using HTTP, in which case, it would be simpler and better to use HttpURLConnection.
Code sample for downloading of images using HttpURLConnection can be found in this blog post: Downloading image in Android
You may also read about Android's HTTP Clients in Android Developers Blog.


text:
Q: Sparse array support in HDF5 I need to store a 512^3 array on disk in some way and I'm currently using HDF5. Since the array is sparse a lot of disk space gets wasted.
Does HDF5 provide any support for sparse array ?

A: Chunked datasets (H5D_CHUNKED) allow sparse storage but depending on your data, the overhead may be important.
Take a typical array and try both sparse and non-sparse and then compare the file sizes, then you will see if it is really worth.

A: One workaround is to create the dataset with a compression option. For example, in Python using h5py:
import h5py
f = h5py.File('my.h5', 'w')
d = f.create_dataset('a', dtype='f', shape=(512, 512, 512), fillvalue=-999.,
                     compression='gzip', compression_opts=9)
d[3, 4, 5] = 6
f.close()

The resulting file is 4.5 KB. Without compression, this same file would be about 512 MB. That's a compression of 99.999%, because most of the data are -999. (or whatever fillvalue you want).

The equivalent can be achieved using the C++ HDF5 API by setting H5::DSetCreatPropList::setDeflate to 9, with an example shown in h5group.cpp.

A: HDF5 provides indexed storage: http://www.hdfgroup.org/HDF5/doc/TechNotes/RawDStorage.html


text:
Q: Gradle dependency management plugin I am trying to run the following minimal gradle build file including the dependency management plugin:
buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
}

plugins {
    id "java"
    id "io.spring.dependency-management" version "1.0.4.RELEASE"
}

But then running gradle fails:
* What went wrong:
Plugin [id: 'io.spring.dependency-management', version: '1.0.4.RELEASE'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'io.spring.dependency-management:io.spring.dependency-management.gradle.plugin:1.0.4.RELEASE')
  Searched in the following repositories:
    Gradle Central Plugin Repository

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
See https://docs.gradle.org/4.5.1/userguide/command_line_interface.html#sec:command_line_warnings

Is there a missing dependency in the gradle file?

A: The plugin cannot be found because you defined repositories inside your build script and tried to use plugin outside it. Remove buildscript or add repositories for your build file also.
(Dependencies and repositories defined inside build script are accessible in that buildscript scope)
Example:
plugins {
    id "java"
    id "io.spring.dependency-management" version "1.0.4.RELEASE"
}

repositories {
        mavenCentral()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }


text:
Q: .htaccess redirect remove "?_route_=" form URL I am using .htaccess redirect in my website. I am using those code

Redirect /addgiftmr/widgetjs.aspx https://www.mysite.com/

But when redirect, it is adding extra word. I am getting url as https://www.mysite.com/?route=addgiftmr/widgetjs.aspx
how can I remove ?route=addgiftmr/widgetjs.aspx form link?

A: Here is how to do it in .htaccess if mod-rewrite is installed. The advantage of mod-rewrite is that it is easier to expand later if you want to use more complex rules.
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteRule ^addgiftmr/widgetjs.aspx https://www.mysite.com/ [L,R]


text:
Q: Sum of cubes with time limit of execution How can I make the time limit for the execution of the code to be 2 seconds. The code calculates if a given number(the input)is expressible as the sum of two cubes in at least two different ways.
#include<stdio.h>

int main() {
int n, j, k, int_count;

scanf("%d", &n);

   int_count = 0;
   for (j=1; j<=n; j++) {
      for(k=j+1; k<=n; k++) {

          if(j*j*j+k*k*k == n)

          int_count++;
      }
   }
   if(int_count >= 2) {

      printf("YES");

   }
   else
   printf("NO");

}

A: Maybe just use time() or gettimeofday().
#include<stdio.h>
#include<time.h>
int main() {
    long n, j, k, int_count;
    time_t t;

    scanf("%d", &n);
    t = time(0);
    int_count = 0;
    for (j = 1; j <= n; j++)
        for(k = j+1; k < n; k++) {
            if(j*j*j + k*k*k == n)
                if(++int_count > 1) {
                    puts("YES");
                    return 0;
                }
            if (time(0) - t >= 2) {
                puts("timeout");
                return 1;
            }
        }
    puts("NO");
    return 0;
}


text:
Q: Count all characters in string and output as string in ES6 Javascript Javascript implementation to print the characters and frequencies in the order of their occurrence. Please if anyone knows a better solution how to count characters in the string and output the result as a string as i dont like "converting an object to string" part.
See test cases below

function process (str) {

  //reject empty string
  if (!str) return "";

  //clean up
   str = str.replace(/[\s\W\d]/g, '').toLowerCase();

  //get result
  let result = str.split('').reduce((total, letter) => {
    total[letter] ? total[letter]++ : total[letter] = 1;
    return total;
  }, {});

   //convert to string
   let objToString = "";
   for (let key in result) {
     if (result.hasOwnProperty(key)) {
       objToString += `${key}${result[key]}`;
     }
   }
   return objToString;
}

//TEST
console.log('numbers', process('826'));
console.log('chars', process('**************'));
console.log('caps', process('ABC'));
console.log('spaces', process('AC  DC'));
console.log('mix', process('aaaa7682647828467823486^^&*^&*@^*@&*@^*@^*&^*&@^*&ssw1231323&*(&*(S&(*(*S(S&(23232132wwaaaabbbccccccccdddddd'));
console.log('mix', process('aabbbbccccdddddd'));

A: hope this helped.
function process (str) {
    if (!str) return "";

    str = str.replace(/[\s\W\d]/g, '').toLowerCase();

    const result = [...new Set(str.split(""))].reduce((p, c) => {
        return p += c + (str.split(c).length - 1);
    }, "");

    return result;
}

A: Added a filter that can be modified via second parameter.

function chars(string, filter = 'all') {
  if (!string) return "";
  let rgx;
  switch (filter) {
    case 'a': // Alphabet
      rgx = /[A-Za-z]/;
      break;
    case 'd': // Digits
      rgx = /[\d]/;
      break;
    case 'u': // Uppercase
      rgx = /[A-Z]/;
      break;
    case 'l': // Lowercase
      rgx = /[a-z]/;
      break;
    case 's': // Whitespace
      rgx = /[\s]/;
      break;
    case 'x': // Other
      rgx = /[!`~@#$%&*\^\\\-\][_;:<>,.+=(){}|?/]/;
      break;
    case 'all': // All
      rgx = /[!`~@#$%&*\^\\\-\][_;:<>,.+=(){}|?/\s\dA-Za-z]/;
      break;
    default:
      break;
  }
  let result = string.split('').reduce((total, char) => {
    let letter = rgx.test(char) ? char : '';
    total[letter] ? total[letter]++ : total[letter] = 1;
    return total;
  }, {});
  // Filter all ''
  result = Object.fromEntries(Object.entries(result).filter(([k, v]) => k != ''));

  let objToString = "";
  for (let key in result) {
    if (result.hasOwnProperty(key)) {
      objToString += `${key}: ${result[key]}, `;
    }
  }
  return objToString.slice(0, -2);
}

//TEST
console.log('numbers', chars('826', 'd'));
console.log('chars', chars('**************', 'x'));
console.log('caps', chars('AaBCCCc', 'u'));
console.log('spaces', chars('AC  DC', 's'));
console.log('all', chars('aaaa7682647828467823486^^&*^&*@^*@&*@^*@^*&^*&@^*&ssw1231323&*(&*(S&(*(*S(S&(23232132wwaaaabbbccccccccdddddd'));
console.log('letters', chars('aaCCbbbBccccdddddd', 'a'));


text:
Q: Using buzzer without delay [C] STM32 i using interruptcounter from STM32 to count a rotating speed of fan.
On the beginning of counting - I give a buzzer tone with:
void Beep(int ton) {
    uint16_t i = 0;
    do {
        GPIO_SetBits(GPIOD, GPIO_Pin_4);
        Delay(ton);
        GPIO_ResetBits(GPIOD, GPIO_Pin_4);
        Delay(ton);
        i++;
    } while (i < 50);
}

of course of delay interruptconter get more counts. How can realize a buzzer without using Delay function?
// Start beep, begin measurement
        if (sec_cnt == 3 && measuring == TRUE) {
//          Beep(5000);
            }

        // Stop beep, measurement done
        if (sec_cnt == timer + 3 && measuring == TRUE) {
//          Beep(4000);
        }


text:
Q: How to start a child workflow? I've created a new list-based workflow which has one step that's pretty simple. After that step I'd like to launch another workflow - the Collect Signatures workflow. How can I launch a child workflow from my workflow?
I'm using SharePoint Designer to create the workflow.
I've read that some people have used the Invoke action or the Code action to write custom code to invoke the child workflow, but I don't see either of these options in Designer.

A: SharePoint Designer workflows do not natively have any way to launch another workflow, but there are ways to accomplish this.

*

*Configure the secondary/child workflow to start "On Change"

*Create a site column that will be used as control field between the parent/child

*Add the site column as an Association Column on both workflows so they can see it

*Have the parent workflow set the control field with a status value (e.g. "Start")

*Have the child workflow read the status to know it should fire. When done, have it update the status (e.g. "Complete")

It is possible that other native fields (e.g. an existing status column) could be used instead of a control field, but I like using a specific control field to communicate between the parent and the child.
If you need the parent workflow to wait for the child, add a "Wait for ..." activity to wait for the control field to be set to "Complete".
If you need to pass additional state between the workflows you can either add additional association columns, or use a secondary list.


text:
Q: HERE API: Clicking project doesn't go to Generate AppID page When I had only one project, clicking it didn't go to the Generate AppID page. Once I added a second project, clicking either of them took me to that page. Is this a bug or a feature?

A: This may be one time issue but as of now this is not happening.
https://developer.here.com/projects
taking to the project page where credentials are generated.
Please do let us know if you still have this issue.


text:
Q: Testing Windows Phone 8 Enterprise Applications Can we use a self signed certificate to test the MDM Server with WP8 for distribution of sample enterprise applications as this process requires a certificate from Symantec ???

A: A regular signed app installed via web / email must be correctly signed using the $299 Symantec certificate. The device checks the validity of both your cert and your dev center account prior to install (and launch?). Most MDMs will need to play by the same rules, but I've no idea if Microsoft Intune gets special treatment.


text:
Q: numericUpDown control to increment according to column in DataTable On Form Load I tried this:
numericUpDown1.DataBindings.Add(new Binding("Value", dt, "ID", true, DataSourceUpdateMode.OnValidation));

This didn't worked for me, the data field incremented by one.
but the column ID has different values that doesn't increment by one.
How can I use the up or down button of the object and the data field will be changed according to the next value of id column?
Thanks.


text:
Q: launchctl load -w No such file or directory I'm trying to set an automatically program for getintraday.py in mac using launchctl.
1. Create run.sh
go to getintraday.py directory
cd /Users/yindeyong/Desktop/Django_Projects/pythonstock

vi run.sh

Following is run.sh:
#!/bin/sh

# record start time
echo `date` >> /Users/yindeyong/Desktop/Django_Projects/pythonstock/log &&

# go to getintraday.py directory

cd /Users/yindeyong/Desktop/Django_Projects/pythonstock &&

# Execute python scripts according to my virtual environment
/Users/yindeyong/Desktop/Django_Projects/envs/stockenv/bin/python3.6 getintraday.py
# Execute done
echo 'finish' >> /Users/demo/log/Users/yindeyong/Desktop/Django_Projects/pythonstock/log

Then save and quite
 :wq
chmod 777 run.sh

2. Create plist document
go to ~/Library/LaunchAgents,create com.demo.plist
Following is create com.demo.plist:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <!-- Label -->
      <key>Label</key>
      <string>com.demo.plist</string>
      <!-- the script to Execute -->
      <key>ProgramArguments</key>
      <array>
        <string>/Users/yindeyong/Desktop/Django_Projects/pythonstock/run.sh</string>
      </array>
      <!-- the time to Execute  -->
      <key>StartCalendarInterval</key>
      <dict>
            <key>Minute</key>
            <integer>37</integer>
            <key>Hour</key>
            <integer>10</integer>
      </dict>
    <!-- Standard output file -->
    <key>StandardOutPath</key>
    <string>/Users/yindeyong/Desktop/Django_Projects/pythonstock/run.log</string>
    <!--
Standard error output file, error log -->
    <key>StandardErrorPath</key>
    <string>/Users/yindeyong/Desktop/Django_Projects/pythonstock/run.err</string>
    </dict>
    </plist>

*Load command
launchctl load -w com.demo.plist
But I get /Users/yindeyong/Desktop/Django_Projects/pythonstock/com.demo.plist: No such file or directory

A: Since you didn't specify a path for the plist file, it assumed your current working directory (/Users/yindeyong/Desktop/Django_Projects/pythonstock). Try specifying the actual location of the plist file:
launchctl load -w ~/Library/LaunchAgents/com.demo.plist

BTW, you should actually use a different name and label for your launch agent. The current name implies that it's produced by the owners of the domain demo.com, which I presume is not you (see: reverse domain name notation). If you don't have a domain name of your own to attribute the agent to, use something with a "local." prefix (e.g. "local.demo"). Also, the label should not include ".plist", that's a suffix that's added to the file name. Thus, you could use the label "local.demo" and name the file "local.demo.plist".


text:
Q: How to extract the timestamps whenever an e.g. categorical pandas time series changes state I recently had the problem where a pandas time series contained a signal that could take several states, and I was interested in the start and end timestamps of each state so that I could construct timeslots for each event. The input signal was a Pandas Series with a Timestamp index, and values could either be integers (e.g. numerical representation of a category) or NaN. For NaN, I could assume that there had been no state change since the last state (ffill would basically fix this) and that the state change happened exactly when it was logged (so the plot actually ought to be a step chart, not linearly interpolated as illustrated below).
Since timeslots are defined by their start time and the end time, I am interested in a method that can extract the pairs of (start time, end time) for the timeslots illustrated at the bottom of the figure.

Data:
import pandas as pd

data = [2,2,2,1,2,np.nan,np.nan,1,3,3,1,1,np.nan,
        2,1,np.nan,3,3,3,2,3,np.nan,3,1,2,1,3,3,1,
        np.nan,1,1,2,1,3,1,2,np.nan,2,1]
s = pd.Series(data=data, index=pd.date_range(start='1/1/2020', freq='S', periods=40))

A: Ok, so this is the method I came up with. If anyone has a more efficient or elegant approach, please share.
import numpy as np
import pandas as pd

# Create the example Pandas Time Series
data = [2,2,2,1,2,np.nan,np.nan,1,3,3,1,1,np.nan,2,1,np.nan,3,3,3,2,3,np.nan,3,1,2,1,3,3,1,np.nan,1,1,2,1,3,1,2,np.nan,2,1]
dt = pd.date_range(start='1/1/2020', freq='S', periods=40)
s = pd.Series(data=data, index=dt)

# Drop NAN and calculate the state changes (not changing states returns 0)
s_diff = s.dropna().diff()

# Since 0 means no state change, remove them
s_diff = s_diff.replace(0,np.nan).dropna()

# Create a series that start with the time serie's initial condition, and then just the state change differences between the next states.
s_diff = pd.concat([s[:1], s_diff])

# We can now to a cumulative sum that starts on the initial value and adds the changes to find the actual states
s_states = s_diff.cumsum().astype(int)

# If the signal does not change in during the last timestamp, we need to ensure that we still get it.
s_states[s.index[-1]] = int(s[-1])

# Extract pairs of (start, end) timestamps for defining the timeslots. The .strftime method is only applied for readability. The following would probably be more useful:
# [(s_states.index[i], s_states.index[i+1] for i in range(len(s_states)-1)]
[(s_states.index[i].strftime('%M:%S'), s_states.index[i+1].strftime('%M:%S')) for i in range(len(s_states)-1)]
Out:
[('00:00', '00:03'),
 ('00:03', '00:04'),
 ('00:04', '00:07'),
 ('00:07', '00:08'),
 ('00:08', '00:10'),
 ('00:10', '00:13'),
 ('00:13', '00:14'),
 ('00:14', '00:16'),
 ('00:16', '00:19'),
 ('00:19', '00:20'),
 ('00:20', '00:23'),
 ('00:23', '00:24'),
 ('00:24', '00:25'),
 ('00:25', '00:26'),
 ('00:26', '00:28'),
 ('00:28', '00:32'),
 ('00:32', '00:33'),
 ('00:33', '00:34'),
 ('00:34', '00:35'),
 ('00:35', '00:36'),
 ('00:36', '00:39')]

A: Here's a slightly more compact method. We'll create a label for each group and then use groupby to determine where that group starts. To form these groups ffill to deal with NaN, take the difference and check where that's not 0 (i.e. it changes to any state). A cumsum of this Boolean Series forms the groups. Since the next group has to start when the previous group ends we  shift to get the end times.
gps = s.ffill().diff().fillna(0).ne(0).cumsum()

df = s.reset_index().groupby(gps.to_numpy()).agg(start=('index', 'min'))
df['stop'] = df['start'].shift(-1)

Output
print(df.apply(lambda x: x.dt.strftime('%M:%S')))
## If you want a list of tuples:
# [tuple(zip(df['start'].dt.strftime('%M:%S'), df['stop'].dt.strftime('%M:%S')))]

    start   stop
0   00:00  00:03
1   00:03  00:04
2   00:04  00:07
3   00:07  00:08
4   00:08  00:10
5   00:10  00:13
6   00:13  00:14
7   00:14  00:16
8   00:16  00:19
9   00:19  00:20
10  00:20  00:23
11  00:23  00:24
12  00:24  00:25
13  00:25  00:26
14  00:26  00:28
15  00:28  00:32
16  00:32  00:33
17  00:33  00:34
18  00:34  00:35
19  00:35  00:36
20  00:36  00:39
21  00:39    NaT   # Drop the last row if you don't want this


text:
Q: MySQL After Insert and After Update Trigger I have two tables t1 and t2. i have created two triggers tr1 after insert on t1 and tr2 after update on t2. in both the tables i m updating table t2. so, it is throwing an error saying the t2 table is already getting updated in another trigger so can not update it again.
Please let me know if anyone has faced this type of problem and fixed it.
Thanks in advance!
MySQL DBA.

A: If you want to modify the data that is being updated or inserted, you should use a BEFORE UPDATE and/or BEFORE INSERT trigger and then make use of NEW alias (it references the row, that is being inserted or the row as it will look after the update is applied) - you can actually modify the fields that are being inserted. OLD alias references the row before the update is applied or the row before it is deleted (in triggers that fire on delete).
So probably for trigger tr2 you need to something along the lines of:
DELIMITER $$
    CREATE TRIGGER tr2 BEFORE UPDATE ON t2
    FOR EACH ROW BEGIN
      SET NEW.field1 = some_value_you_want_to_set_it_to;
    END;
$$
DELIMITER ;

Because in a trigger you can not actually UPDATE a table, that is being already updated, thats right.

A: I have fixed this problem, there was a problem as i was trying to update and insert on same table tb1 from two triggers but Mysql does not allowed the same table to be modified i suppose.
Thanks


text:
Q: Methods to generate random PrintCard I need to use public static void PrintCard (int number, int suit) as the header in my program to print 5 random cards (number & suit) example "Ace of Spades".
I'm not entirely sure where to go about it, but I was wondering if there was a way to make a randomly generated number = Ace or etc., because Ace isn't a variable I get a error.
example: 0 = Ace (won't work because variable on wrong side) and
number == 0
return Ace;

those are things I've tried, sorry if its really broad or etc. I'm just pretty lost and novice when it comes to coding.
edit:
#  Card
_______
0  Ace
1  Two
2  Three
3  Four
4  Five
5  Six
6  Seven
7  Eight
8  Nine
9  Ten
10 Jack
11 Queen
12 King

#  Suit
_______
0 Spaces
1 Hearts
2 Clubs
3 Diamonds

Structure of your program

import....

class {

  main method {
    num
    suit

    loop {
      loop 5x {
         num = generate random number 0-12
         suit = generate random number 0-3
         PrintCard (num, suit)
      }
      Prompt the user to continue
      read input from the user into a string
      if (input is yes)
         stay inside this loop, otherwise get out
     }
  }

  PrintCard (number, suit) {
    switch (number)
      // print the word for the card value
    print " of "
    switch (suit)
      // print the word for the card suit
  }

}

A: You could put the face and suit names into String arrays, and then pick a random entry from each array. First, you'd need a way to pick an item at random from an array. Something like,
private static Random rand = new Random();
public static <T> T randomEntry(T[] arr) {
    return (arr != null) ? arr[rand.nextInt(arr.length)] : null;
}

Then you could generate card names and add them to a LinkedHashSet (to preserve insertion order) until you have 5 entries,
String[] names = { "Ace", "Deuce", "Trey", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
String[] suits = { "Spades", "Clubs", "Hearts", "Diamonds" };
Set<String> cards = new LinkedHashSet<>();
while (cards.size() < 5) {
    cards.add(String.format("%s of %s", randomEntry(names),
        randomEntry(suits)));
}

Then your output is just
for (String card : cards) {
    System.out.println(card);
}

A: Before you start to write code i suggest you to do some planning using classic pen and paper. There is several steps, that you can go through that will help you to simplify your work.
First, write down WHAT you want your program to have. In your example it can be like this:

*

*Generating random suit of a card

*Generating random number of a card

*Storing generated cards

*Storing generated cards in group of 5

*Printing out the results

Next step after you did this is to ask and answer guestion HOW you can do things written in the list. For example:

*

*How to generate random suit or number? Java has a class called Random. All the methods could be found here.

*How to store generated card? Java has lot's of utilities to store sets of data. For example ArrayList. All the methods and info could be found here.
There are 13 cards in suit. There are 4 suits. So you must have two ArrayList to store all the naming of cards and suits.
You must generate 2 different integers: 0-12 and 0-3.
You must store generated card in another ArrayList so you can access it later.
Loop process, as far as you can do this there is nothing in printing out the results taken from Array.
UPD1 code example:
Here is example of a code you may need:
    //variables to store generated card as string

    private String generatedCard;
   //create Array list for suits
  ArrayList<String> suits = new ArrayList<>();
  //fill the List
  suits.add("spades"); //index no [0]
  suits.add("hearts");
  suits.add("diamonds");
  suits.add("clubs"); //index no [3]
  //create Array list for numbers
   ArrayList<String> numbers = new ArrayList<>();
  //fill the list
   - - - -
  //create ArrayList for generated Cards
   ArrayList<String> cards = new ArrayList<>();
  //create Randomiser
    Random rnd = new Random();
  for (int i = 0; i <5; i++){
        generatedCard = ""+suits.get( rnd.nextInt(4)) + " " + numbers.get(rnd.nextInt(13));
      cards.add(i, generatedCard);
  }

For printing out use for loop with System.out.println(cards.get(indexer));


text:
Q: java.lang.RuntimeException: This query has an outstanding network connection. You have to wait until it's done I am trying to populate the list view  with the address by running query on the nearby locations from point g to the list of address/geopoint in the parse server.:
public class Map_Masti extends FragmentActivity {
    ParseGeoPoint g;
    private SupportMapFragment mapFragment;
    private TextView textView;
    private  ParseQueryAdapter<Rahees> adapter;
    private ParseQueryAdapter<Rahees> postsQueryAdapter;//this is outside oncreate
  private List <ParseGeoPoint> points=new ArrayList<ParseGeoPoint>();

    private void getG() {
        ParseQuery<ParseUser> query = ParseUser.getQuery();
        query.getInBackground("ccm3xKMmr4", new GetCallback<ParseUser>() {
            public void done(ParseUser object, ParseException e) {
                if (e == null) {
                    g = (ParseGeoPoint) object.get("user_Location");

                    display();

                } else {

                }
            }
        });
    }

    public void display()
    {

        // Set up a customized query
        ParseQueryAdapter.QueryFactory<Rahees> factory =
                new ParseQueryAdapter.QueryFactory<Rahees>() {
                    public ParseQuery<Rahees> create() {
                        ParseQuery<Rahees> query = Rahees.getQuery();

                        query.include("user");
                        query.whereWithinKilometers("Locations", g, 1000);

                        query.findInBackground(new FindCallback<Rahees>() {//here is the error
                            @Override
                            public void done(List<Rahees> objects, ParseException e) {
                                //to check if there is a result

                                }
                            }
                        });
                        return query;
                    }
                };

        // Set up the query adapter
        postsQueryAdapter = new ParseQueryAdapter<Rahees>(this, factory) {
            @Override
            public View getItemView(Rahees post, View view, ViewGroup parent) {
                if (view == null) {

                    view = View.inflate(getContext(), R.layout.row1_of_listvew, null);
                }
                TextView contentView = (TextView) view.findViewById(R.id.textView1);
                TextView usernameView = (TextView) view.findViewById(R.id.textView2);
                contentView.setText(post.getInt("Address"));
                usernameView.setText(post.getInt("Address"));
                return view;
            }
        };

        postsQueryAdapter.setAutoload(false);

// ***************************Disable pagination, we'll manage the query limit ourselves********************************/

        postsQueryAdapter.setPaginationEnabled(false);

        //********************************** Attach the query adapter to the view/

        ListView postsListView = (ListView) findViewById(R.id.listview);

        postsListView.setAdapter(postsQueryAdapter);

        postsQueryAdapter.loadObjects();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_masti);
        textView = (TextView) findViewById(R.id.text);
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
      getG();
    }
}
 //****************************************************************************//

Below is the error that I'm getting
01-17 12:35:11.434: E/AndroidRuntime(21497): FATAL EXCEPTION: main
01-17 12:35:11.434: E/AndroidRuntime(21497): Process: in.easyway2.com.learn_parse, PID: 21497
01-17 12:35:11.434: E/AndroidRuntime(21497): java.lang.RuntimeException: This query has an outstanding network connection. You have to wait until it's done.
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQuery.checkIfRunning(ParseQuery.java:948)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQuery.doWithRunningCheck(ParseQuery.java:1129)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQuery.findAsync(ParseQuery.java:1193)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQuery.findInBackground(ParseQuery.java:1180)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQueryAdapter.loadObjects(ParseQueryAdapter.java:387)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.parse.ParseQueryAdapter.loadObjects(ParseQueryAdapter.java:362)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at in.easyway2.com.learn_parse.Map_Masti.display(Map_Masti.java:177)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at in.easyway2.com.learn_parse.Map_Masti$1.done(Map_Masti.java:50)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at in.easyway2.com.learn_parse.Map_Masti$1.done(Map_Masti.java:45)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at android.os.Handler.handleCallback(Handler.java:733)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at android.os.Looper.loop(Looper.java:136)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at android.app.ActivityThread.main(ActivityThread.java:5001)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at java.lang.reflect.Method.invoke(Method.java:515)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-17 12:35:11.434: E/AndroidRuntime(21497):    at dalvik.system.NativeStart.main(Native Method)

New to Parse so not very sure , have just followed the instructions from the guide.

A: You should try uninstalling and reinstalling the app again. This solved the problem for me at least.
Another thing you can try is to delete and recreate the object or class you are querying about.
Tell me if this worked.

A: I should not have added execution of the query in factory query, the below part: query.findInBackground(new FindCallback() {//here is the error @Override public void done(List objects, ParseException e) { //to check if there is a result } } });


text:
Q: Cannot connect to CVS repo from outside lan I recently installed cvs onto by ubuntu server (11.10).  I am able to connect to my repos via eclipse IDE from within my lan by using the server name.  However, when I use the IP address instead I cannot connect.
This error is given:  "Cannot connect to host: Connection refused".
I have port forwarding on and can connect to apache2, mysql, etc. from outside my lan just fine.

A: I found this when I was Googling a bit.
http://kulitkulit.wordpress.com/2009/08/06/installation-cvs-ubuntu-jaunty/


text:
Q: How can I prove that $(a_1+a_2+\dotsb+a_n)(\frac{1}{a_1}+\frac{1}{a_2}+\dotsb+\frac{1}{a_n})\geq n^2$ I've been struggling for several hours, trying to prove this horrible inequality:
$(a_1+a_2+\dotsb+a_n)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dotsb+\frac{1}{a_n}\right)\geq n^2$.
Where each $a_i$'s are positive and $n$ is a natural number.
First I tried the usual "mathematical induction" method, but it made no avail, since I could not show it would be true if $n=k+1$.
Suppose the inequality holds true when $n=k$, i.e.,
$(a_1+a_2+\dotsb+a_k)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dotsb+\frac{1}{a_k}\right)\geq n^2$.
This is true if and only if
$(a_1+a_2+\dotsb+a_k+a_{k+1})\left(\frac{1}{a_1}+\frac{1}{a_2}+\dotsb+\frac{1}{a_k}+\frac{1}{a_{k+1}}\right) -a_{k+1}\left(\frac{1}{a_1}+\dotsb+\frac{1}{a_k}\right)-\frac{1}{a_{k+1}}(a_1+\dotsb+a_k)-\frac{a_{k+1}}{a_{k+1}} \geq n^2$.
And I got stuck here.
The question looks like I have to use AM-GM inequality at some point, but I do not have a clue. Any small hints and clues will be appreciated.

A: It is AM-HM inequality
$$\frac{a_1+a_2+a_3+...+a_n}{n}\geq \frac{n}{\frac{1}{a_1}+\frac{1}{a_2}+\frac{1}{a_3}+...+\frac{1}{a_n}}$$

A: Here is the proof by induction
that you wanted.
I added a more exact
version of
the identity used
in the proof
at the end.
Let
$s_n
=u_nv_n
$
where
$u_n=\sum_{k=1}^n a_k,
v_n= \sum_{k=1}^n \dfrac1{a_k}
$.
Then,
assuming
$s_n \ge n^2$,
$\begin{array}\\
s_{n+1}
&=u_{n+1}v_{n+1}\\
&=(u_n+a_{n+1}) (v_n+\dfrac1{a_{n+1}})\\
&=u_nv_n+u_n\dfrac1{a_{n+1}}+a_{n+1}v_n+1\\
&=s_n+u_n\dfrac1{a_{n+1}}+a_{n+1}v_n+1\\
&\ge n^2+u_n\dfrac1{a_{n+1}}+a_{n+1}v_n+1\\
\end{array}
$
So it is sufficient
to show that
$u_n\dfrac1{a_{n+1}}+v_na_{n+1}
\ge 2n
$.
By simple algebra,
if $a, b \ge 0$ then
$a+b
\ge 2\sqrt{ab}
$.
(Rewrite as
$(\sqrt{a}-\sqrt{b})^2\ge 0$
or,
as an identity,
$a+b
=2\sqrt{ab}+(\sqrt{a}-\sqrt{b})^2$.)
Therefore
$\begin{array}\\
u_n\dfrac1{a_{n+1}}+v_na_{n+1}
&\ge \sqrt{(u_n\dfrac1{a_{n+1}})(v_na_{n+1})}\\
&= \sqrt{u_nv_n}\\
&=2\sqrt{s_n}\\
&\ge 2\sqrt{n^2}
\qquad\text{by the induction hypothesis}\\
&=2n\\
\end{array}
$
and we are done.
I find it interesting that
$s_n \ge n^2$
is used twice in the
induction step.
Note that,
if we use the identity above,
$a+b
=2\sqrt{ab}+(\sqrt{a}-\sqrt{b})^2$,
we get this:
$\begin{array}\\
s_{n+1}
&=s_n+u_n\dfrac1{a_{n+1}}+a_{n+1}v_n+1\\
&=s_n+2\sqrt{u_n\dfrac1{a_{n+1}}a_{n+1}v_n}+1+(\sqrt{u_n\dfrac1{a_{n+1}}}-\sqrt{a_{n+1}v_n})^2\\
&=s_n+2\sqrt{s_n}+1+\dfrac1{a_{n+1}}(\sqrt{u_n}-a_{n+1}\sqrt{v_n})^2\\
&=(\sqrt{s_n}+1)^2+\dfrac1{a_{n+1}}(\sqrt{u_n}-a_{n+1}\sqrt{v_n})^2\\
&\ge(\sqrt{s_n}+1)^2\\
\end{array}
$
with equality
if and only if
$a_{n+1}
=\sqrt{\dfrac{u_n}{v_n}}
=\sqrt{\dfrac{\sum_{k=1}^n a_k}{\sum_{k=1}^n \dfrac1{a_k}}}
$.

A: Hint: AM-GM implies
$$
a_1+a_2+\cdots +a_n\ge n\sqrt[n]{a_1a_2\cdots a_n}
$$ and $$
\frac1{a_1}+\frac1{a_2}+\cdots +\frac1{a_n}\ge \frac{n}{\sqrt[n]{a_1a_2\cdots a_n}}.
$$


text:
Q: Textbox not accepting UTF8 How to use universal standard UTF8 on final dashboard layout (not datasets but titles and layout)?
Specifically the textbox  component is not accepting copy/paste of UTF-8 characters as «this» or "→".
PS: my windows locale is wrong and enforce the use of Windows-1252 charset... but I must to use UTF-8 on my Power BI dashboards.

A: I was able to copy-paste in those characters into a Textbox with no dramas - see below:

My Windows display language and Keyboard are both: English (Australia).
Perhaps you need to turn on the Preview feature: Smart narrative visual?  That changes the Textbox UX a lot.


text:
Q: Transparent Activity floating/draggable on Homscreen I know how to create a simple transparent activity, but how do I have both Transparent activity and draggable across the screen. Best example I can think of is the Overskreen app on Google Play.

A: Try This
Manifest:

<activity
       android:name=".popup.PopupActivity"
       android:excludeFromRecents="true"
       android:label="@string/app_name"
       android:launchMode="singleTop"
       android:screenOrientation="portrait"
       android:theme="@style/Theme.Transparent" />

Code:
View mRootView;
WindowManager.LayoutParams params;
WindowManager windowManager;

@Override
protected void onCreate(Bundle savedInstanceState){
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    mRootView = getLayoutInflater().inflate(R.layout.popup_alert_dialog, null);

    params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_TOAST,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.START;
    params.x = 0; // initial position
    params.y = 0; // initial position

    //this code is for dragging the chat head
    mRootView.setOnTouchListener(new View.OnTouchListener() {
        private int initialX;
        private int initialY;
        private float initialTouchX;
        private float initialTouchY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = params.x;
                    initialY = params.y;
                    initialTouchX = event.getRawX();
                    initialTouchY = event.getRawY();
                    return true;
                case MotionEvent.ACTION_UP:
                    return true;
                case MotionEvent.ACTION_MOVE:
                    int newX = initialX
                            + (int) (event.getRawX() - initialTouchX); // new position
                    int newY = initialY
                            + (int) (event.getRawY() - initialTouchY); // new position
                    params.x = newX;
                    params.y = newY;
                    windowManager.updateViewLayout(mRootView, params);
                    return true;
            }
            return false;
        }
    });

    windowManager.addView(mRootView, params);

    // update content view here
    TextView tv = (TextView) mRootView.findViewById(R.id.textView);
    tv.setText("Hello World!!");

    // no need to call setContentView() any more
}


text:
Q: How to filter a dataset according to datetime values in Spark I am trying to filter my data according to it's datetime field. A sample from my data:
303,0.00001747,4351040,75.9054,"2019-03-08 19:29:18"

This is how I initialize spark:
    SparkConf conf = new SparkConf().setAppName("app name").setMaster("spark://192.168.1.124:7077");
    JavaSparkContext sc = JavaSparkContext.fromSparkContext(SparkContext.getOrCreate(conf));

Firstly, I read the data above into my custom object like below:
    // Read data from file into custom object
    JavaRDD<CurrencyPair> rdd = sc.textFile(System.getProperty("user.dir") + "/data/data.csv", 2).map(
        new Function<String, CurrencyPair>() {
            public CurrencyPair call(String line) throws Exception {
                String[] fields = line.split(","); // Split line from commas

                // read each data into custom object
                CurrencyPair cp = new CurrencyPair();
                cp.setId(Integer.parseInt(fields[0].trim()));
                cp.setValue(Double.parseDouble(fields[1].trim()));
                cp.setBaseVolume(Double.parseDouble(fields[2].trim()));
                cp.setQuoteVolume(Double.parseDouble(fields[3].trim()));
                cp.setTimeStamp(new Date(fields[4].trim()));

                System.out.println("Date:" + fields[4].trim()); // To see if it will print or not

                return cp;
            }
        }
     );

In order to get the data which has timestamp bigger than a certain time, I wrote this filter:
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -10); // This is for test issue

    // My filter to get the data for a certain time range
    Function<CurrencyPair, Boolean> filter = new Function<CurrencyPair, Boolean>() {
        @Override
        public Boolean call(CurrencyPair currencyPair) throws Exception {
            if(calendar.getTime().compareTo(currencyPair.getTimeStamp()) > 0){
                return false;
            }else{
                return true;
            }
        }
    };

This is how my custom object looks like:
public class CurrencyPair implements java.io.Serializable {

    private int id;
    private double value;
    private double baseVolume;
    private double quoteVolume;
    private Date timeStamp;

    // all getters and setters are here, but no constructor
}

To check the results of my filter, I tried to see some of them(first 100 here):
Iterator<CurrencyPair> result = rdd.repartition(100).filter(filter).toLocalIterator();
int counter = 0;
while (counter < 100 && result.hasNext()){
    System.out.println("Here: " + result.next());
    counter++;
}

But the problem is that when I run my code I got the following exception at the line where I write the first 100 result (Here: System.out.println("Here: " + result.next());)
Error:
19/05/12 00:05:47 INFO TaskSetManager: Lost task 0.3 in stage 0.0 (TID 6) on 192.168.1.124, executor 0: java.lang.ClassCastException (cannot assign instance of java.lang.invoke.SerializedLambda to field org.apache.spark.rdd.MapPartitionsRDD.f of type scala.Function3 in instance of org.apache.spark.rdd.MapPartitionsRDD

In my filter, I also write the datetime string to console with using System.out.println, but I can not see the result of it in the console as well. What am I doing wrong? How can I achieve this?

Edit: I noticed that I actually downloaded spark 2.3.0 version but in my maven file I was using 2.4.2. So I changed my maven file to 2.3.0 version.
This time I am getting the following error:
19/05/14 00:35:35 INFO BlockManager: BlockManager stopped
19/05/14 00:35:35 INFO BlockManagerMaster: BlockManagerMaster stopped
19/05/14 00:35:35 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
19/05/14 00:35:36 ERROR SparkContext: Error initializing SparkContext.
java.lang.IllegalArgumentException: requirement failed: Can only call getServletHandlers on a running MetricsSystem
at scala.Predef$.require(Predef.scala:281)
at org.apache.spark.metrics.MetricsSystem.getServletHandlers(MetricsSystem.scala:91)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:516)
at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2520)
at org.apache.spark.SparkContext.getOrCreate(SparkContext.scala)
at spark.BasicSpark.readDataFile(BasicSpark.java:107)
at spark.BasicSpark.getWholeData(BasicSpark.java:39)
at controller.TableScreenController$2.handle(TableScreenController.java:66)
at controller.TableScreenController$2.handle(TableScreenController.java:62)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$208(GtkApplication.java:245)
at java.lang.Thread.run(Thread.java:748)
19/05/14 00:35:36 INFO SparkContext: SparkContext already stopped.
19/05/14 00:35:36 INFO SparkContext: Successfully stopped SparkContext
java.lang.IllegalArgumentException: requirement failed: Can only call getServletHandlers on a running MetricsSystem
at scala.Predef$.require(Predef.scala:281)
at org.apache.spark.metrics.MetricsSystem.getServletHandlers(MetricsSystem.scala:91)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:516)
at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2520)
at org.apache.spark.SparkContext.getOrCreate(SparkContext.scala)
at spark.BasicSpark.readDataFile(BasicSpark.java:107)
at spark.BasicSpark.getWholeData(BasicSpark.java:39)
at controller.TableScreenController$2.handle(TableScreenController.java:66)
at controller.TableScreenController$2.handle(TableScreenController.java:62)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$208(GtkApplication.java:245)
at java.lang.Thread.run(Thread.java:748)

I am getting this error at the below code line where I initialize spark context:
JavaSparkContext sc = JavaSparkContext.fromSparkContext(SparkContext.getOrCreate(conf));

Edit 2: It works well when I write local instead of my own spark master IP. But I need to run this on my own IP. So what can be wrong with my master node?

Edit 3: I uploaded whole error stack to code snippet that located under the first edit.

A: This happens when class that defines lambda expression is not available run time. If you are trying to run job on remote cluster from local IDE, you will need to add setJars
SparkConf conf = new SparkConf()
                .setAppName("app name")
                .setJars(new String[]{"/fatJarPath/jar.path"})
                .setMaster("spark://Remote_spark_ip:port");

Alternatively you can build fat jar and submit your job using spark-submit.


text:
Q: How to put seed data into SQL Server docker image? I have a project using ASP.NET Core and SQL Server. I am trying to put everything in docker containers. For my app I need to have some initial data in the database.
I am able to use docker sql server image from microsoft (microsoft/mssql-server-linux), but it is (obviously) empty. Here is my docker-compose.yml:
version: "3"
services:
    web:
        build: .\MyProject
        ports:
            - "80:80"
        depends_on:
            - db
    db:
        image: "microsoft/mssql-server-linux"
        environment:
            SA_PASSWORD: "your_password1!"
            ACCEPT_EULA: "Y"

I have an SQL script file that I need to run on the database to insert initial data. I found an example for mongodb, but I cannot find which tool can I use instead of mongoimport.

A: You can achieve this by building a custom image. I'm currently using the following solution. Somewhere in your dockerfile should be:
RUN mkdir -p /opt/scripts
COPY database.sql /opt/scripts

ENV MSSQL_SA_PASSWORD=Passw@rd
ENV ACCEPT_EULA=Y

RUN /opt/mssql/bin/sqlservr --accept-eula & sleep 30  & /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Passw@rd' -d master -i /opt/scripts/database.sql

Alternatively you can wait for a certain text to be outputted, useful when working on the dockerfile setup, as it is immediate. It's less robust as it relies on some 'random' text of course:
RUN ( /opt/mssql/bin/sqlservr --accept-eula & ) | grep -q "Service Broker manager has started" \
    && /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Passw@rd' -i /opt/scripts/database.sql

Don't forget to put a database.sql (with your script) next to the dockerfile, as that is copied into the image.

A: Roet's answer https://stackoverflow.com/a/52280924/10446284 ditn't work for me.
The trouble was with bash ampersands firing the sqlcmd too early. Not waiting for sleep 30 to finish.
Our Dockerfile now looks like this:
FROM microsoft/mssql-server-linux:2017-GA

RUN mkdir -p /opt/scripts
COPY db-seed/seed.sql /opt/scripts/

ENV MSSQL_SA_PASSWORD=Passw@rd
ENV ACCEPT_EULA=true

RUN /opt/mssql/bin/sqlservr & sleep 60; /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Passw@rd' -d master -i /opt/scripts/seed.sql

Footnotes:

*

*Now the bash command works like this
  run-asych(sqlservr) & run-asynch(wait-and-run-sqlcmd)`

*We chose sleep 60, because the build of the docker image happens "offline", before all the runtine evironment is set up. Those 60 seconds don't occur at container runtime anymore. Giving more time for the sqlservr command gives our teammates' machines more time to complete the docker build phase successfully.

A: One simple option is to just navigate to the container file system and copy the database files in, and then use a script to attach.

A: This
https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker
has an example of using sqlcmd in a docker container although I'm not sure how you would add this to whatever build process you have


text:
Q: Cleaner way to write this MySql query I generate below query through php
$sql .= "Select * from test";

$sub_sql = '';

foreach($value as $n_k => $n_v)
{
    switch($n_v)
    {
        case '1':
            $sub_sql .= " OR (id = 1 )";
        break;
        case '2':
            $sub_sql .= " OR (category = 4) ";
        break;
        case '3':
            $sub_sql .= " OR (location = 'U.S.') ";
        break;
    }
}

if($sub_sql != '')
{
    $sql .= " where ( 0 ".$sub_sql." ) ";
}

$sql .= "GROUP BY id  ORDER BY stored_date DESC LIMIT 0, 5 ";

But as you'll can see where $subsql is concatenated to $sql, that part looks really messy. Evn though it works fine but it looks really poor. Can anyone pls help me with this?

A: Is this a simplified example? Because I see no reason not to simplify it like this:
$sql .= "Select * from test where a=1";

foreach($value as $n_k => $n_v)
{
    switch($n_v)
    {
        case '1':
            $sql .= " AND (id = 1 )";
        break;
        case '2':
            $sql .= " AND (category = 4)";
        break;
        case '3':
            $sql .= " AND (location = 'U.S.')";
        break;
    }
}

$sql .= " ORDER BY stored_date DESC LIMIT 0, 5 ";

Note, that I removed the GROUP BY from your statement. You shouldn't use it, if you don't use aggregate functions. Group by collapses group of rows and displays random rows from each group. If you have a need to remove duplicate rows, consider to use the DISTINCT keyword in the SELECT clause.
UPDATE:
Your new version can be shortened like this:
$sql .= "Select * from test";

foreach($value as $n_k => $n_v)
{
    switch($n_v)
    {
        case '1':
            $sql .= " where (id = 1 ) ";
        break;
        case '2':
            $sql .= " where (category = 4) ";
        break;
        case '3':
            $sql .= " where (location = 'U.S.') ";
        break;
    }
}

$sql .= " GROUP BY id  ORDER BY stored_date DESC LIMIT 0, 5 ";

Basically it comes down to this. If you have to add multiple AND conditions, you always add a WHERE 1=1 (if you have no other fix (non-dynamic) conditions) to the query. It doesn't change anything, the optimizer will throw it away again. But you can easily append as many conditions as you want. That's what I did in my original answer before your edit. Note though, that you can not just append OR whatever = true when you are mixing AND and OR conditions. You will have to use parantheses to not get a false resultset. This is where your (0 OR ...) thing comes from. Since you only have 1 condition, there's no need at all for all I said right now. Just add it as WHERE whatever = true and that's it.

A: How about adding the conditions to the sql?
Something like:
Select * from test where a=1
AND
(
  ($n_v = 1 AND id = 1)
  OR
  ($n_v = 2 AND category = 4)
  OR
  ($n_v = 3 AND location = 'U.S.')
)


text:
Q: error: 'xxx' does not name a type I have a weird problem I don't understand.  I am copying over some C code to a C++ class and cannot get past this error "does not name a type" ... I hope I copied enough code for this to make sense, original program is ~1000 lines
Error is .. error: 'HTTPContext' does not name a type
The line of the error is "HTTPContext MainWindow::*find_rtp_session_with_url(const char *url, const char *session_id)"
className.h:
class MainWindow : public QMainWindow
{
    Q_OBJECT

 public:

     typedef struct HTTPContext{
         int fd;
     }HTTPContext;

     HTTPContext *find_rtp_session_with_url(const char *url,
                                              const char *session_id);
};

className.cpp
#include "className.h"

HTTPContext MainWindow::*find_rtp_session_with_url(const char *url,
                                          const char *session_id)
{
     HTTPContext *rtp_c;

}

A: HTTPContext is declared in class scope, so to use in the function definition in global scope you need specify it explicitly:
MainWindow::HTTPContext *MainWindow::find_rtp_session_with_url...

A: You need to say
MainWindow::HTTPContext* MainWindow::find_rtp_session_with_url( ...

since it's an inner class. Also you don't have to use typedef there:
struct HTTPContext {
    int fd;
};

is enough to name a type in C++.


text:
Q: std::vector pushing speed? I'm using vector to manage my large structure data. But suddenly, when discovering vector source code, I am very surprised to see some code below :
inline void push_back(const _Ty& _X)
    {insert(end(), _X); }
//...

void insert(iterator _P, size_type _M, const _Ty& _X)
    {
//////////////////////////////////////////////////////////////
        iterator _S = allocator.allocate(_N, (void *)0);
        iterator _Q = _Ucopy(_First, _P, _S);
        _Ufill(_Q, _M, _X);
        _Ucopy(_P, _Last, _Q + _M);
        _Destroy(_First, _Last);
        allocator.deallocate(_First, _End - _First);
//////////////////////////////////////////////////////////////
    }

It's the snippet code which "destroys" then reallocates its whole vector data. It's so annoying, because my structure has a large size and a vector has to manage hundreds of elements, while I only use vector::operator [] and vector::push_back(), especially pushing back takes most of my program time (it's time-consuming). In my case, is there any better container which can perform faster than std::vector, while I tried to google but no luck?

A: The allocate-copy-delete (or allocate-move-delete in C++11) only happens once each time the vector exceeds its current capacity. With each such reallocation, the capacity doubles. This averages out over time, so the amortized complexity of push_back() is constant.
You can pre-allocate the vector's capacity by using its reserve() member function.

A: Would reserving all the space you need before adding elements solve your problem ?

A: Reallocation only occurs if your vector size increases past its capacity. If you know in advance (even roughly) how many items your vector will contain, you can use its reserve member to pre-allocate enough capacity. You can also trigger reallocation yourself in a controlled manner, even while filling the vector, to reduce the number of times it is called and thus get better performance.
Now if you want guaranteed constant-time insertion there are containers that can be used for that but at a trade-off (eg. std::list will allocate lots of small memory blocks which may end up not any faster that your current vector use, because new is quite slow, and the memory usage will be more important too, and you lose random access, but sure every insertion will take roughly the same time as the others).

A: If you know your final data size, you can use reserve to preallocate the memory needed for the vector.  That will remove all reallocating and copying.
If you don't know the exact size, make an educated guess based on what you do know about your incoming data.

A: A vector is a dynamically expanding container, but its contents are required to be in a contiguous block of memory (as I recall, this was unspecified in pre-C++11 but everybody did it).  So if your vector already holds 8 elements, and the current capacity of the vector is 8 elements, then when you push_back a 9th element, the container must allocate new space for the larger capacity, copy the 8 elements that are already in the container, copy the 9th element into the new space, then destroy the old.   If you are using C++11, and your elements support move-construction, then the 8 copies can become 8 moves.  Or if you want to incur the overheads of managing pointers, you could store pointers to elements instead of elements (copying a pointer is cheap, but now you need to deal with the lifespan issue).
As for which container is faster than vector, that's a large open-ended question.  It depends on all sorts of access/manipulation patterns.   std::list was mentioned as a candidate.  O(1) adding to the end of the list, but is probably a bigger O(1) than the amortized O(1) that vector uses.  You lose random-access into the container.

A: Yes push_back() is known to be constant most of time, but needs to re-allocate the whole vector when the size() reach the capacity().
If you want constant time insertion, you must try a std::list or a std::deque. Especially a std::deque provides correct performance for insertion at the end of your container while being close to a vector in its interface.
Extract from cpp reference:

Therefore they provide a similar functionality as vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations, thus not allowing direct access by offsetting pointers to elements.


text:
Q: Online UPS ground question A very simple question before I purchase an online UPS.
I have a ground loop problem with an audio workstation, I temporarily removed the earth (to test only) and the noise went away, so I am considering an online UPS with this PC to isolate the circuits.
Is the ground from the mains plug of the online UPS also isolated from the PSU's outlets? I've read that online UPSs are a good electrical firewalls.

A: The ground on your UPS input and the ground on the UPS output should be connected together inside the UPS.  That is how they are supposed to be.
Ground is for your safety, and the safety of anyone who touches the equipment.
Do not defeat the safety ground on your UPS, or on the equipment directly.
Plug the equipment into one outlet so that all devices are connected to the same ground.  If that doesn't help, get an audio isolation transformer to put in line between the audio devices.

You can often get away with defeating the safety ground.  As long as the equipment and cables are all good, nothing bad will happen - until some day, something does go wrong and the safety ground isn't there to save your bacon.
Don't break the ground.


text:
Q: Error when trying to insert data into the table I'm using Android studio. I am trying to insert links into SQLite but keep on getting an error in the boolean addData method.
All my imports/codes appear to be correct. I am just unsure as to why I am getting these errors. Do I have to add a permission?
This is the code for the DataBase methods:
public class DataBase extends SQLiteOpenHelper {

private static final String TAG = "Database";
private static final String TABLE_NAME = "SongList_Table";
private static final String Column0 = "ID";
private static final String Column1 ="Music Link";

public DataBase(Context context){
    super(context, TABLE_NAME, null, 1);

}

public Cursor getData(){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME;
    Cursor data = db.rawQuery(query, null);
    return data;
}

public boolean addData(String item){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Column1, item);

    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result <0){
        return false;
    }
    else {
        return true;
    }
}
@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + Column1 + "TEXT)";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

}
The errors:

D/Database: addData: Adding https://www.soundhelix.com/audio-examples to SongList_Table
  E/SQLiteLog: (1) near "Link": syntax error
  E/SQLiteDatabase: Error inserting Music Link=https://www.soundhelix.com/audio-examples
      android.database.sqlite.SQLiteException: near "Link": syntax error (code 1): , while compiling: INSERT INTO SongList_Table(Music Link) VALUES (?)
          at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
          at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
          at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
          at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
          at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
          at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
          at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1500)
          at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1373)
          at com.example.mobilecomputingcw2.DataBase.addData(DataBase.java:37)
          at com.example.mobilecomputingcw2.MainActivity.dataAdd(MainActivity.java:69)
          at com.example.mobilecomputingcw2.MainActivity$1.onClick(MainActivity.java:47)
          at android.view.View.performClick(View.java:5675)
          at android.view.View$PerformClick.run(View.java:22651)
          at android.os.Handler.handleCallback(Handler.java:836)
          at android.os.Handler.dispatchMessage(Handler.java:103)
          at android.os.Looper.loop(Looper.java:208)
          at android.app.ActivityThread.main(ActivityThread.java:6304)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

Edit: Even with after the changes to the Column1 and createTable String i am getting the same error with inserting links into SQLite.
Edit2: Turns out i just had to uninstall the app. Thanks @forpas
Edit 3: am now getting an error on the getData method

A: That's because of the space in "Music Link". Change it to an underscore (or any other string)
...
private static final String Column1 ="Music_Link";
...

or put quotes around it
...
private static final String Column1 ="\"Music Link\"";
...

And here
...
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + Column1 + "TEXT)";
...

a space is missing before TEXT. It should rather be
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + Column1 + " TEXT)";

A: Change to:
private static final String Column1 ="[Music Link]";

then uninstall the app from the device so the database is deleted and rerun to recreate the database.


text:
Q: 'module' object has no attribute 'gethostbyname' error google app engine Obtained the tweepy example from here.
Tried to run on google app engine launcher version 1.6.3 on mac lion but I get the error
'module' object has no attribute 'gethostbyname'

Status: 200 OK Content-Type: text/html; charset=utf-8 Cache-Control:
no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 0

Any ideas as to what might be causing this?

A: Presumably, you're trying to use the gethostbyname function that's in the socket module, which isn't supported on AppEngine. See the docs (cf. "The Sandbox", emphasis below mine):

To allow App Engine to distribute requests for applications across
  multiple web servers, and to prevent one application from interfering
  with another, the application runs in a restricted "sandbox"
  environment. In this environment, the application can execute code,
  store and query data in the App Engine datastore, use the App Engine
  mail, URL fetch and users services, and examine the user's web request
  and prepare the response.
An App Engine application cannot:

*

*write to the filesystem. Applications must use the App Engine datastore for storing persistent data. Reading from the filesystem is
  allowed, and all application files uploaded with the application are
  available.

*open a socket or access another host directly. An application can use the App Engine URL fetch service to make HTTP and HTTPS requests
  to other hosts on ports 80 and 443, respectively.

*spawn a sub-process or thread. A web request to an application must be handled in a single process within a few seconds. Processes that
  take a very long time to respond are terminated to avoid overloading
  the web server.

*make other kinds of system calls.

A: Whichever module you think has your gethostbyname object does not have it. You don't show your code, or even the full error, so it's impossible to tell you more.


text:
Q: ElasticSearch Best approach for Searching a similar document I have a set of documents that each could be described as a list of unique words(features) e.g. [12, 45, 56, 78, ...]. The number of features is around 1k. Features contained in a document may appear in another document. I want to return the most similar documents. What would be the most efficient approach?

A: You may straightforwardly try this type of query and see how good it works for you. Just work out your, so to say, "highest-common-factor" reference doc to get most results.
P.S. If your terms ("features") are morphing in some way, it also make sense to look at fuzzy queries.


text:
Q: Design Pattern for Pipleline/Stages in application In my application, there are some stages through which a lead has to go through.
For example:
New
In Progress
Won
Lost

These are just four stages of 11 stages. On every stage, there will be some action that has to be performed.
For example, a lead moves from New to In Progress, I need to update a certain set of values in four tables.
What could be the ideal design pattern that I could use here so that in future if any new stage comes in, it becomes easy to accommodate that in code?
I was thinking of using Factory Pattern.
EDIT:
I did something like this:
interface StageInterface
{
    public function changeStage($previous_stage, $next_stage, $ticket_details);
}

abstract class ParentStage implements StageInterface
{
    public function changeStage($previous_stage, $next_stage, $ticket_details)
    {
        $ticket_details->stage_id = $next_stage;
        $ticket_details->save();

        return $this;
    }
}

Class InProgress extends ParentStage
{
}

class TicketStagesFactory
{
    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function getObject()
    {
        switch ($this->data) {

            case Stage::IN_PROGRESS:
                return new \App\Http\Controllers\Stages\InProgress();
                break;
     }
}

And then I am using the factory like this:
$factory = new TicketStagesFactory($next_stage);
$test = $factory->getObject()->changeStage($previous_stage, $next_stage, $ticket_details);

Is this the right way to do it?

A: This actually looks more like a workflow.
State machine works more like this:
 for a state, a event will cause it to transition to another state.
A workflow works more like what you've said:
 For a state, actions have to be performed, the outcome of these actions decide the next state.
I would look for a workflow engine for php to make your work maintainable.

A: It depends on you program flow, but and idea could be:
//ABSTRACT CLASS FOR A STAGE
abstract class LeadStage
{
    protected $lead;

    //INJECT YOUR LEAD OBJECT
    public function __construct( Lead $lead )
    {
        $this->lead = $lead;
    }

    //handle the stage logic on the $lead object
    public abstract function handle();
}

//CONCRETE CLASS FOR A STAGE
class InProgress extends LeadStage
{
    //HANDLE THE CONCRETE STAGE LOGIC ON THE LEAD OBJECT
    public function handle()
    {
        //do some logic on $this->lead;
    }
}

//LEAD OBJECT
class Lead
{
    protected $leadStage;

    public function construct(  )
    {
        //here build your first LeadStage object: you could also use a factory
        //pattern to create the LeadStage instance
        $this->leadStage = //...
    }

    public function setStage( LeadStage $stage )
    {
        $this->leadStage = $stage;
    }

    public function handleStage()
    {
        $this->leadStage->handle();
    }
}

And use the classes like this:
$lead = new Lead();

//will handle the first stage
$lead->handle();

//something causes the stage to change
$lead->setStage( new InProgress( $lead ) );

//will handle the InProgess stage logic
$lead->handleStage();

So, using a single class for every stage, will delegate the responability to handle the stage logic to the object of the specific class.
When you need to add a status you only have to create e new LeadStage implementation


text:
Q: Game Center corruption. How to fix? Lately I'm finding that I am not able to use any software that utilizes Game Center. In iOS 6 on login (or opening any game) it says, "Could not connect to Game Center server." In OS X Mountain Lion on login, it says, "The data couldn't be read because it has been corrupted."
I've tried some steps to fix that were suggested in Apple's Support Discussions without success. These include rebuilding permissions, resetting PRAM, restoring the /etc/hosts file to its default state, and in OS X, logging in using Chess instead of Game Center.
That this is happening on both of my devices (MacBook Pro and iPhone 4S) makes me think the 'corruption' is occurring on Apple end, in the cloud. I'm wondering if anyone has experienced this issue and conquered it, or if Apple Support can do anything to restore this functionality on their end at a customer's request.

A: I'm thinking that the server just must be down. I'm having the same issues logging into my game center on my iphone 4s. Perhaps it will fix itself within the hour as things like this apparently have happened before.

A: Restore or reboot the device to fix this issue


text:
Q: Using an API from a remote repository UPDATE: I was compiling my source files using javac, which was (obviously) not linking my dependency on the YahooFinance API, as specified in my build.gradle file. I issued a gradle build command instead, and the dependency was successfully linked.
I'm writing a Java program that uses an API from the Maven Central repository, located here.
I believe I have properly connected to the API from my build.gradle file, because when I run gradle dependencies from the command line, I get a BUILD SUCCESSFUL message in return.
However when I try to use the API in my code, something like...
import yahoofinance.YahooFinance;
// ...
YahooFinance yf = new YahooFinance();

... my program will not compile. The compilation errors:
Allocate.java:7: error: package yahoofinance does not exist
import yahoofinance.YahooFinance;
                   ^
Allocate.java:15: error: cannot find symbol
        YahooFinance yf = new YahooFinance();
        ^
  symbol:   class YahooFinance
  location: class Allocate
Allocate.java:15: error: cannot find symbol
        YahooFinance yf = new YahooFinance();
                              ^
  symbol:   class YahooFinance
  location: class Allocate
3 errors

What must I fix to be able to use this API in my code?
Here is my build.gradle file, if that is any help:
apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.yahoofinance-api', name: 'YahooFinanceAPI', version: '3.2.0'
}


text:
Q: how to switch between authenticated user and anonymous user in Djnango I have this kind of view in my web application. and i have two main kids of users which are the suppliers and the admin, i am also trying to make the application usable by normal user but some functions will be restricted, i have made all the functions for the suppliers and admin and was working on the anonymous users. I have a line of code in my view dependent on the request.user, i still want the anonymous users to have access to that page but there is a button in form of an icon which has a login_required decorator, so they will have to login.
views.py
def products(request):
    title = "All Products"

    all_products = Product.objects.annotate(
        favourited_by_user=Count(Case(
            When(
                is_favourite=request.user,
                then=1
            ),
            # default=0,
            output_field=BooleanField(),
        )),
    ).order_by('-id')

    context = {"all_products":all_products, "title":title}

    return render(request, 'core/products.html', context)

For the is_favourite, what kind of logic can i make for the anonymous users.

A: Just use an if-else for the annotation:
def products(request):
    title = "All Products"

    all_products = Product.objects.all()
    if request.user.is_authenticated:
        all_products = all_products.annotate(
            favourited_by_user=Count(Case(
                When(
                    is_favourite=request.user,
                    then=1
                ),
                # default=0,
                output_field=BooleanField(),
            )),
        ).order_by('-id')
    else:
        all_products = all_products.order_by('-id')
    context = {"all_products":all_products, "title":title}

    return render(request, 'core/products.html', context)

If I remember correctly you allow users to favourite / unfavourite on this page. You would have to write some condition for that in the template also Simplest would be to simply hide the button by putting the form inside an if block:
{% if request.user.is_authenticated %}
    form here
{% endif %}


text:
Q: Batch list folder, count pdf files and get file name I would like to create a summary of all the files that I received weekly from other department. The folder structure shown below. Each folder will contain multiples pdf files and only 1 .docx file. So, i would like to list down the folder name, count total pdf files inside and get the name of docx file. If docx missing, show "missing", is this possible too?
I did try this code, but this will show all files in the folder instead.
@echo off
FOR /F "delims=" %%F IN ('dir /B /A /S *') DO (
for %%D in ("%%~dpF\.") do echo/ FolderName: %%~nxD ^| FileName: %%~nxF
)
pause

UPDATE:Today while Im testing suggested code, they send me last week file. AND to my surprised, the other department changed folder structure (facepalm!). Below updated folder structure for reference.
Updated folder structure:
Current
|count.bat
|--FolderA-Folder1-Nov 2020.docx
|                 -pdf1.pdf
|                 -pdf2.pdf
|                 -pdf3.pdf
|                 -pdf4.pdf
|          Folder2-Dec 2020.docx
|                 -pdf1.pdf
|                 -pdf2.pdf
|                 -pdf3.pdf
|                 -pdf4.pdf
|--FolderB-Folder1-Nov 2020.docx
|                 -pdf1.pdf
|                 -pdf2.pdf
|                 -pdf3.pdf
|                 -pdf4.pdf
|          Folder2-Dec 2020.docx
|                 -pdf1.pdf
|                 -pdf2.pdf
|                 -pdf3.pdf
|                 -pdf4.pdf
|--FolderC-Folder1-Nov 2020.docx
|                 -pdf1.pdf
|                 -pdf2.pdf
|                 -pdf3.pdf
|                 -pdf4.pdf

Expectation Results
FolderName: Folder A Folder 1    PDFtotal: 4pdfs   DocFile: Nov 2020.docx
FolderName: Folder A Folder 2    PDFtotal: 4pdfs   DocFile: Dec 2020.docx
FolderName: Folder B Folder 1    PDFtotal: 4pdfs   DocFile: Nov 2020.docx
FolderName: Folder B Folder 2    PDFtotal: 4pdfs   DocFile: Dec 2020.docx
FolderName: Folder C Folder 1    PDFtotal: 4pdfs   DocFile: Nov 2020.docx

A: @echo off
setlocal enabledelayedexpansion
set "spaces=                         "
FOR /F "delims=" %%F IN ('dir /B /AD /S *') DO (
 rem new foldername in %%F
 set "foldername=%%~nxF%spaces%"
 set /a pdfcount=0
 set /a docxcount=0
 set "docxmessage=missing"
 for /f "delims=" %%D in ('dir /B /A-D "%%F\*"') do (
  if /i "%%~xD"==".pdf" set /a pdfcount+=1
  if /i "%%~xD"==".docx" set /a docxcount+=1&set "docxmessage=%%~nxD"
 )
 set "pdfcount=%spaces%!pdfcount!"
 if !docxcount! gtr 1 (set "docxcount= MULTIPLE") else (set "docxcount=")
 echo/ FolderName: !foldername:~0,20! PDFtotal: !pdfcount:~-3!pdfs  Docfile: !docxmessage! !docxcount!
)

Note that the first dir command now contains AD to list directories only.
With each directoryname, record it in foldername and add some spaces at the end. Reset the counters and establish the missing value in the docxmessage.
Then get the filename list within the directory found, count each .pdf and .docx and if any .docx is found, record its name in docxmessage
Modify docxcount to a message if more than 1 .docx is present, and empty otherwise
When the directory-scan is finished, apply some spaces to the start of pdfcount and then produce your output line using the current values of the variables and using the modifiers to produce the first 20 characters of the padded directoryname and the last 3 characters of the padded pdfcount.
When you use the point-click-and-giggle method of executing a batch, the batch window will often close if a syntax-error is found. You should instead open a 'command prompt' and run your batch from there so that the window remains open and any error message will be displayed.
Fixed : for /F %%D... needed "delims=" to assign the whole filename to %%D
Revised code for new structure:
@echo OFF
setlocal ENABLEDELAYEDEXPANSION
PUSHD U:\sourcedir
set "spaces=                         "
FOR /F "delims=" %%F IN ('dir /B /AD /S *') DO (
 rem new foldername in %%F
 set "foldername=%%~nxF%spaces%"
 rem find parent directory
 FOR /F "delims=" %%Q IN ("%%~dpF\.") DO SET "parent=%%~nxQ%spaces%"
 rem is a leaf directory if this directory has no subdirectories
 SET "isleaf=Y"
 FOR /F "delims=" %%Q IN ('dir /B /AD "%%F"') DO SET "isleaf="
 set /a pdfcount=0
 set /a docxcount=0
 set "docxmessage=missing"
 for /f  "delims=" %%D in ('dir /B /A-D "%%F\*" 2^>nul') do (
  if /i "%%~xD"==".pdf" set /a pdfcount+=1
  if /i "%%~xD"==".docx" set /a docxcount+=1&set "docxmessage=%%~nxD"
 )
 set "pdfcount=%spaces%!pdfcount!"
 if !docxcount! gtr 1 (set "docxcount= MULTIPLE") else (set "docxcount=")
 IF DEFINED isleaf echo/ FolderName: !parent:~0,20! !foldername:~0,20! PDFtotal: !pdfcount:~-3!pdfs  Docfile: !docxmessage! !docxcount!
)
popd
GOTO :EOF

Some small additions to the code.
first, find the parent directoryname. By using the directoryname in %%F and adding \., the resultant resolved string appears to be a filename, the name and extension of which is the parent directory; store this in parent with padding.
Next, determine whether this is a leaf directory. Set the flag isleaf to assume it is a leaf directory, then perform a dir/ad so that any detected subdirectory name will clear the flag.
Then just process the directory as before, using 2^>nul to suppress file not found messages if the directory %%F contains no files.
...And only generate the report line if isleaf is defined, with the parent directoryname added.

A: Original Script
The dir command without the /B option displays the count of matching items in the penultimate line, which could be captured and parsed by a for /F loop.
Since you have got a flat directory structure, I would not do a recursive approach (like dir /S or for /R).
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=."         & rem // (target directory; `.` is current, `%~dp0.` is parent)
set "_MASK=Doc*.docx" & rem // (pattern to find particular file)
set _LIST="pdf"       & rem // (space-separated list of file extensions without `.`)

rem // Loop through immediate sub-directories of the target directory:
for /D %%D in ("%_ROOT%\*") do (
    rem // Return name of current sub-directory without trailing line-break:
    < nul set /P ="FolderName: %%~nxD    "
    rem // Loop through given list of file extensions:
    for %%E in (%_LIST%) do (
        rem // Initialise variables:
        set /A "CNT=0, NUM=0" & set "NAME="
        rem // Capture number of matching files from last but one line of `dir`:
        for /F "eol= " %%C in ('2^> nul dir /A:-D-H-S "%%~D\*.%%~E"') do (
            2> nul set /A "CNT=NUM, NUM=%%C"
        )
        rem // Return count of matching files without trailing line-break:
        < nul call set /P ="PDFtotal: %%CNT%%%%~Es   "
    )
    rem // Find file that matches the given pattern (assuming there is only one):
    for %%F in ("%%~D\%_MASK%") do set "NAME=%%~nxF"
    rem // Return name of found file, with trailing line-break this time:
    call echo DocFile: %%NAME%%
)

endlocal
exit /B

The option /A:-D-H-S of the dir command in the code prevents hidden and system files from being counted; change it to /A:-D if you do want to regard them as well.

Updated Script
In the following you will find the new code adapted to your changed directory structure (you will notice that there were only a few modifications necessary):
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=."           & rem // (target directory; `.` is current, `%~dp0.` is parent)
set "_MASK=* 2020.docx" & rem // (pattern to find particular file)
set _LIST="pdf"         & rem // (space-separated list of file extensions without `.`)

rem // Loop through immediate sub-directories of the target directory:
for /D %%S in ("%_ROOT%\*") do (
    rem // Loop through next level of sub-directories:
    for /D %%D in ("%%~S\*") do (
        rem // Return names of current sub-directories without trailing line-break:
        < nul set /P ="FolderName: %%~nxS %%~nxD    "
        rem // Loop through given list of file extensions:
        for %%E in (%_LIST%) do (
            rem // Initialise variables:
            set /A "CNT=0, NUM=0" & set "NAME="
            rem // Capture number of matching files from last but one line of `dir`:
            for /F "eol= " %%C in ('2^> nul dir /A:-D-H-S "%%~D\*.%%~E"') do (
                2> nul set /A "CNT=NUM, NUM=%%C"
            )
            rem // Return count of matching files without trailing line-break:
            < nul call set /P ="PDFtotal: %%CNT%%%%~Es   "
        )
        rem // Find file that matches the given pattern (assuming there is only one):
        for %%F in ("%%~D\%_MASK%") do set "NAME=%%~nxF"
        rem // Return name of found file, with trailing line-break this time:
        call echo DocFile: %%NAME%%
    )
)

endlocal
exit /B

A: This can be placed into a .bat file script and run in cmd.exe. Note that this does not identify directories which contain no .pdf file, no .docx file, or multiple .docx files.
powershell.exe -NoLogo -NoProfile -Command ^
    "$Dirs = Get-ChildItem -Directory -Path 'C:\src\t';" ^
    "foreach ($Dir in $Dirs) {" ^
    "    $PdfCount = (Get-ChildItem -File -Path $Dir.fullname -Filter '*.pdf').Count;" ^
    "    if (($null -ne $PdfCount) -and (0 -ne $PdfCount)) {" ^
    "        $DocxFiles = (Get-ChildItem -File -Path $Dir -Filter '*.docx');" ^
    "        if ($null -ne $DocxFiles) { $DocxFile = $DocxFiles[0] } else { $DocxFile = 'none' };" ^
    "        """FolderName: $($Dir.Name)  PDFtotal: $($PdfCount.ToString())pdfs  DocFile: $DocxFile""";"  ^
    "    }" ^
    "}"

It would be easier to put the script into a file.
=== Get-DocxAndPdfCount.ps1
[CmdletBinding()]
Param()

$Dirs = Get-ChildItem -Directory
foreach ($Dir in $Dirs) {
    Write-Verbose "dir is $($Dir.fullname)"
    $PdfCount = (Get-ChildItem -File -Path $Dir.fullname -Filter '*.pdf').Count
    Write-Verbose $PdfCount
    if ($null -ne $PdfCount -and 0 -ne $pdfCount) {
        Write-Verbose $PdfCount
        $DocxFiles = (Get-ChildItem -File -Path $Dir -Filter '*.docx')
        if ($null -ne $DocxFiles) { $DocxFile = $DocxFiles[0] } else { $DocxFile = 'none' }
        "FolderName: $($Dir.Name)  PDFtotal: $($PdfCount.ToString())pdfs  DocFile: $DocxFile"
    }
}

Then, run it in a PowerShell console using:
.\Get-DocxAndPdfCount
.\Get-DocxAndPdfCount -Verbose      # to see debugging information

Run from cmd.exe using:
powershell -NoLogo -NoProfile -File '.\Get-DocxAndPdfCount'
powershell -NoLogo -NoProfile -File ".\Get-DocxAndPdfCount" -Verbose