text:
Q: Golang replace previously opened file when new file is created Ok so I am monitoring certain file and doing some tail -f analysis of that file.
However another application has specific logic and it will create a new file on next date or even before.
I'm looking for a way to detect newly created file (host is linux machine) and then without restart of my current go service to start tailing newly created file.
Here is my current logic for tailing "current file":
func main(){

    currentTime := time.Now().Local()
    currentFileName := strings.Replace(currentTime.Format("2006-01-02"), "-","",2)
    newFileName := currentFileName + "_1111.log.txt"

    //using github.com/hpcloud/tail for tail
    t, err := tail.TailFile("/var/log/"+newFileName, tail.Config{Follow: true, ReOpen: true})
    for line := range t.Lines {
        //fmt.Println("Line is:", line.Text)

        //check do we have error inside new line
        if strings.Contains(strings.ToLower(line.Text), "mfc"){
            fmt.Println("MFC located: ", line.Text)

            //now send e-mail to all interested parties
            //sendEmail(line.Text)
        }

    }

    fmt.Println(err)
}

Well current file instead 20161219_1111.log can be 20161219_2222.log or similar, and on next day it starts from 20161220_1111.log etc.
Any hints are welcome.

A: have a try with github.com/fsnotify/fsnotify
a simple example:
func newFileCheck() (newFilename chan string, err error) {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        // do some log
        return
    }

    err = watcher.Watch("testDir")
    if err != nil {
        // do some log
        return
    }

    newFilename = make(chan string)

    // Process events
    go func() {
        for {
            select {
            case ev := <-watcher.Event:
                log.Println("event:", ev)
                newFilename <- ev.Name // Relative path to the file
            case err := <-watcher.Error:
                log.Println("error:", err)
            }
        }
    }()

    return
}

func yourApp() {

    newFilenameChan, err := newFileCheck()
    if err != nil {
        // err check
    }

    go func() {
        for {
            select {
            case name := <-newFilenameChan:
                // close the old one and read new file
            }
        }
    }()
}

more details, see the doc

A: Treat the following as a hacked up example.
I'm not sure about the procedure to close a tail.Tail properly, assuming you call Stop or StopAtEOF and then Cleanup.
Also the concurrency aspects need to be refined. Goroutines need to be gracefully shut down.
Imports :

*

*github.com/fsnotify/fsnotify

*github.com/hpcloud/tail

Function to check for New Files :
func newFileCheck(dir string) (newFileAlert <-chan string, err error) {

    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        return
    }

    err = watcher.Add(dir)
    if err != nil {
        return
    }

    newFileAlertSender := make(chan string)
    newFileAlert = newFileAlertSender

    go func() {
        for {
            select {
            case ev.Op := <-watcher.Events:
                log.Println("Event : ", ev)
                if ev == fsnotify.Create {
                    newFileAlertSender <- ev.Name
                }
            case err := <-watcher.Errors:
                log.Println("Watcher Error : ", err)
            }
        }
    }()

    return
}

Function to Tail a file :
func tailFile(dir, newFileName string, cfg tail.Config, stop <-chan struct{}) {

    t, err := tail.TailFile(dir+newFileName, cfg)
    if err != nil {
        log.Fatalln("TailFile failed - ", err)
    }

    for line := range t.Lines {

        if strings.Contains(strings.ToLower(line.Text), "mfc") {
            fmt.Println("MFC located: ", line.Text)
            //sendEmail(line.Text)
        }

        select {
        case <-stop:
            t.StopAtEOF()
        default:
        }

    }

    t.Cleanup()
}

Main :
func main() {

    dir := "/var/log/"

    currentTime := time.Now().Local()
    currentFileName := currentTime.Format("20060102")
    newFileName := currentFileName + "_1111.log.txt"

    newFileAlert, err := newFileCheck(dir)
    if err != nil {
        log.Fatalln("File watching failed - ", err)
    }

    stop := make(chan struct{})

    cfg := tail.Config{Follow: true, ReOpen: true}

    go tailFile(dir, newFileName, cfg, stop)

    for fileName := range newFileAlert {
        stop <- struct{}{}
        go tailFile(dir, fileName, cfg, stop)
    }
}


text:
Q: How fast a quantum state updates in a quantum experiment when the experimental setup itself changes. Are there known experiments on this? Consider the following Sagnac interferometer setup:

where $B$ is a beam splitter which can be raised and lowered with an adjustable frequency $f$, $D$ is a detector which does not click when $B$ is up and clicks when $B$ is down. $S$ is an electron beam source which fires single electrons with some classical velocity $v << c$
I am trying to model the hypothesis on whether there is a finite speed that the quantum state updates as the experiment setup changes due to raising and lowering $B$. If there is a finite speed $u$, then a delay between the appearing and disappearing of the clicks registered and the raising/lowering of $B$ should be observed
Let $\lvert ⟳\rangle$ and $\lvert ⟲\rangle$ be the clockwise and anticlockwise route of the electron travelled respectively. When $B$ is down, we have $\lvert ⟲\rangle$ arriving the detector which produces a click. When $B$ is up, we have instead $\lvert ⟲\rangle + \lvert ⟳\rangle$ arriving at $D$ which does not produce a click. Thus when $B$ is send to oscillate at a frequency $f$, we have the following state in the system:
$$\frac{1}{f}(\lvert ⟲\rangle + \lvert ⟳\rangle) + \lvert ⟲\rangle$$
which after normalisation, we have:
$$\sqrt{\frac{f+1}{f+2}}\lvert ⟲\rangle + \sqrt{\frac{1}{f+2}}\lvert ⟳\rangle$$
Thus as $f \to \infty$, contributions from $\lvert ⟳\rangle$ vanishes and $D$ will be always clicking. Likewise when $f \to 0$, we have equal contributions from $\lvert ⟳\rangle$ and $\lvert ⟲\rangle$ thus $D$ will not click. For all intermediate values of $f$, we end up with a scenario where $D$ clicks $\frac{f+1}{f+2}$ of the time and does not click $\frac{1}{f+2}$ of the time.

*

*How does the deterministic oscillation of $B$ lead to a probabilistic outcome on whether $D$ will click, is it due to the Heisenberg uncertainty principle that relates the status of $D$ clicking with the oscillation frequency?

*How can I incorporate $v$ into my state description?

*Are there known literature examples that investigate this phenomenon?

A: Your treatment of the state of the electrons is incorrect and does not make sense. It is not clear what your expression for the "state of the system" is supposed to be, but it is not the expression for the state of any object involved in this experiment.
I will use $\lvert r\rangle$ for an electron that was not deflected by the beam splitter and $\lvert l\rangle$ for an electron that was deflected, corresponding to your "clockwise" and "counterclockwise" motions, respectively.
There are three options for an electron emitted from the source:

*

*The electron passes through the beam splitter, its state is then $\frac{1}{\sqrt{2}}(\lvert l\rangle+ \lvert r\rangle)$.

*The electron does not pass through the beam splitter, its state is them $\lvert r\rangle$.

*The electron passes through the location of the beam splitter while it is being raised/lowered. It is unclear what its state after that is, since we don't really have an obvious model of what's happening in that case. This case only occurs if $f$ is so large that $v$ does not suffice for the electronic wave packet to pass the location of the beam splitter without it moving significantly. If you wish to analyze what one would expect in such an experiment, you need an entirely different approach.
"The electron" here stands equivalently for the decently localized wave packet wavefunction that a typical electron source will emit. Each individual electron is in one of these three states (although the third state hides a plethora of complicated possible states), and this state can deterministically be determined from the time of emission and its velocity, there's no randomness to it.
There is no such thing as a "state of the system", just the states of the individual electrons emitted, and you seem to expect electrons that have long passed through the beam splitter to somehow react to the splitter being lowered. This is not the case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: scala foreach and map initializers Just seen an interesting possibility to initialize code blocks in Scala for high order functions such as foreach or map:
(1 to 3) map {
  val t = 5
  i => i * 5
}

(1 to 3) foreach {
  val line = Console.readLine
  i => println(line)
}

