text:
Q: Python - List elements being overwritten somehow I have a recursive function that tries to find combinations of numbers that add to a certain number. I store the results in a list called    validCombinations
The code:
sum = 4
digits = 2
currentDigit = digits
validCombinations = []

#recursion function to find combinations of numbers that add to the sum variable
def recursive(index):
    if 10 not in digitList:
        if index >= 0:
            total = 0
            for n in digitList:
                total += n
            if total == sum:
                validCombinations.append(digitList)
            digitList[index] += 1
            recursive(index-1)
        else:
            recursive(currentDigit-1)

digitList = []

for n in range(digits,0,-1):
    for i in range(n):
        digitList.append(0)
    recursive(n-1)
    digitList = []
    currentDigit -= 1

print validCombinations

When running this it outputs
[[9, 10], [10, 0]]

When i expect to see this
[[2, 2], [4]]

I have stepped through the code and it seems like it is somehow overwriting the elements in the list, however in my code I only ever interact with validCombinations by using the append() method, which should just add it to the end.
Am I missing something or is the recursion causing this?

A: Use list:
        if total == sum:
            validCombinations.append(list(digitList))

You have to get a copy of digitList, not digitList.


text:
Q: Is this graph Hamiltonian?
I know that a Hamiltonian graph has a path that visits each vertex once. But I am not sure how to figure out if this one does. Obviously I can try and trace various different paths to see if one works but that is incredibly unreliable.
So my question is, if this graph is Hamiltonian, where would the Hamilton cycle be? And if it is not Hamiltonian, how can we prove it?
Thank you!

A: This is a bipartite graph. Colour the three middle vertices red
and the other four vertices blue. Each path in the graph has
vertices alternating in colour. So any Hamiltonian cycle has
an equal number of red and blue vertices...

A: A more verbose explanation of the argument made by Lord Shark the Unknown's answer:
This is a bipartite graph (two sets of vertices that form a graph such that no edge places two vertices from the same set adjacent). Colour the three middle vertices red and the other four vertices blue (indicating the two sets).
Every edge in the graph connects a red and a blue vertex. Therefore every path in the graph will visit vertices alternating in color.
Since any cycle has to end on the same vertex as it started, the path has to visit an even number of vertices. Otherwise the path would require connecting a red to a red vertex or a blue to a blue vertex, which we know we cannot do since this is a bipartite graph. This means every cycle will contain an equal amount of red and blue vertices.
Since any Hamiltonian cycle has to contain all vertices and this graph does not have an equal amount of red and blue vertices, it is impossible in this graph to create a Hamiltonian cycle.
Note that the argument does not work the other way around; bipartite graphs exist with equal amounts of points in both sets where Hamiltonian cycles are not possible. Imagine a graph like the one provided in the question, but with four groups of vertices: 2 (red) - 1 (blue) - 1 (red) - 2 (blue). Here it is impossible to create a Hamiltonian cycle since it would require crossing the middle vertices twice.

A: One can never trace a Hamiltonian cycle in a graph with vertices having odd egde number.
One can never find a Hamiltonian path in a graph with more than two vertices having odd egde number.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the content from clipboard on Firefox in Javascript I am very frustrated to make Paste from the clipboard on my React app.
I used navigator.clipboard.readText(), which works perfectly on Chrome browser.
But it doesn't work on my latest Firefox browser.
I tried to search SO and there are few posts related to it. But all of them don't make me happy.
According to MDN documentation, it says:

Blockquote Firefox only supports reading the clipboard in browser extensions, using the "clipboardRead" extension permission.

But I really don't know how to enable it.
Could you help me out with this issue?
Is there any good library for it?
Thanks in advance.

A: Based on Can I use, Firefox only supports reading the clipboard in browser extensions.
This article's selected answer says that Firefox currently doesn't allow web pages to access the clipboard via JavaScript, so your only option would be to use the keyboard.

A: What I did in one of my projects is to register an eventListener for the document to handle the paste event in a useEffect hook.
  useEffect(() => {
    const pasteFn = (event) => {
      const data = event.clipboardData.items;
      for (let i = 0; i < data.length; i += 1) {
        if (data[i].kind === 'string' && data[i].type.match('^text/plain')) {
          data[i].getAsString((str) => console.log('text/plain', str));
        } else if (data[i].kind === 'string' && data[i].type.match('^text/html')) {
          data[i].getAsString((str) => console.log('html', str));
        } else if (data[i].kind === 'string' && data[i].type.match('^text/uri-list')) {
          data[i].getAsString((str) => console.log('uri', str));
        } else if (data[i].kind === 'file' && data[i].type.match('^image/')) {
          const f = data[i].getAsFile();
          console.log('File', f);
        }
      }
    };
    document.addEventListener('paste', pasteFn);
    return () => {
      document.removeEventListener('paste', pasteFn); // clean up
    };
  }, []);

A: navigator.clipboard is an API that works only on secure environments. It could be just that you are running your React app on localhost, a non-secure env and it doesn't have access to the clipboard object from the browser.
You could have a check to see if navigator.clipboard is available on the environment and then use it.
if (navigator.clipboard !== undefined) {
  // make use of clipboard functions here
}


text:
Q: three.js, dat.GUI slider controlled by code, morph targets do not move I work on a human face that the mouth should move about external coordinates (OpenCV and dlibs). In a first step I try to control the dat.GUI by code, which already works. But now I have the problem that the morph targets do not move when I control by code. The sliders move, but the face doesn't. When I use the mouse, they work perfectly. I ask for help with this problem.

<script>

 // Laden der 3DScene
 var scene = new THREE.Scene();

 // Laden der Kamear Perspektive
 var camera = new THREE.PerspectiveCamera(15, window.innerWidth/window.innerHeight, 1, 10000);
  camera.position.z = 17;
  camera.position.y = 3;

 // Laden des Renderers
 var renderer = new THREE.WebGLRenderer({ alpha: false });
  renderer.setClearColor( 0x000000 );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

 // Laden des Orbitcontrollers
 var controls = new THREE.OrbitControls( camera, renderer.domElement );

 // Laden der Lichter (Beleuchtung)
 var ambientLight = new THREE.AmbientLight(0x111111);
    scene.add(ambientLight);

 var light = new THREE.PointLight( 0xFFFFDD );
    light.position.set( -15, 10, 15 );
    scene.add(light);

 // Laden des Json Modells
 var loader = new THREE.JSONLoader();
  loader.load( "./three/models/JSON/test/mkh_shapes.json", function (geometry) {
 var material = new THREE.MeshLambertMaterial({morphTargets: true});
 var mesh = new THREE.Mesh(geometry, material);
    mesh.scale.set(1.2,1.2,1.2);        //Modellgrösse die angezeigt wird
    mesh.position.x = 0;    //Position (x = nach rechts+ links-)
    mesh.position.y = -19;    //Position (y = nach oben +, unten-)
    mesh.position.z = 0;    //Position (z = nach vorne +, hinten-)

    scene.add(mesh);

 //dat.Gui
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 var shape = {
    mouth_open: 0.0,  //Anfangsposition 0.0
 };

 var gui = new dat.GUI();
 var folder = gui.addFolder( 'Morph Targets' );
   folder.add( shape, 'mouth_open', 0, 1 ).step( 0.01 ).name('mouth_open').listen().onChange ( function( a ) {       mesh.morphTargetInfluences[ 40 ] = a;} );
   folder.open();

 var updateGui = function() {
  for (var i in folder.__controllers) {
   folder.__controllers[i].updateDisplay();
  }
 }

 var time = Date.now() * 0.003;
  shape.mouth_open = 0.50 //* Math.sin( 0.5 * time ) + 0.3;

  //scene.add(shape);

 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
});

function animate() {
  render();
  requestAnimationFrame( animate );
}

function render() {
  renderer.clear();
  renderer.render( scene, camera );
}

animate();

</script>

A: I have made my own version with extra features like :

*

*Gui auto resize based on content div.

*Improved slidecontroller as unique controller (slide or number insert);

*Multi language automatic support

*Auto check for conflicts in options, then ask for confirm or cancel.

*Auto Show/hide other controllers when option selected deselected (example show color list only if "custom color is selected")
ecc.. ecc..

here is the Video
Now is more confortable and easy to use.


text:
Q: Retrieve corrupted git commit My git repository got corrupted after a couple of hard reboots due to power supply issues and now I'm unable to fix it and after verification of logs files (in .git\logs\refs\heads) i ve seen my branche with commit:
0000000000000000000000000000000000000000 2af7fde85969d445579df272716e8d78db9 user <user_mail> 1372352519 +0100  branch: Created from branch refs/heads/master
null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null

and i have verified logs and copied to the corrupted file the line related to my commit and replace nulls with this
2af7fde85969d445579df272716e8d78db9 6c668139241332dbc7c7462a49978006de0 user <user_mail> 1372352552 +0100   commit: assignement report not verified

I have restared Eclipse and switch to my last commit and i always have the same error::
Branch failed
Object 6c668139241332dbc7c7462a49978006de0 is corrupt: invalid type

So, as you can see, my current branch is pretty screwed up and I don't seem to be able to fix it. Any ideea what can I try to repair this?


text:
Q: how can I be sure about the correctness of a .d.ts file I'm writing? (is there is way VScode warns me? like its intellisense) for example, in the below file structure if I change the type of thing to string (defined type in my-module.d.ts file) I won't see any warning in either of those three files by VScode.
src/
  my-module.js
  my-module.d.ts
  index.ts

my-module.js:
const thing = 42;
module.exports = { thing };

my-module.d.ts:
export declare const thing: number;

index.ts:
import { thing } from "./my-module";
console.log(thing); // 42
type TypeOfThing = typeof thing; // number


