text:
Q: how to do this , append html to other dropdown? I will make it in simple way I want to "return" in the if that inside if
if(condition){
    ...
       if(another_condition)
         {
           ...
               return;//I want this "return" return from the first if also
         }
}

actually I have complex script for me to do , I have liste of content like this generated from document docx...:
chapitre1
I. title1
   1)subtitle1
   2)subtitle2
II.title2
  1)subtitle1
  2)subtitle2
  3)subtitle3
chapitre2
I.title1
  etc
first I want to separate the grand title for each chapter with dropdown hover style.
I want the script to append the content of each chapter in other dropdown and each grand title to another sub dropdown like dropdown hover style
enter image description here

A: I'm going to guess you don't really mean return, you just want to break out of the body of the outer if.
Don't do that. Instead, either:

*

*Use else, putting all the rest of the body of the outer if's block in the else block, or

*Break up your logic into smaller pieces, wrap them in functions, and then combine those functions. That typically removes the need for this kind of convoluted logic.
else example:
if (someCondition) {
    doThis();
    if (someOtherCondition) {
        doThat();
    } else {
        doSomethingElse();
    }
}

Live Example:

function doThis() { console.log("doThis"); }
function doThat() { console.log("doThat"); }
function doSomethingElse() { console.log("doSomethingElse"); }

function foo(someCondition, someOtherCondition) {
    if (someCondition) {
        doThis();
        if (someOtherCondition) {
            doThat();
        } else {
            doSomethingElse();
        }
    }
    console.log("foo done");
}

console.log("foo(true, false):");
foo(true, false);
console.log("foo(true, true):");
foo(true, true);

Having said that: JavaScript does actually let you use a directed break in if statements, unlike many other languages. So you could do:
// REALLY BAD PRACTICE
outer:
if (someCondition) {
    doThis();
    if (someOtherCondition) {
        doThat();
        break outer;
    }
    doSomethingElse();
}

In that, if both someCondition and someOtherCondition are true, doSomethingElse will never be called.
Live Example:

function doThis() { console.log("doThis"); }
function doThat() { console.log("doThat"); }
function doSomethingElse() { console.log("doSomethingElse"); }

function foo(someCondition, someOtherCondition) {
    outer:
    if (someCondition) {
        doThis();
        if (someOtherCondition) {
            doThat();
            break outer;
        }
        doSomethingElse();
    }
    console.log("foo done");
}

console.log("foo(true, false):");
foo(true, false);
console.log("foo(true, true):");
foo(true, true);

But....don't do that. :-)

A: If you want to return the result of the function you're inside of, just use 'return' like normal.
If you want to avoid executing the rest of the code inside the first if, you could set up an external variable, something like:
if (first condition) {
    var continue = true;
    if (second condition) {
        ...
        continue = false;
    }

    if (continue) {
        ....
    }
}


text:
Q: Check urls (strings) I have some troubles in parsing urls as strings. i need to check if urls belongs to domains in whitelist, but the check is miserably failing. I woulf like to understand the reason and if my code is lacking.
whitelist = []
whitelist_file = open(whitelist_file, 'r')
url = whitelist_file.readline()
for url in whitelist_file:
    whitelist = whitelist + [str(url)]
whitelist_file.close()

test_file = open(test_file, 'r')
url_to_check = test_file.readlines()

for url in url_to_check:
    for word in whitelist:
        print(str(word), str(url), word in url)
        print("-----")

this is the printout of what above (so you have samples of the checked strings). You can see the it fails for a2a.eu
a2a.eu
 https://www.medgadget.com/2017/10/adenosine-a2a-receptor-antagonist-pipeline-insights-2017.html
 False
-----
ansa.it
 https://www.medgadget.com/2017/10/adenosine-a2a-receptor-antagonist-pipeline-insights-2017.html
 False
-----
atlantia.it
 https://www.medgadget.com/2017/10/adenosine-a2a-receptor-antagonist-pipeline-insights-2017.html
 False
-----
azimut-group.com
 https://www.medgadget.com/2017/10/adenosine-a2a-receptor-antagonist-pipeline-insights-2017.html
 False
-----
a2a.eu
 https://www.a2a.eu/en/2017-financial-calendar-a2a-spa
 False
-----
ansa.it
 https://www.a2a.eu/en/2017-financial-calendar-a2a-spa
 False
-----
atlantia.it
 https://www.a2a.eu/en/2017-financial-calendar-a2a-spa
 False
-----
azimut-group.com
 https://www.a2a.eu/en/2017-financial-calendar-a2a-spa
 False
-----
a2a.eu
 http://www.a2a.eu/en
 False
-----
ansa.it
 http://www.a2a.eu/en
 False
-----
atlantia.it
 http://www.a2a.eu/en
 False
-----
azimut-group.com
 http://www.a2a.eu/en
 False

thanks

A: Firstly, according to your output for some of the cases this check should produce a True result. That is really just judging by the output print. My suspicion is that your url or word (in whilelist) are not the string objects that you think they are; try to convert to str in your print statement as
  print(str(word), str(url), str(word) in str(url))