Is this some documented feature or should I avoid such constructs? I could imagine, the "initialization" block comes into the constructor and the closure itself becomes an apply() method?
Thanks Pat for the original Question (http://extrabright.com/blog/2010/07/10/scala-question-regarding-readline)

A: While the features used are not uncommon, I'll admit is is a fairly odd combination of features.  The basic trick is that any block in Scala is an expression, with type the same as the last expression in the block.   If that last expression is a function, this means that the block has functional type, and thus can be used as an argument to "map" or "foreach" .  What happens in these cases is that when "map" or "foreach" is called, the block is evaluated.  The block evaluates to a function ( i=> i*5 in the first case ), and that function is then mapped over the range.
One possible use of this construct is for the block to define mutable variables, and the resulting function mutate the variables each time it is called.   The variables will be initialized once, closed over by the function, and their values updated every time the function is called.
For example, here's a somewhat surprising way of calculating the first 6 factorial numbers
(1 to 6) map {
      var total = 1
      i => {total *= i;total}
    }

(BTW, sorry for using factorial as an example.  It was either that or fibonacci. Functional
Progamming Guild rules.  You gotta problem with that, take it up with the boys down at the hall.)
A less imperative reason to have a block return a function is to define helper functions earlier in the block.  For instance, if your second example were instead
(1 to 3) foreach {
  def line = Console.readLine
  i => println(line)
}

The result would be that three lines were read and echoed once each, while your example had the line read once and echoed three times.

A: First, the comment of the original blog "Scala Question Regarding readLine" post mention

The "line" is a value and cannot be executed, it is assigned only once from the result of the "Console.readLine" method execution.
  It is used less than three times in your closure.
  But if you define it as a method, it will be executed three times:

(1 to 3) foreach {
  def line = Console.readLine
  i => println(line)
}

The blog Scala for Java Refugees Part 6: Getting Over Java has an interesting section on Higher Order function, including:

Scala provides still more flexibility in the syntax for these higher-order function things.
  In the iterate invocation, we're creating an entire anonymous method just to make another call to the println(String) method.
  Considering println(String) is itself a method which takes a String and returns Unit, one would think we could compress this down a bit.  As it turns out, we can:

iterate(a, println)

By omitting the parentheses and just specifying the method name, we're telling the Scala compiler that we want to use println as a functional value, passing it to the iterate method.
Thus instead of creating a new method just to handle a single set of calls, we pass in an old method which already does what we want.
  This is a pattern commonly seen in C and C++. In fact, the syntax for passing a function as a functional value is precisely the same. Seems that some things never change…


text:
Q: Filtering jqGrid datetime columns using date picker just on date I currently have an issue where I have datetime columns in a grid that are formatted to only display the date portion of the field. So the raw data looks like "2015-04-15T15:31:49.357" and the grid column looks like "4/15/2015".
I am using a datepicker to support column filtering and would like to be able to use the "eq" operator to filter using "equals" but just on the date portion. Currently I do not get any matches because the time is getting in the way.
Is it possible to get around this? I know I can manipulate the raw data to strip off the time portion of the date, but I would prefer to keep that information in the raw data since I also support exporting to excel and the time might be needed.
My current options for the column are:
          formatter = "date";
          formatoptions = {srcformat: "Y-m-d", newformat: "n/j/Y"};

I have tried various options but so far have not had any luck.
I am also using the free-jqgrid fork.

A: I introduced custom filtering feature in free jqGrid to allow easy implements the scenarios like youth. The answer provide an example of such implementation.
In your case one can define new Date only "equal"compare operation under the short name "deq" for example and the compare operation Date only "not equal" under the short name dne. The code of customSortOperations option could be the following:
customSortOperations: {
    deq: {
        operand: "==",
        text: "Date only \"equal\"",
        filter: function (options) {
            var p = this.p, iCol = p.iColByName[options.cmName], cm = p.colModel[iCol],
                newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
                        cm.formatoptions.newformat :
                        $(this).jqGrid("getGridRes", "formatter.date.newformat"),
                srcformat = cm.formatoptions != null && cm.formatoptions.srcformat ?
                        cm.formatoptions.srcformat :
                        $(this).jqGrid("getGridRes", "formatter.date.srcformat"),
                fieldData = $.jgrid.parseDate.call(this, srcformat, options.item[options.cmName]),
                searchValue = $.jgrid.parseDate.call(this, newformat, options.searchValue);
            return fieldData.getFullYear() === searchValue.getFullYear() &&
                fieldData.getMonth() === searchValue.getMonth() &&
                fieldData.getDate() === searchValue.getDate();
        }
    },
    dne: {
        operand: "!=",
        text: "Date only \"not equal\"",
        filter: function (options) {
            var p = this.p, iCol = p.iColByName[options.cmName], cm = p.colModel[iCol],
                newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
                        cm.formatoptions.newformat :
                        $(this).jqGrid("getGridRes", "formatter.date.newformat"),
                srcformat = cm.formatoptions != null && cm.formatoptions.srcformat ?
                        cm.formatoptions.srcformat :
                        $(this).jqGrid("getGridRes", "formatter.date.srcformat"),
                fieldData = $.jgrid.parseDate.call(this, srcformat, options.item[options.cmName]),
                searchValue = $.jgrid.parseDate.call(this, newformat, options.searchValue);
            return fieldData.getFullYear() !== searchValue.getFullYear() ||
                fieldData.getMonth() !== searchValue.getMonth() ||
                fieldData.getDate() !== searchValue.getDate();
        }
    }
}

To be able to use new "deq" and "dne" operation you should include there in sopt of searchoptions of the column with the date.
The demo uses the above code. The input data contains 3 dates: "2015-04-15T15:31:49.357", "2015-04-15T21:15:40.123", "2015-04-15":
var mydata = [
        { id: "10",  invdate: "2015-04-15T15:31:49.357", name: "test1",... },
        { id: "20",  invdate: "2015-04-15T21:15:40.123", name: "test2",... },
        { id: "30",  invdate: "2015-04-15", name: "test3", ...},
        ...
    ]

The filtering by 15-Apr-2015 display all the three rows:

Another demo uses practically the same code, but displays the date in full date/time format. Nevertheless the filtering works. Be carefully, that I use the latest free jqGrid sources from GitHub in the demo. It's really needed because I made some small changes in the code of parseDate to make the demo working.

A: Response from OlegKi on github:  https://github.com/free-jqgrid/jqGrid/issues/50
I introduced custom filtering feature in free jqGrid to allow easy implements the scenarios like youth. The answer provide an example of such implementation.
In your case one can define new Date only \"equal\"compare operation under the short name "deq" for example and the compare operation Date only "not equal" under the short name dne. The code of customSortOperations option could be the following:
customSortOperations: {
deq: {
    operand: "==",
    text: "Date only \"equal\"",
    filter: function (options) {
        var p = this.p, iCol = p.iColByName[options.cmName], cm = p.colModel[iCol],
            newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
                    cm.formatoptions.newformat :
                    $(this).jqGrid("getGridRes", "formatter.date.newformat"),
            srcformat = cm.formatoptions != null && cm.formatoptions.srcformat ?
                    cm.formatoptions.srcformat :
                    $(this).jqGrid("getGridRes", "formatter.date.srcformat"),
            fieldData = $.jgrid.parseDate.call(this, srcformat, options.item[options.cmName]),
            searchValue = $.jgrid.parseDate.call(this, newformat, options.searchValue);
        return fieldData.getFullYear() === searchValue.getFullYear() &&
            fieldData.getMonth() === searchValue.getMonth() &&
            fieldData.getDate() === searchValue.getDate();
    }
},
dne: {
    operand: "!=",
    text: "Date only \"not equal\"",
    filter: function (options) {
        var p = this.p, iCol = p.iColByName[options.cmName], cm = p.colModel[iCol],
            newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
                    cm.formatoptions.newformat :
                    $(this).jqGrid("getGridRes", "formatter.date.newformat"),
            srcformat = cm.formatoptions != null && cm.formatoptions.srcformat ?
                    cm.formatoptions.srcformat :
                    $(this).jqGrid("getGridRes", "formatter.date.srcformat"),
            fieldData = $.jgrid.parseDate.call(this, srcformat, options.item[options.cmName]),
            searchValue = $.jgrid.parseDate.call(this, newformat, options.searchValue);
        return fieldData.getFullYear() !== searchValue.getFullYear() ||
            fieldData.getMonth() !== searchValue.getMonth() ||
            fieldData.getDate() !== searchValue.getDate();
    }
}

}
To be able to use new "deq" and "dne" operation you should include there in sopt of searchoptions of the column with the date.
The demo uses the above code. The input data contains 3 dates: "2015-04-15T15:31:49.357", "2015-04-15T21:15:40.123", "2015-04-15". The filtering by 15-Apr-2015 display all the three rows.
Another demo uses practically the same code, but displays the date in full date/time format. Nevertheless the filtering works. Be carefully, that I use the latest free jqGrid sources from GitHub in the demo. It's really needed because I made some small changes in the code of parseDate to make the demo working.


text:
Q: CollectionView cells Confused I am busy with a speech app with a soundboard when you tap on a CollectionView Cell then iPhone will speak the text. I have a little bug in my app and I don't know what the reason is.
I have built a CollectionView with images as backgroundViews. It works  but when I go to an other view ,for example to the Paint view, and I will go back then the cells will confuse.
Can anybody tell me what goes wrong and how I solve it?
Thanks!

This is my code:
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    loadData()

    let itemSize = UIScreen.main.bounds.width/2 - 5
    let itemHeight = itemSize / 2
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets.init(top: 3, left: 3, bottom: 3, right: 3)
    layout.itemSize = CGSize(width: itemSize, height: itemHeight)

    layout.minimumInteritemSpacing = 3
    layout.minimumLineSpacing = 3

    soundboard.collectionViewLayout = layout

    navigationItem.rightBarButtonItem = editButtonItem

    if(traitCollection.forceTouchCapability == .available){
        registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: collectionView)
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    loadData()
}

func loadData() {
    let soundRequest:NSFetchRequest<Soundboard> = Soundboard.fetchRequest()

    do {
        soundBoardData = try managedObjectContext.fetch(soundRequest)
        self.soundboard.reloadData()
    } catch {
        print("Error")
    }
}

// MARK: - Collection View
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return soundBoardData.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> soundboardCellVC {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! soundboardCellVC

    let soundItem = soundBoardData[indexPath.row]

    if let getCellPhoto = soundItem.photo as Data? {

        cell.title.text = "";

        let cellPhoto = UIImage(data: getCellPhoto)

        let cellPhotoFrame = UIImageView(image:cellPhoto)

        cellPhotoFrame.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
        cellPhotoFrame.contentMode = UIView.ContentMode.scaleAspectFill

        cell.backgroundView = UIView()
        cell.backgroundView!.addSubview(cellPhotoFrame)
    }
    else
    {
        cell.title.text = soundItem.title;

        cell.backgroundColor = UIColor(red: CGFloat(soundItem.colorRed), green: CGFloat(soundItem.colorGreen), blue: CGFloat(soundItem.colorBlue), alpha: 1)

        let fontAwesomeIcon = FAType(rawValue: Helper.FANames.index(of: soundItem.icon!)!)

        cell.icon.setFAIconWithName(icon: fontAwesomeIcon!, textColor: UIColor.white)
    }

    cell.layer.cornerRadius = 10
    cell.layer.masksToBounds = true

    cell.delegate = self as SoundboardCellDelegate

    return cell
}

A: Cells are re-used, which means that you are adding new image views to cells that have existing image views.
You should create a single UIImageView that is in your soundboardCellVC class and simply put the image into that, or set the image to nil as required.
A couple of other style points:
By convention, classes should start with an uppercase letter and it is a cell subclass, not a View Controller subclass, so it should be something like SoundboardCell not soundboardCellVC
Finally, your cellForItemAt signature should match the protocol declaration and be declared as returning a UICollectionViewCell, not your specific cell subclass:
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

A: A good practice when working with cells is to clear any properties that you don't want to persist when the cell gets reused.
https://developer.apple.com/documentation/uikit/uicollectionreusableview/1620141-prepareforreuse
For example in your cells class you can do:
override func prepareForReuse() {
    super.prepareForReuse()
    self.title.text = nil
}

This keeps your cellForItem method cleaner, and you know for sure that the above actions will have been carried out before you reuse it.


text:
Q: Slackware 14.2 - Turn on the auditd daemon I want to turn on / enable the auditd daemon to record system events in Slackware 14.2. I could not see the daemon auditd, when I run the code below:
ls /etc/rc*.d | grep "auditd"

It means it was not existing. How will I enable auditd in Slackware? I know how to start, stop and restart services but if it is not existing , how will I make that service up and running?

A: The distribution does not provide auditd, but one can find the build script SlackBuild. (The URLs will change in the future.) Create a working directory and acquire the required files.
mkdir /usr/local/src/audit && cd /usr/local/src/audit
wget http://people.redhat.com/sgrubb/audit/audit-2.3.6.tar.gz
wget https://slackbuilds.org/slackbuilds/14.2/system/audit.tar.gz

Unpack the Build script, and move the source code into the Build directory.
tar xf audit.tar.gz && rm audit.tar.gz
cd /usr/local/src/audit/audit
mv /usr/local/src/audit/audit-2.3.6.tar.gz /usr/local/src/audit/audit/

It's important to read notes associated with the Build.
less README
less README.SLACKWARE

Execute the Build script.
/usr/local/src/audit/audit/audit.SlackBuild

After the software has been compiled successfully, the script installs all of the binaries, libraries, and configuration files required for the software to execute inside of a package file. Use installpkg.
installpkg /tmp/audit-2.3.6-x86_64_SBo.tgz

Optionally remove the source, temporary, and package files.
rm -rf /usr/local/src/audit/ /tmp/SBo/ /tmp/audit*

The audit subsystem is not enabled in Slackware kernels, so one must also rebuild the kernel with support for the audit subsystem in order to use auditd as intended.


text:
Q: Cancel xargs loop command without exit loop i have two example of function in my bash script and BTW i do work most of time on zsh in case that would make a deference in my issue.
first
i declare the following function in the first of script
cancel() {
        echo -e "\nCancelling command."
}

then i execute functions as below example.
fun1
my_fun_xargs(){
    trap cancel SIGINT
    xargs -n1 -P 5 -I {} sh -c "command {}" < test.txt
}

fun2
my_fun_for(){
    trap cancel SIGINT
    for url in $(cat test.txt);
        do
        command $url ;
    done
}

so this script contains a lot of functions which should run one after another.
so every funcion contains list of command and most of it is loop either using for or xargs to speed the process.
MY ISSUE is sometimes command inside function for some reason hang or i need to escape it for now so i put command trap cancel SIGINT to till the shell cancel the command not the loop itself and this is working probably in FOR LOOP.
The Q is why that is not working in xargs and it exit the whole command.
is there any special argument in xargs to accept keyboard interpreter ctrl c as cancel the current command in loop not the while xargs loop command.
Thanks

