text:
Q: Check if a process exists in go way If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it's terminated (or killed)?
Edit:
I've just wrote a wrapper function around kill -s 0 (old-style bash process testing). This works without any problem, but I'm still happy if there is other solutions (done with go libraries) to this problem.:
func checkPid(pid int) bool {
    out, err := exec.Command("kill", "-s", "0", strconv.Itoa(pid)).CombinedOutput()
    if err != nil {
        log.Println(err)
    }

    if string(out) == "" {
        return true // pid exist
    }
    return false
}

A: On unix like systems (linux, freebsd, etc) os.FindProcess will never return an error. I don't know what happens on Windows. This means you won't know if the PID is correct until you try to use the *os.Process for something.
You can look at the code here.

A: Here is the traditional unix way to see if a process is alive - send it a signal of 0 (like you did with your bash example).
From kill(2):

   If  sig  is 0, then no signal is sent, but error checking is still per‐
   formed; this can be used to check for the existence of a process ID  or
   process group ID.

And translated into Go
package main

import (
    "fmt"
    "log"
    "os"
    "strconv"
    "syscall"
)

func main() {
    for _, p := range os.Args[1:] {
        pid, err := strconv.ParseInt(p, 10, 64)
        if err != nil {
            log.Fatal(err)
        }
        process, err := os.FindProcess(int(pid))
        if err != nil {
            fmt.Printf("Failed to find process: %s\n", err)
        } else {
            err := process.Signal(syscall.Signal(0))
            fmt.Printf("process.Signal on pid %d returned: %v\n", pid, err)
        }

    }
}

When you run it you get this, showing that process 123 is dead, process 1 is alive but not owned by you and process 12606 is alive and owned by you.
$ ./kill 1 $$ 123
process.Signal on pid 1 returned: operation not permitted
process.Signal on pid 12606 returned: <nil>
process.Signal on pid 123 returned: no such process

A: You can also just use syscall.Kill. It amounts to less code.
killErr := syscall.Kill(pid, syscall.Signal(0))
procExists := killErr == nil

A: If a previously known pid is not found in the system (not sure of go functions), it means process has definitely terminated and has been joined (on Unix, with wait call) too.
But other way around is not necessarily true. Just because a pid exists, it does not quarantee it is same process as before. There are only 65535 valid pids in standard Linux for example, and they can get re-used when there is a wrap-around. However, if you check reasonably often, for practical purposes you don't need to care about this (as long as pid of wrong new process being found is not a security vulnerability or something else critical, which somebody might try to trigger intentionally for malicious purposes).
Related links (and Related questions on their right columns):

*

*https://superuser.com/questions/135007/how-are-pids-generated

*https://unix.stackexchange.com/questions/26677/will-process-ids-be-recycled-what-if-you-reach-the-maximal-id

A: All the answers so far are incomplete implementations.  See https://github.com/shirou/gopsutil/blob/c141152a7b8f59b63e060fa8450f5cd5e7196dfb/process/process_posix.go#L73 for a more complete implementation (copied inline)
    func PidExists(pid int32) (bool, error) {
        if pid <= 0 {
            return false, fmt.Errorf("invalid pid %v", pid)
        }
        proc, err := os.FindProcess(int(pid))
        if err != nil {
            return false, err
        }
        err = proc.Signal(syscall.Signal(0))
        if err == nil {
            return true, nil
        }
        if err.Error() == "os: process already finished" {
            return false, nil
        }
        errno, ok := err.(syscall.Errno)
        if !ok {
            return false, err
        }
        switch errno {
        case syscall.ESRCH:
            return false, nil
        case syscall.EPERM:
            return true, nil
        }
        return false, err
    }

A: Here is one way of how to check if a process exists/running with Golang on Windows.
We execute the command:
TASKLIST /V /NH /FI "PID eq 23232"

Which can return either:
INFO: No tasks are running which match the specified criteria.

Or if found:
Image Name                     PID Session Name        Session#    Mem Usage Status          User Name                                              CPU Time Window Title
========================= ======== ================ =========== ============ =============== ================================================== ============ ========================================================================
chrome.exe                   23232 Console                    1     42,472 K Unknown         THANOS\MARVEL                                       0:00:00 N/A

Here is a function that takes advantage of this information.
func isProcessRunning(pid int) bool {
    cmd := exec.Command("TASKLIST", "/FI", fmt.Sprintf("PID eq %d", pid))
    result, err := cmd.Output()
    if err != nil {
        return false
    }
    return !bytes.Contains(result, []byte("No tasks are running"))
}

The best thing about this is you can find the process by other parameters too:
ImageName   eq, ne                  Image Name String
PID         eq, ne, gt, lt, ge, le  Process ID, A Positive integer.
Session     eq, ne, gt, lt, ge, le  Any valid session number.
SessionName eq, ne                  String
Status      eq, ne                  RUNNING | NOT RESPONDING | UNKNOWN
CPUTime     eq, ne, gt, lt, ge, le  Time hh:mm:ss
MemUsage    eq, ne, gt, lt, ge, le  Memory usage in KB, specify a valid integer.
Username    eq, ne                  User name ([Domain\]User).
Services    eq, ne                  Service Name String
Windowtitle eq, ne                  Window Title String
Modules     eq, ne                  DLL Name String

A: On Windows checking the result of os.FindProcess() seems to be enough to check if process is running.
func isProcessRunning(pid int) bool {
    _, err = os.FindProcess(pid)
    if err != nil {
        return false
    }
    if runtime.GOOS == "windows" {
        return true
    }
    return false // further checking for other systems then Windows is not supported here
}

A: After searching for a few hours, the correct answer to know if a process is running on Windows is the following:
func CheckProcessLife(pid int){
    cmd,_ := exec.Command("tasklist","/FI", "PID eq " + strconv.Itoa(pid)).Output()
    output := string(cmd[:])
    splitOutp := strings.Split(output, " ")
    if !(splitOutp[1] == "no") {
        time.Sleep(500 * time.Millisecond)
        fmt.Println("Process is running...")
        CheckProcessLife(pid)
    }else{
        fmt.Println("Process is no longer running.")
    }
}

You can check if the process is running with his PID or directly with his name, only change this line:
cmd,_ := exec.Command("tasklist","/FI", "IMAGENAME eq yourprocessname.exe").Output()


text:
Q: Does Node.js support parallelism? I've been looking more into the difference between concurrency and parallelism. I came upon a talk on YouTube given by Rob Pike speaking about the differences between concurrency and parallelism. His talk was in the context of the Google Go language. From what I understand, concurrency is the design of being able to handle multiple things, but parallelism is the physical execution of multiple things at the same time.
From what I also understand, Node.js runs as a single thread process. So although Node supports concurrency with the way it implements callbacks and such, does it have the ability to handle parallel execution of tasks? Can it be set up to run multiple threads on separate processors?

A: Node can support "Parallelism" via either the Cluster or child_process modules packaged in the Nodejs Core API. Both of these modules create additional processes and not additional threads.
Threads are created and managed, sometimes in a pool, "under-the-hood" by libuv which node implements and uses to perform the asynchronous operations such as reading from a file. You cannot explicitly create a thread from your executing Javascript. You can read more about libuv at the below resources

*

*libuv API Docs

*libuv book

*Threading in libuv (part of libuv book)

Also, this is great question on Threads and Pooling which has a lot of detail.
Cluster is used distribute the workload of a Server across multiple cores and still have them share a port. However, Cluster uses child_process.fork() under the hood and communicates via inter-process communication. You can read more about Cluster in the Nodejs Core API Docs.
child_process offers a couple different ways to parallelize work via exec(), spawn() or fork(). The parent process can communicate with the child process using inter-process communication via pipes.
Basically, Node wants you to leverage the event loop and leave thread management to libuv. This is why it is so easy to build code that would typically require locking and thread safety measures. If you must do work that requires heavy lifting, or a significant amount of blocking (synchronous) work, then you could use child_process to offload that work. If you need to scale out a web app across cores then use Cluster.

A: If I'm not mistaken, you're looking for something along the lines of multithreading and/or computing multiple things at the same time.
Multiple executions at once
SIMD is beginning to find its way into Browsers, with Node implementations not far behind. Take a look at node-simd or MDN SIMD (browsers).
SIMD is still experimental, and only works on supported CPUs at the moment (obviously, since not all CPUs have this functionality). It executes multiple things at once, an example comparing normal JS to SIMD JS would be:
// Normal addition, 4 actions are executed.
var a = [1, 2, 3, 4];
var b = [5, 6, 7, 8];
var c = [];

c[0] = a[0] + b[0];
c[1] = a[1] + b[1];
c[2] = a[2] + b[2];
c[3] = a[3] + b[3];
c; // Array[6, 8, 10, 12]

// SIMD execution - all additions are processed simultaenously through the CPU
var a = SIMD.Float32x4(1, 2, 3, 4);
var b = SIMD.Float32x4(5, 6, 7, 8);
var c = SIMD.Float32x4.add(a,b);
c; // Float32x4[6, 8, 10, 12]

Multithreading
In regards to multithreading, webworkers have existed in the Browser environment for a while now. This has been ported to Node fully according to the HTML spec as seen in this repository.
Here's a good explanation as to why webworkers were even ported to Node in the first place, since you can already run child processes in other threads and on other CPUs with the child_process module. node-webworker is a great module since each process is run within its on context, and in its own node process, so it is truly multithreading with node.
So, to run different processes on different CPUs, you would either adopt node-webworker or use child_process to spawn other threads to do separate actions at the same time with different CPU cores. node-webworker can listen for events using the familiar postMessage API, and child_process will communicate through stdin / stdout / stderr.
Hope that answers your question :)

A: Running multiple threads in separate processors on one host machine can be achieved by leveraging the native Node os and cluster modules. Following is a simple contrived example
const cluster = require('cluster');
const os = require('os');