additionally you seem to just to check for the domain, have a look at urllib https://docs.python.org/3/library/urllib.html, where you can dissect the url into the domain part only and check against it:
  from urllib.parse import urlparse
  print(str(word), str(url), str(word) in urlparse(str(url)).hostname

A: Your URL in line 5 contains the newline character. Call strip() and that should fix it:
whitelist = []
whitelist_file = open(whitelist_file, 'r')
url = whitelist_file.readline()
for url in whitelist_file:
  whitelist = whitelist + [str(url.strip())]
  whitelist_file.close()

test_file = open(test_file, 'r')
url_to_check = test_file.readlines()

for url in url_to_check:
  for word in whitelist:
    print(str(word), str(url), word in url)
    print("-----")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete Button not working with json server using angularjs I am doing angular crud operation using JSON server, post and get are working properly but delete is not working DELETE /posts1 404. My code is as follows -
deleteEmployee(id : number){
    return this.http.delete<any>("http://localhost:3000/posts"+id)
    .pipe(map((res:any)=>{
      return res;
    })

DELETE http://localhost:3000/posts1 404 (Not Found)

A: fix url
 return this.http.delete<any>("http://localhost:3000/posts/"+id)

or maybe
 return this.http.delete<any>("http://localhost:3000/posts?id="+id)


text:
Q: "The process cannot access the file" error in Winforms in C# I made an .sdf file (SQL CE) from an XML file. When the file is ready, I want to attach it to an e-mail. But when I try to attach it, I get this error:
The process cannot access the file......because it is being used by another process

How can I fix it?

A: Do you have an SqlCeConnection open on the file? Is it open in Visual Studio?
I suggest you use Process Explorer so you can identify the process which has a handle on it.

A: I'm guessing that because SQLCE databases are run in-proc with your program that you can't get exclusive access to the file while your program is running.


text:
Q: Solana installation failure with curl: (23) Failure writing output to destination When following the Solana tool suite installation guide I got the following error which says curl: (23) Failure writing output to destination.
sh -c "$(curl -N -sSfL https://release.solana.com/v1.9.4/install)"

downloading v1.9.4 installer
curl: (23) Failure writing output to destination
solana-install-init: command failed: downloader http://release.solana.com/v1.9.4/solana-install-init-x86_64-unknown-linux-gnu /tmp/tmp.mbRp5X2BUn/solana-install-init

A: According to the previously asked question about curl: (23) Failure writing output to destination it seems like there is an issue with the script which at least I don't want to change myself to install Solana. Why does cURL return error "(23) Failed writing body"?
When I tried to read the Solana installation script I found that alternatively I can use wget to install Solana which I decided to use instead of curl. There are two steps you have to follow in order to get it fixed.

*

*Uninstall curl from your system temporarily sudo snap remove curl.

*Execute sh -c "$(wget https://release.solana.com/v1.9.4/install)" instead of the given command in the Solana tool suite page.

Once you install you have to update your path to add solana, you can do it by adding the following line to the ~/.bashrc file. (Make sure you update the path)
export PATH="/home/{user}/.local/share/solana/install/active_release/bin:$PATH"

A: I had the same problem and the problem for me was that I installed curl via sudo snap install curl . So I tried:

*

*removing curl using sudo snap remove curl and went with the comment above, using "wget" wich did not work for me.

*Then i tried reinstalling curl with sudo apt  install curl and then finally

*sh -c "$(curl -sSfL https://release.solana.com/v1.10.29/install)"
And it worked like a charm. I hope this helps someone!


text:
Q: How to draw without lines in between nodes []
Hi I'm trying to draw the image below without the line going through the nodes but I can't seem to figure it out. Below is the code.
\documentclass[12pt,a4paper,top=1in,bottom=1in,left=1.5in,right=1.5in,margin=1.5in]{article}
\usepackage{tikz}
\usetikzlibrary{automata}

\begin{tikzpicture} [scale = 0.4]
\tikzstyle{vertex} = [circle, fill = black!10]
\tikzstyle{edge} = [thick]

\node[vertex](v1) at (0,0){1};
\node[vertex](v2) at (3,0){2};
\node[vertex] (v3) at (6,0) {3};
\node[vertex](v4) at (9,0){4};
\node[vertex](v5) at (12,0){5};
\node[vertex](v6) at (15,0){6};
\node[vertex](v7) at (18,0){7};
\node[vertex](v8) at (21,0){8};
\node[vertex](v9) at (24,0){9};
\node[vertex](v10) at (27,0){10};
\node[vertex](v11) at (30,0){11};
\node[vertex](v11) at (33,0){12};
\node[vertex](v13) at (36,0){13};

\draw [edge](v1) --(v13);

\path
(v1) edge [bend left] node {} (v13)
(v3) edge [bend left] node {} (v11)
(v5) edge [bend left] node {} (v8)

\end{tikzpicture}
\end{document}

A: See if the following solution works for you:
\documentclass[12pt,a4paper]{article}
\usepackage{geometry}

\usepackage{tikz}
\usetikzlibrary{chains,
                positioning
                }

\begin{document}
\begin{figure}
\centering
    \begin{tikzpicture}[
node distance = 5mm,
  start chain = A going right,   % <---
vertex/.style = {circle, fill=gray!30,
                 minimum size=1.3em, inner sep=0pt,
                 font=\small\bfseries,
                 on chain=A, join = by arr,
                 },
   arr/.style = {-, semithick},
                       ]
    \foreach \i in {1,...,13}
\node[vertex]   {\i};
%
\path[arr, bend left=45]
    (A-1) edge  (A-13)
    (A-3) edge  (A-11)
    (A-5) edge  (A-8);
    \end{tikzpicture}
\end{figure}
\end{document}

Note:

*

*for positioning of nodes are used chains and positioning packages

*nodes names is defined by start chain = A going right; so the first node name is A-1 and the last in your case is A-13

*distances between nodes are determined by node distance; it define distance between nodes' borders

*lines between nodes are draw by the chains package macro join.

*in your document class options you have a mess, for page layout is added the `geometry˙ package


text:
Q: how To Improve that ComplexPlot3D I have in mind the result of
ComplexPlot3D[Log[MittagLefflerE[1/2, z]],{z, -50 - 50*I, 50 + 50*I},
PlotPoints -> 300,PlotRange -> All]

In particular, the plot should be seen over the whole quadrat.
Addition 1. Up to @J.M. is away sugestion,
ComplexPlot3D[Log[MittagLefflerE[1/2, z]], {z, -50 - 50*I, 50 + 50*I},
   PlotPoints -> 300, PlotRange -> All,   WorkingPrecision -> 25] // AbsoluteTiming

{874.714, }
Addition 2. The command
ComplexPlot3D[MittagLefflerE[1/2, z], {z, -50 - 50*I, 50 + 50*I},PlotRange -> All]

performs an empty plot.
Addition 3. Following another suggestion by @J. M. will be back soon,
ComplexPlot3D[Log[MittagLefflerE[1/2, z]], {z, -50 - 50*I, 50 + 50*I},
 PlotPoints -> 300, PlotRange -> {0, 200}, WorkingPrecision -> 30]

A: The branch cut structure here is very dense, which can be very hard for plotters to pick up.
Here are the cuts in a part of your domain:
Quiet @ Show[
  ComplexPlot[
    Log[MittagLefflerE[1/2, z]], {z, 0, 20 + 20 I},
    Exclusions -> None, ColorFunction -> {Automatic, None}, ImageSize -> Large
  ],
  ContourPlot[
    Im[E^(x + I y)^2 Erfc[-x - I y]] == 0,
    {x, 0, 20}, {y, 0, 20},
    RegionFunction -> Function[{x, y, f}, Re[E^(x + I y)^2 Erfc[-x - I y]] <= 0],
    PlotPoints -> 200, MaxRecursion -> 1, ContourStyle -> Black
  ]
]

We can turn these off with Exclusions -> None:
ComplexPlot3D[
  Log[MittagLefflerE[1/2, z]],
  {z, -50 - 50*I, 50 + 50*I},
  Exclusions -> None,
  NormalsFunction -> None,
  PlotRange -> All,
  WorkingPrecision -> 25
]


text:
Q: Laravel union within model functions Hello i am new here and not a native English speaker so please forgive me for any mistakes on my grammar and on my question formatting.
I am building an app with php using laravel framework 5.4 version.
The web app is very simple its for reviewing articles and users that posts articles.
I would like to learn how i can union the results of the functions within my model.
I want the allReviews function from user model to return the reviews the user has mixed with the reviews his articles have orderby createdtime.
let me explain better.
here is my 3 main tables:
Users     | Articles  | Reviews
--------- | --------- | ---------
id        | id        | id
name      | user_id   | reviewable_id
email     | title     | reviewable_type
password  | body      | reviewtext
etc..     | etc..     | created_time

and here is my models code :
class User extends Model{

    protected $table = 'users';

    public function articles()
    {
        return $this->hasMany(Article::class,'user_id');
    }

    public function reviews(){
        return $this->morphMany(Review::class,'reviewable');
    }

    public function allReviews(){
        /*
         i want union something like this:

        $result = $this->reviews() union
        foreach ($this->Articles() as $Article) {
            union $Article->reviews();
        }
        orderby created_time ASC or DESC doesn't matter

        return $result
        */
    }
}

class Article extends Model{

    protected $table = 'articles';

    public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }

    public function reviews(){
        return $this->morphMany(Review::class,'reviewable');
    }
}

class Review extends Model{

    protected $table = 'reviews';

    public function reviewable(){
        return $this->morphTo('reviewable');
    }
}

So my question is how i can do the function allReviews from user to work ?
Any help is appreciated :)
Thank You

A: Calling the $user->reviews property will return all reviewable models. You don't have to UNION anything, Eloquent will take care of that for you.
Try this:
public function allReviews(){
    $reviews = new \Illuminate\Database\Eloquent\Collection;

    foreach($this->articles as $article)
    {
        $reviews = $reviews->merge($article->reviews);
    }

    $reviews = $reviews->merge($this->reviews);

    return $reviews;
}

I'm really tired now and I have a feeling you might get the N+1 query problem situation here but it should work for you.


text:
Q: How to get a Struct's value inside a Dictionary Newbie programmer here!
I want to get nested structs' value inside a dictionary but I can't reach inside the dictionary.
This is my struct
struct Forecast: Decodable {
    let cod: String
    let message: Int
    let cnt: Int
    let list: [List]
    let city: City
}

struct List: Decodable {
    let dt: Int
    let main: Main
    let weather: [Weather]
    let clouds: Clouds
    let wind: Wind
    let sys: Sys
    let dt_txt: String

    private enum CodingKeys: String, CodingKey {
        case dt, main, weather, clouds, wind, sys, dt_txt = "dt_txt"
    }
}

struct Main: Decodable {
    let temp: Double                           // I want to get this!
    let feels_like: Double
    let temp_min: Double
    let temp_max: Double
    let pressure: Int
    let sea_level: Int
    let grnd_level: Int
    let humidity: Int
    let temp_kf: Double
}

I tried to reach it as struct syntax but couldn't make it:
self.tempLbl.text = "\(Int(round(weather.list.main.temp)) - 273)°"
// Value of type '[List]' has no member 'main'

Thank you!

A: Sorry for my dumb question, I feel really bad for asking this..
I am able to reach my destination with this:
self.tempLbl.text = "\(Int(round(weather.list[1].main.temp)) - 273)°"
// weather.list[1].main.temp


text:
Q: How to loop through data so insert each bigquery row Node.js In this function, it is taking cron times (expected start time) from one bigquery table (expected_sla) parsing it and the end time from that same table and inserting those two into 2 fields called expected start date and expected end time fields in the sla_table table. I want it to where it checks the dag_id and depending on the dag id insert the parsed expected start time and expected end time. Right now its just creating new rows on bigquery with these 2 dates and having all the other fields as null. I want it to where it will loop through and insert the appropriate expected start time and end time for each dag depending on the dag_id.
BigQuery table screenshot

(async function () {
    const runs = [
        {
            start_date: '2022-06-26T23:00:00.742495+00:00',
            end_date: '2022-06-27T14:10:23.108401+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-06-25T23:00:00+00:00',
            dag_id: 'EFS-Winning-Route-daily-batch'
        },
        {
            start_date: '2022-07-07T21:20:00.566888+00:00',
            end_date: '2022-07-07T23:20:55.250911+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-07-06T21:20:00+00:00',
            dag_id: 'ft-parm-trumping-daily'

        },
        {
            start_date: '2022-07-03T14:00:00.779718+00:00',
            end_date: '2022-07-03T14:00:41.250433+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-06-26T14:00:00+00:00',
            dag_id: 'ft-parm-trumping-weekly'
        },
        {
            start_date: '2022-07-08T04:00:01.038023+00:00',
            end_date: '2022-07-08T05:08:59.597408+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-07-07T04:00:00+00:00',
            dag_id: 'IP_MASTER'
        },
        {
            start_date: '2022-07-08T13:45:00.757997+00:00',
            end_date: '2022-07-08T14:02:48.050405+00:00',
            state: 'success',
            dag_run_id: 'scheduled__2022-07-07T13:45:00+00:00',
            dag_id: 'IPP_CYCLE_PARMS'
        },
        {
            start_date: '2022-07-08T02:00:00.821824+00:00',
            end_date: '2022-07-08T02:02:06.027268+00:00',
            state: 'success',
            dag_run_id: 'scheduled__2022-07-07T02:00:00+00:00',
            dag_id: 'ipp-daily-backups'
        },
        {
            start_date: '2022-07-07T23:00:01.313332+00:00',
            end_date: '2022-07-07T23:02:37.032427+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-07-06T23:00:00+00:00',
            dag_id: 'oclt-leadtime-daily'
        },
        {
            start_date: '2022-07-08T13:00:00.471935+00:00',
            end_date: '2022-07-08T13:00:49.819534+00:00',
            state: 'success',
            dag_run_id: 'scheduled__2022-07-07T13:00:00+00:00',
            dag_id: 'ope-metrics'
        },
        {
            start_date: '2022-07-07T21:30:00.682954+00:00',
            end_date: '2022-07-07T21:33:29.885878+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-07-06T21:30:00+00:00',
            dag_id: 'parm-lite-daily'
        },
        {
            start_date: '2022-07-08T08:00:01.756909+00:00',
            end_date: '2022-07-08T08:35:55.043131+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-07-07T08:00:00+00:00',
            dag_id: 'parm-lite-data-migration'
        },
        {
            start_date: '2022-07-03T09:00:00.825694+00:00',
            end_date: '2022-07-03T09:10:31.680879+00:00',
            state: 'failed',
            dag_run_id: 'scheduled__2022-06-26T09:00:00+00:00',
            dag_id: 'parm-lite-sunday-push-instance'
        }
    ];

async function determineStartEnd(result){
    dagID = result ? result.dag_id : 0
    console.log(dagID)
    job = await bqConnection().query(`SELECT * FROM \`np-inventory-planning-thd.IPP_SLA.expected_sla\` where dag_id = "${dagID}"`)
    cronTime = job[0][0].cron_time
    endTime = job[0][0].expected_end_time
    var interval = parser.parseExpression(cronTime);
    const d = new Date(interval.next().toString()).toISOString()
    //var timeStamp = d.getTime();
    //const parts = interval.next().toString().split(' ');
    expectedStartDate = d
    console.log(d);
    console.log(endTime)
}
        const date = {expected_start_date:expectedStartDate,expected_end_date:endTime}
        for (let run of runs) {
            await determineStartEnd(run);
            await bqConnection()
                .dataset('IPP_SLA')
                .table('sla_table')
                .insert(date);
        }
}

)
();