A: There's a lot of detail missing from the question, so I'm speculating.
When you write:
my_fun_xargs(){
    trap cancel SIGINT
    xargs -n1 -P 5 -I {} sh -c "command {}" < test.txt
}

any SIGINTs that are received will not be acted on by the shell until after xargs terminates.  If the commands running by xargs do not terminate gracefully (or quickly), that may take some time.  You might be able to mitigate the issue with xargs ... & wait, which will cause the shell to react more quickly to the SIGINT.  But this won't address the underlying issue, which seems to be that the processes invoked by xargs are not terminating quickly in response to the signal.


text:
Q: Elasticsearch - get child documents of (get parent documents which has hit in child documents) This is my first post on stackoverflow!
I'm new to elasticsearch and I'm trying build search query for my complex scenario.
Here is index and data setup.
I have created index using below template.
PUT /files
{
    "settings" : {
        "number_of_shards" : 1,
        "number_of_replicas" : 0
    },
    "mappings" : {
      "properties" : {
        "docid": { "type": "long" },
        "parentdocid": { "type": "long" },
        "name": {"type":"text"},
        "info": {"type":"text"}
      }
    }
}

Inserted below data
POST /files/_bulk
{"index":{"_id":1}}
{ "docid" : 1, "parentdocid": 0, "name": "apple", "info": "file 1" }
{"index":{"_id":2}}
{ "docid" : 2, "parentdocid": 0, "name": "microsoft", "info": "file 2" }
{"index":{"_id":3}}
{ "docid" : 3, "parentdocid": 2, "name": "minit", "info": "child 1 of file 2" }
{"index":{"_id":4}}
{ "docid" : 4, "parentdocid": 2, "name": "oribi", "info": "child 2 of file 2" }
{"index":{"_id":5}}
{ "docid" : 5, "parentdocid": 1, "name": "primephonic", "info": "child 1 of file 1" }

Here is scenario
I want to build query that can get all child documents which have same parent with any one or more child document has query hit.
So if I search for "minit" term in index then I want result as below
    "hits" : [
      {
        "_index" : "files",
        "_id" : "3",
        "_score" : 0.5897495,
        "_source" : {
          "docid" : 3,
          "parentdocid" : 2,
          "name" : "minit",
          "info" : "child 1 of file 2"
        }
      },
      {
        "_index" : "files",
        "_id" : "4",
        "_score" : 0.5897495,
        "_source" : {
          "docid" : 4,
          "parentdocid" : 2,
          "name" : "oribi",
          "info" : "child 2 of file 2"
        }
      }
    ]

because minit is child of microsoft, and I want to include all child documents of microsoft.
so on if I search for "minit or primephonic" then it would produce above result plus below
      {
        "_index" : "files",
        "_id" : "5",
        "_score" : 0.47733158,
        "_source" : {
          "docid" : 5,
          "parentdocid" : 1,
          "name" : "primephonic",
          "info" : "child 1 of file 1"
        }
      }

Thanks,
Adi

A: After some brainstorming, I'm able to achieve this with help of parent/child relation.
Index and data setup
PUT /files
{
    "settings" : {
        "number_of_shards" : 1,
        "number_of_replicas" : 0
    },
    "mappings" : {
      "properties" : {
        "docid": { "type": "long" },
        "parentdocid": { "type": "long" },
        "name": {"type":"text"},
        "info": {"type":"text"},
        "parent_relations":{
          "type": "join",
          "relations": {
            "parentdocid": "docid"
          }
        }
      }
    }
}
POST /files/_bulk
{"index":{"_id":1}}
{ "parentdocid" : 0, "parent_relations":{"name":"parentdocid"} }
PUT /files/_bulk?routing=1
{"index":{"_id":2}}
{ "docid" : 1, "name": "apple", "info": "file 1", "parent_relations":{"name":"docid","parent":1} }
{"index":{"_id":3}}
{ "docid" : 2, "name": "microsoft", "info": "file 2", "parent_relations":{"name":"docid","parent":1} }
POST /files/_bulk
{"index":{"_id":4}}
{ "parentdocid" : 1, "parent_relations":{"name":"parentdocid"} }
{"index":{"_id":5}}
{ "parentdocid" : 2, "parent_relations":{"name":"parentdocid"} }
PUT /files/_bulk?routing=4
{"index":{"_id":6}}
{ "docid" : 3, "name": "primephonic", "info": "child 1 of file 1", "parent_relations":{"name":"docid","parent":4} }
PUT /files/_bulk?routing=5
{"index":{"_id":7}}
{ "docid" : 4, "name": "minit", "info": "child 1 of file 2", "parent_relations":{"name":"docid","parent":5} }
{"index":{"_id":8}}
{ "docid" : 5, "name": "oribi", "info": "child 2 of file 2", "parent_relations":{"name":"docid","parent":5} }

search query
GET /files/_search
{
  "query": {
    "has_parent": {
      "parent_type": "parentdocid",
      "query": {
        "has_child": {
          "type": "docid",
          "query": {
            "match": {
              "name": "minit"
            }
          }
        }
      }
    }
  }
}

result
      {
        "_index" : "files",
        "_id" : "7",
        "_score" : 1.0,
        "_routing" : "5",
        "_source" : {
          "docid" : 4,
          "name" : "minit",
          "info" : "child 1 of file 2",
          "parent_relations" : {
            "name" : "docid",
            "parent" : 5
          }
        }
      },
      {
        "_index" : "files",
        "_id" : "8",
        "_score" : 1.0,
        "_routing" : "5",
        "_source" : {
          "docid" : 5,
          "name" : "oribi",
          "info" : "child 2 of file 2",
          "parent_relations" : {
            "name" : "docid",
            "parent" : 5
          }
        }
      }

above query satisfy my need.
Please share your thoughts if there is scope of improvement or any other better way.
Thank You


text:
Q: google maps v3: check if geojson feature exists on the map I am looking to find a way of checking if a geometry feature (from big geojson object) is already added to the map (it has already contains other geojson object with lots of features) in google maps v3 (javascript). I've searched everywhere and the only solutions I have found does not work just coming up with the following error:

InvalidValueError: not a Geometry or LatLng or LatLngLiteral object

I also searched by the error, but I didn't find the answer that works for me, because two test geojson object are almost the same and it is ok when I try to add the to the map without any check.
I created a pen here http://codepen.io/hackzilla/pen/qqYjzB
Here is the code:
// add first pool of data
GoogleMap.data.addGeoJson(jsonGeoData_1);

// add second pool of data
jsonGeoData_2.features.map(function(feature, index) {
  // if the feature is on the map
  if(!GoogleMap.data.contains(feature)){
    GoogleMap.data.add(feature);
  }
  else console.log('feature' + index + 'already exist');
})


text:
Q: Can GCC cross-compile for AIX? I'm trying to build GCC as a cross-compiler for AIX; the host and the build platforms are Linux x86_64, the target is powerpc-aix5.2.0.  I've managed to cross-compile Binutils 2.20.1 and GCC 4.4.7 with native AIX 6.1 headers (from /usr/include) and libs (only /usr/lib/{crt0.o,crt0_64.o,libc.a,libc_r.a,libpthreads.a}).  Then gcc correctly cross-builds simple C code (such as "Hello, world!") into stand-alone executables but it refuses to cross-build shared objects:

collect2: init function found in object < path to cross-compiled libgcc_s.a >

I tried using newer versions of Binutils up to 2.26 with the same result.
Then I found the following comment:

Binutils was updated to support AIX 4.3.3, but has not been maintained, improved, or updated for AIX 5.  It can do simple things, but does not fully support more advanced features.  For instance, some aspects of shared object creation are not complete.

So I tried re-building the above toolchain with target=powerpc-aix4.3.0 (the only difference this time was that I configured GCC with --disable-multilib to avoid the error "Unrecognized opcode: `fmsub'").  I tried both Binutils 2.20.1 and Binutils 2.26 but I still got the error init function found in object libgcc_s.a.
Now I wonder if there is a version of AIX for which cross-compilation, esp. of shared objects, is supported by GCC and Binutils.

A: The answer to your question is "no".  As the comment says, the GCC version of the linker (ld) does not really work for AIX.  All of the open source code that I compile on AIX I use GCC but I use the native ld command.


text:
Q: Cycles in mapping Domain models to DTOs can you tell me what is the best practice to mapping dto to domain and back for that object with has cycles? For example I have these 2 objects:
User object:
public class User {
   private int id;
   private String firstname;
   private String lastname;
   private List<Order> orders;
   // ... some other properties and getters and setters
}

and Order object:
public class Order {
   private int id;
   private User owner;
}

How should I mapping these domain models to DTOs? Here is example of my mapping function:
public UserDTO userToDto(User user) {
   UserDTO dto = new UserDTO();

   dto.setIs(user.getId());
   dto.setFirstname(user.getFirsname());
   dto.setLastname(user.getLastname());

   List<OrderDTO> ordersDto = new List<OrderDTO>();

   for (Order order : user.getOrders()) {
      OrderDTO orderDto = new OrderDTO();
      orderDto.setId(order.getId());
      orderDto.setUser(...) // what I should I set here?

      ordersDto.add(orderDto);
   }

   dto.setOrders(ordersDto);

   return dto;
}

I have problem with orderDto.setUser(...) function. Can you show my what is the best practice? When I start mapping properties of User step by step, I end with mapping Orders, which I actually mapping, and creates cycle. Thanks for answers.

A: First of all I assume you need the relation on the client side, too. Otherwise you wouldn't have a problem with the cycle anyways.
Further I assume you have both a UserDTO and OrderDTO, where the OrderDTO has UserDTO as member (and UserDTO a list of OrderDTOs).
Imho you simply have to set
orderDTO.setUser(dto); // where dto is the UserDTO created initially.

Now you get a cycle, which you need to handle when sending the DTO to the client (e.g. using Rest). On the JPA side you likely have something like @OneToOne (in Order) and @OneToMany (in User) annotations.
I'd recommend jackson for JSON processing. If you do so you can use
// in UserDTO
@JsonManagedReference
private List<Orders> orders;

// in OrdersDTO
@JsonBackReference
private UserDTO owner;

I hope this helps!


text:
Q: How can I alias 'gvim filename' to 'gvim filename &' I want gvim to always open in a separate window and return the command prompt immediately.  In other words I want
gvim filename

to be the same as
gvim filename &

it seems like I should be able to do this with an alias.  Is there a special wildcard character for aliases?  Something like:
alias gvim="gvim <wildcard> &"

Where "wildcard" would be replaced by whatever text comes after gvim on the command line.
I also tried:
function gvim()
{
    "/cygdrive/c/program files (x86)/vim/vim72/gvim.exe" "$@" "&" ;
}

But it only opens gvim and doesn't return the prompt like I want it to.
If someone could point me in the right direction, it would greatly improve my understanding of how .bashrc works.
Thanks!
-Derek
UPDATE: I got it to work by getting rid of the quotation marks around the & and the semicolon at the end:
function gvim()
{
    "/cygdrive/c/program files (x86)/vim/vim72/gvim.exe" "$@" &
}

A: The last is almost right. What is wrong is that plain & tells shell to run process in the background and "&" adds argument to the gvim command-line (i.e. instructs gvim to open file named &). By using quotes here you just instruct shell not to treat & specially and gvim has no reason to do the shell's job.

A: instead of using alias, use a shell function.  It works the same in general, and you've got more options available to you:
function gvim() {
 gvim.bat `cygpath -w $*` &
}