((port) => {
    if (cluster.isMaster) {
        // fork the process
        os.cpus().forEach((cpu) => {
            cluster.fork();
        });

    } else {
        // if we're not in the master thread, start the HTTP server
        http.createServer((req, res) => {
            // Handle request
        }).listen(port, () => {
            console.log(`The server is listening on port ${port}`);
        });
    }
})(3000)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Concat many video: wrong out FPS & audio Pitch I have a process like this:

*

*i have N input video; I cut & transcode them using the following code:
ffmpeg.exe -c:v h264_cuvid -resize 1920x1080 -noaccurate_seek -ss 00:00:04.000 -to 00:00:44.240 -i "input_N.MP4" -v error  -filter:v fps=fps=25 -c:v h264_nvenc -preset medium -profile high -b:v 8000k -bufsize 8000k -maxrate 10000k -qmin 0 -g 250 -bf 2 -i_qfactor 0.75 -b_qfactor 1.1 "output_N.mp4"

*I create a videoArrayFile.txt in the following format:
file 'myFilePath\output_N.mp4'
file 'myFilePath\output_N.mp4'
file 'myFilePath\output_N.mp4'
...

*I concat the files in videoArrayFile.txt using the following command:
ffmpeg.exe -f concat -v error -safe 0 -i "myPath\videoArrayFile.txt" -filter:a "volume=1" -c:v copy -c:a aac "myPath\outputConcat.mp4"
This is the ffmpeg log when I run the above command:
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (50) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input
[aac @ 000001fa4273e000] Number of scalefactor bands in group (51) exceeds limit (49).
Error while decoding stream #0:1: Invalid data found when processing input

The procedure is working but, using some input files, I'm facing some FPS & audio pitch problem:
the output file is variable frame rate and the audio speed is wrong.
Ffprobe on the the "output_N" produce the following:
file 'D:\SharedExp_SSD\Outs\0.51.8\2020-10-30_11-45_LancioTandem-30FPS_1604054749\video_HL\tmp\introEncoded.mp4'

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'introEncoded.mp4':   Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.42.100   Duration: 00:00:04.60, start: 0.000000, bitrate: 2707 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 2575 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : Core Media Video
    Stream #0:1(ita): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 131 kb/s (default)
    Metadata:
      handler_name    : Core Media Audio
       file 'D:\SharedExp_SSD\Outs\0.51.8\2020-10-30_11-45_LancioTandem-30FPS_1604054749\video_HL\tmp\Exp_1488_clip_0.mp4'

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Exp_1488_clip_0.mp4':   Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.42.100   Duration: 00:00:40.27, start: 0.000000, bitrate: 8142 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 8221 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 12:52:03:24
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 32000 Hz, mono, fltp, 69 kb/s (default)
    Metadata:
      handler_name    :  GoPro AAC
    Stream #0:2(eng): Data: none (tmcd / 0x64636D74)
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 12:52:03:24 Unsupported codec with id 0 for input stream 2

file 'D:\SharedExp_SSD\Outs\0.51.8\2020-10-30_11-45_LancioTandem-30FPS_1604054749\video_HL\tmp\Exp_1488_clip_1.mp4'

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Exp_1488_clip_1.mp4':   Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.42.100   Duration: 00:00:05.03, start: 0.000000, bitrate: 8460 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 10239 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 13:22:01:01
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 32000 Hz, mono, fltp, 69 kb/s (default)
    Metadata:
      handler_name    :  GoPro AAC
    Stream #0:2(eng): Data: none (tmcd / 0x64636D74), 0 kb/s
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 13:22:01:01 Unsupported codec with id 0 for input stream 2

file 'D:\SharedExp_SSD\Outs\0.51.8\2020-10-30_11-45_LancioTandem-30FPS_1604054749\video_HL\tmp\Exp_1488_clip_2.mp4'

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Exp_1488_clip_2.mp4':   Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.42.100   Duration: 00:00:08.03, start: 0.000000, bitrate: 8926 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 9303 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 13:22:01:01
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 32000 Hz, mono, fltp, 69 kb/s (default)
    Metadata:
      handler_name    :  GoPro AAC
    Stream #0:2(eng): Data: none (tmcd / 0x64636D74), 0 kb/s
    Metadata:
      handler_name    :  GoPro AVC
      timecode        : 13:22:01:01 Unsupported codec with id 0 for input stream 2

While ffprobe on outputConcat.mp4 produce
outputConcat.mp4:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'outputConcat.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.42.100
  Duration: 00:00:57.54, start: 0.000000, bitrate: 7900 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 7820 kb/s, 24.28 fps, 25 tbr, 15360 tbn, 50 tbc (default)
    Metadata:
      handler_name    : Core Media Video
    Stream #0:1(ita): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 111 kb/s (default)
    Metadata:
      handler_name    : Core Media Audio

The timebase in outputConcat.mp4 change from the others: is this behaviour related to the different different sample rate of the audio streams( the only difference I can notice in input files)?
As you can see from point 1) the input FPS is set to 25 and all the input video have exactly the same codec and resolution.
How can I concatenate the videos so that the output one have the same FPS of the inputs and no audio pitch problem? Can it be the timebase problem?
Thx, Marco

A: I found a partial solution to the problem:
the problem was that the audio sample rate of the inputs is not coherent and I was not managing this during the first conversion.
Adding -ar 32000 to all the initial conversion string I solved the audio pitch problem. I'm still tring to understand why the fps change


text:
Q: How to extract month from date time picker in a string format I want month in a string format from date time picker in vb. Net. Please help me

A: The exact answer will depend on your local date format. In the following code, in the UK, longDate will be assigned "06 May 2018". The next line splits longDate into an array of 3 elements using the space character as the split point :-
element 0 = "06"
element 1 = "May"
element 2 = "2018"
and returns element 1 to monthString
    Dim longDate As String = DateTimePicker1.Value.ToLongDateString
    Dim monthString As String = longDate.Split(" "c)(1)

If your month is the first element, then you will need to change (1) to (0)


text:
Q: Scala memory use I've been trying out Scala in a pet project recently and noticed that the following code snippet was eating up memory (I call this method a lot):
private[this] def isConsistent(startLang2: Int, lengthLang2: Int,
    startLang1: Int, lengthLang1: Int,
    lang2FinalAlignments: ArrayBuffer[ArrayBuffer[Int]]): Boolean = {

    (startLang2 to (startLang2 + lengthLang2)) foreach {
      i =>
        val valueSeq = lang2FinalAlignments(i)
        if (valueSeq.size == 0 || valueSeq.exists { value => value < startLang1 || value > (startLang1 + lengthLang1) })
          false
    }
    true
}

When I changed the 'false' to 'return false' the situation seems to have resolved itself:
private[this] def isConsistent(startLang2: Int, lengthLang2: Int,
    startLang1: Int, lengthLang1: Int,
    lang2FinalAlignments: ArrayBuffer[ArrayBuffer[Int]]): Boolean = {

    (startLang2 to (startLang2 + lengthLang2)) foreach {
      i =>
        val valueSeq = lang2FinalAlignments(i)
        if (valueSeq.size == 0 || valueSeq.exists { value => value < startLang1 || value > (startLang1 + lengthLang1) })
          return false
    }
    true
}

When I think about it snippet #2 makes sense with regards to how I expect/want the method to work. Could someone please explain to me what the first snippet is doing?

A: Let's see what foreach does:
def foreach[U](f: Elem => U): Unit

So it runs f on every element of the collection and discards its result - it doesn't care about the return type of f.
In your case when you call
... foreach {
  i => {
    ...
    if (...)
      false
  }
true

the body of the function return false if the condition is satisfied and Unit otherwise. Their common supertype is Any, so the function passed to foreach is of type Int => Any. It's result is discarded and you traverse the whole collection. (Try giving an explicit type such as foreach[Any] or foreach[Boolean].)
In the second snippet the situation is very different:
... foreach {
  i => {
    ...
    if (...)
      return false
  }
true

Here foreach traverses the range only until the condition is satisfied and then return escapes the foreach execution and makes the main function exit.


text:
Q: Redirect to login page onajax request I am using jsp, jquery, and struts. I have a problem understanding the redirect to login page for ajax request. I tried to see request on browser on XHR tab and it gives me 302 status code in header. I am not able to comprehend how do I redirect.
My approach

*

*The application has a function which checks if the user is signed in or not and has function to redirect to login url.

*Else do some other processing.

How do I come back to same page after login? Is there any way? Also for redirecting on server side I am using Response.redirect(). When I debug the code and response comes on client side the error function in ajax function is executed not success function. Can someone explain how to catch response from server?
function buttonpress(param1,param2){
  $.ajax({
    type:"GET",
    data:{
      X:param1,
      Y:param2,
    },
    url:"/application",
    success:function(){
      alert("success message");
    }
    error:function(){
      alert("error message")
    }
  });
}

A: success:function(){
    //current page URL
    var ref = document.URL;
    location.href = '/login/?ref=' + ref;
}

You can use variable "ref" to come back the same page

A: Note that when you use ajax to call server and receive a redirect response. The browser will not redirect, but will automatically retrieve the content at redirected location and your success function will end up being passed the content from the redirected location. For ajax request, you should not respond with a redirect if the user is not signed in, you should return a 401 Unauthorized instead and the browser will handle this in your callback. Here are the steps:

*

*Check if the user is signed in or not

*If the user is not signed in, check the headers for X-Requested-With: XMLHttpRequest (this indicates an ajax request)

*If found and not authenticated, respond with 401 (for ajax requests) else respond with 302 (for not ajax requests).

And your ajax callback could check if there is a 401 response, set location.href to your login page. You could have something like returnUrl query string parameter in your login page, if there is you could set it to your current page to redirect to this page after login. Sample code on client side:
$.ajax({
    type:"GET",
    data:{
      X:param1,
      Y:param2,
    },
    url:"/application",
    success:function()
    {
      alert("success message");
    },
    error:function()
    {
      alert("error message")
    },
    statusCode: {
     401: function() {
      location.href = '/login/?returnUrl=' + document.URL;
    }
 });

A:
        jQuery(document).ready(function () {
        jQuery('#dialog').show(false);
        jQuery('#MsgDel').show(false);
        jQuery("#dialog").dialog({
            bgiframe: true, autoOpen: false, height: 250, modal: true, width: 250,
            buttons: {
                "Delete": function () {

                    var txtValue = $("#<%=txtid.ClientID %>").val();
                    var txtrea = $("#<%=txtreason.ClientID %>").val();
                    if (txtrea == '') {

                    }
                    else {
                        Delete(txtValue, txtrea);
                        $(this).dialog("close");
                    }
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            },
            close: function () {
                $('#txtreason').val("");

            }
        });
    });

</script>

A: <script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery('#MsgDel').show(false);
        jQuery("#MsgDel").dialog({
            bgiframe: true, autoOpen: false, height: 150, modal: true, width: 300,
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                      --To Reload Page Again After Success Function
                    window.location.href = "DispatchInstructionList.aspx";
                }
            },
            close: function () {
            }
        });
    });