text:
Q: Is it possible to stream music from Android/iOS devices to desktop devices? I have a ucLinux microcontroller, which connects to loudspeakers. Now I want to stream music from Android/iOS devices to the microcontroller, and make the loudspeaker play music on my mobile devices. The microcontroller and mobile devices can connect via wi-fi. Is it possible to do so? Thanks.

A: If you write your own music streaming server, or find somebody who has written one, sure. There is no music streaming server built into Android itself.

A: There's two parts to this - getting the files to the micro, and controlling the playback. The second part is easy - use mpd (http://mpd.wikia.com/). There's good clients available for Android and mpd is lightweight enough to run well on low-end or embedded devices, and ucLinux is specifically supported.
Getting the files there is trickier. mpd expects to get the files from a filesystem, which tends to require more "serverness" than Android typically has. I found two options.
If you can root the Android device you can run a samba server on the device (http://mobilitydigest.com/woah-samba-server-for-android/) and mount that.
If you can't or don't want to root the device, there is a WebDAV server for Android (http://www.androidzoom.com/android_applications/productivity/davdrive_fwtl.html) and Linux supports mounting WebDAV shares as a filesystem. It can be pretty fiddly to get working though, and reliability can be a bit iffy too.
Having said that, I think your best bet might be to give some local storage to the microcontroller and have it sync the files in advance, then control the playback with an mpd client.


text:
Q: ffmpeg getting syntax error when run inside shell script only.. Why? OS: Raspbian
I'm currently working on a bash script that will merge all .AVI videos in the current directory, to one .AVI file. I've found the following to work perfectly for me, when run directly in the terminal:
ffmpeg -f concat -safe 0 -i <(find . -name '*.avi' -printf "file '$PWD/%p'\n") -c copy "$(date -d '-1 day' +'%F')".avi

This works perfectly, and I find a new .AVI file listed in the current directory (with a date name from yesterday).
Now, when I add this same command to my script (merge.sh), I get the following output:
/home/pi/Documents/MotionScripts/merge.sh: 11:
/home/pi/Documents/MotionScripts/merge.sh: Syntax error: "(" unexpected

This is beyond frustrating. And yes, ffmpeg command from earlier is on line 11. The script navigates to the correct directory where the multiple .avi files are stored.
Here is the entire script:
#!/bin/bash

#This script combines multiple AVI files within the current directory, into one long video

cd /media/myBook/Security/yesterday

sudo mv * /home/pi/Videos/tempconversion

cd /home/pi/Videos/tempconversion

ffmpeg -f concat -safe 0 -i <(find . -name '*.avi' -printf "file '$PWD/%p'\n") -c copy "$(date -d '-1 day' +'%F')".avi

sudo mv "$(date -d '-1 day' +'%F')".avi /media/myBook/Security/yesterday

sudo rm -f *

Why am I getting the syntax error only when the same command is being issued within an executable script?
RESOLVED! Shouldn't have used 'sh' to run the script. Make sure the script is executable (sudo chmod +x merge.sh) and run by entering the full path.


text:
Q: Program blocks on httpClient.execute: NullPointerException My android program tries to fetch some data from a database in localhost, and for doing it I use AsynkTask class and a JSONParser class. If I debug the program I can arrive to the lineHttpResponse httpResponse = httpClient.execute(httpPost);: I cannot go to the next one.
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

    // Se mancano dei commenti, andare a quelli del metodo precedente.
    // If there aren't some comments, go to the ones of the previous method.

    // Making HTTP request
    try {

        // Controlla il metodo.
        // Check for request method.
        if(method == "POST"){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // Invio dei parametri.
            // Passing the params.
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);    // LAST LINE WHERE I COME
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            [...]
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    [...]

    // return JSON String
    return jObj;

}

If I filter the Exceptions in the LogCat I get some NullPointerException:
    01-17 12:09:06.800      382-434/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '18 interface fwmark exempt add 10.0.2.2/32' failed with '400 18 Failed to add exemption rule (File exists)'
01-17 12:09:07.050      382-434/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '20 interface fwmark exempt add 10.0.2.3/32' failed with '400 20 Failed to add exemption rule (File exists)'
01-17 12:09:07.070      382-434/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '21 interface route add eth0 secondary 10.0.2.2 32 0.0.0.0' failed with '400 21 ip route modification failed (No such device)'
01-17 12:09:07.110      382-434/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '22 interface route add eth0 secondary 0.0.0.0 0 10.0.2.2' failed with '400 22 ip route modification failed (No such device)'
01-17 12:09:11.820      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '30 interface fwmark exempt add 10.0.2.2/32' failed with '400 30 Failed to add exemption rule (File exists)'
01-17 12:09:13.570      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '32 interface fwmark exempt add 173.194.40.6/32' failed with '400 32 Failed to add exemption rule (File exists)'
01-17 12:09:16.740      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '34 interface fwmark exempt add 10.0.2.2/32' failed with '400 34 Failed to add exemption rule (File exists)'
01-17 12:09:16.920      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '36 interface fwmark exempt add 173.194.40.4/32' failed with '400 36 Failed to add exemption rule (File exists)'
01-17 12:09:20.320      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '38 interface fwmark exempt add 10.0.2.2/32' failed with '400 38 Failed to add exemption rule (File exists)'
01-17 12:09:20.530      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '40 interface fwmark exempt add 173.194.40.6/32' failed with '400 40 Failed to add exemption rule (File exists)'
01-17 12:09:23.850      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '42 interface fwmark exempt add 10.0.2.2/32' failed with '400 42 Failed to add exemption rule (File exists)'
01-17 12:09:24.080      382-681/system_process E/ConnectivityService﹕ Exception trying to add a route: java.lang.IllegalStateException: command '44 interface fwmark exempt add 173.194.40.0/32' failed with '400 44 Failed to add exemption rule (File exists)'
01-17 12:12:59.065    1142-1159/? E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
01-17 12:12:59.075    1142-1159/? E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
01-17 12:12:59.165    1142-1159/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.app, PID: 1142
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:179)
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
01-17 12:14:57.185    1197-1213/? E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
01-17 12:14:57.185    1197-1213/? E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
01-17 12:14:57.205    1197-1213/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.app, PID: 1197
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:179)
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
01-17 12:15:27.805    1232-1246/? E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
01-17 12:15:27.805    1232-1246/? E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
01-17 12:15:27.875    1232-1246/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.app, PID: 1232
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:179)
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
01-17 12:18:37.525    1285-1301/? E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
01-17 12:18:37.525    1285-1301/? E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
01-17 12:18:37.675    1285-1301/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.app, PID: 1285
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:179)
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
01-17 12:24:49.535    1336-1352/? E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
01-17 12:24:49.535    1336-1352/? E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
01-17 12:24:49.555    1336-1352/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.app, PID: 1336
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:179)
            at com.example.app.FragmentControllaCorsa$DownloadUltimaCorsa.doInBackground(FragmentControllaCorsa.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

This NPE are risen at the line 179 and 132 of FragmentControllaCorsa class. At line 132 there is the declaration of the inner class that I post here:
class DownloadUltimaCorsa extends AsyncTask<Void, Void, JSONObject>{   // LINE 132

    private ProgressDialog pDialog;

// Test dall'Emulatore:
// Testing from Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/PrimaAppAndroid/get/ultimaTratta.php";

// Tag(ID) del responso Json restituito dallo script php:
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_DATA = "Data";
private static final String TAG_DURATA = "DurataConvalida";

    /**
     * Metodo che viene eseguito prima di doInBackground.
     * Avvio il ProgressDialog.
     * --
     * Method executed before of doInBackgroung.
     * I start the ProgressDialog.
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Download ultima tratta...");
        // Dura un tempo indeterminato.
        // It lasts a undefined time.
        pDialog.setIndeterminate(false);
        // E' cancellabile dal tasto Back.
        // It's cancelable by the Back key.
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(Void... voids) {

        // Per il controllo se è andato a buon fine.
        // Checking if all goes well.
        int success;
        // Il parametro da passare.
        // The param to pass.
        String codice = codiceDocumento.getText().toString();
        JSONParser jsonParser = new JSONParser();

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();  //http://stackoverflow.com/a/17609232/2337094 Namevaluepair
            params.add(new BasicNameValuePair("codice", codice));

            // Avvio della richiesta.
            // Start the request.
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            // json success tag
            success = json.getInt(TAG_SUCCESS);    // LINE 179
            if (success == 1) {//SE VORRÒ GESTIRE L'ERRORE.
                return json;
            } else {
                return json;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * Metodo eseguito dopo doInBackground. Chiudo il ProgressDIalog.
     * --
     * Method executed after doInBackgroun. I Close the ProgressDialog.
     * @param json
     */
    @Override
    protected void onPostExecute(JSONObject json) {
        super.onPostExecute(json);
        // Chiudo il ProgressDialog.
        // Dismiss the ProgressDialog.
        pDialog.dismiss();

        try {
            ultimaCorsa.setText(json.getString(TAG_DATA));
            validitaCorsa.setText(json.getString(TAG_DURATA));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

At the line 179 there is success = json.getInt(TAG_SUCCESS);. Here is risen the NPE.
In my .php file there is the tag TAG_SUCCESS, so why it is risen this exception?

A: If TAG_SUCCESS is defined in the return than you would need the quotes, if it is defined locally in the Java than you wouldn't need the quotes.
Example:

PHP
echo json_encode(array('myInt' => 1));

Java
int example;
example= json.getInt("myInt");

You are getting a null pointer exception because Java is looking for a locally defined variable called TAG_SUCCESS
Example:
PHP
echo json_encode(array('myInt' => 1));

Java
String myInt = "myInt";
int example;
example= json.getInt(myInt);

A: The error was that there were not the internet permission in the Manifest, as explained here.
I discovered the error thank to this two answer: first one and second one


text:
Q: PHP custom autoload function using spl_autoload_register won't trigger for inherited classes Not sure what i'm doing wrong here, hoping someone can help.
I built the following class with the purpose of detecting when a requested class has not been included so it can be included. I also wanted it to include any inherited classes not included.
The registered onAutoload function triggers as expected when calling a class not already included.
However if calling a class that inherits another class that hasn't been included, the registered onAutoload function does not trigger which is primarily what I want this to do.
I tested this using the default __autoload($class) and it triggers for inherited classes as required.
Any help would be appreciated. Have included a simplified example of what i'm trying to do below and the problem I am encountering.
In Autoload.php file
class Autoload
{
    private $fullPath;

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

    public function onAutoload ($class)
    {
        include ($this->fullpath . $class . ".php");
    }
}

Autoload class created and registered as required
$thisAutoload=new Autoload ("/path/to/file/to/include");
spl_autoload_register(array($thisAutoload,"onAutoload"));

Now in the following example, onAutoload is triggered as expected.
$newClassToInclude=new ClassToInclude();

However in the following example. Assuming ChildClass in included but BaseClass is not included, onAutoload does not trigger.
BaseClass.php
abstract class BaseClass
{
    function __construct()
    {
        print ("Base Class");
    }
}

ChildClass.php
class ChildClass extends BaseClass
{
    function __construct()
    {
        parent::__construct();
        print ("Child Class");
    }
}

I tested this using __autoload() function instead of my custom class and it triggered as expected.
Thanking everyone in advanced

A: Ok, So while not actually a fix, its an explanation and a workaround.
The example I provided wasn't 100% accurate, there's actually three classes. A base class, a second abstract class that inherits the base class, then finally the child class.
The base class was already included beforehand separate from the Autoload functionality, but the second abstract class needed to be included by the Autoload functionality which wasn't triggering.
When I disabled the logic that included the base class the Autoload functionality triggered and included  the base class and the second abstract class.
So going forward, I just need to make sure there isn't separate logic including files, and just let the Autoloader do its job.


text: Q: SSRS Reports parameters greyed out and not rendering In our production environment we have SSRS 2008 R2. When we are trying to access the reports using http://{ServerName}:{Port}/Reports then all the parameters are greyed out, and report is not rendering at all. But when we are trying to access the reports using http://{ServerName}:{Port}/ReportServer OR using the report builder then its working fine, all the parameters are available and it is rendering the reports. What can be the root cause for this issue? I checked the the processing options and its not Snapshot based.


text:
Q: Dynamically appended select menu with 1st option disabled automatically selects 2nd option I have hit a weird case where, to the best of my knowledge, two things that should act the same behave quite differently.
If I have two select menus on a page, one static menu hardcoded in the HTML and one appended to the body at runtime with JQuery. I then disable the first option in both select menus. When displayed both menus have their first options disabled as expected, however the dynamically appended menu has automatically set the value to the second option while the static menu still has the first selected.
http://jsfiddle.net/hm3xgkLg/1/
HTML:
<select class="dropMenu">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">fourth</option>
</select>

Javascript:
var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'},
  {val : 4, text: 'Four'}
];

var sel = $('<select class="dropMenu">').appendTo('body');
$(arr).each(function() {
   sel.append($("<option>").attr('value',this.val).text(this.text));
 });
$('.dropMenu option:nth-child(1)').attr('disabled', 'disabled');

Why are these two seemingly identical select menus behaving differently? I would like both to act like the static menu (keep 1st value selected) is that possible?
It should also be noted I tried wrapping the disable function in $(document).ready to rule out an issue of the menu not being rendered yet but there was no change. I also tried having two distinct classes with two separate calls to disable the options to make sure its wasn't clashing somehow with no change.

A:
Why are these two seemingly identical select menus behaving
  differently

This is because the first select was already part of the document and was parsed. As per the spec here:

The initial state has the first option selected..

and hence the first option was pre-selected. Later on when you disable one option, it doesn't change the selection.
Example 1: You can see that the first select has disabled attribute already applied to the first option in markup. The second option gets pre-selected, as compared to the second select.

<select class="dropMenu">
    <option value="1" disabled>First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">fourth</option>
</select>
<select class="dropMenu">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">fourth</option>
</select>

In your case of dynamically adding a select using Javascript, the second select was created and added to the body immediately. When this became the part of DOM, there are no options and hence no pre-selection possible. Later when you append options to it, and then disable one of the options, it seems that it gets executed too fast and by the time it is loaded the first option is already disabled and the second one gets pre-selected.
Example 2: Do NOT append the select immediately to the body. Append it after you have the options populated. This time the first option will be pre-selected despite you changing the disabled attribute later on.

var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'},
  {val : 4, text: 'Four'}
];

var sel = $('<select class="dropMenu">');
$(arr).each(function () {
    sel.append($("<option>").attr('value', this.val).text(this.text));
});

sel.appendTo('body'); /* <--- append here */

$('.dropMenu option:nth-child(1)').prop('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropMenu">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">fourth</option>
</select>

Example 3:  Add a delay before you disable an option. This will give you the intended behaviour of getting the first option pre-selected because it will have enough time.

var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'},
  {val : 4, text: 'Four'}
];

var sel = $('<select class="dropMenu">').appendTo('body');
$(arr).each(function () {
    sel.append($("<option>").attr('value', this.val).text(this.text));
});

setTimeout(disable, 1000); /* <--- give some delay here */

function disable() {
    $('.dropMenu option:nth-child(1)').prop('disabled', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropMenu">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">fourth</option>
</select>

Example 4: You can also select one option explicitly before disabling them.

var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'},
  {val : 4, text: 'Four'}
];

var sel = $('<select class="dropMenu">').appendTo('body');
$(arr).each(function () {
    sel.append($("<option>").attr('value', this.val).text(this.text));
});

$('.dropMenu option:nth-child(1)').prop('selected', true); /* <-- select explicitly */
$('.dropMenu option:nth-child(1)').prop('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropMenu">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
    <option value="4">fourth</option>
</select>

A: try to set your $('.dropMenu option:nth-child(1)').attr('disabled', 'disabled'); in setInterval, because you are creating dynamic dropdown so it will take some time to execute and create meanwhile you disable dropdown element jquery is going to execute. so that issue comes.
Checkout Code Snippet

var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'},
  {val : 4, text: 'Four'}
];

var sel = $('<select class="dropMenu">').appendTo('body');
$(arr).each(function() {
   sel.append($("<option>").attr('value',this.val).text(this.text));
 });

setTimeout(function() {
    $('.dropMenu option:nth-child(1)').attr('disabled', 'disabled');
}, 1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropMenu">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">fourth</option>
</select>

A: Well by default if you have given option selected to the first option of your dynamic dropdown then it would have been done it for you:
Just see this DEMO:
$(arr).each(function(key,value) {
    if(key==0)
         sel.append($("<option>").attr('value',this.val).text(this.text).attr('selected',true));
    else
         sel.append($("<option>").attr('value',this.val).text(this.text));
});

Now why this happens?
For static select, the element is already present in DOM and then you are adding disabled for first option using jquery and by default first option will be kept as selected already.
Now for dynamic select since you are adding it dynamically may be it is not considering to select the first option by default since it is disabled!!
Even I feel this as strange behavior but ya sometimes we need to take care of these things by trail and error.

A: Just manually select the first option in the dinamically added menu:
$('.dropMenu option:nth-child(1)')
      .attr('disabled', 'disabled')
      .attr('selected', 'selected');

jsfiddle here (I borrowed yours :P):
https://jsfiddle.net/z0dzk5nL/1/
EDIT
A quick update. Here you can find the specification for the "select" element. I've quoted the part that answers your question:

If nodes are inserted or nodes are removed causing the list of options
  to gain or lose one or more option elements, or if an option element
  in the list of options asks for a reset, then, if the select element's
  multiple attribute is absent, the user agent must run the first
  applicable set of steps from the following list:
If the select element's display size is 1, and no option elements in
  the select element's list of options have their selectedness set to
  true Set the selectedness of the first option element in the list of
  options in tree order that is not disabled, if any, to true.
If two or more option elements in the select element's list of options
  have their selectedness set to true Set the selectedness of all but
  the last option element with its selectedness set to true in the list
  of options in tree order to false.

And here's the fiddle to show that if you pre-select the option when appending it, you can than disable without losing the selection (I used a for loop instead of the "each" func exactly to demonstrate that):
jsfiddle.net/xnvbevhm/
(sorry I can't post more than two links, as I don't have enough reputation :P)

A: As an alternative to setting the first attribute as selected, using setTimeout with a minimal time (i.e. 1) seems to make things behave as expected. I'm still researching the reason for this, though.
setTimeout(function() {
    $('.dropMenu option:nth-child(1)').attr('disabled', 'disabled');
}, 1);

Updated fiddle.


text:
Q: Youtube API Post a comment on a Video I am using Youtube API to show video and now i need to Post a comment on YouTube Video. Here is the code for iOS which is working
NSString *urlStr = @"http://gdata.youtube.com/feeds/mobile/videos/W_KEuea8eIw/comments";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *xmlString = @"<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\"xmlns:yt=\"http://gdata.youtube.com/schemas/2007;\"><content>This is a crazy video</content></entry/>";
[request setHTTPMethod: @"POST" ];
[request setValue:@"application/atom+xml" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"2.1" forHTTPHeaderField:@"GData-Version"];
[request setValue:[NSString stringWithFormat:@"key=%@",kSampleDeveloperKey] forHTTPHeaderField:@"X-GData-Key"];
[request setValue:[NSString stringWithFormat:@"Bearer %@",self.auth.accessToken] forHTTPHeaderField:@"Authorization"];
NSURLResponse *response;
NSError *err;
NSData*returnData=[ NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"responseData: %@", content);

Now I'm trying to POST a comment on android using a HTTP Post request but unable to make a POST URL in android
https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId=ffL25JVXbo0&key=AIzaSyAQSINj5dtoLdSNJA3cc6dkziFC2zbbEuk&snippet.topLevelComment.snippet.textOriginal=my%20comment

A: Well, I try it and I successfully posted a comment in the video that you provide.

Try to use the Try it part of this documentation and check if your comment is there in the video.
Take NOTE that change the dropdown button to Newest first to view the latest comment in checking the comments in the video.

Also, it is stated in the documentation of CommentThreads: insert that you must specify a value for these properties:

*

*snippet.channelId

*snippet.topLevelComment.snippet.textOriginal
So try to include also the channelId in your request.


text:
Q: Why bootstrap override internal style? This is my Head tag in a html page
<head>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <style>
        input[type=text] {
            font-size: 18px;
            height: auto;
        }
        select {
            font-size: 18px;
            height: auto;
        }
    </style>
</head>

bootstrap override my inline style for select element,
What is the reason?

A: Rule .form-control in bootstrap is more weighty than your input
just use .form-control and add new style

A: in bootstrap select styled with other elements like input,textarea etc.
The .form-control class name more specific and takes precedence then select element that's why its better to use  .form-control class to override bootstrap default style.
Use  .form-control instead of select element.Add this class to your CSS.


text:
Q: How to set the yAxis by 5 in angular echarts here's the code:
https://stackblitz.com/edit/ngx-echarts-odv9rp?file=src/app/app.component.html
TS
xAxis = {
    type: "category",
    boundaryGap: false,
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  };
  yAxis = {
    type: "value",
    max: "100"
  };
  series = [
    {
      data: [23.2, 24.3, 32.2, 36.5, 32.9, 52.2, 92.1],
      type: "line",
      areaStyle: {}
    }
  ];

HTML
<ngx-echarts
  style="width: 300px; height: 300px;"
  [xAxis]="xAxis"
  [yAxis]="yAxis"
  [series]="series">
</ngx-echarts>

What I'm trying to do is to set the yAxis by 5. for the example 0, 5, 10, 15, 20, 25 ... to 100.
How to set the yAxis to by 5?

A: Use interval:
yAxis = {
  type: "value",
  max: "100",
  interval: 5
}


text:
Q: convolution of all arrangements of a multiset You are given the set of numbers 2,7,8,9,9,23,33,41,41,57 and want to find the sum of all convolutions of the possible arrangement of these ten terms.  Each arrangement is convolved with itself.  One can find the answer by examining case by case each arrangement, but this becomes impracticable if the number of terms is larger than ten.  Is there any faster method to find the sum of all these convolutions?

A: Suppose the multiset $M$ has unique terms $x_1,x_2,x_3,\ldots,x_k$ with these terms appearing $n_1,n_2,n_3,\ldots,n_k$ times each.
Then the total number of unique elements is $\displaystyle T(M)=\sum_{i=1}^k n_i$ and the total number of arrangements is $\displaystyle A(M)=\frac{T(M)!}{\prod_i n_i!}$ with the caveat that $A(M)=0$ if any of the $n_i$ are negative.
Also consider the multisets: $M_{-i}$ where $n_i$ is reduced by $1$ and $M_{-i-j}$ where $n_i$ and $n_j$ are each reduced by $1$ ($i$ and $j$ can be the same or different: if the same then this means $n_i$ is reduced by $2$).
Then I suspect that your result is something like
$$\displaystyle 2\big\lfloor \tfrac{T(M)}{2} \big\rfloor\left( \sum_{i=1}^k \sum_{j=1}^k x_i x_j A(M_{-i-j})    \right) + \left(T(M)-2\big\lfloor\tfrac{T(M)}{2}\big\rfloor \right)\left( \sum_{i=1}^k x_i^2 A(M_{-i})   \right) $$ and you can factor out $A(M)$ using  $A(M_{-i}) = A(M)\frac{n_i}{T(M)}$, $A(M_{-i-i}) = A(M)\frac{n_i(n_i-1)}{T(M)(T(M)-1)}$ and $A(M_{-i-j}) = A(M)\frac{n_i n_j}{T(M)(T(M)-1)}$ when $i\not = j$. [Added] The $2\big\lfloor \tfrac{T(M)}{2} \big\rfloor$ term is $T(M)$ when this is even and $T(M)-1$ when $T(M)$ is odd, while the  $\left(T(M)-2\big\lfloor\tfrac{T(M)}{2}\big\rfloor \right)$ term is $0$ when $T(M)$ is even and $1$ when $T(M)$ is odd.
If you do that and then let  $\displaystyle S(M)=\sum_{i=1}^k n_i x_i$, i.e. the sum over the multiset, and let $\displaystyle Q(M)=\sum_{i=1}^k n_i x_i^2$, i.e. the sum of squares over the multiset, then I think you get the fairly simple
$$\dfrac{A(M)\left(S(M)^2 - Q(M)  \right)  }{(T(M)-1)} \text{ when } T(M) \text{ is even}$$
$$\dfrac{A(M)\,S(M)^2 }{T(M)} \text{ when } T(M) \text{ is odd}$$
For the toy example of $M=\{8,9,9\}$, this has $x_1=8,x_2=9,n_1=1,n_2=2$ and so $T(M)=1+2=3$ and $A(M)=\frac{3!}{1! \times 2!}=3$, $S(M)=8+9+9=26$, $Q(M) = 8^2+9^2+9^2 = 226$,  so the result becomes $\frac{3\times 26^2}{3} = 676$ as expected

A: [Note: I think my solution is slightly different from Henry's and I had much of it written already, so I'll post anyway.]
Assume first that the multiset does not contain any repeated elements, so that its elements $\{a_1, \ldots, a_n\}$ are distinct.
Suppose first $n$ is even. Let $a_i$ and $a_j$ be any pair of elements in the multiset, and count the number of arrangements in which the product $a_ia_j$ is used in the convolution. There are $n$ locations for $a_i$, and then only one choice for $a_j$; the remaining elements can be distributed arbitrarily in $(n-2)!$ ways. For each of these $n(n-2)!$ arrangements, this pair contributes a summand of $2a_ia_j$ to the convolution; hence to the sum of all convolutions, this pair contributes a total of $2a_ia_jn(n-2)!$. Thus the sum of all convolutions is:
$$\displaystyle 2n(n-2)!\sum_{1 \le i < j \le n} a_ia_j$$
If $n$ is odd, we can again let $a_i$ and $a_j$ be any pair of elements in the multiset, and count the number of arrangements where the product $a_ia_j$ is used in the convolution. Since $n$ is odd, there are only $n-1$ locations for $a_i$, since it cannot go in the middle position. But the rest of the calculation is the same, meaning this pair contributes a total of $2a_ia_j(n-1)!$ to the sum of all convolutions. Unlike the even case, a single element $a_i$ can contribute to the convolution without a partner by being in the middle position, where it contributes $a_i^2$ to the convolution. This term appears in $(n-1)!$ arrangements, adding a total of $a_i^2(n-1)!$ to the sum of all convolutions. Thus the total convolution sum in this case is:
$$\displaystyle 2(n-1)!\sum_{1 \le i < j \le n} a_ia_j + (n-1)!\sum_{i=1}^n a_i^2$$
Now suppose our multiset consists of distinct elements $b_1 \ldots b_m$, where $b_i$ has multiplicity $n_i$, and let $n = \sum n_i$. For the moment, treat the $n$ elements of the multiset as being distinct objects, though some might have the same numerical value. Then the analysis above would still give the total convolution sum over all $n!$ arrangements.
By wishing to treat objects of the same numerical value as being equivalent, we are essentially creating equivalence classes over the set of $n!$ arrangements of our distinct objects such that two arrangements are equivalent if both arrangements have the same ordering of numerical values. Clearly, each equivalence class has $\prod_{i=1}^m n_i!$ elements, and moreover, the convolution of each element in the equivalence class is the same. Since each contributing summand to the total convolution sum is counted exactly this many times, we can get the desired answer simply by dividing the above quantities by $\prod_{i=1}^m n_i!$, to get the formulas:
For $n$ even:
$$\frac{2n(n-2)!}{\prod_{i=1}^m n_i!} \left( \displaystyle \sum_{1 \le i < j \le m}b_in_ib_jn_j + \sum_{i=1}^m\frac{n_i(n_i-1)}{2}b_i^2 \right)$$
For $n$ odd:
$$\frac{(n-1)!}{\prod_{i=1}^m n_i!} \left( \displaystyle \sum_{1 \le i < j \le m}2b_in_ib_jn_j + \sum_{i=1}^m n_i^2b_i^2 \right)$$

A: Suppose for the moment that the multiset $S$ contains $n$ unique integers and let $x$ be a vector of these integers.
Let $R$ denote the $n\times n$ reverse order matrix and let $P$ denote an $n\times n$ permutation matrix corresponding to
any of the $n!$ permutations $\sigma$ of $\{1,\ldots,n\}$. Then the convolution of any arrangement of $S$ may be expressed
as $x^TP^TRPx$. Let $Q$ denote the sum of all such matrices of the form $P^TRP$. Then it follows that
the sum of all possible convolutions is given by $x^TQx$. All that remains is to determine the elements of $Q$.
Consider a matrix of the form $P^TRP$ corresponding to the permutation $\sigma$. By the nature of $P$ and $R$ it follows that
$$
(P^TRP)_{ij} = p_i^TRp_j =
\left\{
\begin{array}{ll}
1 & \text{if}~\sigma^{-1}(i) = n - \sigma^{-1}(j) + 1\\
0 & \text{otherwise}
\end{array}\right.
$$
for all $i,j = 1,\ldots,n$.
Hence, by a simple counting argument
$$
q_{ij} = \left\{
\begin{array}{ll}
0 & n~\text{even},~i = j\\
n(n-2)! & n~\text{even},~i \neq j\\
(n-1)! & n~\text{odd}\\
\end{array}\right.
$$
Now consider the case in which $S$ consists of $k$ distinct elements repeated $n_1,\ldots,n_k$ times.
Let $n = n_1 + \cdots + n_k$. Then there are
$$
\frac{n!}{n_1!n_2!\cdots n_k!}
$$
unique permutations of $S$ and so we have overcounted by a factor of $N = (n_1!n_2!\cdots n_k!)$. Thus, the general solution is
$$
\frac{1}{N}x^TQx.
$$
Lastly we note that $Q$ is symmetric, which further reduces the work to compute the sum. Clearly, a computational routine would not form $Q$ explicitly but would rather hard code the product $x^TQx$ to reduce the memory overhead.


text:
Q: In OpenCl, multiple gpu is slower than single gpu. How can I make faster? I made vector addition kernel and run it in the single gpu and multiple gpu.
However in Multi gpu case is much slower than single gpu in the same length of vector addition.
The structure of my code is one context one kernel and multi queues which has same number of devices..
How can I modify for faster in multi gpu case?
The code is below
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <CL/cl.h>
#include <math.h>

//#define VECTOR_SIZE 640000
//#define LOCAL_SIZE 64

#define CHECK_ERROR(err) \
  if (err != CL_SUCCESS) { \
    printf("[%s:%d] OpenCL error %d\n", __FILE__, __LINE__, err); \
    exit(EXIT_FAILURE); \
  }

double get_time() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return (double)tv.tv_sec + (double)1e-6 * tv.tv_usec;
}

char *get_source_code(const char *file_name, size_t *len) {
  char *source_code;
  size_t length;
  FILE *file = fopen(file_name, "r");
  if (file == NULL) {
    printf("[%s:%d] Failed to open %s\n", __FILE__, __LINE__, file_name);
    exit(EXIT_FAILURE);
  }

  fseek(file, 0, SEEK_END);
  length = (size_t)ftell(file);
  rewind(file);

  source_code = (char *)malloc(length + 1);
  fread(source_code, length, 1, file);
  source_code[length] = '\0';

  fclose(file);

  *len = length;
  return source_code;
}

int main() {
  // OpenCl variables
  cl_platform_id platform;
  //cl_device_id device;
  cl_device_id *devices;
  cl_device_id device_temp;

  cl_context context;
  //cl_command_queue queue;
  cl_command_queue *queues;

  cl_mem bufferA, bufferB, bufferC;
  cl_program program;
  char *kernel_source;
  size_t kernel_source_size;

  cl_kernel kernel;
  //cl_kernel *kernels;

  cl_int err;

  //

  size_t VECTOR_SIZE = 64000000 ;
  int num_devices = 4;
  size_t LOCAL_SIZE = 64;

  // Time variables
  double start;
  double end;

  // Get platform
  err = clGetPlatformIDs(1, &platform, NULL);
  CHECK_ERROR(err);

  // Get GPU device

  devices = (cl_device_id *) malloc(sizeof(cl_device_id)*num_devices);
  err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, num_devices, devices, NULL);
  //err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
  CHECK_ERROR(err);

  // Create context
  context = clCreateContext(NULL,num_devices, devices , NULL, NULL , &err);
  //context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
  CHECK_ERROR(err);

  // Get kernel code
  kernel_source = get_source_code("kernel.cl", &kernel_source_size);

  // Create program
  program = clCreateProgramWithSource(context, 1, (const char**)&kernel_source,
    &kernel_source_size, &err);
  CHECK_ERROR(err);

  // Build program
  err = clBuildProgram(program, num_devices, devices, "", NULL, NULL);

  if(err == CL_BUILD_PROGRAM_FAILURE) {
    size_t log_size;
    char *log;

    // Get program build
    //err = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
    //  0, NULL, &log_size);
    err = clGetProgramBuildInfo(program,devices[0],CL_PROGRAM_BUILD_LOG,0,NULL,&log_size);
    CHECK_ERROR(err);

    // Get build log
    log = (char*)malloc(log_size + 1);
    //err = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
    //  log_size, log, NULL);
    err = clGetProgramBuildInfo(program,devices[0],CL_PROGRAM_BUILD_LOG,log_size,log,NULL);
    CHECK_ERROR(err);

    log[log_size] = '\0';
    printf("Compiler error : \n%s\n", log);
    free(log);
    exit(0);
  }
  CHECK_ERROR(err);
  // Create Vector A, B, C
  float *A = (float*)malloc(sizeof(float) * VECTOR_SIZE);
  float *B = (float*)malloc(sizeof(float) * VECTOR_SIZE);
  float *C = (float*)malloc(sizeof(float) * VECTOR_SIZE);

  // Initial Vector A, B
  //cl_ushort idx;
  /*for(idx = 0; idx < VECTOR_SIZE; idx++) {
    A[idx] = rand() % 100;
    B[idx] = rand() % 100;
  }*/
  printf("start\n");
  start = get_time();
  for(int i = 0; i <VECTOR_SIZE; i++){
      A[i] = sinf(i)*sinf(i);
      B[i] = cosf(i)*cosf(i);
  }
  end = get_time();
  printf("Initialization time : %f seconds elapsed\n", end-start);

  // Create kernel
  /*kernels = (cl_kernel *) malloc(sizeof(cl_kernel)*num_devices);
  for(int i=0; i<num_devices; i++){
      kernels[i] = clCreateKernel(program,"vec_add", &err);
      CHECK_ERROR(err);
  }*/
  kernel = clCreateKernel(program, "vec_add", &err);
  CHECK_ERROR(err);

  // Create Buffer
  bufferA = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float) * VECTOR_SIZE, NULL, &err);
  CHECK_ERROR(err);

  bufferB = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float) * VECTOR_SIZE, NULL, &err);
  CHECK_ERROR(err);

  bufferC = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * VECTOR_SIZE, NULL, &err);
  CHECK_ERROR(err);

  printf("error hi\n");
  // Create command-queue
  queues = (cl_command_queue *) malloc(sizeof(cl_command_queue)*num_devices);
  for(int i=0; i<num_devices; i++){
      if (i==0){
          queues[i] = clCreateCommandQueue(context,devices[i],CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,&err);
          CHECK_ERROR(err);
      }
      else{
          queues[i] = clCreateCommandQueue(context,devices[i], CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err);
          CHECK_ERROR(err);
      }
  }
  printf("error bye\n");

  //queue = clCreateCommandQueue(context, device, 0, &err);
  //CHECK_ERROR(err);

  // Write Buffer
  for (int i = 0; i<num_devices; i++){
      err = clEnqueueWriteBuffer(queues[i],bufferA,CL_FALSE,0,sizeof(float)*VECTOR_SIZE,A,0,NULL,NULL);
      CHECK_ERROR(err);
      err = clEnqueueWriteBuffer(queues[i],bufferB,CL_FALSE,0,sizeof(float)*VECTOR_SIZE,B,0,NULL,NULL);
      CHECK_ERROR(err);
  }
  //err = clEnqueueWriteBuffer(queue, bufferA, CL_FALSE, 0, sizeof(float) * VECTOR_SIZE, A, 0, NULL, NULL);
  //CHECK_ERROR(err);
  //err = clEnqueueWriteBuffer(queue, bufferB, CL_FALSE, 0, sizeof(float) * VECTOR_SIZE, B, 0, NULL, NULL);
  //CHECK_ERROR(err);

  for(int i=0; i<num_devices; i++){
      err=clFinish(queues[i]);
      CHECK_ERROR(err);
  }

  // Set Kernel arguments
  start = get_time();
  /*for(int i=0; i<num_devices; i++){
      err=clSetKernelArg(kernels[i], 0, sizeof(cl_mem), &bufferA);
      CHECK_ERROR(err);
      err=clSetKernelArg(kernels[i], 1, sizeof(cl_mem), &bufferB);
      CHECK_ERROR(err);
      err=clSetKernelArg(kernels[i], 2, sizeof(cl_mem), &bufferC);
      CHECK_ERROR(err);
      err=clSetKernelArg(kernels[i], 3, sizeof(unsigned int), &VECTOR_SIZE);
      CHECK_ERROR(err);
  }*/
  err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufferA);
  CHECK_ERROR(err);
  err = clSetKernelArg(kernel, 1, sizeof(cl_mem), &bufferB);
  CHECK_ERROR(err);
  err = clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufferC);
  CHECK_ERROR(err);
  err = clSetKernelArg(kernel, 3, sizeof(unsigned int), &VECTOR_SIZE);
  CHECK_ERROR(err);

  end = get_time();

  printf("Send Vector A, B to GPU : %f seconds elapsed\n", end - start);

  for(int i=0; i<num_devices; i++){
      err=clFinish(queues[i]);
      CHECK_ERROR(err);
  }

  cl_event ooo_events[num_devices];
  start = get_time();
  // Execute Kernel
  size_t global_size = VECTOR_SIZE;
  size_t local_size = LOCAL_SIZE;
  for(int i=0; i<num_devices; i++){
      //start=get_time();

      err= clEnqueueNDRangeKernel(queues[i],kernel,1,NULL,&global_size,&local_size,0,NULL,NULL);
      CHECK_ERROR(err);
      //err = clEnqueueNDRangeKernel(queues[i],kernels[i],1,NULL,&global_size, &local_size,0,NULL,NULL);
      //CHECK_ERROR(err);
      //end=get_time();
      //printf("Calculate C : %f seconds elapsed\n", end-start);
  }
  //err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL,&global_size, &local_size, 0, NULL, NULL);
  //CHECK_ERROR(err);
  for(int i=0; i<num_devices; i++){
      err=clFinish(queues[i]);
      CHECK_ERROR(err);
  }

  end = get_time();

  printf("Calculate C : %f seconds elapsed\n", end - start);

  // Read Buffer
  start = get_time();
  for(int i=0; i<num_devices; i++){
      err = clEnqueueReadBuffer(queues[i],bufferC,CL_TRUE,0,sizeof(float)*VECTOR_SIZE,C,0,NULL,NULL);
      CHECK_ERROR(err);
  }
  //err = clEnqueueReadBuffer(queue, bufferC, CL_TRUE, 0, sizeof(float) * VECTOR_SIZE, C, 0, NULL, NULL);
  //CHECK_ERROR(err);

  end = get_time();
  printf("Receive C from GPU : %f seconds elapsed\n", end - start);

  // Evaluate Vector C
  start = get_time();
  double sum = 0;
  for(int i = 0; i < VECTOR_SIZE; i++) {
    sum += C[i];
  }
  end = get_time();
  printf("Verification time : %f seconds elapsed\n", end-start);
  printf("%lf, %ld \n", sum,VECTOR_SIZE);
  if (abs(VECTOR_SIZE - sum) < 1) {
    printf("Verification success!\n");
  }
  printf("Sum : %f\n", sum);

  // Release OpenCL object
  clReleaseMemObject(bufferA);
  clReleaseMemObject(bufferB);
  clReleaseMemObject(bufferC);
  free(A);
  free(B);
  free(C);
  clReleaseKernel(kernel);
  //clReleaseKernel(kernels[0]);
  //clReleaseKernel(kernels[1]);
  clReleaseProgram(program);

  clReleaseCommandQueue(queues[0]);
  clReleaseCommandQueue(queues[1]);
  //clReleaseCommandQueue(queue);
  clReleaseContext(context);

  return 0;
}