Update
Also, there are some hooks in the default .bashrc (on my box anyway) to automatically load functions from a ".bash_functions" file, you just need to uncomment it (about line 117 for me):
# Functions
#
# Some people use a different file for functions
if [ -f "${HOME}/.bash_functions" ]; then
  source "${HOME}/.bash_functions"
fi

then add the function definition to .bash_functions to have it auto-loaded when you start a bash shell.
Update 2 added call to cygpath to handle full paths in unix form

A: The first thing to understand about .bashrc is probably that it only gets read when the shell starts -- in the case of cygwin, when you open the command window.  It's not clear from your post whether you are restarting your command window, or what.
You can experiment with the aliases/functions without putting them in the .bashrc, just to find out what works.  Just enter the aliases or function definitions directly on the command line, and then try to run them.
I think the problem with the function you provided is you put the & inside double quotes.  Take off the quotes and it should work.

A: What I do is have a small bash script that I call gvim with and alias that.
==> alias vi
alias vi='~/include/bin/dvim'

==> cat ~/include/bin/dvim
#!/bin/bash.exe

/cygdrive/c/Program\ Files/Vim/vim73/gvim.exe $1 &


text:
Q: An error occurred while executing batch. Error message is: Signature specified is zero-sized. (Exception from HRESULT: 0x80131237) When I want to execute a stored procedure I have below error .  How can i fix it?

An error occurred while executing batch. Error message is: Signature specified is zero-sized. (Exception from HRESULT: 0x80131237)


text:
Q: Cannot upload video to iTunesConnect: The frame rate of your app video preview is too high I made an App Store preview video using QuickTime player on OS X Yosemite.
When I try to upload the video to iTunesConnect, I get an error message:

The frame rate of your app video preview is too high.

I can't see any options in the QuickTime Player to change frame rate.

Does anybody knows what to do with it?

A: Just did my first movie. hit lots of snags - heres quick steps to avoid them:

*

*RECORD

*Record in Quick Time Player > File > New Movie Recording

*Use iPhone 6/7 PLUS to get right dimensions

*use drop down beside red record button to choose iphone

*record your video - max 30 secs but easy to trim

*Trim in Quicktime to be under 30 secs

*Edit/Trim - drag the ends of the yellow bounds

*had problems splitting and combining clips in Quicktime - use iMovie

*save as mp4 or mov

*IMOVIE - CONVERT TO APP PREVIEW

*Use iMovie to get correct framerate

*File > New App Preview

*import exported movie file from quicktime

*drag movie to timeline

*press space to test play

*add sound if you like - google "royalty free sounds"

*drag wav into project/ drag into timelime

*EXPORT APP PREVIEW

*Share button top right

*choose App Preview (if missing check prev steps dont use File option fps dimesions may not be right)

*save to file mp4

*UPLOAD USING SAFARI

*Upload using Safari to iTunes Connect - wont work in chrome

*In pictures section of you app version, choose file, pick mp4 exported from imovie

*set frame to display when movie not playing

*save itunes version info

*movie uploaded

*itunes said 'can take up to 24 hours'

A: Videos can be easily converted using ffmpeg, a handy tool that can be installed using homebrew.
ffmpeg -r 30 -i 60fpsvideo.m4v -vcodec copy -acodec copy 30fpsvideo.avi

A: I have followed the following steps :
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

then
brew install ffmpeg

then used the following command :
/usr/local/Cellar/ffmpeg/3.1.3/bin/ffmpeg -i SpeechToText_usage.mov  -qscale 0 -r 24 -y speechtotext_framerate_changed.mov

It worked well!

A: I found out, that there is no possibility to edit the frame rate in the QuickTime Player.
I ended up downloading trial version of Final Cut Pro. In Final Cut Pro it's just a few clicks.

A: For Quicktime videos user this command, worked for me fine:
ffmpeg -i demo_app.mov -qscale 0 -r 24 -y -vf scale=1080:1920,setsar=1:1 app_preview.mov

A: You can fix it easily in iMovie (I used 10.1.10).
1. Go to main screen of iMovie.
2. File -> New App Preview.
3. Drag your movie to the project.
4. File -> Share -> App Preview.

A: This is what worked for me:
ffmpeg -i input.mov -qscale 0 -r 24 -y output_5.mov

-qscale 0 made sure the length stayed the same but the frame rate dropped from 56 or so (as it was recorded from my iPhone6 by the QuickTime) to exactly 24 !!
Then managed to successfully upload to iTunes, yay!
March 28, 2019
EDIT:
There is also this option to just do it with iMovie:
Creating App Previews with iMovie

A: For Quicktime videos use this command line:
ffmpeg -r 30 -i 60fpsvideo.m4v 30fpsvideo.avi

A: This rescales one video into all the required framerate and sizes to match what App Store Connect needs:
IN=IMG_3518.TRIM.MOV
ffmpeg -i $IN -s 1080x1920 -r 30 5.5.mov
ffmpeg -I $IN -s 886x1920 -r 30 6.5.mov
ffmpeg -I $IN -s 1200x1600 -r 30 ipp3.mov

Don't use this. You should make all your videos by running on the actual different devices. Your account will be banned, your house will catch fire, your cat will die.

A: I scripted this into a borne again shell (bash) to convert a bunch of files.  You can add 'rm $file' to the script to delete the original file if you wish, but do not do this unless you know exactly what you are doing and take full responsibility for the risks involved.  I list 30s in my filename convention to specify the length of the video.  If your file name convention is different you will need to adjust accordingly.
#!/bin/bash
for file in `ls *s.mov`
do
newFileName=`echo $file | sed s/s.mov/s_r24.mov/`
# echo $file  $newFileName
if [ -e $newFileName ]; then
echo $newFileName "exists"
else
echo ""
# echo $newFileName "does not exist"
ffmpeg -i $file  -qscale 0 -r 24 -y $newFileName
fi
done

A: *

*Create the file resize_video.sh, with the code below

*Open the terminal, run the command:

sh resize_video.sh

This script, will convert videos as needed by the AppStore.
INPUT_VIDEO=app_preview.mov

mkdir -p 6.5
mkdir -p 5.5
mkdir -p 12.9

WIDTH=886
HEIGHT=1920
OUTPUT_VIDEO=6.5/app_preview.mov
rm -f $OUTPUT_VIDEO
ffmpeg -i $INPUT_VIDEO -qscale 0 -r 24 -y -vf scale=$WIDTH:$HEIGHT,setsar=1:1 $OUTPUT_VIDEO

WIDTH=1080
HEIGHT=1920
OUTPUT_VIDEO=5.5/app_preview.mov

rm -f $OUTPUT_VIDEO
ffmpeg -i $INPUT_VIDEO -qscale 0 -r 24 -y -vf scale=$WIDTH:$HEIGHT,setsar=1:1 $OUTPUT_VIDEO

WIDTH=1200
HEIGHT=1600
OUTPUT_VIDEO=12.9/app_preview.mov

rm -f $OUTPUT_VIDEO
ffmpeg -i $INPUT_VIDEO -qscale 0 -r 24 -y -vf scale=$WIDTH:$HEIGHT,setsar=1:1 $OUTPUT_VIDEO

https://gist.github.com/5lineofcode/ba6fc90ed7628c3acf11a735437c7944


text:
Q: How to find and embed a native window application using Java SWT in Linux - Debian 10.x / 11.x? I am trying to embed a native window application running on Linux - Debian using Java SWT. I tried using GTK library and X11 library to embed a native window,but not working.
For windows, I used OS.FindWindow where I pass the title of the native window as parameter to be embedded, it worked.
Is there a way to get the native window title running on Linux debian and embed them into SWT application.
I tried using OS.gtk_container_get_children, OS.gtk_widget_reparent, but getting error saying undefined reference in OS class, though I have imported the correct package org.eclipse.swt.internal.gtk.OS.
I tried the following code using X11 lib, the code is not wrt SWT application, I just wanted to check if I can embed a native window running on debian into a new window. But facing some issue when I run the code
void reparent (Display *d, Window child, Window new_parent)
{
XUnmapWindow(d, child);
XMapWindow(d, new_parent);
XSync(d, False);
XReparentWindow(d, child, new_parent, 0, 0);
XMapWindow(d, child);
usleep(1e3);
XSync(d, False);
}

int main (int argc, char **argv)
{
Display *d = XOpenDisplay(XDisplayName(NULL));
int s = DefaultScreen(d);
Window root = RootWindow(d, s);
if (argc != 2)
{
    printf("Wrong number of arguments, exiting.");
    exit(1);
}

Window child = strtol(argv[1], NULL, 0);
Window new_parent = XCreateSimpleWindow(
    d, root, 0, 0, 500, 500, 0, 0, 0
);
reparent(d, child, new_parent);
XEvent e;
while (1)
{
    XNextEvent(d, &e);
}

return 0;
}

Can anyone please help me which API or how to use them for Linux? The requirement is to embed multiple native apps/browsers running on Linux Debian into SWT application. Request for your support.
Thanks in advance.


text:
Q: How to write Composition and Aggregation in java I want to know how to identify composition and aggregation code in java. I have C++ Code, But I don't understand how to write in java.
Composition
class A {};
class B { A composited_A; };

Aggregation via Pointer
class A {};
class B
{
A* pointer_to_A;
B(A anA){
pointer_to_A = &anA;
}

Can anyone please tell me how both are working in JAVA. (I know what is meant by Composition and aggregation )
    };

A: Java itself simply does not make the distinction between composition and aggregation. You cannot express the idea of ownership of a reference in the Java type system – if you explicitly need to express ownership you must denote this with some other means (usually simply by constructing a new object to be stored in the instance of a class).
Since Java has a GC, ownership for memory doesn't need to be expressed at all; memory is owned and managed solely by the GC. Of course, the same is not true for other resources and here you might still want to express ownership.

A: In Java, objects are only referenced by pointers. This means that a field of type A is really a reference to an A object. It also means that that field will always start as a null pointer, and you must explicitly assign it to new A() or whatever.
Edit:
class B {
   A a;

   B(A a) {
      this.a = a;
   }

   B() {
      this(new A());
   }
}

A: I think this is best way to express Composition and Aggregation With Java Code.
Composition
public class Person
{
    private final Name name;

    public Person (String fName, String lName)
    {
        name = new Name(fName, lName);
    }

    //...
}

Aggregation
public class Person
{
    private Costume currentClothes;

    public void setClothes(Costume clothes)
    {
        currentClothes = clothes;
    }

    //...
}

Source


text:
Q: cakephp download png file I dynamically generate png files which after clicking "generate" button appears "under"  link.
 "generate button : click" ---> DOWNLOAD

After clicking link DOWNLOAD I wish content of link(in my case png) start download  - no open in another window but download!
I am using cakePHP. Can I please for help?

A: you can use the MediaView to pass it through and force downloading:
http://book.cakephp.org/2.0/en/views/media-view.html?highlight=media#MediaView

A: Alternatively if you are using Apache web server and have mod_headers enabled you can use an .htaccess file to force download of the png files.
Create a .htacess file and place it in the directory where your png files are being generated/downloaded from.  In that file put this:
<FilesMatch "\.(?i:png)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>


text:
Q: Symbol Table scope in compilers for object oriented languages I'm building up a Symbol Table for a compiler of a subset of C++.
My question here is how to deal with the scope in objects. I mean, in a normal language such as Pascal we should create a Symbol Table for every scope. But with C++ should I consider another approche for the case of methods and attrubtes of an object?
Regards.