</script>


text:
Q: Using SAMtools and storing outputs for a large number of files I've got 500+ files that I need to change from .bam to .sam so am trying to use samtools. I've done some looking on here and found this answer (Changing file paths outputs within a loop, in a shell script) and modified it to fit my work:
input_files="/scratch/spectre/h/homeTCGA_Data/*.bam"
output_files="/scratch/spectre/h/home/Data_Sam"
for i in $input_files
do
tmp=$(i/scratch/spectre/h/home/Data_Sam)
samtools view -h $i > $(tmp/.bam/.sam)
done

I'm a complete novice at this so I'm assuming that I've made an obvious mistake somewhere. The error I'm getting with this is that the directory 'Data_Sam' doesn't exist along with 'ambiguous redirect'. I've checked and it definitely does exist in scratch. I've also tried this in case I'm way over complicating things:
 for i in `ls ${/scratch/spectre/h/home/Data/}/*.bam`
 do
 samtools view -h <$i >${/scratch/spectre/h/home/Data_Sam}/$i.sam
 done

For this I'm getting the error 'bad substitution' for ${/scratch/spectre/h/home/Data/}/*.bam`.
I've also tried the following and get the error 'bad substitution':
for i in "ls ${/scratch/spectre/h/home/Data/}/*.bam";
do filename "${i%%.*}";
samtools view $i ${filename}.sam;
done

Is there any way that I can loop over my 500+ files, change them from bam to sam and store them somewhere new?

A: In your first attempt, the syntax you are looking for string substitution is ${parameter/pattern/string} where parameter gets expanded and in the result the longest match of pattern gets substituted with string. Note that this syntax uses curly braces, not parentheses (see Shell Parameter Expansion in the Bash manual).
I think this is what you were trying to do:
input_files="/scratch/spectre/h/home/Data/*.bam"
for i in $input_files
do
    tmp=${i/Data/Data_Sam}                 # replace 'Data' with 'Data_Sam'
    samtools view -h $i > ${tmp/.bam/.sam} # replace '.bam' with '.sam'
done

With small changes you could easily make it more robust against file names containing spaces or containing ".bam" somewhere in the middle:
input_files="/scratch/spectre/h/home/Data/*.bam"
for i in $input_files
do
    tmp="${i/Data/Data_Sam}"
    samtools view -h "$i" > "${tmp/%.bam/.sam}"
done


text:
Q: Flink event-time session windows with max total time I was wondering if it's possible to create a WindowAssigner that is similar to:
EventTimeSessionWindows.withGap(Time.seconds(1L))

Except I don't want the window to keep growing in event-time on each element. I want the beginning of the window to be defined at the first element received (for that key), and end exactly 1 second later, no matter how many elements arrive in that second.
So it would probably look like this hypothetically:
EventTimeSessionWindows.withMax(Time.seconds(1L))

Thanks!

A: There is no built-in window for this use case.
However, you can implement this with a GlobalWindow, which collects all incoming elements, and a Trigger that registers a timer when an element is received and the window is empty, i.e., the first element or the first element after the window was purged. The window collects new elements until the timer fires. At that point, the window is evaluated and purged.


text:
Q: Issue updating state reactively in Vuex Creating a Vuejs application whereby I use Vuex for state management between the components.In Vuex store, I have an action that fetches some data from an API (which works fine) then populate it to the state (via a mutation). Next, I pass the updated state to the component using getters.
Am having a problem populating data to the state (reactive manner) from the action (via mutation). In the DOM when I log the getter am getting an empty string.
Vuex Store
const getDefaultState = () => {
    return {
        clientDeposit: ''
    }
}

//state
const state = getDefaultState();

//getters
const getters = {
    getDeposit: (state) => state.clientDeposit
}

//actions
const actions = {
    fetchClients({ commit}) {

       const clientId ="23"
       axios.post('/api/motor/fetchClients', {
         ClientId: clientId,
        })
         .then((response)=> {

          //console.log(response);  //returns data

          const deposit = response.data;
          commit('setDeposit', deposit);
        })
    }
}

//mutations
const mutations = {
    setDeposit: (state, value) => (state.clientDeposit = value)
}

export default {
    state,
    getters,
    actions,
    mutations
}

Component
<template>
  <div>
        <button onclick="fetchClients()">Fetch Clients</button>
        Deposit (Via computed property) : {{ fetchDeposit }}
        Deposit (from getter) : {{ getDeposit }}
  </div>
</template>

<script>
import { mapGetters , mapActions } from "vuex";
import axios from "axios";

export default {
  name: "",
  data() {
    return {
    }
  },
  computed: {
    ...mapGetters([
        "getDeposit"
    ]),
    fetchDeposit(){
        return this.getDeposit
    },
  },
  methods:{
    ...mapActions([
        "fetchClients"
    ])
  }
};
</script>

<style scoped>

</style>


text:
Q: Autoreload in Jetty with Gradle and Kotlin Using the Spark web framework I'd like to enable autoreload with the embedded jetty whenever I've compiled files.
Trying
  gradle run -Djetty.reload=automatic -Djetty.scanIntervalSeconds=2

does not work though. Any ideas?

A: This doesn't work, because you pass this args to gradle jvm, not to jvm which runs Jetty.
As i see you using Application Plugin so you can pass args via applicationDefaultJvmArgs property:
applicationDefaultJvmArgs = ["-Djetty.reload=automatic", "-Djetty.scanIntervalSeconds=2"]

Hope this would help.


text:
Q: What is the most computationally efficient way to flatmap a List of Lists? There is a problem on my server where it became a bottle neck due to a specific problem to solve resolving a List<List<SomeObject>> into a List<SomeObject>. The CPU of the server spiked above normal means.
DataStructure is:
Object:
List<SomeObject> childList;

Trying to make a List<Object> flatmapped to List<SomeObject> in the most computationally efficient way.
If parentList = List<Object>:
I Tried:
parentList.stream().flatMap(child -> child.getChildList().stream()).collect(Collectors.toList())

Also tried:
List<Object> all = new ArrayList<>();
parentList.forEach(child -> all.addAll(child.getChildList()))

Any other suggestions? These seem to be similar in computation but pretty high due to copying underneath the hood.

A: This may be more efficient since it eliminates creating multiple streams via flatMap. MapMulti was introduced in Java 16.  It takes the streamed argument and a consumer which puts something on the stream, in this case each list's object.
List<List<Object>> lists =  new ArrayList<>(
                List.of(List.of("1", "2", "3"),
                List.of("4", "5", "6", "7"),
                List.of("8", "9")));

List<Object> list = lists.stream().mapMulti(
         (lst, consumer) -> lst.forEach(consumer))
         .toList();

System.out.print(list);

prints
[1, 2, 3, 4, 5, 6, 7, 8, 9]

A: In java 8
List<Object> listOne = new ArrayList<>();
List<Object> listTwo = new ArrayList<>();
List<Object> listThree = new ArrayList<>();
...

Stream.of(...) concatenate many lists
List<Object> newList = Stream.of(listOne,listTwo,listThree).flatMap(Collection::stream).collect(Collectors.toList());

In Java 16+
List<Object> newList=Stream.concat(Stream.concat(listOne, listTwo), listThree).toList();

Being an ETL ("Extract Transform and Load") process, Streams processes collections of data using multiple threads of execution at each stage of processing.

A: Do we know more about which List implementation is used?
I would try to init the resulting list with the correct expected size.
This avoids unnecessary copying.
This assumes that the size of the lists can be retrieved fast.
int expectedSize = parentList.stream()
                             .mapToInt(entry -> entry.getChildList().size())
                             .sum();
List<SomeObject> result = new ArrayList<>(expectedSize);
for (var entry : parentList) {
   result.addAll(entry.getChildList());
}