A: Using multiple GPUs is only beneficial in terms of performance if the amount of computational work that each GPU performs takes more time then the communication, scheduling and synchronization overhead. This is true for a single GPU as well.
In your case, each GPU performs a simple vector addition. but that rarely takes more time then transferring the data to the GPU, waiting for the kernel to actually get scheduled for execution, etc.
Your code is not measuring the total kernel execution time but also the scheduling overhead.
I would advise you to use proper GPU profiling tools (depending on your GPU vendor) instead of manual CPU timings to properly examine what is going on. You can also try measuring kernel execution time via events.


text:
Q: MSSQL Select Top 10 winning scores, including Ties and at least one from each category I got some help finding the top 10 scores, including tied entries, using the following statement
select T.EntryID, T.CategoryID, T.Score
from (
   select EntryID, CategoryID, Score,
          dense_rank() over(order by Score) as rn
   from YourTable
 ) T
where T.rn <= 10

(thanks [mikael-eriksson]: https://stackoverflow.com/users/569436/mikael-eriksson)
[question]: MSSQL Selecting top 10 but include columns with duplicate values Here is sample data:
EntryID CategoryID  Score
3036    1           85
3159    1           85
3039    1           84
3146    1           83
3225    1           82
3045    1           82
3047    1           80
3048    1           80
3049    1           80
3193    1           80
3098    1           80
3025    1           72
3082    1           70
3167    1           70
3122    1           67
3220    1           65
3080    1           65
3168    1           64
______________________
Total Entries >= 18

There is a requirement that there be at least one entry from each category in the top 10 (or top whatever it may be i.e. top 100), in this case there are 3 Categories.
Now all I need to do is to include at least one entry per category in the top 10. i.e. if all the top 10 scores are from Category 1, and there are 3 categories,  I need to drop the 2 lowest scores from Category 1 and include the highest score entry for both Category 2 and 3.
As you can see from the results all the entries are from Category 1, so I need to drop EntryID's 3220, 3080 and 3168 from the resultset as they are the lowest scored, and include the highest scoring entry in Category 2 as well as the highest scoring entry in Category 3 so that the result looks something like this:
EntryID CategoryID  Score
3036    1           85
3159    1           85
3039    1           84
3146    1           83
3225    1           82
3045    1           82
3047    1           80
3048    1           80
3049    1           80
3193    1           80
3098    1           80
3025    1           72
3082    1           70
3167    1           70
3122    1           67
3019    3           60
3800    2           54
______________________
Total Entries >= 17

Same thing goes for the following scenario, let's look at the top 5 instead of top 10 to make it a little easier on the eye, as you can see in this example the Top 5 scores exclude entries from Category 2
EntryID CategoryID  Score
3036    1           85
3159    1           85
3039    1           84
3146    1           83
3225    1           82
3045    1           82
3019    3           60
______________________
Total Entries >= 7

In this case entries 3225 and 3045 needs to drop as they are the lowest scored entries (3047 needs to be included as even though it's the lowest scored entry I need an entry from all categories in the result) and I need to include the highest scored entry from Category 2, I would expect something like this:
EntryID CategoryID  Score
3036    1           85
3159    1           85
3039    1           84
3146    1           83
3019    3           60
3800    2           54
______________________
Total Entries >= 6

And then there may be the scenario where there may not be an entry into a specific category, let say for example no Category 2 entries so the result should still have the top 5 as with the original result set for the top 5 above (included below as reference)
EntryID CategoryID  Score
3036    1           85
3159    1           85
3039    1           84
3146    1           83
3225    1           82
3045    1           82
3019    3           60
______________________
Total Entries >= 7

Please excuse if I'm repeating myself, I'm just trying to make it clear to understand ;)
I really Appreciate the help!

A: As I can see it, you need to rank your rows in a more sophisticated way, so that entries that are the top ones in every category are included regardless of their values, and entries that are not the top ones are included according to their overall rankings.
What I'm about to suggest may not be the most efficient solution, but it should work and, if nothing else can, might inspire someone else to come up with something better:
WITH ranked1 AS (
  SELECT
    *,
    RankByCategory = DENSE_RANK() OVER (
      PARTITION BY CategoryID
      ORDER BY Score DESC
    )
  FROM YourTable
),
ranked2 AS (
  SELECT
    *,
    FinalRank = DENSE_RANK() OVER (
      ORDER BY
        CASE RankByCategory WHEN 1 THEN 1 ELSE 2 END,
        Score DESC
    )
  FROM ranked1
)
SELECT
  EntryID,
  CategoryID,
  Score
FROM ranked2
WHERE FinalRank <= @top_n
;

The first CTE is ranking rows by categories, thus letting us find out which entries become the top ones in their respective categories. The next step (second CTE) is about obtaining global rankings, this time taking into account whether an entry is the top one in its category or not. The category top values receive lower rankings and thus are ensured to be included in the final results. (Of course, you need to make sure that the number of categories is not greater than the number of distinct values you want to receive in the output.)
Here's a live example at SQL Fiddle to play with.


text:
Q: Objectify 4 throwing strange error in GAE Objectify ofy = objectifyFactory.begin();
        User user= ofy.load().type(User.class).filter("userName", userName).first().now();

But eclipse is complaining that The method now() is undefined for the type Ref<User>.
I am using objectify4 with spring for a GAE project.

A: Ref does not have a method now(). You can see its signature here:
http://docs.objectify-appengine.googlecode.com/git/apidocs/com/googlecode/objectify/Ref.html

A: The correct method is
User user= ofy.load().type(User.class).filter("userName", userName).first().get();


text:
Q: Core Data not saving after using Firebase to fetch value - swift I've looked around different posts trying to put together reasons why saving core data isn't working for me.
My entity name is [ImportantData] with 2 attributes's [attribute1] [attribute2] set at Strings (either "yes" or "no").
I use firebase to see if a value has changed. Firebase name is ["FirebaseName"] with child ["firebaseChild"]
The below func is called in 'performFetchWithCompletionHandler' in AppDelegate.
var importantData = [ImportantData]()
var refFetchWorking: DatabaseReference!

func isFetchWorking() {
refFetchWorking = Database.database().reference().child("FirebaseName")
refFetchWorking?.observeSingleEvent(of: .value, with: {(snapshot } in
     let dict = snapshot.value as! [String: Any]
     let fetch = dict["firebaseChild"] as! String
     let context = (UIApplication.shared.delegate as! AppDelegate).persistantContainer.viewContext

     let data = ImportantData(context:context)
     let attribute1 = data.attribute1
     let attribute2 = data.attribute2

  do {
      self.attribute1 = try context.fetch(ImportantData.fetchRequest())
      print(attribute1!, attribute2!, "fetch")
   } catch {
       print("fail fetched"
     }

  if fetch != "closed" {
      data.setValue("yes", forKey: "attribute1"
      data.setValue("yes", forKey: "attribute2"

   do {
        try context.save()
    print(attribute1!, attribute2!, "test")
} catch {
 print("error after test"
}

} else {
print ("is closed!")
}

do { context.save()
  print(attribute1!, attribute2!, "after save")
} catch {
  print("error saving)
}
})
}

the NSLog is printing:
"no no fetch"
"no no test"
"no no after save"
but fetch != "closed"
any help is much appreciated! Thank you!


text:
Q: Is the statement is True or False? Is the following statement correct or incorrect?
Let $X $ be a topological space and $W \subset X$. Then, the induced subspace
topology on $W$ is the smallest topology such that $$\text{id} | _{W} : W \rightarrow X,$$ where $\text{id}$
is the identity map, is continuous.
My attempt : I was taking $ X $ with usual topology  and $W$ with lower limit topology, and I take $ f(x) = x.$ Then
$$\text{id} |_W : W → X$$ will not continuous because lower limit topology is  finer than  the usual topology, so the map will not be continuous.
Is my answer correct or not? I would be  thankful who will verify my mistakes.

A: The statement is true. Recall that the subspace topology on $W \subseteq X$ induced from $(X,\mathcal{T}_X)$ by definition equals $\mathcal{T}_W = \{O \cap W: O \in \mathcal{T}_X\}$.
This topology makes $i: W \to X$ defined by $i(x) = x$ continuous, because $$i^{-1}[O] = O \cap W$$ for all subsets $O$ of $X$, in particular for open ones. ($x \in i^{-1}[O]$ iff $x \in W$ and $i(x)\in O$ iff $x \in W$ and $x \in O$ iff $x \in O \cap W$).
And if $\mathcal{T}$ is any arbitrary topology on $W$ such that $i: (X, \mathcal{T}) \to (X,\mathcal{T}_X)$ is continuous this forces that $i^{-1}[O]$ are in $\mathcal{T}$ for all $O$ in $\mathcal{T}_X$.
This just says that $\mathcal{T}_W \subseteq \mathcal{T}$, proving the claim that the subspace topology is the smallest (or coarsest) topology on $W$ that makes $i$ continuous.


text:
Q: Spring Boot Actuator - Custom Endpoints I am using Spring Boot Actuator module in my project which exposes REST endpoint URLs to monitor & manage application usages in production environment, without coding & configuration for any of them.
By default, only /health and /info endpoints are exposed.
I am customising the endpoints via application.properties file as per my use case.
application.properties.

#To expose all endpoints
management.endpoints.web.exposure.include=*

#To expose only selected endpoints
management.endpoints.jmx.exposure.include=health,info,env,beans

I want to understand, where exactly does Spring Boot create actual endpoints for /health and /info and how does it expose them over HTTP?

A: Thanks @Puce and @MarkBramnik for helping me out with the reference docs & code repository.
I wanted to understand how the endpoints were working and how they were exposed over HTTP, so that I could create custom endpoints to leverage in my application.
One of the great features of Spring Framework is that it's very easy to extend, and I was able to achieve the same.
To create a custom actuator endpoints, Use @Endpoint annotation on a class. Then leverage @ReadOperation / @WriteOperation / @DeleteOperation annotations on the methods to expose them as actuator endpoint bean as needed.
Reference Doc : Implementing Custom Endpoints
Reference Example :
@Endpoint(id="custom_endpoint")
@Component
public class MyCustomEndpoint {

    @ReadOperation
    @Bean
    public String greet() {
        return "Hello from custom endpoint";
    }
}

The endpoint id i.e custom_endpoint needs to be configured in the list of actuator endpoints to be enabled.
application.properties :
management.endpoints.web.exposure.include=health,info,custom_endpoint

After a restart, endpoint works like a charm!


text:
Q: Vertical spacing in index with idxlayout I have some trouble formatting my index with idxlayout.
As my MWE demonstrates, the vertical spacing between the entries is inconsistent. For example the vertical spacing among the entries of entrygroup A is larger than in D. The group themselves are spaced varaibly: D and E are spaced ok, A and B are not.
My real example (which is too large) is even worse. Sometimes the middle column is filled only with 6 lines spread erratically over the column whereas the other lines are filled with more entries.
How do I prevent the rubber spacing and use a fixed one?
Optionally: How do I set a penalty which prevents only the group heading from apperaring alone?
Your help is greatly appreciated!

% !TEX encoding = UTF-8 Unicode
% !TeX TXS-program:compile = txs:///pdflatex/[--shell-escape]

\documentclass[%
    12pt,a4paper,twoside,parskip=never,ngerman,headings=normal,]{scrbook}

\setlength\parindent{0pt}
\usepackage[english,main=ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{filecontents}
\begin{filecontents*}{xindystyle.xdy}
(define-location-class "Roman-page-numbers"  ("roman-numbers-uppercase"))
(define-location-class "arabic-page-numbers" ("arabic-numbers")
                    :min-range-length 1)

(define-attributes (("definition" "usage" "default" "hyperpage")))

(define-crossref-class "see")
(markup-crossref-list :class "see" :open "\seelinkk{" :sep "; " :close "}{}")

(define-crossref-class "seealso")
(markup-crossref-layer-list :sep ", ")
(markup-crossref-list :class "seealso" :open "\seealsolinkk{" :sep "; " :close "}{}")

(markup-range :class "arabic-page-numbers" :close "\,f."  :length 1 :ignore-end)
(markup-range :class "arabic-page-numbers" :close "\,ff." :length 2 :ignore-end)
(markup-range :class "arabic-page-numbers" :sep "--")

(define-crossref-class "hyperindexformat")
(markup-crossref-list :class "hyperindexformat" :open
       "\hyperindexformat{" :sep "; " :close "}{}")

(define-location-class-order (
            "Roman-page-numbers"
              "arabic-page-numbers"
              "see"
              "seealso"))

(sort-rule "-" "")

(markup-index :open  "~n\begin{theindex}
                    \providecommand*\lettergroupDefault[1]{}
                    \providecommand*\lettergroup[1]{%
                        \par\textbf{#1}\par
                        \nopagebreak
                    }
                    \newcommand{\targetindexentryy}[1]{\hypertarget{index:#1}{#1}}
                    \newcommand{\seelinkk}[1]{\see{\hyperlink{index:#1}{#1}}}
                    \newcommand{\seealsolinkk}[1]{\seealso{\hyperlink{index:#1}{#1}}}
                ~n"
    :close "~n~n\end{theindex}~n"
    :tree)

(markup-indexentry :open "~n \item "            :depth 0)
(markup-indexentry :open "~n    \subitem "      :depth 1)
(markup-indexentry :open "~n      \subsubitem " :depth 2)

(markup-locref-list :sep ", ")
(markup-locclass-list :open "\dotfill " :close "" :sep ", ")
(markup-locref :open "\hyperpage{" :close "}")
(markup-locref :open "\hyperpage{" :close "}" :attr "hyperpage")

(markup-keyword-list :open "\targetindexentryy{" :close "}" )
\end(filecontents)
\usepackage[
]{imakeidx}
    \makeindex[
        columns=3,
        name=person,
        title={Personenverzeichnis},
        program=truexindy,
        options=-M texindy -M page-ranges -M xindystyle -C utf8 -L german-duden,
        ]
\usepackage[%
    totoc=true,
    columns=3,
    itemlayout=abshang,
    unbalanced=true,
    indentunit=0.5cm,
]{idxlayout} % Index layout

\newcommand{\person}[2][]{%
    \ifstrempty{#1}{%
        \textsc{#2\index[person]{#2}}}{%
        \textsc{#2\index[person]{#1}}{}}%
}

\usepackage[%
    hyperindex=false,hypertexnames=true,plainpages=false,breaklinks=true,hidelinks,pageanchor=true,
]{hyperref}

\begin{document}
\raggedbottom
    \person{A} \person{Aa} \person{Ab} \person{Ae} \person{B} \person{ba} \person{bbA} \person{bcA} \person{dc} \person{d} \person{ce} \person{dee} \person{fe} \person{ff} \person{few} \person{z} \person{h} \person{eh} \person{erhy} \person{jr} \person{rty} \person{gh} \person{bn} \person{sh} \person{shs} \person{ert} \person{ll} \person{l} \person{fyu} \person{io} \person{erys} \person{syh} \person{yy} \person{ty} \person{jl} \person{ui} \person{pi} \person{oi} \person{m} \person{mn} \person{ji} \person{fh} \person{nn} \person{A} \person{A} \person{A} \person{ttt} \person{tA} \person{eyA} \person{hA} \person{mA} \person{gnA} \person{nnA} \person{nnnA} \person{Amm} \person{Adf} \person{Azds} \person{ssdfA} \person{sdfA} \person{dfghA} \person{dhA} \person{asdas} \person{dsf} \person{d} \person{asdaA} \person{dddaA} \person{asdas} \person{a} \person{asdA} \person{A2} \person{A23} \person{A1} \person{A123} \person{eAf32} \person{A323} \person{A123} \person{A12f3} \person{A123f} \person{A12f3} \person{eA112}\person{etA} \person{ewewA} \person{eeeweA} \person{werA} \person{erwA} \person{eeeA} \person{Asaa} \person{nnnA}  \person{iA} \person{iiA} \person{iiiA} \person{iuA} \person{yiA} \person{dd2A} \person{adA} \person{guA224}

    \backmatter
    \idxlayout{columns=3}
    \printindex[person]
\end{document}

Using a real world example the problem becomes more apparent. I've marked the erratic spaces in red:

A: The idxlayout you are using set \parskip to a value with some stretch. You could patch \theindex with (after loading idxlayout)
\usepackage{xpatch}

\makeatletter
\xpatchcmd\theindex{\z@ \@plus 0.3\p@}{0pt}{}{\fail}
\makeatother

The general space between the letter groups are set by \indexspace which you could redefine if you want. But the large spaces between the letter groups are triggered by the hypertargets which seems to suppress pagebreaks. Insert a \leavevmode in the definition of \targetindexentryy:
 \newcommand{\targetindexentryy}[1]{\leavevmode\hypertarget{index:#1}{#1}}


text:
Q: How to make divs wrap *only* at their max-width, and not because its parent container is being overflown? I have a parent container with a fixed size, and absolutely positioned child divs inside it. The position of the child divs have dynamic text content and a max-width and can move around freely, and extend outside of the parent, which is set to overflow: hidden. See the snippet at the bottom for illustration.
This works fine except for one small problem: If a child partially sticks outside the parent container to the right, the text inside of it will wrap, trying to stay inside of the parent container. I do explicitly not want this - if a child moves out of the parent, it should not change its wrapping or size because of it, it should just move out of view. The parent should simply act as a "window" of sorts through which the children are viewed.
I've tried different combinations of applying white-space: nowrap to the parent and/or children, none of which have worked for me so far. Is this just not possible?
This snippet demonstrates the problem:

/* Relevant parent and child styles */

.parent {
  position: relative;
  width: 500px;
  height: 400px;
  overflow: hidden;
}

.child {
  position: absolute;
  max-width: 250px;
}

/* Individual positioning of child elements */

#fine {
  top: 30px;
  left: 100px;
}

#wrapped {
  top: 90px;
  left: 400px;
}

#unwrapped {
  top: 330px;
  left: 170px;
  white-space: nowrap;
}

/* The rest is only styles to make the example easier on the eye */

body {
  background-color: hsl(0, 0%, 90%);
  margin: 0;
  padding: 24px;
}

.parent {
  background-color: white;
  border: 2px solid grey;
}

.child {
  padding: 12px;
  background: yellowgreen;
}

    Text should be wrapped normally with the max-width of the child, like this

    This text will be wrapped much earlier though because it is running out of the parent container

    "white-space: nowrap" only prevents *all* wrapping

A: Don't use left to position the element but consider translate instead. The left property will restrict the width of your element.

/* Relevant parent and child styles */

.parent {
  position: relative;
  width: 500px;
  height: 400px;
}

.child {
  position: absolute;
  max-width: 250px;
}

/* Individual positioning of child elements */

#fine {
  top: 30px;
  transform: translateX(100px);
}

#wrapped {
  top: 90px;
  transform: translateX(400px);
}

#unwrapped {
  top: 200px;
  left: 170px;
}
#extra {
  top: 300px;
  left: 170px;
}

/* The rest is only styles to make the example easier on the eye */

body {
  background-color: hsl(0, 0%, 90%);
  margin: 0;
  padding: 24px;
}

.parent {
  background-color: white;
  border: 2px solid grey;
}

.child {
  padding: 12px;
  background: yellowgreen;
}

    Text should be wrapped normally with the max-width of the child, like this

    This text will be wrapped much earlier though because it is running out of the parent container

    "white-space: nowrap" only prevents *all* wrapping

    short text

Or consider a big negative margin (at least equal to max-width) to negate the use of left:

/* Relevant parent and child styles */

.parent {
  position: relative;
  width: 500px;
  height: 400px;
}

.child {
  position: absolute;
  max-width: 250px;
  margin-right:-250px;
}

/* Individual positioning of child elements */

#fine {
  top: 30px;
  left:100px;
}

#wrapped {
  top: 90px;
  left: 400px;
}

#unwrapped {
  top: 200px;
  left: 170px;
}
#extra {
  top: 300px;
  left: 170px;
}

/* The rest is only styles to make the example easier on the eye */

body {
  background-color: hsl(0, 0%, 90%);
  margin: 0;
  padding: 24px;
}

.parent {
  background-color: white;
  border: 2px solid grey;
}

.child {
  padding: 12px;
  background: yellowgreen;
}

    Text should be wrapped normally with the max-width of the child, like this

    This text will be wrapped much earlier though because it is running out of the parent container

    "white-space: nowrap" only prevents *all* wrapping

    short text

To understand how both tricks work you need to refer to the specification where you can find the formula to calculate the width of your element:

The constraint that determines the used values for these elements is:
'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

You can then read the different case where some values are specified and other auto


text:
Q: how to cut an object array to get specific attributes in typescript I have an array like this
array = [
{
  id: 1,
  name: 'Apple',
  color: 'red
},
{
  id: 2,
  name: 'Orange',
  color: 'orange'
},
{
  id: 3,
  name: 'Banana',
  color:'yellow'
},
{
  id: 4,
  name: 'Malta',
  color:'orange'
}
];

and I just want to get "id" attribute from this array like this
 array = [
{
  id: 1,
},
{
  id: 2,
},
{
  id: 3,
},
{
  id: 4,
}
];

What should be the method to handle this situation.
I tried filter method , map method but it didn't work

A: Use map operator to iterate over the array like this -
array.map(res => {return {id: res.id}})

PS - or Another shortcut way as @amadan suggested in comment
array.map(({id}) => ({id}))

A: Use map on the array:

var initial = [{
    id: 1,
    name: 'Apple',
    color: 'red'
  },
  {
    id: 2,
    name: 'Orange',
    color: 'orange'
  },
  {
    id: 3,
    name: 'Banana',
    color: 'yellow'
  },
  {
    id: 4,
    name: 'Malta',
    color: 'orange'
  }
];

var finalArray = initial.map(item => {
  return {
    id: item.id
  }
});

console.log(finalArray);

A: You can use map to get the id property,
 arrayData.map(a => {
  return {
    id: a.id
  }
 })

var arrayData = [{
    id: 1,
    name: 'Apple',
    color: 'red'
  },
  {
    id: 2,
    name: 'Orange',
    color: 'orange'
  },
  {
    id: 3,
    name: 'Banana',
    color: 'yellow'
  },
  {
    id: 4,
    name: 'Malta',
    color: 'orange'
  }
];

const newarray = arrayData.map(a => {
  return {
    id: a.id
  }
})
console.log(newarray);


text:
Q: Multithreading, Tracing Garbage Collectors and Native C APIs Many programming languages native C APIs with tracing garbage collectors have a root and unroot functions to protect temporary values from being collected.
In a multithreaded environment, if a native function unroot all of its objects and then return one of said objects, what happens if between unrooting and returning, another thread allocates causing a collection? Will the value that I'm trying to return be collected as well?
I've looked at Ruby, Julia, Janet and V8 for solutions, but I couldn't find nothing obvious regarding this. Is it safe to just to just use pairs of root and unroot functions in a multithreaded environment?
I'm trying to build a simple stop the world mark and sweep garbage collector for my scripting language,
and I'm trying to make everything that needs to be thread safe, safe. Currently my garbage collector has two singly linked lists, one for allocated objects and the other for roots, protected by a global mutex.

A: If all objects are removed from the set of root objects, then all object can be garbage collected (possibly from another thread). This include the returned object. This is true even if it is for a very short period of time, unless one ensures that the garbage collector does not pass by during that portion of time (this is hard to ensure in a parallel context).
There are many different implementation of tracing garbage collectors. AFAIK, many store the returned object in a stack (possibly the system stack or a manual one) tracked by the garbage collector. This stack typically hold (a part of) the root object set. The stack can be automatically managed or manually. There are callee/caller conventions so that returned objects can never unsafely be "unrooted" and collected. There is also possibly another data structure for global object references. This is the case of the GC of R for example which is pretty simple (see here). Java use a similar concept based on thread-local stack frames (with an automatic storage duration) for local references. Global references are implicitly created but explicitly manually deleted inside low-level codes (eg. JNI). You can find more information here.


text:
Q: Ubuntu Kylin Artful Aardvark (17.10) Hello my name is Tyler T. I'm wondering, when will "Ubuntu Kylin 17.10" be officially available to download? Please reply whenever you can, please and thank you.

A: It is already available. Please visit official site - http://www.ubuntukylin.com.


text:
Q: Private Properties in Controllers As my controllers become more complicated, i have properties that should not be mofified. What is the best practice for creating private properties on controllers which can only be accessed by mutators?
A contrived example:
.controller('ProjectManagerController', function($scope){
    $scope.formVisible = false;

    $scope.showForm = function(){
        $scope.formVisible = true;
    }
 })

Is it ok to indicate $scope.formVisible is private by convention (a la pythons leading underscore)?
Should i use some sort of closure?

A: I like this approach.
.controller('ProjectManagerController', function($scope){
var formVisible = false;

$scope.showForm = function(value){
    if(value === undefined){
        return formVisible;
    }
    formVisible = value;
}
})

Usage:
.showForm() //get value
.showForm(true/false); //to update value


text:
Q: Directed cyclic graph traversal to find a path of certain length I have a directed graph that looks sort of like
this. All edges are unidirectional, cycles exist, and some nodes have no children.
I want a traversal algorithm where the goal is to find a path of length n nodes anywhere in the graph. The algorithm should do the following:

*

*Starting node is randomly chosen, it traverses its children, and visited nodes is kept somewhere to return a path at the end

*Same nodes can be visited again

*If it reaches a node with no children, it traverses the most recent node with unexplored children. If all possible paths from the starting node are traversed, try starting from other nodes. (I think this method ensures all possible paths are explored)

*Traversal stops when number of nodes visited reaches n and path is returned

*If no path of length n is found, it returns "No valid path"

I'm not sure if an algorithm for this already exists. Most search algorithms seem to deal with finding shortest path, MSTs, and can't visit same nodes. Pathfinding algorithms like A* and Dijkstra's seem overcomplicated for my needs. I might need a modified version of one of these, but not sure exactly which one to use.

A: It sounds like you just want a simple recursive algorithm.  Here's some basic pseudocode.
find_path(node, n):
   if n == 1:
       yield [node]
       return
   for each child of node n:
       for each path in find_path(child, n - 1):
           yield [node] + path

A: I would use Node's and Edge's every node keeps track track of all the connecting edges. And the Edges cheap track of the length of the length of the edge and the node it connects to.
class Node(object):
    def __init__(self, identity):
        self.id = identity
        self.edges = set()

    def __str__(self):
        return f"node <id: {self.id}, edges: {self.edges}"
    __repr__=__str__

class Edge(object):
    def __init__(self, _from, to, length=1):
        _from.edges.add(self)
        self.to = to
        self.len = length

    def __str__(self):
        return f"edge <length: {self.len}, to: {self.to}"

    def __repr__(self):
        return f"edge <length: {self.len}>"

than find a path of certain length like this
def getPathOfLength(nodes, length):
    for node in nodes:
        path = subGetPathOfLength(node, length)
        if not path is None:
            return path

def subGetPathOfLength(node, length):
    if length==0:
        return []

    for edge in node.edges:
        path = subGetPathOfLength(edge.to,
                                  length-edge.len)
        if not path is None:
            return [node] + path
    return None

after creating the connectivity graph like this
nodes = []
for idx in range(8):
    nodes.append(Node(idx))

edges = []

edges.append(Edge(nodes[0], nodes[3]))
edges.append(Edge(nodes[3], nodes[4]))
edges.append(Edge(nodes[4], nodes[0]))

edges.append(Edge(nodes[7], nodes[0]))
edges.append(Edge(nodes[6], nodes[7]))
edges.append(Edge(nodes[2], nodes[6]))
edges.append(Edge(nodes[2], nodes[3]))

edges.append(Edge(nodes[1], nodes[3]))
edges.append(Edge(nodes[3], nodes[5]))