A: I'd say an object has a symbol table for every scope for its methods and attributes, plus another table for friend class and methods.
It's just an idea.


text:
Q: How to get selected value from mysql to dropdown list? I have question about dropdown list in php using mysql to populate it.
I'll try to describe it as clear as possible.
First, the tables
|              Cars            |      |      Colors       |
--------------------------------      ---------------------
|car_id|     name   | color_id |      |color_id|color_name|
--------------------------------      ---------------------
| 01   |   BMW      |   c1     |      |  c1    |  Silver  |
| 02   |   Audi     |   c2     |      |  c2    |  Black   |
| 03   | Chevrolet  |   c3     |      |  c3    |  White   |

I already create form to input a car data to cars table. In that form i create a dropdown list to get color_name,
and there was no problem to save it. The problem is how to get selected color_name on update form using dropdown?

A: If selected_color is the color what you got from DB. Then use the following code to set your drop down list.
$("#dropDownList").val(selected_color);

A: This may be what you're looking for...
                            <select name="color" id="color">
                            <?php do { ?>
                            <option value="<?php echo $row['color_id'] ?>" <?php if (!(strcmp($row['color_id'], $row_rsEdit['color_id']))) {echo "selected=\"selected\"";} ?>><?php echo $row['color_name'] ?></option>
                            <?php } while ($row = $rsColors->fetch(PDO::FETCH_ASSOC)); ?>
                            </select>

A: Is it that you're looking for?
<select>
  <option selected>Silver</option>
  <option>Black</option>
</select>

In order to get that dynamically, do something like this:
<select>
  <?php foreach($colors as $color): ?>
     <option <?php echo ($color == $theActualSelectedColor) ? 'selected' : ''; ?>><?php echo $color ?></option>
  <?php endforeach; ?>
</select>

This is simplified. You may wanna use the color IDs as the option's values instead and just output the color names in the visible part of the dropdown.


text:
Q: How to set variables for `dotnet new`? Standard template for command
dotnet new console
contains #if for the preprocessor:
#if (csharpFeature_TopLevelProgram)
// See https://aka.ms/new-console-template for more information
#endif
#if (!csharpFeature_ImplicitUsings)
using System;

#endif
#if (csharpFeature_TopLevelProgram)
Console.WriteLine("Hello, World!");
#else
namespace Company.ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
#endif

What command line switches should I specify to dotnet new so that the variable "csharpFeature_TopLevelProgram" is not defined and so that when I execute dotnet new console the file is generated not for Net6 but without TopLevelProgram as before in the good old Net5?

A: If you use the -h command line option, it tells you how to use the template and that you can specify the --use-program-main parameter:

For example:
dotnet new console --use-program-main true

Note: You may need to update to a newer version of .NET 6 for this command line option to exist. This was tested with v6.0.401


text:
Q: Java JDBC Connection with Heroku I'm trying to create a Java Web App on Heroku. When connecting the App to Heroku Database I encountered a Issue:
org.postgresql.util.PSQLException: ERROR: relation "sc_user" does not exist
The connection part is:
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();

BasicDataSource connectionPool = new BasicDataSource();

if (dbUri.getUserInfo() != null) {
    connectionPool.setUsername(dbUri.getUserInfo().split(":")[0]);
    connectionPool.setPassword(dbUri.getUserInfo().split(":")[1]);
}
connectionPool.setDriverClassName("org.postgresql.Driver");
connectionPool.setUrl(dbUrl);
connectionPool.setInitialSize(3);

Connection conn = connectionPool.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM SC_User");

I see on Heroku Dashboard that 3 connections are used from pool, but the last line throws exception saying no relation sc_user.
I created the table with add-on tool Adminium, is there something i'm missing in the commands? Thanks for your help!

A: Try delimiting the table name with quotations
ResultSet rs = stmt.executeQuery("SELECT * FROM \"SC_User\"");

A: When you create a column in postgres with Upper Letter the DBMS use it between "SC_User" si in case your column is in upper Letter you have to use :
stmt.executeQuery("SELECT * FROM \"SC_User\"");
//--------------------------------^--------^

else you have to use the correct name with lowercase
stmt.executeQuery("SELECT * FROM sc_user");
//---------------------------------^^

read more about that here :
Cannot query Postgres database that has column names with capital letters


text:
Q: Is there a way to set Unity 3d's dock/launcher to be completely opaque like Unity 2d's?
Possible Duplicate:
Can I change the Unity Launcher transparency?

Unity 3d icons and launcher:

Unity 2d icons and launcher:

In unity 2d, the icons looks darker than in 3d. In 3d, the icons have a clearer color to them because of the transparency they're given. I really like the 2d dark color. I have searched frantically and have found NOTHING about this.
I have used confity, compiz (with extra plugins), gconf-editor, and searched for compiz rules. Nothing.
EDIT: I understand that you can edit the top panel's opacity with compiz settings manager, but I haven't found a way to do this for the Dock/Launcher alone.

A: As discussed in this question, you can adjust the background opacity if you use unity-df.


text:
Q: HTTP Status 500 - oracle.adfinternal.controller.faces.context.StubJSFPageLifecycleContext cannot be cast to We are developing web applications using Oracle ADF (jdeveloper 11.1.2.4). We need to run these applications on tomcat6.x. We have setup our tomcat6.x environment using the post ADF Essentials on tomcat.
We are able to run only one application on tomcat. Means if we deploy only one application it is successfully running on browser and everything is fine. Whenever we are trying to deploy more than one application no exception is coming on tomcat server console.
But when we are trying to open any page like http://localhost:1234/E/faces/j.jsf it is giving the following error.
HTTP Status 500 - oracle.adfinternal.controller.faces.context.StubJSFPageLifecycleContext cannot be cast to oracle.adf.controller.faces.context.FacesPageLifecycleContext
exception

java.lang.ClassCastException: oracle.adfinternal.controller.faces.context.StubJSFPageLifecycleContext cannot be cast to oracle.adf.controller.faces.context.FacesPageLifecycleContext
    oracle.adfinternal.controller.application.model.UpdateBindingListener.beforePhase(UpdateBindingListener.java:66)
    oracle.adfinternal.controller.lifecycle.ADFLifecycleImpl$PagePhaseListenerWrapper.beforePhase(ADFLifecycleImpl.java:550)
    oracle.adfinternal.controller.lifecycle.LifecycleImpl.internalDispatchBeforeEvent(LifecycleImpl.java:100)
    oracle.adfinternal.controller.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:191)
    oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener.access$200(ADFPhaseListener.java:23)
    oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener$PhaseInvokerImpl.startPageLifecycle(ADFPhaseListener.java:232)
    oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener$1.after(ADFPhaseListener.java:274)
    oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener.afterPhase(ADFPhaseListener.java:75)
    oracle.adfinternal.controller.faces.lifecycle.ADFLifecyclePhaseListener.afterPhase(ADFLifecyclePhaseListener.java:53)
    oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:447)
    oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:202)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
    oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:173)
    oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:125)
    org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)
    oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
    org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)
    org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:293)
    org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:199)
    org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)

Please help us. We have to deploy and successfully run more than one adf application on tomcat 6.x.

A: Might be the same issue as posted here: https://community.oracle.com/thread/724037?start=15&tstart=0
In short, the correct answer was:

I cannot say for sure, but this sounds like you have the same library
  placed in both web application library folder and Tomcat common
  library directory. Depending of where you place those libraries, they
  will be loaded by application classloader or the parent Tomcat
  classloader. In other words, I believe that you have one library
  loaded by webapplication's lib folder instead of having it loaded into
  the parent classloader.
  - Florin

A: I'm noting that this exception will/can also appear on Tomcat 9+ as a result of the FacesInitializer (a SCI ServletContainerInitializer) being loaded as part of the Tomcat root loader. This will "confuse" the ADF Faces application, with the result of a ClassCastException.
A possible fix for this is to go into the jsf-impl and comment out the contents of META-INF/services/javax.servlet.ServletContainerInitializer or remove this file in its entirety.


text:
Q: Getting full file path of android file? Good day, all! I'm currently coding a plugin for Unity so that the user can access the file browser and pick an app. Upon picking the app, the file path is supposed to be saved. My code works so far, it's able to get the file path of the file but not the full one.
This is my code so far
int PICKFILE_RESULT_CODE = 1;
@Override
protected void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/vnd.android.package-archive");
    startActivityForResult(intent, PICKFILE_RESULT_CODE);

 }

@SuppressLint("InlinedApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode==RESULT_OK && requestCode==PICKFILE_RESULT_CODE && data != null)
    {
        String apkPath = data.getData().getPath();

        UnityPlayer.UnitySendMessage("Browser", "OnApkPick", apkPath);
        Browser.this.finish();

        super.onActivityResult(requestCode, resultCode, data);

    }
}

Thanks in advance.


text:
Q: Reading datagridview (table) using pywinauto I want to do some automation using pywinauto and I'm stuck at reading DataGridView table. How do I convert it to readable table? I need to see the actual data in the table. The columns in the table are dynamic, you can add or remove the one you need. As far as I understand I need to convert ir using ListViewWrapper but I can't get the element of the table. The control identifiers:
app = Application(backend='uia').connect(title_re=app_regex)
dgv = app.top_window().DataGridView
dgv.print_control_identifiers()