A: One way to make the flat mapping more computationally efficient is to use a for loop instead of the stream API or forEach method. The for loop would iterate over the parent list, and for each element, it would add the child list to the flat list. This avoids the overhead of creating streams and using the collect method. Additionally, using an ArrayList to store the flat list instead of a LinkedList can also improve performance since it has a more efficient implementation of the addAll method.
List<SomeObject> flatList = new ArrayList<>();
for (Object o : parentList) {
flatList.addAll(o.getChildList());

Another way would be to use an iterator. Iterator is an interface for traversing a collection and it's more efficient than forEach or for loop.
List<SomeObject> flatList - new ArrayList<>();
Iterator<Object> iterator = parentList.iterator();
while(iterator.hasNext()){
Object o = iterator.next():
flatList.addAll(o.getChildList()):
}

You could also use the concat method for List, which concatenates two lists in an efficient way and results in a new list.
List<SomeObject> flatList = new ArrayList<>()
for (Object o : parentList){
flatList.concat(o.getChildList());
}

THERE ARE SERVERAL RESOURCES THAT YOU CAN USE FOR ADDITIONAL READING ON THIS TOPIC. HERE ARE A FEW THAT I WOULD RECOMMEND.
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/List.html
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/ArrayList.html
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Iterator.html
https://www.oreilly.com/library/view/java-performance-the/9781449358652/
https://www.tutorialspoint.com/java_data_structure_algorithms/index.htm


text:
Q: Share 13.10 & win 8 cpu's on home network? I have a home network that shares folders between two win 8 systems. I can not get a connection between win systems and my Ubuntu 13.10 system but the win systems connect to each other. This is a wireless network. Suggestions on what to look for?
---11/15 Tried new workgroup, I can see the win pc now but it will not connect (details below).

A: You will need to create a new workgroup in your windows machines.
http://windows.microsoft.com/en-us/windows-8/join-or-create-a-workgroup
homegroups are the default and do not work for Linux. You can create a new user and password shareing all the resources you want. You should then see your windows machines and be able to log in as the new user.
Hope this helps
Larry Keenan


text:
Q: Cannot be formatted with the default formatted mystring.rs
pub fn return_string() {
  return "Some String"
}

then in main, I want to print this string
mod mystring;
const test = config::return_string();
println!("{}", test);

the error I get is
println!("{}", test);
   |                    ^^^^ `()` cannot be formatted with the default formatted

A: I assume that your minimal reproducible example is:
pub fn return_string() {
    return "Some String"
}

fn main() {
    const test = return_string();
    println!("{}", test);
}

error: missing type for `const` item
 --> src/main.rs:6:11
  |
6 |     const test = return_string();
  |           ^^^^ help: provide a type for the constant: `test: ()`

error[E0308]: mismatched types
 --> src/main.rs:2:12
  |
1 | pub fn return_string() {
  |                        - help: try adding a return type: `-> &'static str`
2 |     return "Some String"
  |            ^^^^^^^^^^^^^ expected `()`, found `&str`

error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src/main.rs:7:20
  |
7 |     println!("{}", test);
  |                    ^^^^ `()` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `()`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

Solution
There are two errors in your code:

*

*don't use const inside of functions. Use let. let is an immutable value. let mut would be mutable. const is only used for immutable globals.

*you are missing the return type for your return_string() function

I'll assume here that the return type is &str, but it might as well have to be String. For more info search for &str vs String.
Third, as a minor annotation, avoid return as much as possible, if not required. The last line of a function is automatically the return type if you don't finish it with ;.
pub fn return_string() -> &'static str {
    "Some String"
}

fn main() {
    let test = return_string();
    println!("{}", test);
}

Some String

Explanation of the error message
The error message says that () is not printable.
() is the empty type, analogous to void in C++. As you don't annotate the return type of return_string(), Rust assumes it's (). And () cannot be printed directly, at least not with the Display formatter.
You could print it with the Debug formatter, though:
pub fn return_void() {}

fn main() {
    let test = return_void();
    println!("{:?}", test);
}

()

Note that contrary to C++, () is actually a storable type, even if it is of size 0 with no data in it. That makes things a lot easier for generics. C++ templates that need to be able to deal with void return values were a major pain factor for me in the past, as they always required a special case.


text:
Q: Best way to define tokens I'm trying to optimize my javacc parser and I have a question about defining tokens in the grammar definition.
Is it good or bad practice? Does it affect much the performance of the parser.
example:
void name() :
{
  Token name;
}
{
  name = < NAME : ( < LETTER > | < DIGIT > ){2, 7}>
  {
    System.out.println(name.image);
  }
}

A: It won't affect performance, but it will affect readability and maintainability. Keep in mind that the order of token definitions can make a difference to the meaning.  I suggest putting all token definitions up front.


text:
Q: automate the reactivation of the service httpd after the instance reboot I have automated to stop the ec2 instance using lambda function also automated for starting also. I have initially activated the httpd service in that instance. I need to know whether it is possible to automate the process to reactivate the service httpd after the restart. i have another question also after every reboot the public ip of the instance changes why?
Thanks in advance.
Subramanian L.

A: You can try this command.
chkconfig httpd on This will restart the httpd service when the instance reboots.
You can refer this link as well: https://www.liquidweb.com/kb/chkconfig-command-examples-for-red-hat-and-centos/


text:
Q: Finding last child in a hierarchy in oracle I have a table like
prnt_id   child_id
-----------------
1           2
2           4
3
5
6           7
7           8
8           9

My result should contain
prnt_id  child_id
-----------------
1          4
3
5
6          9

I am using oracle 10g.
I tried doing it with connect by but did not get expected result.

A: Use CONNECT_BY_ROOT to get the prnt_id from the root and CONNECT_BY_ISLEAF to indicate, wherever this is the leaf node. Something like that should work:
SELECT PRNT_ID,
       CHILD_ID
FROM (SELECT CONNECT_BY_ROOT PRNT_ID PRNT_ID, CHILD_ID, CONNECT_BY_ISLEAF leaf
      FROM TABLE
      CONNECT BY PRIOR CHILD_ID = PRNT_ID
      START WITH prnt_id NOT IN (SELECT CHILD_ID
                                 FROM TABLE
                                 WHERE CHILD_ID IS NOT NULL))
WHERE leaf = 1

For example, this will give you the desired result:
WITH dat AS (SELECT 1 prnt_id, 2 child_id FROM DUAL
             UNION ALL
             SELECT 2 prnt_id, 4 child_id FROM DUAL
             UNION ALL
             SELECT 3 prnt_id, NULL child_id FROM DUAL
             UNION ALL
             SELECT 5 prnt_id, NULL child_id FROM DUAL
             UNION ALL
             SELECT 6 prnt_id, 7 child_id FROM DUAL
             UNION ALL
             SELECT 7 prnt_id, 8 child_id FROM DUAL
             UNION ALL
             SELECT 8 prnt_id, 9 child_id FROM DUAL)
SELECT PRNT_ID,
       CHILD_ID
FROM (SELECT CONNECT_BY_ROOT PRNT_ID PRNT_ID, CHILD_ID, CONNECT_BY_ISLEAF leaf FROM dat
      CONNECT BY PRIOR CHILD_ID = PRNT_ID
      START WITH prnt_id NOT IN (SELECT CHILD_ID
                                 FROM dat
                                 WHERE CHILD_ID IS NOT NULL))
WHERE leaf = 1

PRNT_ID CHILD_ID
1       4
3
5
6       9


text:
Q: Is there a performance difference in JavaScript between ">" and "!="? Doing a bind for a previous link in a nav. If we're on the first position don't do the same thing for the previous link. I was doing a "!=" not equal to test, but realized it could be a ">" greater than.
Then I thought, is one faster?
if (numberToCheck != 0) {
    //doSomething();
}

vs.
if (numberToCheck > 0) {
    //doSomething();
}

A: Performance questions should be resolved via measurement, not speculation.
You can see for yourself here http://jsperf.com/inequality-vs-greater-than.  The results of this test (on my computer) vary by browser.  Some are faster with inequality.  Some are faster with less than.  You will likely find much bigger speed differences in other areas of your code.
If you want to test something slightly different than what I put in the test, just add your own test for comparison.

A: Do you mean like... absolute difference, or "meaningfully different"?
In any case, it would depend 100% on the underlying VM implementation. It might be faster to set a flag and have that flag be the first in an && (for short-circuiting), though, and have the numerical part second.
if (keepChecking && numberToCheck != 0) {
    keepChecking == false;
    // doSomething();
}

Again, VM-dependent, and I can't believe it'd matter a lot either way.

A: What about -
if (numberToCheck !== 0) {
//doSomething();
}

Actually, I doubt a human could notice the difference.  Plus, each browser js engine might yield different results.

A: I made a test page at jsperf:
http://jsperf.com/different-from
In Chrome on my MacBook Pro, they are exactly the same.


text:
Q: Any reason why this .click is not working I have this page that i have a rotate slideshow running. I have it currently changing every second for testing. The slideshow works great but stopping it it not easy for some reason. I have a link on the top that should stop it.
Stop to play the video

$('.stop').click(function(){
   $('#slideshow').cycle('stop');
});

This should stop the script but doesnt. But if you open up firebug and paste this line into the console the script stops. What gives?
   $('#slideshow').cycle('stop');

A: Just had a closer look at your code and you're emitting the javascript outside of your $(document).ready(...) handlers and before the element in the html, so you're trying to attach the event to an element that doesn't exist.
Either move your click handler inside a the $(document).ready(...) or put it below the link in the html.

A: It may be a timing issue, on page load I am getting this message in FireBug:
[cycle] terminating; zero elements found by selector
[cycle] terminating; too few slides: 1
[cycle] terminating; zero elements found by selector
[cycle] terminating; zero elements found by selector
[cycle] terminating; zero elements found by selector
[cycle] terminating; zero elements found by selector

However if I execute the following code after the page loads, the link works correctly.
$('.stop').click(function(){
$('#slideshow').cycle('stop');
});

A: Use the $.live() or $.delegate() methods instead - they will bind to all current and future elements that match the selector.
http://api.jquery.com/live/
http://api.jquery.com/delegate/

A: do you have more than one elements to which the class "stop" has been added in that case you might run into a problem.
if the above is the case you can try the following:
$('a.stop').click(function(){
   $('#slideshow').cycle('stop');
});

if you have more than one link with class stop then if you want to bind each one of them you should do something like this
$('a.stop').each(function(){
$(this).each("click",function(){
   $('#slideshow').cycle('stop');
});
});

if you want to bind only one of the links then just add an id property and then bind it to the element after getting the element by id.
Note: I am assuming that you are binding the elements after page load only.


text:
Q: CSS3 menu bar with rounded corners, I think I'm messing up the selectors I have a ul for a navigation bar. In my CSS, I have a hover color transition. Here's the code:
HTML:

     Home

     About

        Download

CSS:
.sideBarButton {
    font-family: Verdana;
    font-size: 14px;
    font-style: normal;
    font-weight: bold;
    font-variant: normal;
    color: #000;
    background-color: #000;
    border: 2px none #FFF;
    clear: none;
    float: left;
    height: auto;
    list-style-type: none;
    display: block;
    width: 90px;
    margin: 0px;
    padding: 0px;
    text-align: center;
    text-align-last: center;
    opacity: 1;
}

.sideBarButton a {
    background-color: #000;
    background-image: url(woodbutton.gif);
    transition: opacity .25s ease-in-out;
    -moz-transition: opacity .25s ease-in-out;
    -webkit-transition: opacity .25s ease-in-out;
    text-align: center;
    text-decoration: none;
    width: 90px;
    display: block;
    color: black;
}
.sideBarButton a:hover {
    opacity: 0.7;

(Sorry for the slightly messy code, I've been meaning to sort through it and weed out the unneeded bits.) The buttons are pictures. I had the idea to round the two first-child and last-child selectors, but I think I've messed up somehow in (layering?) the selectors, for when I assign a class to the full ul, and set up a css selector (ex: .ulClass .sideBarButton:first-child) it doesn't do anything. What am I missing, and how would I fix it?
Thanks in advance! (NOTE: Ignore the class names, this is a top navbar, not a side, no matter what they might suggest!)
Edit: just to clarify, I want to round all four corners of the navbar.

A: You can target the li instead of the class
.ulClass > li:first-child
 {
   border-bottom-left-radius: 4px;
   border-top-left-radius: 4px;
 }
.ulClass > li:last-child
 {
   border-bottom-right-radius: 4px;
   border-top-right-radius: 4px;
 }

I also removed the offending style Display:block from .sideBarButton a which was causing the rounded corners not being applied.
Probably a good idea to clean up your code and take out the unnecessary styles.
Check out this fiddle http://jsfiddle.net/aSn8C/5/


text:
Q: C - Struct has too many initializer values I have code from another site:
typedef struct {
  byte x, y;
} Point;

typedef struct {
  Point topLeft;   /* top left point of rectangle */
  Point botRight;  /* bottom right point of rectangle */
} Rectangle;

byte rectanglesOverlap(Rectangle *Rectangle1, Rectangle *Rectangle2) {
  // If one rectangle is on left side of other
  if (Rectangle1->topLeft.x > Rectangle2->botRight.x || Rectangle2->topLeft.x > Rectangle1->botRight.x)
    return 0;

  // If one rectangle is above other
  if (Rectangle1->topLeft.y < Rectangle2->botRight.y || Rectangle2->topLeft.y < Rectangle1->botRight.y)
    return 0;

  return 1;
}

I was under the impression that
Rectangle *thisR = {{x, y}, {x+width, y+height}},
        *oldR = {{x2, y2}, {x2+width2, y2+height2}};

would be OK to use.
It compiles fine, but the overlap check always returns false (meaning, it returns as if they never overlap even if they do)
So switching to Visual Studio, I got the error on the second point's brace
{{x, y}, {
         ^

saying that I have "Too many initializer values"
Why is this only an error presented in Visual Studio and not GCC, and can it explain why the overlap code never works for me? I've been looking for the answer to this question for days D:

A: OP is trying to incorrectly initialize a pointer with the following
 @kaylum
Rectangle *thisR = {{x, y}, {x+width, y+height}},
          *oldR  = {{x2, y2}, {x2+width2, y2+height2}};

With C11, if code needs to make a Rectangle * in the middle of an equation or assignment, could use a compound literal.
Rectangle *thisR = &( (Rectangle) {{x, y}, {x+width, y+height}});

Doubt if this works with Visual Studio
Else use the old-fashion way.
Rectangle tmpR = {{x, y}, {x+width, y+height}};
Rectangle *thisR = &tmpR;


text:
Q: How to update status of data in SQL table when it has expired I have a sql table. Every item has a column with the name 'expiredDate' with datetime type and a column with the name 'isExpired'.
I want to update 'isExpired'columns when ExpiryDate > Datetime.Now

A: Use update:
update t
    set isExpired = 0
    where expirydate > now();

I'm guessing you want these to be "not expired".
That said, you don't really need both columns.  You could use a view:
create view v_t as
    select t.*, coalesce(expirydate < now(), 0) as isExpired
    from t;


text:
Q: Android progressBar not showing or invisible My custom progress bar doesn't show. I animate it in my activity and also use drawable resource file for it. Here is my code.
Activity.java
  ProgressBar progressBar;

   @Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
      progressBar =  findViewById(R.id.progressBar);
    ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress",
   0, 500);
    animation.setDuration(5000); // in milliseconds
    animation.setInterpolator(new DecelerateInterpolator());
    animation.start();

activity.xml
      <ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"

    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular"
    app:layout_constraintBottom_toBottomOf="@+id/relativeLayout"
    app:layout_constraintEnd_toEndOf="@+id/relativeLayout"
    app:layout_constraintHorizontal_bias="0.475"
    app:layout_constraintStart_toStartOf="@+id/relativeLayout"
    app:layout_constraintTop_toTopOf="@+id/relativeLayout"
    app:layout_constraintVertical_bias="0.153" />

drawableResource.xml
     <?xml version="1.0" encoding="utf-8"?>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:useLevel="true"
        android:indeterminate="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/colorPrimary" />
     </shape>

want this kind of progress bar

A: Here is exactly what you are looking for.
Add this dependency in your gradle.
dependencies {
    implementation 'com.github.lzyzsd:circleprogress:1.2.1' // or compile for old versions gradle
}

in your project level build.gradle
allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

In your layout add this.
<com.github.lzyzsd.circleprogress.DonutProgress
    android:layout_marginLeft="50dp"
    android:id="@+id/donut_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    custom:donut_progress="30"/>

for more customization please see library link.


text:
Q: How do get city population by name with SPARQL I need to get city population by its name. I'm sure SPARQL could provide this, but I'm not sure how to write the query. I have a query which provides COuntry's capital and coordinates by it's name, so I assume it should be something similar. HELP!
PREFIX o: <http://dbpedia.org/ontology/>
PREFIX p: <http://dbpedia.org/property/>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?country ?population ?capital ?lat ?long WHERE {
    ?country a o:Country ; foaf:name "Germany"@en; o:capital [ geo:lat ?lat ; geo:long ?long ; p:name ?capital ]
}

A: All you need is:
PREFIX o: <http://dbpedia.org/ontology/>
PREFIX p: <http://dbpedia.org/property/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?name ?pop WHERE {
    ?country a o:Country ;
             foaf:name ?name ;
             p:populationEstimate ?pop .
}

The only tricky part was finding out the name of the property that links Countries and Populations.


text:
Q: Set dynamic custom headers in http-outbound gateway I have http outbound gateway :
<int-http:outbound-gateway encode-uri="true" http-method="POST" header-mapper="headerMappper"
        charset="UTF-8" url="{url}"  expected-response-type="java.lang.String">
        <int-http:uri-variable name="url" expression="headers.uri"/>
    </int-http:outbound-gateway>

Header Mapper bean configuration :
<bean    class="com.cc.gateway.HeaderMapper"/>

public class HeaderMapper extends org.springframework.integration.http.support.DefaultHttpHeaderMapper{

    @Bean("headerMappper")
    public HeaderMapper mapHeader()
    {
        this.setOutboundHeaderNames(getHeaderMapper());
        this.setUserDefinedHeaderPrefix("");
        return this;
    }

    public String[] getHeaderMapper()
    {
        Object [] headersArray =new HeadersConfig().getHeaders().keySet().toArray();

        return Arrays.copyOf(headersArray,headersArray.length,String[].class);

    }

}

How I can set header mapper configuration on every request ?
My configuration reads only once at deployment time.

A: The DefaultHttpHeaderMapper isn't structured for that kind of use; it is not thread-safe to change the mapped headers for each request.
You would have to override so many methods to make it thread-safe, it would probably be easier to just implement your own custom HeaderMapper<HttpHeaders>.
If you only have one message being sent at a time, though, simply override fromHeaders() and update the headers to map before calling super.fromHeaders().
That said, it's rather unusual to want to dynamically change mapped headers.


text:
Q: Using velocity/time data to create a displacement/acceleration matrix I've recently started a new job and having never used MATLAB before, I'm a little stuck. Any help would be much appreciated.
Here is the story. I have been given the velocities of fragmentation pellets at time intervals of 0.001 milliseconds. There are 28 gauges (i.e 28 sets of data) and each gauge has 20,000 readings. I have created a matrix consisting of all this data.
My objective to take that matrix and create 2 more matrices with the corresponding displacement and acceleration values of each reading. The next step is to export the time and acceleration values to an excel spreadsheet.
I am at a loss as to how to do this. I have tried to integrate and differentiate but I cant seem to get it right. Is it possible to create a function that takes the velocity data and automatically calculates acceleration/displacement? (This would make things easier as people in the future could use that same code)
Any help on how to solve any part of this problem would be much appreciated. I've only been using the software 3 days.
Many thanks.


text:
Q: MVC5 validation on email address client side I have the following property in my model:
[Required(ErrorMessage = "{0} is a required field.")]
[StringLength(150, ErrorMessage = "There are too many characters in this field.")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[MaxLength(150, ErrorMessage = "Maximum of 150 characters allowed.")]
[Display(Name = "Customer budget owner")]
public string CustomerBudgetOwner { get; set; }

All the attributes are build-in ones from microsoft.
The html in the view looks like this:

  @Html.LabelFor(m => m.HardwareRequest.CustomerBudgetOwner, htmlAttributes: new { @class = "form-label" })

      @@

    @Html.TextBoxFor(m => m.HardwareRequest.CustomerBudgetOwner, htmlAttributes: new { @class = "form-control input-sm", id = "txtCustomerBudgetOwner" })

  @Html.ValidationMessageFor(m => m.HardwareRequest.CustomerBudgetOwner, "", new { @class = "text-danger" })

If I enter just a few characters but not the @ character, the validation error message is shown.
If I enter something like aaaa@bbbbb.ccc there is not error because it looks like an email address.
If I enter something like aaaa@bbbbb no client side error is shown, but in the controller the modelstate is not valid as it should be.
Did I make a mistake in the model validation attributes?
Or is it something else beyond my control?
[EDIT]
After removing the DataType attribute, the HTML generated looks like this:
<input class="form-control input-sm valid" data-val="true" data-val-email="The Customer budget owner field is not a valid e-mail address." data-val-length="There are too many characters in this field." data-val-length-max="150" data-val-maxlength="Maximum of 150 characters allowed." data-val-maxlength-max="150" data-val-required="Customer budget owner is a required field." id="txtCustomerBudgetOwner" name="HardwareRequest.CustomerBudgetOwner" type="text" value="" aria-required="true" aria-invalid="false" aria-describedby="txtCustomerBudgetOwner-error">

This is the value in the textbox: sdfsdfsdf@sdfsdfsdf
ModelState:

A: I too have discovered this issue whereby the validation rules differ between client side and server side. It seems weird that given the data annotation is applied on the model you would expect consistent behaviour.
In saying that I am on the fence a bit - technically the client side validation is probably more accurate, but it is edge case.


text:
Q: Python regex doesn't work on string I have an HTML file that I process using lxml and BeautifulSoup (convert from HTML to text). Somehow, the ill-formed HTML below makes it into the text and I'd like to remove it. I tried matching something like "<.+>" in the text string, but it doesn't work. The string I want to remove is this:
string = """ .trb_m_b:befoe{ctent:'Hide comments'}.trb_c_so{padding-top:10px;min-height:500px}||

"""

The exact code I tried on it is:
pattern = re.compile(r'<.+>')
if (pattern.search(string)):
    print ("Found")

However, that regex doesn't match the string, although it should.
Why would that be?
Thanks.
EDIT. It looks like the problem is not with the regular expressions, but with something very bizarre. I have this string in a list, it's the last item. When I loop through it the first time, for some reason, the program never hits it. The second time, however, it does. I don't understand the reason for it.
EDIT2. It turns out the problem was that I was trying to remove elements in a loop (if they matched the regex), which is not permitted. I rewrote the code to use a list comprehension, and now it works fine.

A: I believe what you want is this:
import re
data = re.findall("\<(.*?)\>", string)

A: Your HTML is not a complete HTML tag, if you really want to match the string that you give,you can use this:

re.findall("\.trb_m_b.*?>

", string)


text:
Q: Submitting a nested form, weird behavior I have a ad banner that has a form and this is used by 3rd party site owners that grab this code and have this banner on there site.
Since some sites that use this banner have a <form> wrapping there entire site I have found that the banners form doesn't submit it rather submits the outer form.
Here is the code:
  <form onSubmit="return alert('outer form submitted')">

    <!-- only if i add this empty form it submits the inner -->
         <form></form>
    <!-- End Empty form -->

    <!-- inner form -->
      <form onSubmit="return alert('inner form submitted')" >
           <input type="submit" />
      </form>
    <!--end  inner form -->

 </form>

As you can see only if I add a empty <form>  before the inner <form> it alert (submits) the inner, otherwise it submits the outer.
What is the best way to code a banner ad for a site with a form?

A: Having a <form> inside a <form> is malformed HTML, and all bets are off how any browser/user-agent/javascript-engine/dom implementation is going to handle it. Expect wildly different or equal results between different visitors. Just don't have a <form> in a <form>. Period :)
Most likely scenario in your observed behavior: starting a <form> tag inside a form is probably 'discarded' as invalid, including any actions/events (but probably not <input>s), the first </form> closes the 'main' form.


text:
Q: How do I proceed to load a ga_instance as ".pkl" format in PyGad? I have been trying to load the PyGad trained instance in another file, in order to make some prediction. But I have been having some problems in the loading process.
After the training phase, I saved the instance like this:
The saving function:
filename = 'GNN_CPTNet' #GNN_CPTNet.pkl
ga_instance.save(filename=filename)
The loading function:
loaded_ga_instance = pygad.load(filename=filename)
loaded_ga_instance.plot_result()
But, when I tried to load the instance in a new notebook or script, I could not load the instance, especially the "GNN_CPT Net.pkl" file.

A: Edit on February 28, 2023
Starting from PyGAD 2.19, the library cloudpickle is used instead of pickle. Now, you do not have to re-define the functions. So, it is enough to call the load() function.
In the new script, you should define the the fitness function and all the callback functions you used in the original script.
For example, if you used only the on_generation (callback_generation) parameter, then the following functions should be defined:
def fitness_func(solution, solution_idx):
    ...

def callback_generation(ga_instance):
    ...

This way, the saved instance will be loaded correctly.
Anyway, it is better to post the sample codes you used to give more accurate answer.
Thanks for using PyGAD :)


text:
Q: Increase font size in JTable using hotkey With increasing age I have come to use Ctrl-+ more and more in OSX to increase font size in all kinds of windows (browser, editors etc). However, on JTable in custom apps it doesn't work of course.
How shall I add this feature to my own Swing JTables?
I would like it to increase/decrease whatever font I already have in the JTable, and also adjust column widths appropriately.
I have a general idea how to code it (add hotkey, take current Font, increase size, set new Font, invalidate), but not how to apply it to the many tables I already have. Also not how to adjust column width properly.
Shall I create a new base class or add some kind of plugin? Other ideas?

A: This solution is a bit crude but it demonstrates how to implement zooming in and out with ctrl + and ctrl -:
public class FontTable extends JPanel {

    JTable table;

    FontTable() {

        Object[][] data = {{"aaa", "122", "_____"}, {",,,,,", ",,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}};
        Object[] names = {"C1", "C2", "C3"};
        table = new JTable(data, names);

        InputMap im = table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        im.put(KeyStroke.getKeyStroke('=', InputEvent.CTRL_DOWN_MASK), "zoom in");
        im.put(KeyStroke.getKeyStroke('-', InputEvent.CTRL_DOWN_MASK), "zoom out");
        table.getActionMap().put("zoom in", new ZoomAction(true));
        table.getActionMap().put("zoom out", new ZoomAction(false));

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    class ZoomAction extends AbstractAction {

        boolean in;

        ZoomAction(boolean in) {

            this.in = in;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            Font oldFont = table.getFont();
            float size = oldFont.getSize() + (in ? +2 : -2);
            table.setFont(oldFont.deriveFont(size));

            for (int row = 0; row < table.getRowCount(); row++) {
                int rowHeight = table.getRowHeight(row);

                for (int col = 0; col < table.getColumnCount(); col++) {
                    Component comp = table.prepareRenderer(table.getCellRenderer(row, col), row, col);
                    TableColumn column = table.getColumnModel().getColumn(col);
                    int colWidth = column.getWidth();

                    rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
                    colWidth = comp.getPreferredSize().width;

                    column.setPreferredWidth(colWidth);
                }
                table.setRowHeight(row, rowHeight);
            }
        }
    }
}

I used Camick's answer as a reference. Put it in some frame to test.
As for implementing it backwards, you can either subclass JTable and add this new functionality and then replace your existing ones with the new class, or do something more tricky with nested classes in an interface and implement that interface.


text:
Q: CSS vertical middle border I'm trying to achieve the following using CSS: (focus on the middle part of the photo)

My first attempt was something like:

But then I have no way to create the colored line in the middle.
(Correct me if I'm wrong?)
I assume a better way would be to create a 50% height div, and then creating a floating div for the photos.
I use bootstrap which is not great for vertical align, so I tried using this FlexBox.
Any help would be very appreciated, thanks.

A: You can specify more than one background image (including gradients) for one element, e.g.

html, body {
    height: 100%;
    min-height: 350px;
    margin: 0;
}

body {
    background-color: #006;
    background-image:
        linear-gradient(to right, #f00, #ff0 25%, #0f0 50%, #0ff 75%, #00f),
        linear-gradient(to top, #fff, #fff),
        radial-gradient(circle closest-side at center,
        rgba(255,255,255,1) 0%, rgba(255,255,255,1) 39%,
        rgba(255,255,255,.7) 40%, rgba(255,255,255,.7) 59%,
        rgba(255,255,255,.4) 60%, rgba(255,255,255,.4) 79%,
        rgba(255,255,255,.1) 80%, rgba(255,255,255,.1) 99%,
        rgba(255,255,255,.0) 100%),
        radial-gradient(circle closest-side at center,
        rgba(255,255,255,1) 0%, rgba(255,255,255,1) 39%,
        rgba(255,255,255,.7) 40%, rgba(255,255,255,.7) 59%,
        rgba(255,255,255,.4) 60%, rgba(255,255,255,.4) 79%,
        rgba(255,255,255,.1) 80%, rgba(255,255,255,.1) 99%,
        rgba(255,255,255,.0) 100%);
    background-size: 100% 4px, 100% 50%, 62.5% auto, 62.5% auto;
    background-repeat: no-repeat;
    background-position: 50% 50%, 50% 100%, 0 50%, 100% 50%;
}


text:
Q: iPhone showing a blank infoWindow fro google maps The info window shows ok on desktop, and if I set an alert to show the content it will show the correct html code. However, on the iPhone it will just pop a blank info window (No text within it).
Here is my code:
function showPOICategory(category) {
        // Icons { ID, Image }
        // Entry { Latitude, Longitude, Name, Description, iconID);
        $.getJSON('ajax/poi.php?key=' + jQGMSettings.apiKey + '&c=' + category , function(data) {
            $.each(data.poi, function(key, val) {
                // Set current position marker
                var $image = new google.maps.MarkerImage('/images/pois/'+data.icons[val.image],
                    // This marker is 20 pixels wide by 32 pixels tall.
                    new google.maps.Size(32, 37),
                    // The origin for this image is 0,0.
                    new google.maps.Point(0,0),
                    // The anchor for this image is the base of the flagpole at 0,32.
                    new google.maps.Point(16, 37)
                );

                var $marker = new google.maps.Marker({
                    title: val.title,
                    icon: $image,
                    clickable: true,
                    draggable: false,
                    position: new google.maps.LatLng(val.latitude,  val.longitude),
                    animation: google.maps.Animation.DROP,
                    map: map
                });

                // Info Window
                if( val.info == null ) {
                    var $infowindow = new google.maps.InfoWindow({
                        content: '

' + val.title + '
Prueba
'
                    });
                } else {
                    var $infowindow = new google.maps.InfoWindow({
                        content: '

' + val.title + '
' + val.info + 'Prueba
',
                        maxWidth: 200
                    });
                }

                var $listener = google.maps.event.addListener($marker, 'click', function() {
                    if( infoWindow != null ) {
                        infoWindow.close();
                    }

                    infoWindow = $infowindow;
                    infoWindow.open(map,$marker);
                });

                // Keep track of the marker to remove it ;)
                pois.push({
                    marker: $marker,
                    listener: $listener
                });

            });

        });
    }

Anyone had this problem before? I'm going nutts to find out where the problem could be located.

A: OK I finally was able to solve my issue but not sure if it will help you.  Are you using loadHTMLString method?  if so and you aren't declaring a baseURL try declaring in the call
baseURL:[NSURL URLWithString:@"/"]


text:
Q: Deciding FK between tables which have one to one relation I'am new at DB design and sorry for this noob question.I have 2 simple tables and they have 1 to 1 relation between each other. Which table's PK should be FK in other table ? How can i decide that ?

A: In order to decide this, the question to ask is whether the relationship is a true 1 :: 1 or not.
If the relationship is a 1 :: 0..1 (i.e. every row in B will have a related row in A but the rows in A may not (all) have a row in B), then there should be a FOREIGN KEY in table B (pk) that REFERENCES A (pk). This is the most common situation and it is easy to be implemented in almost all DBMS.
If the relationship is a true 1 :: 1 (i.e. every row in table A will have a related row in table B - and vice versa), then there should be two foreign keys, one from B towards A and another from A towards B. This is also easy to declare but not so trivial to actually make it work.
The problem arises due to the chicken-and-egg problem: Which table should I first insert a row into? If we insert into A first, the foreign key (towards B) will forbid the insert. If we insert into B first, the foreign key (towards A) will forbid the insert this time.
In order to make this work, the 2 insert statements have to be in one transaction - and the foreign keys have to have been defined as DEFERRABLE - i.e. checked at the end of the transaction. So, if you work in SQL-Server (or MySQL) you simply can't do this. If you are in Postgres or Oracle or any other DBMS that has implemented deferrable constraints, this is achievable.

A:
Which table's PK should be FK in other table?

Both. For a true "1 to 1" you'll need circular foreign keys (which also implies you'll need deferred foreign keys to break "chicken-and-egg" problem when inserting new data, which not all DBMSes support).
Or just merge both tables into one table (which is recommended in most cases).

However, I suspect you are not talking about true "1 to 1", but "1 to 0 or 1", in which case the "0 or 1" endpoint should contain the foreign key, for example:
CREATE TABLE ONE (
    ID INT PRIMARY KEY
);

CREATE TABLE ZERO_OR_ONE (
    ID INT PRIMARY KEY REFERENCES ONE (ID)
);


text:
Q: Url.Action return the current link in browser I am currently on the page /Customer/Edit/13244.
When I use @Url.Action("Edit", "Customer") on the same page it returns me /Customer/Edit/13244, but I want it to return /Customer/Edit/.
Kindly tell me how to fix this issue.

A: This is a "feature" of MVC that many people find unnatural and was previously reported as a bug.
Microsoft's official response:

Ultimately if you want the most control over what gets generated for a URL there are a few options to consider:

*

*Use named routes to ensure that only the route you want will get used to generate the URL (this is often a good practice, though it won't help in this particular scenario)

*Specify all route parameters explicitly - even the values that you want to be empty. That is one way to solve this particular problem.

*Instead of using Routing to generate the URLs, you can use Razor's ~/ syntax or call Url.Content("~/someurl") to ensure that no extra (or unexpected) processing will happen to the URL you're trying to generate.

Actually, this bug only rears its ugly head when you try to re-purpose an action method name. If you use a different action method name other than Edit in the case where it is not followed by id, this problem will magically disappear.

A: You will need to use (assuming your using the default route with id = UrlParameter.Optional
@Url.Action("Edit", "Customer", new { id = "" })


text:
Q: Add sections to beamer presentation using rmarkdown and knitr I am trying to add section slides to a beamer presentation written in rmarkdown using the latex command \section{}. However, it gets inserted between a \begin{frame} & \end{frame} automatically during the conversion, which causes the compilation to fail. Is there any way to stop this happening so that the section slide can be added without having to manually edit the tex file?
Here is my rmarkdown code:
---
title: "Beamer presentation"
output: beamer_presentation
---

\section{Section one}

which gets converted to:
\title{Beamer presentation}

\begin{document}
\frame{\titlepage}

\begin{frame}
\section{Section one}
\end{frame}

\end{document}

A: Slides and section slides are both defined by markdown headings, a series of # character at the beggining of a line, the number of # indicating the hierarchical level of the title.

By default [the level that defines frames] is the highest header level in the
  hierarchy that is followed immediately by content, and not another
  header, somewhere in the document.

All title of higher level than this one will become section titles.
From the rmarkdown documentation ; See also the pandoc documentation on slideshows.
For instance :
# Section title

## Frame title

Frame content

### Subtitle inside a frame


text:
Q: Clicker Heroes Ruby chance? What is the chance of getting 1 Ruby from a Fish?
Is it a 50% chance, or the chance of not getting a Ruby is higher?
I get only coins more often than I get Rubies.

What exactly is the chance of Rubies from a fish?

A: Let's take a look at the source code, shall we?
The script responsible for (currently) the fish and the bee is heroclickerlib.managers.HiddenObjectManager.
Inside that script we find a function private function onHiderClick(param1:MouseEvent) : void.
This function is responsible for the on-click event when you click the fish.
private function onHiderClick(param1:MouseEvent) : void
  {
     var _loc4_:* = 0;
     var _loc5_:* = NaN;
     var _loc6_:* = NaN;
     this.removeHider();
     if(Rnd.boolean(0.44))
     {
        _loc4_ = 1;
        if(Rnd.boolean(0.04 + this._userData.ancients.doubleRubyPercent / 100))
        {
           _loc4_ = 2;
        }
        this._userData.addRubies(_loc4_,"hidden_object",-1);
        _loc5_ = this._battleManager.display.mouseX;
        _loc6_ = this._battleManager.display.mouseY;
        this._battleManager.uiManager.battleUI.transientEffects.showGeneralMessage(_loc5_,_loc6_,_("+%s Ruby!",_loc4_));
     }
     var _loc2_:Monster = new Monster();
     _loc2_.id = 2;
     _loc2_.level = this._userData.highestFinishedZone + 1;
     var _loc3_:Number = this._userData.getMonsterReward(_loc2_) * 10;
     _loc2_.isBoss = true;
     this._battleManager.itemDropManager.goldSplash(_loc3_,_loc2_,ServerTimeKeeper.instance.timestamp);
     HeroClickerSoundManager.instance.playSoundEffectById(36);
     this._battleManager.uiManager.battleUI.transientEffects.showGeneralMessage(580,152,"Yay!!");
  }

Two function calls are important here:

*

*if(Rnd.boolean(0.44)): this internally checks if a (uniformly distributed) random number is less than 0.44. This evaluates to a chance of nearly exact 44% of at least one ruby.

*if(Rnd.boolean(0.04 + this._userData.ancients.doubleRubyPercent / 100)): This rather lengthy call checks if a random number is less than 0.04 + the additional double ruby percentage of your ancients. This means that in 4% of all cases of getting a ruby, you get 2.
Without any ancients, the chance of getting 2 rubies is about 0.44*0.04=0.0176 => 1.76%

The average amount of rubies you get after 1000 times clicking on the fish is: 444,4 => 44,44%
440 times at least one ruby
=>  440*4%  =     11 times 2 rubies = 22    +
=>  440*96% =  422,4 times 1 ruby   = 422,4

==> 444,4 rubies => ~444,4/1000 = 44,44% chance of getting one ruby on average

The expected amount of rubies per click is then 0,4444.
I used JPEXS Free Flash Decompiler to get to the source code.

A: Adding to @GiantTree's otherwise great answer:
The expected ruby count, E(R) from a single clickable is:
E(R) = 1 * P(1) + 2 * P(2), (1)
where P(x) is the probability of getting x rubies.
Using @GiantTree's information as source, we see that double ruby is rolled for after the first one, meaning:
P(1) = 0.44 - P(2),
which means the (1) can be expressed as:
E(R) = 0.44 - P(2) + 2 * P(2) = 0.44 + P(2). (2)
Now, P(2) can be calculated by:
P(2) = 0.44 * (0.04 + DRC),
where DRC is your double ruby chance, expressed as a fraction (so 15% means DRC = 0.15).
Finally, we insert this expression into (2):
E(R) = 0.44 + 0.44(0.04 + DRC) = 0.44 * (1.04 + DRC) = 0.4576 + 0.44 * DRC.
Or for short:
E(R) = 0.4576 + 0.44 * DRC.
This means the base expected value is 0.4576 rubies per clickable.
Since the highest value of the DRC-boosting ancient is 15%, we get a maximum value (excluding relics) of:
Emax(R) = 0.4576 + 0.44 * 0.15 = 0.5236,
meaning the maximum expected ruby yield (again, excluding relics) is 0.5236.


text:
Q: Launch jar files on 64 bit java in Windows 7 I wanted to run java programs on a 64 bit Windows 7 computer and I have a 64 bit Java VM. How do I launch the jar files via command line ? It seems that 64 bit Windows 7 have a seperation between 32 bits and 64 bits programs.

A: Try giving the explicit path for each JRE you have installed:

*

*"C:\Program Files\Java\jre7\bin\java.exe" -jar yourfile.jar

*"C:\Program Files (x86)\Java\jre7\bin\java.exe" -jar yourfile.jar

*"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar yourfile.jar
Make sure you have a 64 bit JRE and a 32 bit JRE. Most java software provided still needs a 32 bit JRE (as it uses JNI or other non-portable stuff).

A: I commented, but since somebody else agrees I'll post it as an answer instead:
java -jar /path/to/jar/jarFile.jar
Take care to note what mbx said too:

In case you have more than one JRE try giving the explicit path (C:\Programs..., "C:\Programs (x86)...")

A: Some jar files have information in them allowing to be executed with the -jar switch.  If that information is not present you must use the -cp myjar.jar my.main.method.class argument to java.exe to execute  your program.
Basically, if you install Java (the easiest is through http://java.com) then you can use that to run Java programs.  It takes care of the correct version.
But it is not a problem to run a 32-bit JVM on a 64-bit system - the primary limitation is that your application is limited to a few gigabytes of memory.
So, if you can run java -version you will be fine with just using the default java command available to you.

A: Some Jar's I've had to lunch using the java.exe that is in the SysWOW64 folder.
c:\Windows\SysWOW64\java.exe -jar /path/to/jar/file.jar


text:
Q: Clickable file that adds code in terminal and runs it automatically? As my wi-fi driver is doing a bit weird I need to add codes into the terminal everytime I restart my PC to use Wi-Fi.
I get that opening the terminal and typing in two lines of code isn't that much work, but I was kind of curious if there was a way to just be able to click on a file, and that the file would paste the codes in the terminal and run them automatically.
EDIT :
The codes:
sudo modprobe mt7630e
sudo modprobe mt76xx

A: From the commands you have provided, it is clear that you are trying to load two modules into the kernel in the runtime after just starting your computer.
This can be done easily by the /etc/modules file. This file is the designated place to put the modules that will be loaded into the kernel upon system boot every time.
In your case, to load the mentioned two modules use the following command:
printf "mt7630e\nmt76xx" | sudo tee -a /etc/modules


text:
Q: perl 'last' statement and variable scope Should-be simple Perl construction is not behaving as I expect.
The @closest array holds strings of the form "NNN-NNN". I am trying to find the first array element where the initial "NNN" matches a specific value.
Since I have declared $compoundKey outside the loop, I expect it to be persistent. The loop behaves as expected, exiting when I get a match. However, after the code exits the loop, the $compoundKey variable is empty. (See log output after code. I am looking for "83". The matched element is not the last element in the array.)
    my $compoundKey;
    foreach $compoundKey (@closest)
    {
        logentry("In loop compoundKey is $compoundKey\n");
        last if ($compoundKey =~ /^$RID/);
    }
    logentry("Outside loop compoundKey is $compoundKey\n");

Log file:
    2019-02-27 18:15:26: In loop compoundKey is 90-1287
    2019-02-27 18:15:26: In loop compoundKey is 86-1223
    2019-02-27 18:15:26: In loop compoundKey is 86-1235
    2019-02-27 18:15:26: In loop compoundKey is 87-1316
    2019-02-27 18:15:26: In loop compoundKey is 89-1219
    2019-02-27 18:15:26: In loop compoundKey is 83-1224
    2019-02-27 18:15:26: Outside loop compoundKey is

I assume I can fix this by doing an explicit assignment of a temporary loop variable to $compoundKey, but I'm still somewhat mystified. Is there some bug in my code that I am not seeing? Or does the "last" statement in Perl behave in a totally different way than "break" in C or Java?
Thanks!

A: It's not the last statement, it's the foreach statement.

The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop. (Emphasis added).


text:
Q: Tab Layout not showing fragments I have a fragment named "Notification fragment" in which I want to show another fragment named "Watching Fragment" using Tab layout . When I run the app, the tab layout bar is visible but the fragments are not visible.
My Fragment inside which other fragments are to be shown (Notifications Fragment)
public class NotificationsFragment extends Fragment{

    GridView listv;
    FragmentAdapter fragmentAdapter;

    private NotificationsViewModel notificationsViewModel;
    private FragmentNotificationsBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel =
                new ViewModelProvider(this).get(NotificationsViewModel.class);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        TabLayout tabLayout = root.findViewById(R.id.tabLayout);
        ViewPager vp = root.findViewById(R.id.vp2);

        fragmentAdapter = new FragmentAdapter(getChildFragmentManager() , tabLayout.getTabCount());
        vp.setAdapter(fragmentAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    vp.setCurrentItem(tab.getPosition());

                    if(tab.getPosition() == 0 || tab.getPosition() == 1 || tab.getPosition() == 2)
                            fragmentAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {

                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });

               vp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    return  root; }

My First Fragment (Watching Fragment)
public class WatchingFragment extends Fragment {

    ArrayList<String> list = new ArrayList<String>();
    GridView gridv1;

    private WatchingViewModel mViewModel;

    public static WatchingFragment newInstance() {
        return new WatchingFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.watching_fragment, container, false);

        gridv1 = view.findViewById(R.id.gridv1);

        Intent intent = getActivity().getIntent();
        String animename = intent.getStringExtra("nameanime");
        list.add(animename);

        loadData2();
        saveData2();

        ListNewAdapter adapter = new ListNewAdapter(getContext(), R.layout.watch_list, list);
       gridv1.setAdapter(adapter);
        gridv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                list.remove(position);
                adapter.notifyDataSetChanged();
                saveData2();
                return true;
            }
        });

    return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(WatchingViewModel.class);
        // TODO: Use the ViewModel
    }

    private void saveData2() {
        SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        ed.putString("anime list", json);
        ed.apply();
    }

    private void loadData2() {
        SharedPreferences sp = getActivity().getSharedPreferences("shared preferences", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sp.getString("anime list", "");
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        list = gson.fromJson(json , type);

        if (list == null) {
            list = new ArrayList<String>();
        }

    }

}

My View pager adapter
public class FragmentAdapter extends FragmentPagerAdapter {
int tabcount;
    public FragmentAdapter(@NonNull @NotNull FragmentManager fm, int behavior) {
        super(fm, behavior);
        tabcount = behavior;
    }

    @NonNull
    @NotNull
    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0: return new WatchingFragment();
            case 1: return new CompletedFragment();
            case 2: return new WantToWatchFragment();
            default: return null;
        }
    }

    @Override
    public int getCount() {
        return 0;
    }
}

Notifications Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.notifications.NotificationsFragment">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Watching" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Completed" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Want To Watch" />
    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp2"
        android:name="com.example.animeguide.ui.notifications.NotificationsFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tabLayout" />

</androidx.constraintlayout.widget.ConstraintLayout>

Watching Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.notifications.FragmentsInsideList.watching.WatchingFragment">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="184dp"
        android:layout_height="58dp"
        android:text="hello world"
        android:textSize="34sp" />

    <GridView
        android:id="@+id/gridv1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2" />

</LinearLayout>

A: In order for the Adapter to know how many pages it has, you need to override getCount method. You did override it, but used 0 as the number of pages, thus having no pages.
In your FragmentAdapter class, try changing this:
@Override
public int getCount() {
    return 0;
}

To this:
@Override
public int getCount() {
    return tabcount;
}


text:
Q: Desperately trying to build open source tools (octave) on a Mac 10.6 Snow Leopard (involves Xcode, gcc, fink) The ironic thing is that all this used to work on my Mac, but Apple no longer supports 10.5.8, so I was forced to update to Snow Leopard, 10.6.  And everything broke (thank you Apple).
On the surface, it seems simple.  Build an open source package like octave under Snow Leopard (Mac OS X 10.6)
Apple has made this difficult, to say the least.  They no longer download XCode for older operating systems unless you are a paid developer.  My Macbook pro 2.16Ghz cannot load Lion, so that option is not available.
My old fink doesn't work because it was old.  In order to build a new one, I need Xcode 3.2, which I can't get (see above).
I downloaded a free gcc 4.2, and it works fine.
So in order to try to build octave, it's the old style gnu install:
./configure
make
make install
./configure fails because there is no fortran installed.  That's a special case because the install of gcc didn't include fortran.  So a fallback would be building a complete gcc which I have done in the past.
downloaded gcc 4.9:
gcc-4.9-20130728
inside, gcc49
gcc can't build because it needs the three subsidiary packages gmp, mpfr and mpc
I am now trying to build these, so that I can bootstrap a complete gcc build, but in the meantime, is there any simpler way to bootstrap these things?  I find it hard to understand why no binaries are available for:
fink
octave
which would solve part of my current problems.

A: You can still get XCode. You just have to be registered on Apple Developer, but you do not have to pay for the license. You then download it through the Mac App store, or you can get a link that opens it in the App store here. Finally, you have to install the command line tools from within Xcode. These can be found under the Components tab of the Download Preferences panel.
Let me know if that does not help. My iMac running 10.6 is currently in for repairs, so I am on my 10.7 laptop and cannot test all the specifics yet.