A: From what I understand, your table contains values for the espected_start_date & expected_end_date. The other fields all contain NULL values.
Try the below code changes:
        //const date = {expected_start_date:expectedStartDate,expected_end_date:endTime}
        for (let run of runs) {
            await determineStartEnd(run);
            run['expected_start_date'] = expectedStartDate;
            run['expected_end_date'] = endTime;
            await bqConnection()
                .dataset('IPP_SLA')
                .table('sla_table')
                .insert(run);
        }


text:
Q: Generating RSA keys from a master password Is there a simple and deterministic way to generate a RSA key pair (private and public) based on a user's master password?
Imagine an encrypted messenger application. Here the user wants to login on different devices using his password, and always have the same private and public key for sending and receiving messages. So the keys should be only dependent on the password.


text:
Q: how cereal load or save XML attribute I'm trying to save/load XML file use cereal, but can not figure out how to save/load XML attribute. For example:
I have a XML file:
<windows height="101", width = "200"/>

and a struct
struct window
{
    int height;
    int width;
}

how can i define serialize function to load/save XML attribute value using cereal?

A: cereal is not a general purpose XML parser. The XML archive that comes with cereal expects to be reading in XML that it itself generates, or at the very least XML in an identical format to what it expects.
For your example, cereal would expect as input:
<?xml version="1.0" encoding="utf-8"?>
<cereal>
    <windows>
        <height>101</height>
        <width>200</width>
    </windows>
</cereal>

To get the behavior you desire you would need to modify the XML archive or create your own archive.


text:
Q: How to use server side observers in a multi server environment? I've recently added another server to my app and placed an Nginx load balancer in front of them. So a load balancer, and two servers running the same app. This is all very new to me, and I'm running into issues I wouldn't have in a single server environment. One of them is that the server side observers on the app run on BOTH servers, which is undesirable. For example, I'll have the following observer.
                var initializing = true;
                Jobs.find({
                    $or: [{
                        processed: {
                            $ne: true
                        }
                    }, {
                        restart: true
                    }]
                }).observeChanges({
                    added: function(id, doc) {
                        if (!initializing) {
                            // do stuff
                        }
                    }
                });
                initializing = false;

Which then runs on both servers. I only want it to run on one - I don't care which one, but I guess the one that the user is currently on makes sense. What are some of my options? I wouldn't think this is an uncommon scenario but I wasn't able to find anything online. My current workaround is to remove the observers off the servers, and have a THIRD server that does all of the observing. However, this won't scale if my app takes off, which obviously I hope it does. Thanks for any help.

A: I'll present two possible solutions to this problem: designated master, and dynamic master.
Designated Master
In this strategy, we'll elect a single server to act as the "master" for the job task. There are a variety of ways you can do this, but as @sbking suggested above, using an environment variable is probably the easiest. On one of you servers, set a variable like MASTER_SERVER=1. On all servers you can check for the existence of said variable, and run the task only if it's set. For example:
server A start script
export PORT=3000
export ROOT_URL=https://app.example.com
export MASTER_SERVER=1
forever start /path/to/your/bundle/main.js

server B start script
export PORT=3000
export ROOT_URL=https://app.example.com
forever start /path/to/your/bundle/main.js

server/main.js
if (process.env.MASTER_SERVER) {
  Jobs.find(...).observeChanges(...);
}

Because only A was started with MASTER_SERVER set, it will be the only server to perform the task. While this strategy is simple to implement, it has one critical flaw - it isn't fault tolerant. If A were to fail, the task would not continue to run.
Dynamic Master
Rather than pre-designating a master, an alternative approach is for each server to attempt to become the master at regular intervals. This strategy works well if you can convert you task into something that looks like a cron job. Then you need only use synced-cron which will ensure that only one server can execute the task during that interval. In this example, each server will attempt to run the task every minute:
server/main.js
SyncedCron.add({
  name: 'Process all the things!',
  schedule: function(parser) {
    return parser.text('every 1 mins');
  },
  job: function() {
    // do job processing here
    return true;
  }
});

SyncedCron.start();

This is a more robust solution, however you would need to decide if checking the Jobs collection at regular intervals (rather than observing its changes) fits your use case.

A: As you mentioned you are using nginx. Nginx can do server affinity on the upstream module. This will make sure that each client will hit the same server. The are many disadvantages to server affinity but meteor lends it self to using server affinity.
upstream backend {
    server backend1.example.com;
    server backend2.example.com;

    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

There are other methods with nginx. above is the cookie method, but could use route or learn
http://nginx.org/en/docs/http/ngx_http_upstream_module.html


text:
Q: How to expose port 22 via NGINX Ingress Controller? I have a Kubernetes Cluster with a NGINX Ingress Controller. In the cluster I have deployed a Gitea POD. The Web UI and the HTTPS access is exposed via an Ingress object like this one:
---
kind: Service
apiVersion: v1
metadata:
  name: gitea-service
  namespace: gitea-repo
spec:
  selector:
    app: gitea
  ports:
  - name: gitea-http
    port: 3000
  - name: gitea-ssh
    port: 22
---
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: git-tls
  namespace: gitea-repo
  annotations:
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
  tls:
  - hosts:
    - git.foo.com
    secretName: tls-gitea
  rules:
  - host: git.foo.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: gitea-service
            port:
              number: 3000

This works all fine for HTTPS.
But Gitea also provides a SSH access through port 22. My Question is, how can I tell the NGINX Ingress Controller to route also port 22 to my pod?
As far as I understand I should patch my NGINX controller deployment with something like that:
spec:
  template:
    spec:
      containers:
      - name: controller
        # defind cusotm tcp/udp configmap
        args:
        - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-configmap-giteassh

        ports:
         - name: ssh
           containerPort: 22
           protocol: TCP

and providing a config map pointing to my gitea service:
apiVersion: v1
kind: ConfigMap
metadata:
  name: tcp-configmap-giteassh
  namespace: ingress-nginx
data:
  22: "gitea-repo/gitea-service:22"

Do I need also an additional Ingress configuration in my Gitea POD now?
I wonder if this is the correct approach. Why I am forced to define this in the NGINX controller and not in my POD namespace as I do for HTTP? This would mean that for each POD exposing a TCP port other than HTTP I have to adjust my Ingress NGINX Controller?

A: I decided to improve my answer by adding more details and explanations.
I found your blog post which contains all the information I need to reproduce this problem.
In your example you need TCP traffic to pass through on port 22 (it is TCP protocol).
NGINX Ingress Controller doesn't support TCP protocol, so additional configuration is necessary, which can be found in the documentation.
You can follow the steps below to expose the TCP service:

*

*Create a ConfigMap with the specified TCP service configuration.

*Add the --tcp-services-configmap flag to the Ingress controller configuration.

*Expose port 22 in the Service defined for the Ingress.

Ad 1. We need to create a ConfigMap with the key that is the external port to use and the value that indicates the service to expose (in the format <namespace/service name>:<service port>:[PROXY]:[PROXY]).
NOTE: You may need to change Namespace depending on where the NGINX Ingress controller is deployed.
$ cat ingress-nginx-tcp.yml
apiVersion: v1
kind: ConfigMap
metadata:
  name: ingress-nginx-tcp
  namespace: default
data:
  "22": gitea-repo/gitea-service:22

Ad 2. After creating the ConfigMap, we can point to it using the --tcp-services-configmap flag in the Ingress controller configuration.
NOTE: Additionally, if you want to use a name (e.g. 22-tcp) in the port definition and then reference this name in the targetPort attribute of a Service, you need to define port 22 (see: Defining a Service documentation).
$ kubectl get deployment ingress-nginx-controller -oyaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ingress-nginx-controller
  namespace: default
spec:
...
  template:
...
    spec:
      containers:
      - args:
        - /nginx-ingress-controller
        - --tcp-services-configmap=$(POD_NAMESPACE)/ingress-nginx-tcp
...

Ad 3. Then we need to expose port 22 in the Service defined for the Ingress.
$ kubectl get svc -oyaml ingress-nginx-controller
apiVersion: v1
kind: Service
metadata:
  name: ingress-nginx-controller
  namespace: default
spec:
  ports:
  - name: 22-tcp
    nodePort: 30957
    port: 22
    protocol: TCP
    targetPort: 22
...
  type: LoadBalancer
...

Finally, we can check if it works as expected by creating a new repository on the command line:
Note: We need to have a gitea user with the proper SSH keys associated with this account.
$ git add README.md
$ git commit -m "first commit"
[master (root-commit) c6fa042] first commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README.md
$ git remote add origin git@<PUBLIC_IP>:<USERNAME>/repository.git
$ git push -u origin master
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 211 bytes | 211.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: . Processing 1 references
remote: Processed 1 references in total
To <PUBLIC_IP>:<USERNAME>/repository.git
 * [new branch]      master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

In addition, we can log to the NGINX Ingress Controller Pod and check if it is listening on port 22:
$ kubectl exec -it ingress-nginx-controller-784d4c9d9-jhvnm -- bash
bash-5.1$ netstat -tulpn | grep 22
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 :::22                   :::*                    LISTEN      -


text:
Q: read a string from the file till we get '\n' character or EOF in c/c++ I want to open two files and and save those strings into third file which are present in the first file but not in the second file.
for that i have to read line by line string (i.e till i arrive at the next line character).
But for the last line of the file i don't have '\n' in the end because there is EOF .so, please help me in reading all the string of a file and store then in a character array..
code:-
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f1ptr,*f2ptr,*f3ptr;
f1ptr=fopen("1stfile.txt","r");
f3ptr=fopen("3rdfile.txt","w");
char arr1[100],arr2[100];
while(fscanf(f1ptr," %[^\n]",arr1)!=EOF)
    {
    f2ptr=fopen("2ndfile.txt","r");
    int flag=1;
    while(fscanf(f2ptr," %[^\n]",arr2)!=EOF)
        {
        if(strcmp(arr1,arr2) ==0)
            {
            flag=0;//flag=0 means i will not store this string into file
            }
        }
    fclose(f2ptr);
    if(flag)
        fprintf(f3ptr,"%s\n",arr1);
    }
return 0;
}