Table - 'DataGridView'    (L198, T191, R1366, B621)
['DataGridViewTable', 'Table', 'DataGridView']
child_window(title="DataGridView", auto_id="dgvBrowser", control_type="Table")
   |
   | ScrollBar - 'Vertical Scroll Bar'    (L1348, T192, R1365, B620)
   | ['ScrollBar', 'Vertical Scroll BarScrollBar', 'Vertical Scroll Bar']
   | child_window(title="Vertical Scroll Bar", auto_id="4261242", control_type="ScrollBar")
   |    |
   |    | Button - 'Line up'    (L1348, T192, R1365, B209)
   |    | ['Button', 'Line up', 'Line upButton', 'Button0', 'Button1']
   |    | child_window(title="Line up", control_type="Button")
   |    |
   |    | Thumb - 'Position'    (L1348, T209, R1365, B590)
   |    | ['Position', 'PositionThumb', 'Thumb']
   |    | child_window(title="Position", control_type="Thumb")
   |    |
   |    | Button - 'Page down'    (L1348, T590, R1365, B603)
   |    | ['Button2', 'Page down', 'Page downButton']
   |    | child_window(title="Page down", control_type="Button")
   |    |
   |    | Button - 'Line down'    (L1348, T603, R1365, B620)
   |    | ['Button3', 'Line down', 'Line downButton']
   |    | child_window(title="Line down", control_type="Button")
   |
   | Custom - 'Top Row'    (L198, T191, R1348, B213)
   | ['Custom', 'Top RowCustom', 'Top Row', 'Custom0', 'Custom1']
   | child_window(title="Top Row", control_type="Custom")
   |    |
   |    | Header - ''    (L199, T191, R239, B213)
   |    | ['', 'Header', '0', '1', 'Header0', 'Header1']
   |    |
   |    | Header - ''    (L239, T191, R264, B213)
   |    | ['2', 'Header2']
   |    |
   |    | Header - 'Data'    (L264, T191, R352, B213)
   |    | ['DataHeader', 'Header3', 'Data']
   |    | child_window(title="Data", control_type="Header")
   |    |
   |    | Header - 'Technikas'    (L352, T191, R484, B213)
   |    | ['TechnikasHeader', 'Technikas', 'Header4']
   |    | child_window(title="Technikas", control_type="Header")
   |    |
   |    | Header - 'Paskyros numeris'    (L484, T191, R638, B213)
   |    | ['Paskyros numerisHeader', 'Header5', 'Paskyros numeris']
   |    | child_window(title="Paskyros numeris", control_type="Header")
   |    |
   |    | Header - 'Objektas-Adresas'    (L638, T191, R762, B213)
   |    | ['Objektas-Adresas', 'Objektas-AdresasHeader', 'Header6']
   |    | child_window(title="Objektas-Adresas", control_type="Header")
   |    |
   |    | Header - 'Klientas'    (L762, T191, R866, B213)
   |    | ['Klientas', 'Header7', 'KlientasHeader']
   |    | child_window(title="Klientas", control_type="Header")
   |    |
   |    | Header - 'Stadija'    (L866, T191, R997, B213)
   |    | ['StadijaHeader', 'Header8', 'Stadija']
   |    | child_window(title="Stadija", control_type="Header")
   |    |
   |    | Header - 'Darbu vykdytojas'    (L997, T191, R1147, B213)
   |    | ['Darbu vykdytojasHeader', 'Darbu vykdytojas', 'Header9']
   |    | child_window(title="Darbu vykdytojas", control_type="Header")
   |    |
   |    | Header - 'Projektas'    (L1147, T191, R1348, B213)
   |    | ['ProjektasHeader', 'Header10', 'Projektas']
   |    | child_window(title="Projektas", control_type="Header")
   |
   | Custom - 'Row 0'    (L199, T213, R1348, B234)
   | ['Custom2', 'Row 0Custom', 'Row 0']
   | child_window(title="Row 0", control_type="Custom")
   |    |
   |    | Custom - ' Row 0'    (L199, T213, R239, B234)
   |    | ['Custom3', ' Row 0', ' Row 0Custom', ' Row 00', ' Row 01', ' Row 0Custom0', ' Row 0Custom1']
   |    | child_window(title=" Row 0", control_type="Custom")
   |    |
   |    | Custom - ' Row 0'    (L239, T213, R264, B234)
   |    | ['Custom4', ' Row 02', ' Row 0Custom2']
   |    | child_window(title=" Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Data Row 0'    (L264, T213, R352, B234)
   |    | ['Custom5', 'Data Row 0Custom', 'Data Row 0']
   |    | child_window(title="Data Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Technikas Row 0'    (L352, T213, R484, B234)
   |    | ['Custom6', 'Technikas Row 0', 'Technikas Row 0Custom']
   |    | child_window(title="Technikas Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Paskyros numeris Row 0'    (L484, T213, R638, B234)
   |    | ['Custom7', 'Paskyros numeris Row 0Custom', 'Paskyros numeris Row 0']
   |    | child_window(title="Paskyros numeris Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Objektas-Adresas Row 0'    (L638, T213, R762, B234)
   |    | ['Custom8', 'Objektas-Adresas Row 0', 'Objektas-Adresas Row 0Custom']
   |    | child_window(title="Objektas-Adresas Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Klientas Row 0'    (L762, T213, R866, B234)
   |    | ['Custom9', 'Klientas Row 0Custom', 'Klientas Row 0']
   |    | child_window(title="Klientas Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Stadija Row 0'    (L866, T213, R997, B234)
   |    | ['Custom10', 'Stadija Row 0', 'Stadija Row 0Custom']
   |    | child_window(title="Stadija Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Darbu vykdytojas Row 0'    (L997, T213, R1147, B234)
   |    | ['Custom11', 'Darbu vykdytojas Row 0', 'Darbu vykdytojas Row 0Custom']
   |    | child_window(title="Darbu vykdytojas Row 0", control_type="Custom")
   |    |
   |    | Custom - 'Projektas Row 0'    (L1147, T213, R1348, B234)
   |    | ['Custom12', 'Projektas Row 0', 'Projektas Row 0Custom']
   |    | child_window(title="Projektas Row 0", control_type="Custom")
   |
   | Custom - 'Row 1'    (L199, T234, R1348, B255)
   | ['Custom13', 'Row 1', 'Row 1Custom']
   | child_window(title="Row 1", control_type="Custom")
   |    |
   |    | Custom - ' Row 1'    (L199, T234, R239, B255)
   |    | ['Custom14', ' Row 1Custom', ' Row 1', ' Row 1Custom0', ' Row 1Custom1', ' Row 10', ' Row 11', ' Row 100', ' Row 101', ' Row 110', ' Row 111']
   |    | child_window(title=" Row 1", control_type="Custom")
   |    |
   |    | Custom - ' Row 1'    (L239, T234, R264, B255)
   |    | ['Custom15', ' Row 1Custom2', ' Row 12', ' Row 120', ' Row 121']
   |    | child_window(title=" Row 1", control_type="Custom")
   |    |
   |    | Custom - 'Data Row 1'    (L264, T234, R352, B255)
   |    | ['Custom16', 'Data Row 1Custom', 'Data Row 1']
   |    | child_window(title="Data Row 1", control_type="Custom")
   |    |
   |    | Custom - 'Technikas Row 1'    (L352, T234, R484, B255)
   |    | ['Custom17', 'Technikas Row 1Custom', 'Technikas Row 1']
   |    | child_window(title="Technikas Row 1", control_type="Custom")
   |    |
   |    | Custom - 'Paskyros numeris Row 1'    (L484, T234, R638, B255)
   |    | ['Custom18', 'Paskyros numeris Row 1', 'Paskyros numeris Row 1Custom']
   |    | child_window(title="Paskyros numeris Row 1", control_type="Custom")

Thanks

A: You may not like the answer, but current situation is not good for your task.

*

*If you have no access to the app source code, it's impossible to get texts using pywinauto.

*But if you have, it requires to implement so called Server Provider for this control type (described in the UI Automation API docs on MSDN). Though I never tried this way.

*Another theoretically possible approach should use managed DLL injection to access internal properties of custom .NET controls. I know TestComplete, Squish and UFT use this way. But they are all very expensive. Never heard about any open source tool using this approach.
P.S. Screen text recognition is also theoretically possible way, but the tools are not mature enough to recognize it reliably.


text:
Q: svg circle tapered fading stroke I am trying to create an svg file with a circle that has a tapered stroke that fades, meaning the stroke width will be the thickest (say 20px) with the original color and will be the thinnest (say 3px) on the opposite side where the color has faded. I was able to create the circle with color fading with the gradient tool, but I am struggling to figure out how to change the stroke width
Here's the code I have so far, which I created in Photoshop and exported to svg.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
  <defs>
    <style>
      .cls-1 {
        fill: none;
        stroke-width: 20px;
        stroke: url(#a);
      }
    </style>
    <linearGradient id="a" x1="255.5" y1="240" x2="255.5" y2="51" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="rgba(96,0,0,1)"/>
      <stop offset="1" stop-color="rgba(96,0,0,.1)"/>
    </linearGradient>
  </defs>
  <circle class="cls-1" cx="255.5" cy="255.5" r="184.5"/>
</svg>

Here's an image of what I am trying to do.

Sorry, one more favor. I am trying to create an icon, so it will have four of these circles with different colors, with one fading to the top as shown, another fading to the bottom, and the other two to each of the sides. I will really appreciate it if you can also show me how to rotate :)
Thank you in advance.
Regards,
Mike

A: I would draw a bigger circle with a hole inside. In this case I'm using a mask. You can also draw a holloed path. In both cases you are using the gradient as a fill not as a stroke

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500" viewBox="0 0 500 500">
  <defs>
    <style>
      .cls-1 {
        fill: url(#a);
      }
    </style>
    <linearGradient id="a" x1="255.5" y1="240" x2="255.5" y2="51" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="rgba(96,0,0,1)"/>
      <stop offset="1" stop-color="rgba(96,0,0,.1)"/>
    </linearGradient>
    <mask id="m">
      <circle id="c1" cx="255.5" cy="255.5" r="184.5" fill="white" />
      <circle fill="black" cx="255.5" cy="245.5" r="164.5"/>
    </mask>
  </defs>
  <circle  cx="255.5" cy="255.5" r="184.5" class="cls-1" mask="url(#m)" />
</svg>

And this is an example where I'm using a holloed path instead of the masked circle. Please note that in this case I'm centering the path atound the point x=0 y=0.

<svg width="500" height="500" viewBox="-250 -250 500 500">
  <defs>
    <style>
      .cls-1 {
        fill: url(#a);
      }
    </style>
    <linearGradient id="a"  y1="200" y2="-200" x1="0" x2="0" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="rgba(96,0,0,1)"/>
      <stop offset="1" stop-color="rgba(96,0,0,.1)"/>
    </linearGradient>
  </defs>
  <path class="cls-1" d="M184.5,0A184.5,184.5 0 0 1 -184.5,0A184.5,184.5 0 0 1 184.5,0M164.5,-10A164.5,164.5 0 0 0 -164.5,-10A164.5,164.5 0 0 0 164.5,-10"/>
</svg>

A:
I am trying to create an icon, so it will have four of these circles
with different colors, with one fading to the top as shown, another
fading to the bottom, and the other two to each of the sides. I will
really appreciate it if you can also show me how to rotate

The first circle rotates clockwise
<animateTransform
  attributeName="transform"
   type="rotate"
    values="0 150 150;360 150 150"
     begin="svg1.click"
      dur="10s"
      repeatCount="indefinite"
      />

The second circle rotates counterclockwise.
Since the top circle is set to the opacity parameter fill-opacity: 0.5;
then the effect of changing the thickness of the stroke is created
Added gradient animation to both circles:
 <animate
     attributeName="stop-color"
     dur="1.5s"
     values="red;yellow;red"
     repeatCount="indefinite"
/>

The text Click me has been added for demonstration it can be removed.
Below is the complete code:

.container {
width:50%;
height:50%;
}

svg {
background:black;
}

#path1 {
fill:url(#gradl);
stroke:none;
fill-opacity:1;
}
#path2 {
fill:url(#grad2);
stroke:none;
fill-opacity:0.5;
}
#crc1 {
stroke:none;
fill:black;
}
#txt1 {
fill:url(#grad2);

}
<div class="container">

<svg id="svg1" xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"  viewBox="0 0 300 300" >
<defs>
<linearGradient id="gradl" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1">
    <stop offset="0%" stop-color="red" stop-opacity="0.9">
      <animate
         attributeName="stop-color"
         dur="1.5s"
         values="red;yellow;red"
         repeatCount="indefinite"
      />
    </stop>
      <stop offset="100%" stop-color="yellow">
       <animate
         attributeName="stop-color"
         dur="1.5s"
         values="yellow;red;yellow" repeatCount="indefinite"
         />
       </stop>

 </linearGradient>

    <linearGradient id="grad2" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0%" stop-color="lime">
          <animate
             attributeName="stop-color"
             dur="1.5s"
             values="lime;purple;lime"
             repeatCount="indefinite"
           />
        </stop>
      <stop offset="100%" stop-color="purple">
       <animate
         attributeName="stop-color"
         dur="1.5s"
         values="purple;lime;purple" repeatCount="indefinite"
         />
       </stop>

    </linearGradient>

</defs>
    <path id="path1" d="M71.9 78.4C90.8 58.1 122.9 50.7 150.6 51.5c26.2 0.7 54.9 10.5 72.8 29.7 16.9 18.1 22.9 45.8 23.4 70.6 0.5 25.1-3.2 54.4-20.7 72.4-18.5 19.1-49.4 24.5-76 24.3-25.4-0.2-54.4-6.3-72.4-24.3C59.5 205.8 53.9 176.5 53 150.8 52.2 125.9 55 96.7 71.9 78.4Z" >
     <animateTransform
      attributeName="transform"
       type="rotate"
        values="0 150 150;360 150 150"
         begin="svg1.click"
          dur="10s"
          repeatCount="indefinite"
          />
    </path>

<path id="path2" transform="rotate(45 150 150)"
  d="M71.9 78.4C90.8 58.1 122.9 50.7 150.6 51.5c26.2 0.7 54.9 10.5 72.8 29.7 16.9 18.1 22.9 45.8 23.4 70.6 0.5 25.1-3.2 54.4-20.7 72.4-18.5 19.1-49.4 24.5-76 24.3-25.4-0.2-54.4-6.3-72.4-24.3C59.5 205.8 53.9 176.5 53 150.8 52.2 125.9 55 96.7 71.9 78.4Z" >
 <animateTransform
  attributeName="transform"
   type="rotate"
    values="360 148 148;0 148 148"
    begin="svg1.click"
     dur="10s"
     repeatCount="indefinite" />
</path>
<circle id="crc1" cx="150" cy="150" r="90" />
 <text id="txt1" x="80" y="160" font-size="36" font-weight="700" > Click me </text>
</svg>
</div>


text:
Q: Wrapping Spring Boot application with Tanuki Service Wrapper How to wrap Spring Boot application as a linux daemon and to set it to read from application.properties.
To start the jar with the parameters from the application.properties I am using this command:

java -Dspring.config.location=/application.properties -jar MyJar.jar

Where to set this in wrapper.conf?
I have tried like this but the jar is not starting with the parameters from the application.properties.
wrapper.java.command=java
wrapper.java.command.loglevel=INFO
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperJarApp
wrapper.java.classpath.1=../lib/wrapper.jar
wrapper.java.classpath.2=/opt/MyService/lib/MyApp.jar
wrapper.java.library.path.1=../lib
wrapper.logfile=../logs/wrapper.log
wrapper.app.parameter.1=/opt/MyService/lib/MyApp.jar
wrapper.app.parameter.2=-c
wrapper.app.parameter.3=/opt/MyService/lib/conf

A: Try with this:
wrapper.java.additional.1=-Dspring.config.location=/opt/MyService/lib/conf/application.properties


text:
Q: Sending email to multiple addresses with php It only sends email to the first email address. The second email address does not work because it is a variable. What do you think?
  $to = "email1@gmail.com,". $rs['email2'];
    $subject = "Hello";
    $from = "admin@itservice.com";
    $headers = "From: $from\r\n";
    $headers .= "MIME-Version: 1.0\r\n"
      ."Content-Type: multipart/mixed; boundary=\"1a2a3a\"";

    $message .= "This is a message..."
      ."--1a2a3a\r\n";

    $file = file_get_contents("memomemomemo4.pdf");

    // Send email

      $success = mail($to,$subject,$message,$headers);

A: Why not:
$rs['email2'] = "me@me.com";
echo "email1@gmail.com,{$rs['email2']}";
# email1@gmail.com,me@me.com

A: Try this syntax instead:
$to = "email1@gmail.com,".$rs['email2'];


text:
Q: Can't launch script with keyboard shortcut I'm trying to bind a script (script1) that starts another script (script2) to a keyboard shortcut, but it doesn't seem to actually start the second script.
The first script is supposed to kill the second script if it is already running and then restart it:
#! /bin/bash
killall -e script2.sh
/home/user/script2.sh

I'm using Ubuntu 20.04 and gnome 3.36.8. The scripts are working when I manually start them from the terminal.
Could anybody help me please?


text:
Q: dynamically remove, modify rows in oracle database using python I have an oracle table- Students.
I want to be able to delete and modify rows dynamically.
an a table example:

student id
course
grade
year

111
math
90
2020

:---------
:------:
:-----:
-----:

222
French
80
2021

:---------
:------:
:-----:
-----:

333
physics
77
2015

:---------
:------:
:-----:
-----:

444
sport
65
2014

and i want dynamiclly delete some row using python lets say row 3 the output should be:

student id
course
grade
year

111
math
90
2020

:---------
:------:
:-----:
-----:

222
French
80
2021

:---------
:------:
:-----:
-----:

444
sport
65
2014

*code
for delete row.
table_variables=[student_id , course, grade, year]

login path

c = conn.cursor()
        id=3

        statement =  ('delete from Students '
           'where rownum = :rownum')
        c.execute(statement,[id])
        conn.commit()

or i want just to modify an existing row using python for example:

student id
course
grade
year

111
math-2
100
2020

:---------
:------:
:-----:
-----:

222
French
80
2021

:---------
:------:
:-----:
-----:

333
physics
77
2015

:---------
:------:
:-----:
-----:

444
sport
65
2014

*code
for modify row.

login path

table_variables=[student_id , course, grade, year]
 c = conn.cursor()
        id=1

        statement =  ('update Students '
           'where student_id = :student_id ' and
course=:course and grade=:grade and year=:year
)
        c.execute(statement,[111,math-2,100,2020       ])
        conn.commit()

hope you can help i didnt find something online.
thanks!


text:
Q: Sort custom date in datatables I am using datatable to show result in table.

When I click on sort it sort date by day and ignores month and year.
ascending

descending

Code that I am using at the moment is
 $('.dtbt2').DataTable({
    "ordering" : true,
    "scrollCollapse" : true,
    "columnDefs" : [{"targets":3, "type":"date-eu"}],
    "bInfo": true
});

What should I do to sort correctly?
Thanks you nice people in advance,
Auj

A: Is type : date-eu an out of box datatables data type? I have never used it. But if it's not, try using the extend function like this example  or try changing the type to just date. That should properly sort. You would only need to use the extend option to define your own custom sort if you need something else that what type date accomplishes.


text:
Q: Laravel exceptions handler reporting I need to understand the professional practice on how to send exception reports. Here is an example code of a function of a controller that calls a service and performs its business logic inside. If it raises one of the exceptions (present in the controller), then it must report to me, but not for all of them. In my case, the report is needed for the first catch and the final exception. How can I manage sending logs to the platform to keep everything monitored? Is it correct to have redundant "report ($e)" in every catch or is it possible to centralize everything? Opinions?
Thank you so much for your support.
 public function verifyUser(VerifyUserRequest $request): JsonResponse
    {
        try {
            // Retrieve the data
            $data = $request->toArray();
            // Verify the phone number
            $this->authService->verifyUser($data['phone_number'], $data['verification_code']);

            // Return true to indicate that it has been verified
            return Response::success(true);
        } catch (UserNotFoundForValidationException $e) {
            report($e);
            return Response::error(__('auth.verification.user_not_found'), $e->getCode());
        } catch (InvalidVerificationCodeException $e) {
            return Response::error($e->getMessage(), $e->getCode());
        } catch (Exception $e) {
            report($e);
            return Response::error(__('auth.error.verification'), HttpResponse::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


text:
Q: Summation with Legendre Symbol $\sum_{a=1}^{p-1}\big(\frac{a}{p}\big)a=0$ I am trying to show the following: if $p$ is prime that is $1$ modulo 4, then $$\sum_{a=1}^{p-1}\bigg(\frac{a}{p}\bigg)a=0$$
I know I need to use the fact that for an odd prime p, $\frac{p−1}{2}$ of the numbers $1\leq k \leq p−1$ are quadratic residues, but I do not know how $p$ being $1$ modulo $4$ comes into play. Do I need to use Fermat's theorem on sums of two squares which tells me that $p$ is the sum of two squares? Any help is appreciated.

A: If $S$ is the set of quadradic residues, then this sum is equal to $$-\sum_{a = 1}^{p-1} a + 2\sum_{a \in S} a = 2\sum_{a \in S} a - \frac{p(p-1)}{2}.$$
Since $p \equiv 1 \mod 4$, $-1$ is a quadradic residue, so each quadradic residue appears in a pair $a$ and $ p -a$.  There are $\frac{p-1}{4}$ total pairs and each pair sums to $p$, so this gives $$2\cdot p\frac{(p-1)}{4} - \frac{p(p-1)}{2} = 0.$$


text:
Q: Send event when module was executed I'm really stuck on this.. I need to send an event when both Load module and Hide module code was executed, and only then send the event. Ideas on how to achieve this?
// Load module
(
    function() {
        var s=document.createElement('script');
        s.type='text/javascript';
        s.async=true;
        s.src='https://example.com/bundles.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
    }
)();

// Hide module
var inverval = setInterval(hideClass, 100);

function hideClass () {
    if ($(".class").hide().length > 0) clearInterval(inverval);
}

// When both happend = Send a event to Google Analytics
DigitalData.push({'event':Module, 'eventLabel':'Page'});

A: If this is your only option, then perhaps there's something you are going about wrongly. Anyway, let's see ... Only when both events have taken place.
var HandleTwoEvents = function (key1, key2) {
   this.count = 0;
   this.pack = [];
   $self = this;
   this.startListening = function(fn) {
      fn = fn || function () {}
      window.addEventListener(key1, function (ev) {
         if ($self.pack.indexOf(key1) < 0) {
            $self.pack.push(key1);
            $self.count++;
            if ($self.count == 2) {
                fn();
                $self.count = 0;
            }
         }
         console.log(key1, ev);
      });
      window.addEventListener(key2, function (ev) {
         if ($self.pack.indexOf(key2) < 0) {
            $self.pack.push(key2);
            $self.count++;
            if ($self.count == 2) {
                fn();
                $self.count = 0;
            }
         }
         console.log(key2, ev);
      });
    }
}

Forgive me, i always use this function to create events
function createEvent(name, obj) {
    var evt = document.createEvent("Event");
    evt.initEvent(name, true, true);
    evt.data = obj;
    dispatchEvent(evt);
}

Now, to log both events ...
var both = new HandleTwoEvents("EventKeyOne", "EventKeyTwo");
both.startListening(function () {console.log("This means that both Events have taken place")});

Now, let's test ...
createEvent("EventKeyOne", {});
//key, data are the arguments ... function defined in startListening above does not execute, and upon inspection, both.count is seen to be 1
createEvent("EventKeyTwo", {});
//Now, function executes.
//It also works if "EventKeyTwo" is raised before "EventKeyOne"

Happy Coding!
PS: I'm sure there's a better way to handle the use of the $self variable, with some function binding, i guess. I've never been able to learn it.


text:
Q: How to show nested JSON value in table header & row I would like to show the nested JSON values in table header and row as per screenshot.

However, my current code show me as per below.

How can I get the result of the first screenshot?
Here is my code:

var tbl_ss564_ib_jsonData = [
 {
  "S_No": "1",
  "SS564 Metric": "Power Usage Effectiveness(PUE)",
  "Baseline": "2.2*",
  "DC": [
    {"A": "2.4"},
    {"B": "2.61"},
    {"C": "2.46"},
    {"D": "2.25"},
    {"E": "2.11"},
    {"F": "3.75"},
    {"G": "2.08"},
    {"H": "2.17"},
    {"I": "1.85"},
    {"J": "2.57"},
    {"K": "2.42"}
   ]
 }
]

    var sortAscending = true;
    var tbl_ss564_ib = d3.select('#ss564_ib_page_wrap').append('table');
    var title_ss564_ib = d3.keys(tbl_ss564_ib_jsonData[0]);
    var header_ss564_ib = tbl_ss564_ib.append('thead').append('tr')
                     .selectAll('th')
                     .data(title_ss564_ib).enter()
                     .append('th')
                     .text(function (d) {
                       return d;
                      })
                     .on('click', function (d) {
                      header_ss564_ib.attr('class', 'header');

                      if (sortAscending) {
                        rows.sort(function(a, b) { return b[d]  a[d]; });
                     sortAscending = true;
                     this.className = 'des';
                      }

                     });

    var rows = tbl_ss564_ib.append('tbody').selectAll('tr')
                 .data(tbl_ss564_ib_jsonData).enter()
                 .append('tr');
    rows.selectAll('td')
      .data(function (d) {
       return title_ss564_ib.map(function (k) {
        return { 'value': d[k], 'name': k};
       });
      }).enter()
      .append('td')
      .attr('data-th', function (d) {
       return d.name;
      })
      .text(function (d) {
       return d.value;
      });
* {
   margin: 0;
   padding: 0;
     }
   #ss564_ib_page_wrap  body {
    font: 14px/1.4 Georgia, Serif;
     }
    #ss564_ib_page_wrap {
   margin: 20px;
    }
    p {
  margin: 20px 0;
    }

 /*
 Generic Styling, for Desktops/Laptops
 */
 #ss564_ib_page_wrap table {
  width: 100%;
  border-collapse: collapse;
 }
 /* Zebra striping */
 #ss564_ib_page_wrap tr:nth-of-type(odd) {
  background: #eee;
 }
 #ss564_ib_page_wrap th {
  background: Teal;
  font-weight: bold;
  cursor: s-resize;
  background-repeat: no-repeat;
        background-position: 3% center;
 }
 #ss564_ib_page_wrap td, th {
  padding: 6px;
  border: 1px solid #ccc;
  text-align: left;
 }

 #ss564_ib_page_wrap th.des:after {
      content: "\21E9";
    }

 #ss564_ib_page_wrap  th.aes:after {
      content: "\21E7";
    }

A: Without changing your D3 code, the easiest solution is just manipulating your data array beforehand:
tbl_ss564_ib_jsonData[0].DC.forEach(function(d, i) {
    for (var key in d) {
        tbl_ss564_ib_jsonData[0][key] = d[key];
    }
});

delete tbl_ss564_ib_jsonData[0].DC;

Here is your code with that change:

var tbl_ss564_ib_jsonData = [{
  "S_No": "1",
  "SS564 Metric": "Power Usage Effectiveness(PUE)",
  "Baseline": "2.2*",
  "DC": [{
      "A": "2.4"
    },
    {
      "B": "2.61"
    },
    {
      "C": "2.46"
    },
    {
      "D": "2.25"
    },
    {
      "E": "2.11"
    },
    {
      "F": "3.75"
    },
    {
      "G": "2.08"
    },
    {
      "H": "2.17"
    },
    {
      "I": "1.85"
    },
    {
      "J": "2.57"
    },
    {
      "K": "2.42"
    }
  ]
}];

tbl_ss564_ib_jsonData[0].DC.forEach(function(d, i) {
  for (var key in d) {
    tbl_ss564_ib_jsonData[0][key] = d[key];
  }
});

delete tbl_ss564_ib_jsonData[0].DC;

var sortAscending = true;
var tbl_ss564_ib = d3.select('#ss564_ib_page_wrap').append('table');
var title_ss564_ib = d3.keys(tbl_ss564_ib_jsonData[0]);
var header_ss564_ib = tbl_ss564_ib.append('thead').append('tr')
  .selectAll('th')
  .data(title_ss564_ib).enter()
  .append('th')
  .text(function(d) {
    return d;
  })
  .on('click', function(d) {
    header_ss564_ib.attr('class', 'header');

    if (sortAscending) {
      rows.sort(function(a, b) {
        return b[d]  a[d];
      });
      sortAscending = true;
      this.className = 'des';
    }

  });

var rows = tbl_ss564_ib.append('tbody').selectAll('tr')
  .data(tbl_ss564_ib_jsonData).enter()
  .append('tr');
rows.selectAll('td')
  .data(function(d) {
    return title_ss564_ib.map(function(k) {
      return {
        'value': d[k],
        'name': k
      };
    });
  }).enter()
  .append('td')
  .attr('data-th', function(d) {
    return d.name;
  })
  .text(function(d) {
    return d.value;
  });
* {
  margin: 0;
  padding: 0;
}

#ss564_ib_page_wrap body {
  font: 14px/1.4 Georgia, Serif;
}

#ss564_ib_page_wrap {
  margin: 20px;
}

p {
  margin: 20px 0;
}

/*
 Generic Styling, for Desktops/Laptops
 */

#ss564_ib_page_wrap table {
  width: 100%;
  border-collapse: collapse;
}

/* Zebra striping */

#ss564_ib_page_wrap tr:nth-of-type(odd) {
  background: #eee;
}

#ss564_ib_page_wrap th {
  background: Teal;
  font-weight: bold;
  cursor: s-resize;
  background-repeat: no-repeat;
  background-position: 3% center;
}

#ss564_ib_page_wrap td,
th {
  padding: 6px;
  border: 1px solid #ccc;
  text-align: left;
}

#ss564_ib_page_wrap th.des:after {
  content: "\21E9";
}

#ss564_ib_page_wrap th.aes:after {
  content: "\21E7";
}


text:
Q: linq GroupBy difficulty I am having a list myTask, in which I want to do a group by Date and calculate the total per date on the Amount.
How can I do that?
public class Task{
public DateTime Date{get;set;}
public string Item {get;set;}
public decimal Amount {get;set;}
}

 public List<Task> taskList{ get; set; }

A: I suspect you want:
var totals = taskList.GroupBy(x => x.Date)
                     .Select(g => new { Date = g.Key,
                                    Total = g.Sum(x => x.Amount) });

Or in one go:
var totals = taskList.GroupBy(x => x.Date, (date, values) =>
                                 new { Date = date,
                                       Total = values.Sum(x => x.Amount) });

Note that this is assuming the Date property really is a date rather than a timestamp. Otherwise you might want x => x.Date.Date as the first argument.
If this isn't what you're after, please say how it differs from what you want.
EDIT: Okay, if you want the items as well - but presumably not the date with each item - you can write:
var totals = taskList.GroupBy(x => x.Date, (date, values) =>
                       new { Date = date,
                             Total = values.Sum(x => x.Amount),
                             Items = values.Select(x => x.Item).ToList(),
                             Amounts = values.Select(x => x.Amount).ToList() });