my files are as follows
1st file
 Minimum Points To Reach Destination
 Maximum Index
 Maximum of minimum for every window size
 Find Prime numbers in a range
 Largest Number formed from an Array
 Find sum of different corresponding bits for all pairs
 Rearrange an array with O(1) extra space
 Return two prime numbers
 Sorting Elements of an Array by Frequency
 A Simple Fraction
 QuickSort on Doubly Linked List
 Reorder List
 Binary Tree to DLL
 Tree from Postorder and Inorder

2nd file
 Maximum Index
 Find Prime numbers in a range
 Rearrange an array with O(1) extra space
 Return two prime numbers
 Sorting Elements of an Array by Frequency

A: Here is a solution using rewind().
f1ptr=fopen("1stfile.txt","r");
//Check f1ptr is not NULL.
f2ptr=fopen("2ndfile.txt","r");
//Check f2ptr is not NULL.
f3ptr=fopen("3rdfile.txt","w");
//Check f3ptr is not NULL.
char arr1[100],arr2[100];

while(fgets(arr1, sizeof arr1, f1ptr) )
{
    int flag=1;
    rewind(f2ptr);  //Moves file pointer to the top.
    while(fgets(arr2,sizeof arr2, f2ptr))
    {
        if(strcmp(arr1,arr2) ==0)
        {
           flag=0;//flag=0 means i will not store this string into file
           break;  //Break out of the loop if 2 files have the same line.
        }
    }
    if(flag)
       fprintf(f3ptr,"%s",arr1);  //No need to print newline. Its already there.
  }
  fclose(f1ptr);
  fclose(f2ptr);
  fclose(f3ptr);

If you do man fgets, here is a part of the description:fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.  Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.  A terminating null byte ('\0') is stored after the last character in the buffer.
So newline char gets added to the string but not EOF.

A: The following could work. If you use fgets, the last line will be add '\n'.
#include<stdio.h>
#include<string.h>
//using namespace std;
int main()
{
    FILE *f1ptr,*f2ptr,*f3ptr;
    f1ptr=fopen("1stfile.txt","r");
    f3ptr=fopen("3rdfile.txt","w");
    char arr1[100],arr2[100];

    while (fgets(arr1, 100, f1ptr) != NULL) {
        f2ptr=fopen("2ndfile.txt","r");
        int flag=1;
        while (fgets(arr2, 100, f2ptr)!=NULL) {
            if (strcmp(arr1,arr2) ==0) {
                flag=0;  //flag=0 means i will not store this string into file
            }
        }
        fclose(f2ptr);
        if (flag)
            fprintf(f3ptr,"%s",arr1);
    }

    return 0;
}


text:
Q: My program shows an error, It says that a semicolon missing import java.util.*;
public class Fact

program to find factorial numbers

{
     Scanner sc=new Scanner(System.in);
     int n;
     Fact()

an empty constructor

     {
        }

void accept()
    {
           System.out.println("Enter the number");
           n=sc.nextInt();
           System.out.println(pact(n));
        }
   **int pact(int n)**

here is where my program says that it is missing a semicolon

  (
           if(n==1)
              return 1;
           else
              return n*fact(n-1);
   }
   public static void main()
{
Fact obj=new Fact();
obj.accept();
}
}