text:
Q: My CSS is not being applied to my html, how do i fix it? So i have this weird problem that any css i write doesn't work. I tried to create multiple pages and link css but it simply doesn't apply.
If i download a template of the internet if i run the page, their html works.
Here is an example of the most basic code i've written that doesn't work, even though i've run it through validators. It doesn't matter what element im trying to apply styling to it doesn't work.
HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title> Test Page </title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1> Sup! </h1>
</body>
</html>

CSS
body {
    font-size: 16px;
    color: #fff;
    background-color: #61122f;
}

I have tried numerous solutions i've found online, but none of them work.

A: Can you check your network tab that your style.css is fetched from server and there is no 404 not found.
I would say try "/styles.css"

A: 1. Check your Devtool, see if any error in network, make sure that style.css successfully loaded.
2. Try - Importing External Style Sheets
Write in html head tag:
<style>
    @import url("css/style.css");
    p {
        color: blue;
        font-size: 16px;
    }
</style>

A: This could be because of the folder structure. So maybe try and make sure your html file and css file are on the same level.
Or you could try "../styles.css" - Again this depends on where your files are in your dir

A: Everyone has given almost everything that I know. Sometimes its the silly things that we missed out that gives us tough time. Do try and follow this:

*

*make sure both the html and css are under the same folder, in my case the folder is named "ROUGH"

*Check for any white spaces before and after the file name. Example: "style " has one white space after the name, it should just be "style"

*Using "/" inside the href. Example below href = "/style.css"

A: So, finnaly figured it out. The encoding was set to utf-16 and everything rendered as chinese kanji. This is the problem solution. Stylesheet taken-over/replaced by Chinese characters


text:
Q: resources for image analysis of test sheets (Choice test) (Scanned pictures)? I'm developing and application for a learning company. I need to image analysis of Test sheet (scanned) and analysis the answer of students.
  Answer sheets are like this picture :

there are 4 options for every test.
I think there is components ready for that. I searched a lot and find different image processing stuffs but nothing about this one.
Where can I find tutorial or information or component for this? I mean any good website or source to start learning the solutions?
I'm using Delphi but I can change it to C# if it is Necessary.

A: Step 1: use edgedetector like Canny to detect the edges...use findContour to select the largest block as shown in green below...make that the region of interest or ROI for future processing..
Step 2: Take TWO template of the square (where students are supposed to tick or darken)..one representing ticked/darkened other one just a blank square...run a template matching of those two templates in the ROI to get possible positions of the answers.
Step 3: since the layout of the answer sheet is supposed to be constant so you can grid the answer sheet before and use it as prior knowledge to map the template match locations to actual answers.


text:
Q: React/React Native viewableItems destructuring question This is React/React Native but the question I feel is related to JavaScript. Anyway, this is what I have:
onViewableItemsChanged={({ viewableItems }) => {
    if (viewableItems.length > 0) {
        setActiveIndex(viewableItems[0].index || 0)
    }
}}

Here, viewableItems is something that is destructured. We can access it because we are working with onViewableItemsChanged. But when I move this function elsewhere, such as:
onViewableItemsChanged={onFlatlistUpdate}

const onFlatlistUpdate = useCallback(({ viewableItems }) => {
    if (viewableItems.length > 0) {
        setActiveIndex(viewableItems[0].index || 0)
    }
}, [])

I dont get where viewableItems is from? I mean in the first example, it is destructured from the context of onViewableItemsChanged. However in the second example, it is completely independent, away from onViewableItemsChanged (of course we are using useCallback but it does not matter) so how come we have access to it?
TL DR: In the 2nd example (onFlatlistUpdate), where is viewableItems destructured from/how come we have access to viewableItems?

A: In both examples, you're passing a function to the onViewableItemsChanged prop. In the first case, you're creating an anonymous function inline, and that function reference is passed to onViewableItemsChanged. In your second case, you're creating a function withuseCallback() which you're then passing to onViewableItemsChanged (the function returned by useCallback() will forward any of the arguments it's passed to the function you give it). Internally, the FlatList component with the onViewableItemsChanged prop will call that function and pass an object with viewableItems, such as onViewableItemsChanged({viewableItems: ...}). This allows you to destructure the object within the function you've passed to your FlatList component.

I mean in the first example, it is destructured from the context of
onViewableItemsChanged

onViewableItemsChanged doesn't really have a "context". onViewableItemsChanged is just a prop that you pass a function to. How that function is then called within FlatList determines the arguments of the function. That's handled by the internals of FlatList component which you don't need to worry much about. You can create that function independently, or create it inline, in both cases, you're passing a function reference to onViewableItemsChanged that can be called by FlatList.
Take the following example code using vanilla JS, as we pass a callback function to another function for it to be invoked. It doesn't matter if we define the function as standalone or inline, all the really matters is that we end up passing a function to myFlatList:

const myFlatList = (onViewableItemsChanged) => {
  onViewableItemsChanged({viewableItems: [1, 2, 3]});
}

// Defining the callback function inline
myFlatList(({viewableItems}) => {
  console.log("inline", viewableItems);
});

// Similar to your `useCallback()` definition
const callbackFn = ({viewableItems}) => {
  console.log("independent", viewableItems);
}
myFlatList(callbackFn);