A: Apart from the fact that
int pact(int n)
(

should be
int pact(int n)
{

You have String args[] missing as the arguments in the main method.
public static void main(String[] args){

A: Try this. Removed invalid language constructs.
import java.util.Scanner;

public class Fact {
Scanner sc = new Scanner(System.in);
int n;

Fact() {
}

void accept() {
    System.out.println("Enter the number");
    n = sc.nextInt();
    System.out.println(fact(n));
}

int fact(int n) {
    if (n == 1)
        return 1;
    else
        return n * fact(n - 1);
}

public static void main(String[] args) {
    Fact obj = new Fact();
    obj.accept();
}
}

A: After return statement you used closed curly, and no open curly is there .
You started with open parenthesis and closed with curly.
Just change that.

A: If you copied the code correctly, you need to use a { instead of ( in this part of the code.
  (
       if(n==1)
          return 1;
       else
          return n*fact(n-1);
  }

so it should be

  {
       if(n==1)
          return 1;
       else
          return n*fact(n-1);
  }


text:
Q: Java Records vs Kotlin Data Classes Java 14 offers a new feature called Records, helping to create javabeans.
I've been using Kotlin for a couple of times, and of course, Java Records remind me Data Classes.
Are they completely similar? Or are there fundamental differences between them apart from the languages syntaxes?

A: This is a great article about all those differences.
In summary:
Similarities

*

*generated methods: equals, hashCode, toString

*generated constructor

*generated getters (but Kotlin getter is called o.name, while Java uses  o.name())

*can modify the canonical constructor

*can add additional methods

Differences
Kotlin's data classes support many other little things:

data class (Kotlin)
record (Java)

copy method for easier object creation
no copy method

variables can be var or val
variables can only be final

can inherit from other non-data classes
no inheritance

can define non-constructor mutable variables
can define only static variables

Both are great for reducing the code bloat.


text:
Q: Can you create AlwaysOn in Azure (primary) with a readable secondary replica on premises? Is it possible to create the following setup using Always on?

Primary replica: in Azure
Secondary: readable replica on premises

I know usually people would create the opposite structure, but I couldn't find a documentation saying that this isn't possible.
I appreciate the help!

A: SQL Server on Azure VMs is just regular SQL Server.  So yes, this is possible.  In fact it's not any different from having the primary on-prem and the secondary in Azure.  Once you set it up you can fail over from on-prem to Azure and back.
But you'll want to understand the differences and choose between a single AG that spans on-prem and Azure, and a Distributed AG where you have replication between an on-prem AG and an Azure AG.


text:
Q: Installing and configuring postgres on ubuntu 14.04 I am trying to startup an instance of postgresql-9.4 on my ubuntu 14.04.
When I type psql, the system output below block
root@IFID:/etc/apt# psql
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
    LANGUAGE = (unset),
    LC_ALL = (unset),
    LC_PAPER = "pt_BR.UTF-8",
    LC_ADDRESS = "pt_BR.UTF-8",
    LC_MONETARY = "pt_BR.UTF-8",
    LC_NUMERIC = "pt_BR.UTF-8",
    LC_TELEPHONE = "pt_BR.UTF-8",
    LC_IDENTIFICATION = "pt_BR.UTF-8",
    LC_MEASUREMENT = "pt_BR.UTF-8",
    LC_NAME = "pt_BR.UTF-8",
    LANG = "en_US.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
root@IFID:/etc/apt#

Anyone know what my next step?

A: try this below

echo "export LC_ALL=C" >> /root/.bashrc
source /root/.bashrc

A: Postgresql makes use of several locale environment variables for the different locale categories:

*

*LC_COLLATE : String sort order

*LC_CTYPE : Character classification (What is a letter? Its upper-case equivalent?)

*LC_MESSAGES : Language of messages

*LC_MONETARY : Formatting of currency amounts

*LC_NUMERIC : Formatting of numbers

*LC_TIME : Formatting of dates and times

The environment variables are consulted in the following order until one is found to be set: LC_ALL, LC_COLLATE (or the variable corresponding to the respective category as listed above), LANG. If none of these environment variables are found to be set then the locale defaults to C.
The first error suggests that the locale doesn't appear to be properly configured on the server.
To generate the Brazilian Portugese locale use this command:
sudo locale-gen pt_BR pt_BR.UTF-8

Afterwards:
sudo dpkg-reconfigure locales

The last message says the database server isn't running. Restart it using this command:
sudo service postgresql restart


text:
Q: For what conditions on sets $A$ and $B$ the statement $A - B = B - A$ holds? The obvious response is $A = B$. But I came up with another response. I can't figure out what's my bias.
Lets say

*

*$S = A - B$

*$T = B - A$
Proving $S=T$ means proving $S \subseteq T$ and $T \subseteq S$
Let's start with $S \subseteq T$
For any $x \in S$ :

*

*$x \in A$

*$x \notin B$

if $S \subseteq T$, $x \in T$ and :

*

*$x \in B$

*$x \notin A$

There is no $x$ giving satisfaction, so $A$ and $B$ are empty.
I prove $T \subseteq S$ by symmetry
My solution is : $A = B = \emptyset$
What's wrong ?

A: Let us look at the flaw in your logic. We are given that $S \subset T$. Then, if $x \in S$, then $x \in A - B$, so $x \in A$, and $x \notin B$. But also, $x \in T$, which means that $x \in B$ and $x \notin A$. Hence, $x \in B$ and $x \notin B$, which is a contradiction. Hence, no such $x$ exists, so $S$ must be empty. Reversing the argument, we conclude that $T$ must be empty. In other words, $A \subset B$ and $B \subset A$, so $B=A$.

A: I tried your reasoning using predicate logic.  I'm posting the answer to show an alternative way of reasoning.
So, $x \in A-B$ if $x \in A$ but $x\not\in B$.  Equivalently, $x\in B-A$ if $x \in B$ but $x \not\in A$.  Thus, $A-B = B-A$ if
\begin{equation}
\forall x : ( x \in A \wedge x\not\in B \Longleftrightarrow x\not\in A\wedge x\in B )
\end{equation}
Remember $\varphi \Longleftrightarrow \psi$ means $(\varphi \wedge \psi) \vee (\neg \varphi \wedge \neg \psi )$.  But in this case, the left term of this re-written equivalence is $x \in A \wedge x\not\in B \wedge x\not\in A\wedge x\in B$ and it is obviously impossible (equal to $\bot$), so the only possibility for $x$ is
\begin{align}
  & \neg(x \in A \wedge x\not\in B) \wedge \neg(x\not\in A\wedge x\in B) \\
  =& (x \not\in A \vee x\in B) \wedge (x\in A\vee x\not\in B) \\
  =& (x \not\in A \wedge x\not\in B) \vee (x\in A\wedge x\in B) \vee (x \in A \wedge x\not\in A) \vee (x\not\in B\wedge x\in B) \\
  =& (x \not\in A \wedge x\not\in B) \vee (x\in A\wedge x\in B) \\
\end{align}
In other words, there are no $x$ such that $A$ contains $x$ but not $B$ or $B$ contains $x$ but not $A$.  That is, $A$ and $B$ have the same elements, i.e. $A=B$.


text:
Q: What order did the particles of nature appear in? in the epochs of the very early universe, the different forces separated from each other in succession. if this is true then at one point there was an electroweak force. and before that, there was the electronuclear force, and before that all four were unified.
my question is about what order the different particles of the standard model came into existence. but the question is in light of the unified nature of the forces.
how did the electroweak force behave before it split? where were w-bosons and photons at this time? where were the leptons? if the forces were "unified," were the particles unified as well? was there a boson that mediated the electroweak interaction? a boson that no longer exists?
and likewise, was there another boson that mediated the electronuclear force when the strong force was still unified with the electroweak?
i have a very rudimentary understanding, but my current framework has me thinking along these lines.
the higgs boson would had to have come first, in order for anything else to even occupy spacetime. then some sort of 4-force boson and 4-way unified fermions? then gravitons split off, leaving a 3-force boson. then the gluons split,leaving a two-force boson and quarks and leptons. and finally the w-bosons and photons separated, allowing for all the elementary and composite particles we have now.
how far off am i?
do we know what particles came in what order and during which epochs?

A: The current mainstream cosmological model is the Big Bang. The model uses our particle physics standard model  in order to project back in time, and see if the predictions fit the astrophysical observations. Here the symmetry breaking order in the BB model is summarized:

It presupposes that a unified quantum field theory exists including gravity, which is not true because gravity is not definitively quantized, only effective models exist.It gives the order of the symmetry breaking according to the existing BB model.
All the elementary particles in the standard model of particle physics are hypothesized to exist , as the SU(3)xSU2xU(1) symmetry has the location of the particles whether symmetry is broken or not.
So the particles in the present theory are always there, whether mass less before symmetry breaking, or massive after.


text:
Q: Edge Selenium shows the error: "Message: The specified window could not be found." I use selenium with edge.
from selenium import webdriver

driver = webdriver.Edge()
driver.get("xxxxx")

When I opened an edge window,it will show
selenium.common.exceptions.NoSuchWindowException: Message: The specified window could not be found. when I run this code.
In other words, if I run this code when there is no edge window,it run well without exception.
How could I run selenium with edge when I has opened a edge window?
About Edge version:
Microsoft Edge 44.18362.449.0
Microsoft EdgeHTML 18.18362

A:
from selenium import webdriver
driver = webdriver.Edge()
driver.get("xxxxx")

I have tested above code, but can't reproduce the problem. As far as I know, when we using selenium Edge webdriver with the legacy version Edge (Microsoft Edge 44.18362.449.0), it will auto close the existing Edge instance.
Please check your code, whether you want to switch handle to another window? Generally, this exception will throw when window target to be switched doesn't exist, you could check this article.
Besides, from your description, the code runs well without exception if there is no Edge window. I suppose perhaps there have some process which is doing the automation test with the existing Edge browser window. Or, the existing Edge browser window is opened by the selenium Edge web driver, and it didn't close, so, it will show this exception.
To solve this issue, we need to close the Edge browser window or Edge browser process(from the Task Manager).
Besides, I suggest you could try to refer the following code, use try statement to catch the exception and remember to add close() and quit() methods to close the close the browser session at the end of automation test.
import time
from selenium import webdriver

print("*******************")

try:
    driver = webdriver.Edge();

    driver.get("https://www.bing.com")
    time.sleep(5)
    driver.close()
    driver.quit()
except NoSuchWindowException:
    print("Window disappeared, seems like it was closed manually")

print("*******************")

A: In our case, we closed open Edge browsers and re-ran the test. This worked!


text:
Q: a "strange" depth inequality The following question arises in the context of the proof of Proposition 3.3.18 in Bruns and Herzog, Cohen-Macaulay Rings.
Let $R$ be a CM ring, not necessarily local, and suppose that $R$ admits a canonical module $\omega_R$, i.e. for every maximal ideal $m$ of $R$ we have that $(\omega_R)_m$ is the canonical module of $R_m$. Suppose in addition that
(a) $\omega_R$ has rank equal to $1$
(b) $\omega_R$ is isomorphic to a proper ideal of $R$ (call it also $\omega_R$)
(c) $\dim R >0$.
Let $p$ be a prime ideal of $R$ that contains $\omega_R$. Then Bruns and Herzog write in their proof that

$\operatorname{depth} \frac{R_p}{\omega_R R_p} \ge \operatorname{depth} R_p -1$.

Where does this inequality come from? I suppose B&H use the fact that $\omega_R R_p$ is a maximal CM $R_p$-module, but i still don't see how the inequality follows.

A: Why don't use Proposition 1.2.9, aka depth lemma? (I leave you the pleasure to find out which one of the three inequalities is suitable here.)


text:
Q: CloudConfigurationManager.GetSetting returning null After publishing I created a Azure project and used the below code to get the Storage ConnectionString
    CloudConfigurationManager.GetSetting("StorageConnectionString"))

When i executed the project locally, it fetched the ConnectionString and i was able to successfully upload an excel file.
But after publishing the Azure project as a website, the connectionstring was returning null.
I have checked with several solutions like "Checking the version of the Azure SDK...." but everything was ok i hope...
Regards
Rajeesh

A: I had quite similar problems. I updated from Azure SDK 2.0 to 2.2 - during this process I used the NuGet Manager to update the Microsoft.WindowsAzure.Storage to the latest. The PackageManager automatically took Microsoft.WindowsAzure.Configuration to 1.8.0.0. I was not able to get this running (it was for .Net 2.0!?). After I manually set all References to

*

*Microsoft.WindowsAzure.Storage 2.1.0.0

*Microsoft.WindowsAzure.Configuration 2.0.0.0

everything worked.
I think this is because of the way CloudConfigurationManager.GetSetting loads the assembly and calls the funktions (via reflection).
hope this helps.

A: the CloudConfigurationManager.GetSetting("ConnectionString") refers to some values whether for local development or for the windows azure storage account.
if you are running the windows azure project locally, the project will run with no problem because you made him running locally.
if you are looking to make it running on the Cloud here are the steps you should do.
1- double click on the role you have created un the folder roles in the Windows Azure project.  this should open the properties page.
2- add setting and name it whatever you like in the code you have entered it was "ConnectionString" for the values click on the left most button of this field, a new window will pop up asking to enter more details for your Windows Azure account.
3- use of the available options whether entering the WIndows Azure storage credentials manually or if you have downloaded the publish settings just import it to the solution.
let me know if this has worked or if you need anything else.


text:
Q: Writing to a 2 byte register from 1 byte registers I am an assembly newbie and I am trying to write an assembly routine to write data to EEPROM of a 8051 variant. (Specifically, AT89C51CC03)
In the datasheet, it says that I need to write to the column latches first. For this, I need to fill DPTR register with the address I want to write (2 bytes). As I am working mainly with C, I needed a way to pass the address from C code to the assembly routine. The following link explains the convention:
http://www.keil.com/support/man/docs/c51/c51_ap_parampassreg.htm
which says that pointer parameters are assigned to R2(MSB) and R1(LSB).
My question is, how can I move the contents of these 1 byte registers to DPTR, which is a two byte register? I have a feeling that if I use MOV, I will overwrite the first byte I have written. And the instruction set manual only provides an example for passing immediate values, not from registers.

A: It seems they're Special Function Registers (SFRs) called DPH and DPL, which should be accessible in 8-bit mode, see here and here (starting page 20).


text:
Q: How to write multiple statements in Ternary operator? I am posting this question because I found nothing similar regarding this type of post.
I am learning ternary operators.
I want to perform action like shown below:
  bool Divisible = false;
  foreach (var Number in NumberList))
  {
    var  Number = 242;
    if ((Number %= 2) | (Number %= 6))
    {
       Divisible = true;
    }
    else
    {
       Divisible = false;
    }
  }

We can write this using the ternary operator like this:
var Divisible = (Number %= 2 | Number %= 6) ? false : true ;

But if in else block there are multiple statements then what to do?
  bool Divisible = false;
  foreach (var Number in NumberList))
  {
    var  Number = 242;
    if ((Number %= 2) | (Number %= 6))
    {
       Divisible = true;
    }
    else
    {
       Divisible = false;
       break;
    }
  }

How can we write ternary operator with multiple else statements?
Please share your knowledge of ternary operators.

A:
But if in else block there are multiple statements then what to do?

If the statements are unrelated, then you don't use the conditional operator. Just use an if-else like you already have.
In your case, since your code needs to break if and only if Divisible is set to false, then you cannot use a conditional operator even if you wanted to hack it in, because a break is a statement, not an expression, and therefore cannot appear as part of a conditional operator.
In general, you only use the conditional operator when you want to decide between assigning one of two values based on a condition. For anything else, you should really be using a regular if-else construct. Don't try to shoehorn the conditional operator into just about any decision-making code because you'll more often than not find yourself running into problems such as this one.

A: The ternary operator (that "shorthand if-else") is only intended to evaluate one of two statements based on the boolean. It's not so much a flow-control construct like if; it actually returns the result of the statement it executes. You can't use it to execute code like that.
You can read more on how the ternary operator works here ?: Operator (C# Reference)
Also for your original code you can just do the following :
var Divisible = !(Number %= 2 | Number %= 6)

A: It's a arguably a shockingly bad idea but you could call methods in the ternary operators that return the type the assignment is looking for. eg
string doNotDoThis = yeahNah ? iToldYou(bad) : notToDoThis(idea);

// ...

string iToldYou(object thing)
    {
    // you can do stuff here with thing but seriously?
    return "yeahNah was yeah";
    }

string notToDoThis(object thing)
    {
    // you can do stuff here with thing but seriously?
    return "yeahNah was nah";
    }


text:
Q: How should one generalize the proper radiation reaction force of a charge to any Lorentz frame? In section 8 of Medina's paper Radiation reaction of a classical quasi-rigid
extended particle, he writes

The motion equations of the dressed mass, (56) and (57), show that the radiation reaction is a mass-conserving force. Then, the four-force of the radiation reaction of the physical point charge is in the rest frame
  $$K^i_R = \frac{2q^2}{3c^3m}\frac{dF_{ex}^i}{dt},\quad K^0_R=0\tag{92}$$

$F_{ex}$ is the external force acting on the point charge and I'm OK with this bit. He immediately concludes:

Therefore, if we call $K^\mu$ the external four-force and $\tau$ the proper time, the radiation reaction four-force is in an arbitrary reference frame given by
  $$K^i_R = \frac{2q^2}{3c^3m}(\frac{dK^\mu}{d\tau}+ (\frac{1}{c^2}\frac{dK^\nu}{d\tau}u_\nu)u^\mu)\tag{94}$$

The obvious way of generalizing (92) to any other frame is by
$$K^i_R = \frac{2q^2}{3c^3m}\frac{dK^\mu}{d\tau}$$
Why didn't he do it this way?


text:
Q: C++ new thread sleeps main thread Running the following code:
methodOne(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    t.join();
}

runChatBubbleThread:
runChatBubbleThread(){
    // code here
    sleep(2000);
    // more code here
}

My understanding is that the new threat t is created, executes its code and then joins the main thread once it has completed, is there a reason sleep() is sleeping the main thread?
Only thing I can think of is that t.join is waiting for the thread to complete before it continues on main thread, but then whats the point of threading if it has to wait!

A: The purpose of thread.join is to block until the thread is dead. If you want to do something in your main thread before waiting on your new thread, do it before you join.

A: A few easy ways to do this.
jwde covers the first
void methodOne(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    // do other stuff that needs to be done here.
    t.join(); // wait for thread to finish before returning in case thread
              // is not done
}

And John C chimed in with the second while I was typing this.
void methodTwo(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    t.detach(); // let thread run to completion on it's own time
}

But a warning on detach. If main exits before the thread finishes... You're gonna have a bad day. You probably want to keep tabs on the threads you have running to make sure they finish before you exit the program.
So method three:
void methodThree(std::vector<std::thread> & threads){
    threads.emplace_back(&ChatBubble::runChatBubbleThread, this);
}

and at the bottom of main
int main()
{
    std::vector<std::thread> threads;
    ...

    object.methodThree(threads);

    ...

    for (std::thread &t: threads)
    {
        t.join();
    }
    return result;
}

Editing to add this won't scale well over time. Threads will build up in the vector even though they have ceased, so running a cleaner from time to time to detect, remove and dispose of completed threads is required.
Edit 2: Missed the & to get a reference. Can't copy threads for a number of really good reasons.
Edit 2B. Yes. This will jam on a hung thread. I'd like to say that never happens in MY code, but look up a couple lines.
Usually my thread's execution loop will look something like this:
while (!terminated)
{
    // do stuff, but no blocking operations without a timeout.
}

If that still hangs, out comes the debugger. I have to say I don't have a good out for this case short of wrapping the loop with a bomb on a timer.

A: The thread is running as soon as you construct it.
t.join does in fact wait for thread t to complete. It doesn't have to wait; you don't have to call join. join is to synchronize the threads; sometimes you want main to wait (usually, arguably always, not right away, but after doing a few other tasks that you want to be in parallel). "The function returns when the thread execution has completed." Source
On the other hand, you can use detach which "Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other." Source. You should call detach before the thread's destructor would be called.


text:
Q: Laravel Auth RedirectTo will be ignored i use the default LoginController from Laravel 5.4 Auth. I just modified the redirectTo property to /
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Now i logged in as a user. After login the redirect to / works fine.
So now i goto /login again and now the trait RedirectsUsers redirect's me to /home.
I think the problem is in the trait on this line:
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';

But i didn't understand why. In the LoginController the redirectTo will be set to /.
I don't want to override the RedirectsUsers trait in the vendor directory.
How i can fix the issue?

A: When user is logging in, redirection is done by using the
/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/';

from app/Http/Controllers/Auth/LoginController.php

When user is already logged in and visits the /login page, redirection (to /home) is defined in
this middleware
app/Http/Middleware/RedirectIfAuthenticated.php source
if (Auth::guard($guard)->check()) {
    return redirect('/home');
}

guest middleware is defined in app/Http/Kernel.php source
Edited answer to respond to the comment
guest middleware is added to app/Http/Controllers/Auth/LoginController.php source
public function __construct()
{
    $this->middleware('guest')->except('logout');
}


text:
Q: Process an http request through database from resource usage & security perspective I fee very skeptical about this part as I have not found an answer on the web that satisfies me.
The questions are:

*

*Should I keep the db connection on forever and then keep processing my requests. This way is easier as I only have to open up the connection once and forget about closing it unless it goes down for some reason. Here, I understand the overheads of keeping a connection on forever.

*Should I open up a fresh connection each time I receive a request that needs some processing in the database and then close after the processing is done.
As per my research, the second part is better, but I need to understand the consequences in both cases.
It will mean a lot if someone can explain me the design overheads here with some examples


text:
Q: Why even after fetching the data and logging it, whenever I render it to the page after reloading the application breaks in React? I am undertaking one of the projects from frontendmentor.io
Whenever I click any of the mapped data, with the help of react-router-dom I am redirecting it to url/countryName.
In this scenario, I am using react-router-dom to fetch a particular country while using the useLocation hook to fetch the url, the problem is everything works fine in the first render but as soon as I reload the website the application breaks. No matter how many times I try it never renders again.
import axios from 'axios'
import React,{ useEffect,useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

const Country = () => {
  const location = useLocation()
  const name = location.pathname.split('/')[1]
  const navigate = useNavigate()
  const [country,setCountry] = useState({})

  useEffect(() => {
    const getCountry = async() => {
      try {
        const res = await axios.get(`https://restcountries.com/v3.1/name/${name.toLowerCase()}?fullText=true`)
        console.log(res.data,res)
        setCountry(res.data)
      } catch (error) {
        console.log(error)
      }
    }
    getCountry()
  }, [name])

  console.log(country[0].name.common) // returns undefined after reload

  const backButton = (event) => {
    event.preventDefault()
    navigate('/')
  }

  return (

      <button onClick={backButton} className='backButton'>back button</button>

  )
}

export default Country

Other resources:

*

*error message screenshot

*API which I am using : https://restcountries.com/

A: You need to wait for your data to be fetched first, and then render it.

const [country,setCountry] = useState({})
//country is an empty object

//but here, your are trying to get the value from the array. (But country is an empty object)

 console.log(country[0].name.common) // returns undefined after reload

The solution is to check if your data is here first
if (country?.[0]?.name?.common){
 console.log(country[0].name.common)
}


text: Q: facebook4j : "Share" a post already posted on a page's wall? Is there a way to use facebook4j, in order to "share" a page's post on an authenticated user's wall so that it will increment the "share number" as show in the attached photo?


text:
Q: How to pass an array of objects to a function in julia? I want to pass an array of objects to a function and return another array of the same size. How should I do this ? The code should be so fast. For example consider the below code:
struct triangle
    height::Float64
    base::Float64
end

function area(height::Float64, base::Float64)
    return 0.5*base*height
end

I want to define a function which returns the area of an array of triangles.
What is the fastest way to do it?

A: Here are some benchmarks for computing this with:

*

*map: map(area, triangles)

*comprehension: `[area(triangle) for triangle in triangles]

*broadcasting: area.(triangles)
using interpolation $ on the non-local global variable triangles (based on @DNF comment).
Definitions
using Pkg
Pkg.add("BenchmarkTools")
using BenchmarkTools

struct Triangle
    height::Float64
    base::Float64
end

function area(t::Triangle)
    0.5 * t.height * t.base
end

triangles = [Triangle(rand(), rand()) for _ in 1:1000000]

Results
julia> @benchmark map(area, $triangles)
BenchmarkTools.Trial:
  memory estimate:  7.63 MiB
  allocs estimate:  3
  --------------
  minimum time:     1.168 ms (0.00% GC)
  median time:      2.510 ms (0.00% GC)
  mean time:        2.485 ms (10.00% GC)
  maximum time:     43.540 ms (91.62% GC)
  --------------
  samples:          2008
  evals/sample:     1

julia> @benchmark [area(triangle) for triangle in $triangles]
BenchmarkTools.Trial:
  memory estimate:  7.63 MiB
  allocs estimate:  3
  --------------
  minimum time:     1.150 ms (0.00% GC)
  median time:      1.921 ms (0.00% GC)
  mean time:        2.327 ms (10.76% GC)
  maximum time:     45.883 ms (91.42% GC)
  --------------
  samples:          2144
  evals/sample:     1

julia> @benchmark area.($triangles)
BenchmarkTools.Trial:
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     1.165 ms (0.00% GC)
  median time:      1.224 ms (0.00% GC)
  mean time:        1.961 ms (10.13% GC)
  maximum time:     44.156 ms (89.33% GC)
  --------------
  samples:          2544
  evals/sample:     1

This would indicate that for this input size, the broadcasting method seems to be the fastest.
For different input size, relative timings may be different, so it is probably a good idea to benchmark it yourself for your use case

A: You can leverage Julia's broadcasting syntax for this. Consider:
struct Triangle # Note: Julia convention is to capitalize types
    height::Float64
    base::Float64
end

# Define an area method for the Triangle type
area(t::Triangle) = 0.5 * t.height * t.base

# Create an area of random triangles
triangle_array = [Triangle(rand(), rand()) for _ in 1:10]

# Now we can use dot syntax to broadcast our area function over the array of triangles
area.(triangle_array)

Note that this differs from your code in that it directly uses the Triangle object for dispatch in the call to the area function. The area function then doesn't take height and base arguments but just a single Triangle object and accesses its height and base fields (t.height and t.base).


text:
Q: How do i overlay video over android apps after a countdown I have an idea to create a prank app for android that I can set a countdown on and when the countdown is finished it will overlay a video over apps. I'm new to coding and I have no idea where to start with this. Could anyone please help me with this.
Any help/suggestions  will be appreciated.


text:
Q: JUnit/Selenium: Splitting my class to use the Page Object Model realise this might be a bit of a big ask, but I'm having trouble splitting my test class to use the Page Object Model.
My current class basically works as so:

*

*@BeforeClass - startUp() Loads properties file for variables and starts ChromeDriverService

*@Before - createDriver() Opens Chrome browser, and navs to homepage

*@Test - desktopHappyCallback() Does some page interaction, then calls:

*hideDynamicElements() Hides some elements on the page

*runScreenshotValidation() Saves a screenshot and compares it by calling:

*compareScreen() Compares and returns a true/false

*@After - tearDown() Quits the ChromeDriver

*@AfterClass - stopService() Kills the ChromeDriverService

The class is currently (have cut bits out of the methods to make it shorter):
public class desktopHappy {

private static ChromeDriverService service;
private static WebDriver driver;
private static Properties obj = new Properties();

//Set up screenshot comparison via im4java
private static boolean compareScreen(String expectedImage, String currentImage, String diffImage) {
    CompareCmd compare = new CompareCmd();
    compare.setErrorConsumer(StandardStream.STDERR);
    IMOperation comparisonExe = new IMOperation();
    comparisonExe.metric("mae"); //mae = Mean Absolute error (average of all the color differences)
    comparisonExe.addImage(currentImage);
}

//Compare via ImageMajick
private void runScreenshotValidation() throws IOException, InfoException {
    String current = "screenshots\\current\\Current.png";
    boolean compareSuccess = compareScreen(baseline, current, difference); //Run the compare method
    }
}

//Hide dynamic elements on the page (if they exist)
private void hideDynamicElements() throws IOException, InterruptedException {
    List<By> criteria = Arrays.asList(
            By.className("telephone-number"),
            By.cssSelector("#chatContainer"),
    );
    for (By dynamicElement : criteria) { //Loop through the criteria
        List<WebElement> elements = driver.findElements(dynamicElement);
        for (WebElement hideElement : elements){ //Loop through each instance of an element
            ((JavascriptExecutor) driver).executeScript("arguments[0].style.visibility='hidden'", hideElement);
    }
}

@BeforeClass //Pulls in Properties, and starts up the ChromeDriverService before the Tests run
public static void startUp() throws IOException {
    FileInputStream propfile = new FileInputStream(System.getProperty
            ("user.dir") + "\\src\\main\\resources\\config.properties");
    obj.load(propfile);

    service = new ChromeDriverService.Builder()
            .usingDriverExecutable(new File(obj.getProperty("chromeDriverLoc"))) //Driver set in properties
            .usingAnyFreePort()
            .build();
    service.start();
}

@Before //Starts up the Chrome browser (on home page) before each Test
public void createDriver() {
    driver = new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome());
    driver.get(obj.getProperty("targetENV")); //Opens home page (set in properties)
}

@Test //Checks the Callback form (modal)
public void desktopHappyCallback() throws Exception {
    driver.findElement(By.cssSelector("#callbackInputPhone")).sendKeys(obj.getProperty("formsPhone"));
    driver.findElement(By.xpath("//input[@value='Request a callback']")).click();
    WebDriverWait waitForSuccessMessage = new WebDriverWait(driver, 5);
    waitForSuccessMessage.until(ExpectedConditions.elementToBeClickable
            (By.cssSelector("#callbackForm > div.success-message")));

    hideDynamicElements(); //Run the hide dynamic elements method
    runScreenshotValidation(); //Run the screenshot comparison method
}

@After //Quits the ChromeDriver after each Test
public void tearDown() throws Exception {
    driver.quit();
}

@AfterClass //Kills the ChromeDriverService at end of Tests
public static void stopService() {
    service.stop();
}}

So in IntelliJ I've tried to split up my project with packages as so:

I've been trying to move into the baseCompare class:

*

*hideDynamicElements()

*compareScreen()

*runScreenshotValidation()

Then into the baseSetup class:

*

*startUp()

*createDriver()

*tearDown()

*stopService()

Then homePage will contain my representations and desktopHappy will contain my test assertions.
However I'm getting really stuck working out how to split things up so that they work together. Is anyone able to give me an example on how I should be splitting things up under these packages? (sorry big ask!)

A: I think you are dividing your logic very fairly.
The only thing that i would change, is to have your base* classes under your base package, rather than an actual physical base package.
For example:
com.salessite/
  baseCompare.java
  baseSetup.java
  basePage.java
  baseTest.java
  pages/
    homePage.java < basePage.java
  tests/
    desktopHappy.java < baseTest.java

Also by creating more base's, you give yourself more leeway for future changes.

so that they work together

IF by work you mean, compile - then you should have no problem.  say for example that homePage.java extends basePage.java, then in homePage.java, you'd have the appropriate import.
import com.salessite.basePage;
Importing is how to access external classes and references. (access modifiers permitting, of course.)


text:
Q: Practicable way of reading xml with huge text nodes in Perl After encountering xml data files containing huge text nodes,
I looked for some ways to read and evaluate them in my data
processing scripts.
The xml files are 3D co-ordinate files for molecular modeling
applications an have this structure (example):
<?xml version="1.0" encoding="UTF-8"?>
<hoomd_xml version="1.4">
   <configuration>
      <position>
        -0.101000   0.011000  -40.000000
        -0.077000   0.008000  -40.469000
        -0.008000   0.001000  -40.934000
        -0.301000   0.033000  -41.157000
         0.213000  -0.023000  -41.348000
         ...
         ... 300,000 to 500,000 lines may follow  >>
         ...
        -0.140000   0.015000  -42.556000
      </position>

      <next_huge_section_of_the_same_pattern>
        ...
        ...
        ...
      </next_huge_section_of_the_same_pattern>

   </configuration>
</hoomd_xml>

Each xml files contains several huge text nodes and has sizes between 60MB and 100MB depending on the contents.
I tried the naíve approch using XML::Simple first but the loader would take forever to initially parse the file:
...
my $data = $xml->XMLin('structure_80mb.xml');
...

and stop with "internal error: huge input lookup", so this approach isn't very practicable.
The next try was to use XML::LibXML for reading - but here, the initial loader would bail out immediately with error message "parser error : xmlSAX2Characters: huge text node".
Befor writing on this topic on stackoverflow, I wrote a q&d parser for myself and sent the file through it (after slurping the xx MB xml file into the scalar $xml):
...
# read the <position> data from in-memory xml file
my @Coord = xml_parser_hack('position', $xml);
...

which returns the data of each line as an array, completes within seconds and looks like this:
sub xml_parser_hack {
 my ($tagname, $xml) = @_;
 return () unless $xml =~ /^</;

 my @Data = ();
 my ($p0, $p1) = (undef,undef);
 $p0 = $+[0] if $xml =~ /^<$tagname[^>]*>[^\r\n]*[r\n]+/msg; # start tag
 $p1 = $-[0] if $xml =~ /^<\/$tagname[^>]*>/msg;             # end tag
 return () unless defined $p0 && defined $p1;
 my @Lines = split /[\r\n]+/, substr $xml, $p0, $p1-$p0;
 for my $line (@Lines) {
    push @Data, [ split /\s+/, $line ];
 }
 return @Data;
}

This works fine so far but cannot considered 'production ready', of course.
Q: How would I read the file using a Perl module? Which module would I choose?
Thanks in advance
rbo

Addendum: after reading choroba's comment, I looked deeper into XML::LibXML.
The opening of the file my $reader = XML::LibXML::Reader->new(location =>'structure_80mb.xml');  works, contrary to what I thought before. The error occurs if I try to access the text node below the  tag:
...
while ($reader->read) {
   # bails out in the loop iteration after accessing the <position> tag,
   # if the position's text node is accessed
   #   --  xmlSAX2Characters: huge text node ---
...

A: Try XML::LibXML with the huge parser option:
my $doc = XML::LibXML->load_xml(
    location => 'structure_80mb.xml',
    huge     => 1,
);

Or, if you want to use XML::LibXML::Reader:
my $reader = XML::LibXML::Reader->new(
    location => 'structure_80mb.xml',
    huge     => 1,
);

A: I was able to simulate an answer using XML::LibXML.  Try this, and let me know if it doesn't work.  I created an XML doc with more than 500k lines in the position element, and I was able to parse it and print the contents of it:
use strict;
use warnings;
use XML::LibXML;

my $xml = XML::LibXML->load_xml(location => '/perl/test.xml');
my $nodes = $xml->findnodes('/hoomd_xml/configuration/position');
print $nodes->[0]->textContent . "\n";
print scalar(@{$nodes}) . "\n";

I'm using findnodes to use an XPath expression to pull out all the nodes that I want.  $nodes is just an array ref, so you can loop through it depending on how many nodes you actually have in your document.


text:
Q: Confirming Taxonomy Caching is enabled with SDL Tridion 2009 Content Delivery Does anyone have any recommendation on a simple but effective method of confirming that Taxonomy Caching is functional. I'm working on a system where the cd_broker_config (Tridion 2009) had the taxonomy caching commented out.
We've now uncommented this and restarted the deployer service but is there any way I can 100% confirm caching is now taking place? Using ORACLE 11.2.0.1

A: Does the Tridion World article about analysing the object cache not help?

A: I think if you publish your taxonomy, load a page that queries it, then turn of the Cache Channel Service (CCS) and unpublish you taxonomy the page will still work if you reload it. Then do the same with the CCS enabled and the page should fail to load the taxonomy driven parts.


text:
Q: CakePhp Router:connect, I don't get the syntax I am trying to connect the next urls:
1) /food/tips
2) /happiness/tips/best_tips
To the following objects:
1) controller=tips / action=index / passed_parameters=food
2) controller=tips / action=index / passed_parameters=(happiness,best_tips)
--edit--
These routes are not fixed.
Meaning: what I try to do is to route every url that have tips as action, to the tips controller, to any fixed(index is good enough) action, and chaining the rest of the url as it was in the original call.
Something like /any_controller/tips/any_param to /tips/index/any_params
-- end edit --
Hope that now there is some sense.
How should it be done?
(please - also explain)
Thanks

A: It's quite easy, just check the Router configuration in the manual. You have to use the connect method from the Router class. This accepts 2 parameters. First your desired routed (e.g. food/tips) and second an array with the actual path it should follow. So for your examples you'd do something like this:
Router::connect('/food/tips', array('controller' => 'tips', 'action' => 'index', 'food');
Router::connect('/happiness/tips/best_tips', array('controller' => 'tips', 'action' => 'index', 'happiness', 'best_tips');

This is equivalent to calling TipsController->index('food') and TipsController('happiness', 'best_tips) respectively.
However, your routes look a bit funny. The Cake convention for routes is /controller/action/param1/param2/etc where the parameters param1 etc. are optional and the index action is assumed when no other action is given.
You're taking a different approach and I would suggest (if you can) change it to the Cake conventional routes, as this will save you a lot of work later on because Cake will automatically connect these routes to the desired methods.
So my suggestion is going for tips/food and tips/happiness/best_tips instead of the routes you suggest. This way, you don't have to do any router configuration.
UPDATE
After you're edit, I think it's best to try something with defining custom routes. I can't test this for you at the moment, so you should do some testing yourself, but in that case it would be something like:
Router::connect('/:section/tips/:param',
    array('action' => 'index'),
    array(
        'section' => '[a-z]*',
        'param' => '[a-z]*'
    )
);

UPDATE2
Sorry, I've tested the above and it doesn't seem to work.

A: I would recommend reading the chapter on Routing the the book, as it will explain things better than I can and it seems counter productive to paste it here.
http://book.cakephp.org/#!/view/948/Defining-Routes
For the sake of explanation I will try,
Router::connect('/food/tips', array('controller' => 'tips', 'action' => 'index', 'food'));
Router::connect('/happiness/tips/best_tips', array('controller' => 'tips', 'action' => 'index', 'happiness','best_tips'));

This should get things working for you. What you are essentially doing is telling the Cake Routing what url you want it to capture, as it will be doing this using Regex. Then you want to tell it which code you want it to run. So this takes a Controller and Action pair, as a set of things to do.
You also want to pass through your named paremeters afterwards. These will tack onto the function in your controller so that you can do stuff with them.

A: the routing is all done through the call Router::connect('thing to catch', 'where to send it');
so it can be as simple as:
Router::connect('/food/tips', '/tips/index/food');

or the preferred method (using cakes built in url builder)
Router::connect('/food/tips/*', array('controller' => 'tips', 'action' => 'index', 'food');

The first method takes a string argument and passes it to another string which would be a url and you would then have to catch it in your controller, and expect a passed parameter through the url.
The second method uses cakes built in url former which takes an array with keys controller and action (there are other options: http://api.cakephp.org/class/router#method-Routerurl)
The second is preferred due to proper formatting and future flexibility (I believe).
any passed parameters in the second method are just passed as un-named items in the array. named parameters are just passed as keyed elements. So if I wanted to create a URL like this

/posts/index/find:all/page:2

I would write the url like this:
Router::connect('/url_to_catch', array('controller' => 'posts', 'action' => 'index', 'find' => 'all', 'page' => 2);

So just to finish up, I would actually pass your parameter through as named:
Router::connect('/happiness/tips/best_tips', array('controller' => 'tips', 'action' => 'index', 'items' => array('happiness', 'best_tips'));

which would need a function in your tips controller that looks like this:
function tips(){ $this->passedArgs['items']; }


text:
Q: Muon $g-2$ experiment: is there any theory to explain the results? The nature of the experiment has been discussed here, but my main question is this: is there any theory that has predicted the results of this experiment or are we completely clueless about what's happening? In other words, have we come up with a new hypothetical interaction that could explain the results?

A: In the standard model the $α=(g-2)/2$ of an elementary particle should be calculable , the calculations as accurate as the higher orders are computed.
For the electron the calculations coincide with the experimental value to great accuracy
The muon $α=(g-2)/2$  has different diagrams dominant so the theoretical  value will be different, but it was seen ,first at the Brookhaven data, that the theory differed , not statistically significantly, with the data and so the Fermi lab experiment was designed at great effort experimentally and expense, because the difference would mean that a new interaction should add to the effect, not in the standard model that the calculations use.
As the comments say there are many extensions of the standard model that can try to fit the new results and thus choose the extension or the new theory. Hit the link given by G.Smith to get a large number of papers using different theories.

A: A Nature paper was published on the same day, which seems to have attracted a lot less press. This presents a recalculation of the muon $g-2$ value, using standard model physics and their value is consistent with the new experimental value (Borsanyi et al. 2021). So there's one theoretical explanation of the result!

A: Yes there is a theory that explains the results ... the Standard Model. In other words, the claim is that the Standard Model already is consistent with the experimental data, and the original "prediction" was calculated wrong.
Check out the paper published in Nature together with the muon g-2 results, or the writeup at popular level.

A: This answer was already suggested above. This is another source that has some really nice embedded links on the authors and the university that hosted the study. Very nice reading some might enjoy so I thought it would be nice to share.  Assuming I am allowed to put in a link. Not sure it is allowed by stack exchange.
https://thenextweb.com/news/did-we-just-discover-new-physics-theoretical-physicists-dont-think-so-syndication


text:
Q: Powershell start-job -scriptblock equivalent in Java error with Callable / Future Hey all new to Powershell so here goes.
I am wanting to take the code below and convert it into java so that I do not have to run a separate Powershell script outside my program when its running.
[string] $wspaceDir         = "C:\Temp\loadDir",
[string] $scmLoc            = "C:\Local Apps\IBM\SDP\scmtools\eclipse\scm.exe",
[string] $portNumForDaemon  = "61938"

start-job -scriptblock {
    Set-Location "$($args[1])"
    Write-Host "Starting Daemon on port $args[2]" -foregroundcolor "Yellow"
    &"$($args[0])" "daemon" "start" "$($args[1])" "--port" $args[2]
} -ArgumentList $scmLoc, $wspaceDir, $portNumForDaemon

And so far the info I have on what its doing above is running that in a separate thread in order to carry on and not wait on it to finish.
In java I have tried to mimic that:
private static String portNumForDaemon  = "61938";
private static String scmLoc            = "C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse\\scm.exe";
private static String wspaceDir         = "C:\\TempRQM";

public static void blah() {
    ExecutorService pool = Executors.newSingleThreadExecutor();
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command("cmd.exe", "/c", scmLoc + " daemon start " + wspaceDir + " --port " + portNumForDaemon);

    try {

        Process process = processBuilder.start();

        System.out.println("process ping...");
        ProcessReadTask task = new ProcessReadTask(process.getInputStream());

        List<String> supplierNames = new ArrayList<String>();
        Future<list<string>> future = pool.submit(task);

        // no block, can do other tasks here
        System.out.println("process task1...");
        System.out.println("process task2...");

        List<string> result = future.get(5, TimeUnit.SECONDS);
        for (String s : result) {
            System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        pool.shutdown();
    }
}

private static class ProcessReadTask implements Callable<list<string>> {
    private InputStream inputStream;

    public ProcessReadTask(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public List<string> call() {
        return new BufferedReader(new InputStreamReader(inputStream))
            .lines()
            .collect(Collectors.toList());
    }
}

And as much as I would like to run this I am getting an error on all the implements Callable< list >, Future< list >.
I am not sure if I am doing this correctly or not. I don't even know for sure that's equivalent to what the Powershell is doing?
And Powershell/Java guru able to help me out would be great!