text:
Q: How to accept records from a list view without being added in a queue? How to accept records from a list view without being added in a queue?
I have not created queue and have created group in which a particular user is added . Now when that users tries to go that the view  list and tries to accept the record, there is no accept button. I do not want to create a new queue in which this person needs to be added. I just want this user to have the accept button.


text:
Q: Using a special calculator to write to a table I have a downloaded Excel spreadsheet that has a special built-in calculator.
In another sheet I have my list of 173 values. These I enter into the calculator cell, press enter in another cell and in another cell the return value pops up.
I want the value of each return cell to be entered adjacent to its list value.
How can I do this without using an IF statement?

A: There is a particular feature in Excel for doing exactly this sort of thing: a Data Table.
You nominate an existing output cell and 1 or 2 input cells from anywhere in the same worksheet (parts of your 'special calculator'), and a range containing the inputs you want to use (in this case, your 173 values). You then get a 1-way or 2-way table containing the values that the output cell would have taken for each of a range of values of the input cells. The intermediate calculation can be as complex as you like and can reference cells on other worksheets.
What you would need to do if you wanted to change more than two inputs at a time is start by listing every combination you want to use as scenarios in a table:
scenario    var1    var2    var3
1   1   1   2
2   1   3   2
3   2   1   1

Then you can use vlookups based on a cell containing the scenario number to populate all the other cells you want to change, and set the scenario cell as the row input to a 1-way data table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is setting overflow: auto to all elements except html bad practice? When it comes to starting a new design I always start my style sheet with overruling the browser's default padding and margin on all elements:
* { margin: 0; padding: 0; }

After reading j08691's answer on a margin collapse problem I realized overflow: auto fixed more than I knew of. I was wondering if it would useful to add  overflow: auto on all elements inside the html (you don't want to loose the scroll-bar there). So:
html * { overflow: auto; }

I tried adding this rule to one of our sites, and at first glance this works well, but I'm afraid it might break the more exotic elements (that I'm not using now, but might later) and ... Internet Explorer.
Do any of you have experience with a default overflow: auto? Is it a bad thing to do? Should I opt for a milder version and defining a default overflow: auto only on div elements?

A: Yeah, I do think it's bad practice. You should only use it when you don't know whether the content can break the size of an element.


text:
Q: Issue with a '?' character I am working on an ASP.NET with C# app on WebForms.
I have textbox which I am using to send SMS to mobile phones using an API.

Whenever I put a ? in the textbox it disables all the events on the page, no event gets fired.
Not able to understand what is an issue?

A: Maybe, because it is a special regex character?
Hard to answer without any code, but try to escape the question mark

\?


text:
Q: Axios get params array is converting to string Axios
    var datas=[{"ticket_no": "1","details": "detail1"}];
    instance.get(`somepath`, {
        params: ({
            data:datas,
        }),
        responseType: 'blob',Accept: 'application/pdf',
        }).then((response) => {
            const file = new Blob(
                [response.data],
                {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            //Open the URL on new Window
            window.open(fileURL);

        }).catch((error) => {
            console.log(error)
        }).finally(() => {
        })

PDF.test
{{data}}

//returns "{ticket_no:1,details:detail1}"
//not an array but a string

A: var datas=[{"ticket_no": "1","details": "detail1"}];
    instance.get(somepath, {
        params: ({
            data:JSON.stringify(datas),
        }),
        responseType: 'blob',Accept: 'application/pdf',
        }).then((response) => {
            const file = new Blob(
                [response.data],
                {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            //Open the URL on new Window
            window.open(fileURL);
    }).catch((error) => {
        console.log(error)
    }).finally(() => {
    })

//Controller
    $pdf = PDF::loadView('PDF.pdf_irregularity',['data' => json_decode($request->data)])->setPaper('A5', 'landscape');
    $fileName = 'Irregulairty';
    return $pdf->output();


text:
Q: Tomcat Management using Ansible I am writing a playbook where i need to stop/start tomcat using ansible. In a normal scenario we execute this command on the server to start/stop tomcat - svcadm disable/enable tomcat and to check the status we do svcs tomcat.
I need to do the same thing from Ansible but need to put some conditions to make sure it is executed fine because only after tomcat has shutdown properly, my main playbook will execute further to deploy the code
Below is my simple playbook for tomcat role -
---
- name: Stop tomcat service
  shell: "svcadm disable tomcat"

The Problem here is sometimes after executing this command it goes into MAINTENANCE mode. We check the status by using svcs tomcat and if it's in MAINTENANCE mode then we need to execute the command again to make sure it goes to DISABLED state. Also we double verify it by executing ps -ef | grep java command to make sure no tomcat running.
Is it possible to achieve this from Ansible by putting some conditions. Let me know if someone can help.

A: The service module supports solaris SMF. This should be as easy as the following task and will respect idempotency:
- name: Stop tomcat
  service:
    name: tomcat
    state: stopped
    enabled: no


text:
Q: Jlist and Jlabel to change views in one panel guys. So we just started to design an Enrollment System GUI which we plan to finish in 3-4 months including its functionality. But right now we focus on design. We are students so our knowledge with JAVA swing is limited but I'm willing to learn all. I've attached a screenshot of a Frame from our project. I would like to know what to learn and if what we're trying to do is possible with the given design.
1.) Can I use the JLabel on the left navbar to change views on panel everytime user clicks on it? If so, how? Can you give a 'basic' example.
2.) Using a Jlist item, can we switch/change views on the panel to show different teacher information? Please provide basic example.
Thank you. I'd appreciate any response.

A: To change the text on labels use
lbl.setText( "New message" );

To change images on labels use
icon = new ImageIcon( "new image.png" );
img.setIcon( icon );


text:
Q: Is there a synonym for "defenestrate"? Thesaurus.com lists no synonyms for defenestrate, and I can't think of any (aside from its definition). However, according to etymonline, it has been in use since 1620 (although Wikipedia refers to two major incidents in the 15th century), and according to Google Ngrams, it was not used in writing before the 20th century (with a steady increase until a peak around 2000).

Are there any synonyms that may have been used in those 300 years where it was apparently not used in print? Could revived popularity of such a synonym be responsible for the slight decrease in use over the past decade, or are people just not thrown out of windows often enough anymore?
Update:
I've searched Google Ngrams for defenestrate vs. defenestration vs. defenestrated, and found many more occurrences. However, there is still a 200-something year gap.

A: First, etymonline says defenestration (and defenestrated) is from 1620 but defenestrate only from 1915. So the simple answer why defenestrate wasn't used before the 20th century is because the word, well, the word hadn't been used before -- it hadn't been 'invented' yet.
Defenestrate may be a bit earler that 1915, here's the earlies I could find, from a 1909 The Athenaeum:

Jehu's command to the Eunuchs to " defenestrate yon luxurious dame " was much appreciated. A new word is always welcome.

Emphasis theirs, and they welcome this new word.
People were never often thrown out of windows, etymonline tells us the term was invented specifically for the "Defenestration of Prague" in 1618 which marked the start of a war. The fact it was also later used to refer to a one or two other similar incidents doesn't mean it happened a lot or that a synonym is needed. The term is now also used to refer to disposing of anything unwanted: "please defenestrate that remark", and at least since 1988 for removing the Windows operating system.
So let's make an Ngram of all these terms:

What's going on here? Why nothing until 1850? Well, Google Ngrams isn't always the most reliable tool. For one thing, not all books are scanned into the Google Books database, especially older ones which are harder to OCR, and not all of the scanned ones are scanned and indexed properly. If we just search for the term "defenestration" in Google Books, the oldest we can find is 1672, very close to the original 1620:

Note two things. First: the word is italic, which suggests it is a new or uncommon word (dum regnabat rosa is italic because it's Latin, for "while a rose reigned"). Second: the 's' looks a bit like an 'f'. (See these two questions for more on this). There are some 17th and 18th century results in Google Books for desenestration and defeneftration.
To summarise: we can't find defenstrate before the 20th century because it hadn't been used yet. The lack of early scanned books and problems with OCR particularly to do with the long-s/f mixup don't help, but we can find defenestration going back to the 17th century in Google Books. For some reason, not all Google Books results show up in Ngram viewer.

A: As Hugo says Defenestration was coined  for the Defenestration of Prague (1618).
But the first occurrence of defenestrate is 1620. As a past participle, it was used by Sir Henry Wotton  in a letter, and this letter was published, with the rest of his correspondence, in 1907. See archive.org for full text of letters by  Sir Henry Wotton.
So the XX th century date found on the internet as first occurrence of  defenestrate is the date these letters were reproduced on print, but not the date they were actually written.
Defenestrate comes from the French défenestrer which existed before the 17th century with the meaning of to take out the windows.

This was first intended as a response @Hugo but with all the urls included it turned out to be much too long for a mere comment.

A: I imagine that the word wasn't invented at the time of the event.
Or if it was then it was only used in a single source, it was probably later historians/novelists looking for an amusing phrase that introduced it.


text:
Q: how to add scroll to an image view Please sugest how to add a scroll to an image view iam writing some message using mouse and saving as image i need a scroll to write bix text in image view ..

A: Please download sample code from here
This will definitely help you.

A: SEE this Example....And implement this..
UIImageView *imgViewCell = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 46.0f, 320.0f, 116.0f)];
NSString *path = [[NSBundle mainBundle] pathForResource:@"detail_bg" ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:path];
[imgViewCell setImage:img];
[ScroollView addSubview:imgViewCell];
[img release];


text:
Q: Question about my t-distribution I've been learning about the t-distribution for my stats class and while running some simulations in R to explore the concept, I've run into an issue. I don't know whether it arises from my code, or whether I have seriously misunderstood how t-distributions arise.
Below I've pasted my code and the graph it gives me. The dataset it works on  is heights from the dslabs package. It's a dataframe that contains two normally distributed recordings of heights, one for men and one for women. In total there are 1050 observations. I ran a Monte Carlo simulation 1000 times, each time sampling 10 observations randomly from the data, got the sample mean $\bar{x}$ and sample standard deviation $s$. The t-value is then
$t=\frac{\bar{x}-\mu}{\frac{s}{\sqrt{n}}}$ and it should have a t-distribution about 0. $\mu$ is the population mean of heights. I made a density plot of these t-values and also 1000 randomly generated normally distributed numbers with $sd= \frac{\sigma}{\sqrt{n}}$. This is the standard deviation of the distribution of sample means of samples of size n. It should be normally distributed.
Here's my code:
n <- 5
tvalues <- replicate(10000,{
    X <- heights[sample(1:1050,size=n),] %>% pull(height)
    Xbar <- mean(X)
    s <- sd(X)
    tvalue <- (Xbar-mu)/(s/sqrt(n))
})
df1 <- data.frame(values=tvalues,category="tvalues")
normal_values <- rnorm(1000,mean=0,sd=sigma/sqrt(n))
df2 <- data.frame(values=normal_values,category="normal sample mean distribution")
df <- rbind(df1,df2)
df$category <- as.factor(df$category)
df %>% ggplot(mapping=aes(values,color=category)) + geom_density(bw=1)

and the graph I get

Shouldn't the t-distribution have fatter tails than the normal?

A: Yes, the t-distribution has heavier tails than the standard normal distribution. But, in your figure, you are comparing it with a normal distribution with standard deviation $\frac{\sigma}{\sqrt(n)} \ne 1$. If you change that to 1 and re-draw you should see what you expect.


text:
Q: How can I extract part of an IEnumerable based on known elements of the collection? I have a collection, specifically an IList<T>. I know two elements within the collection, startElement and endElement.
Is there a LINQ query that will return the enumerable from startElement to endElement, inclusive?
I thought about using sequence.SkipWhile(p=>p!=startElement).TakeWhile(q=>q!=endElement) but that misses out the last element...

A: The best I can think of is:
var subSection = TestData.SkipWhile(p => p != startElement).ToList();
var result = subSection.Take(subSection.IndexOf(endElement) + 1);

A: George wrote a more flexible extension, you can find it in here:
https://stackoverflow.com/a/31940000/5106041
Old version:
public static class MyExtensions
{
    public static IEnumerable <TData> InBetween <TData> (this IEnumerable <TData> Target, TData StartItem, TData EndItem)
    {
        var Comparer = EqualityComparer <TData>.Default;
        var FetchData = false;
        var StopIt = false;

        foreach (var Item in Target) {
            if (StopIt)
                break;

            if (Comparer.Equals (Item, StartItem))
                FetchData = true;

            if (Comparer.Equals (Item, EndItem))
                StopIt = true;

            if (FetchData)
                yield return Item;
        }

        yield break;
    }
}

So, now you can use it like this:
sequence.InBetween (startElement, endElement);

And it wont iterate the entire sequence.
Be aware that the are a lot of read made extensions in here http://linqlib.codeplex.com/

A: This doesn't use LINQ, but it's probably the most straightforward/readable approach.
        int startIndex = sequence.IndexOf(startElement),
            endIndex = sequence.IndexOf(endElement);

        var range = sequence.GetRange(
                         startIndex,
                         // +1 to account for zero-based indexing
                         1 + endIndex - startIndex
                    );

Note that this is technically less efficient than alternatives, but if you already have an IList in memory, the differences will likely be less than a millisecond which is a small sacrifice to make for readable code.
I'd recommend wrapping the code block with a Stopwatch to test against your specific situation to be sure, however.

A: This will be the most efficient, as it doesn't create any unnecessary enumerator objects and only traverses the list one time.
var result = new List<T>();
var inSequence = false;

for (var i = 0; i < list.Length; i++)
{
    var current = list[i];

    if (current == startElement) inSequence = true;
    if (!inSequence) continue;

    result.add(current);
    if (current == endElement) break;
}

This won't handle the case where endElement is missing, but you could do that pretty easily by assigning result = null as the last line of the for loop where i = list.Length - 1

A: I assume you don't want to use extra memory and don't want to exceed the algorithmic complexity of the underlying iteration method, so ToList, GroupBy, IndexOf are not alowed in my proposed implementations.
Also, not to place constraints on the element type, i'm using predicates.
    public static class EnumerableExtensions
    {
        /// <summary>
        /// This one works using existing linq methods.
        /// </summary>
        public static IEnumerable<T> GetRange<T>(this IEnumerable<T> source, Func<T, bool> isStart, Func<T, bool> isStop)
        {
            var provideExtraItem = new[] { true, false };
            return source
                .SkipWhile(i => !isStart(i))
                .SelectMany(i => provideExtraItem, (item, useThisOne) => new {item, useThisOne })
                .TakeWhile(i => i.useThisOne || !isStop(i.item))
                .Where(i => i.useThisOne)
                .Select(i => i.item);
        }

        /// <summary>
        /// This one is probably a bit faster.
        /// </summary>
        public static IEnumerable<T> GetRangeUsingIterator<T>(this IEnumerable<T> source, Func<T, bool> isStart, Func<T, bool> isStop)
        {
            using (var iterator = source.GetEnumerator())
            {
                while (iterator.MoveNext())
                {
                    if (isStart(iterator.Current))
                    {
                        yield return iterator.Current;
                        break;
                    }
                }
                while (iterator.MoveNext())
                {
                    yield return iterator.Current;
                    if (isStop(iterator.Current))
                        break;
                }
            }
        }
    }

These methods can be used as extension methods:
new[]{"apple", "orange", "banana", "pineapple"}.GetRange(i => i == "orange", i => i == "banana")


text:
Q: Choose unique numbers from different sets Suppose that there are n, possibly equal, non-empty sets. The problem is concerning choosing unique n numbers such that first number from first set and so on.
First, is there an algorithm to check if I can do it? And, second, How can I actually choose the numbers?
Examples
$$
\begin{align}
s1 &= \{5,6\}\\
s2 &= \{5\}\\
s3 &= \{6,7\}
\end{align}
\text{In this case, the choices are possible and they are 6,5 and 7 respectively}
$$
$$
\begin{align}
q1 &= \{1,2,3,4\}\\
q2 &= \{2,3\}\\
q3 &= \{2,3\}\\
q4 &= \{3\}\\
\end{align}
\text{In this case, we cannot choose since q2,q3 and q4 have only three possiblities}
$$
I thought of this algorithm to check if it can be done, but I don't know if it's correct
union all n sets. if size < n => CANNOT CHOOSE, else continue
union all smallest n-1 sets. if size < n-1 => CANNOT CHOOSE, else continue
union all smallest n-2 sets. if size < n-2 => CANNOT CHOOSE, else continue
and so on ...
if reached the smallest set => you can choose unique numbers from the set

I don't think this is correct for all cases and I don't know what to do with equal sets. I hope there is something better. An Algorithm to actually choose will be great!

A: You're looking for what's usually called a system of distinct representatives or SDR. A theorem of M. Hall states that the sets $\{S_i\mid 1\le i\le n\}$ have an SDR iff rhe union of any subcollection $S_{i_1},\ldots,S_{i_k}$ has size at least $k$.
However, this condition is not always easy to apply directly; here's an efficient way to find an SDR. Build a bipartite graph where one side consists of the $n$ singleton sets, the other side consists of the given sets, and connect $\{i\}$ to $S_j$ iff $i\in S_j$. An SDR is a perfect matching in this graph, so you can efficiently find an SDR (or show it doesn't exist) using an algorithm for solving the bipartite matching problem, such as the Hungarian algorithm.


text:
Q: Suppose $x:[0,\infty) \to [0,\infty)$ is continuous and $x(0)=0 $ Suppose $x:[0,\infty) \to [0,\infty)$ is continuous and $x(0)=0 $
If $$(x(t))^2 \leq  2+\int_{0}^{t}x\left(s\right){\rm d}s .
$$  for all $t \geq 0$,
Then which of the following is true?
$a$) $x(\sqrt2)\in[0,2]$
$b$) $x(\sqrt2)\in [0,\frac3{\sqrt2}]$
$c$) $x(\sqrt2) \in [\frac5{\sqrt2},\frac7{\sqrt2}]$
$d$) $x(\sqrt2)\in [10,\infty)$
I tried function $x=0$ and $x=\frac{3t}2$.
And I want to discard $a$ or $b$ ...(as I think $a$ should be wrong and $b$ is answer) not arguments like $a$ is true then $b$ should be true and only one answer can be correct so $b$ is correct.

A: I think the correct inequality is $x(t)^2\le2+\int_{0}^{t}x(s)\,ds$.
In that case, let $y(t)=2+\int_{0}^{t}x(s)\,ds$. We have $x(t)=y'(t)\le\sqrt{y(t)}$, so
$$\frac{y'(t)}{2\sqrt{y(t)}}\le\frac12$$ and thus
$$x(t)\le\sqrt{y(t)}=\sqrt{y(0)}+\int^t_0\frac{y'(t)}{2\sqrt{y(t)}}\,dt\le\sqrt{y(0)}+\frac{t}2=\sqrt{2}+\frac{t}2.$$ So $x(\sqrt{2})\le\frac32\sqrt{2}=\frac3{\sqrt{2}},$ meaning it's b).


text:
Q: What is a proper way to modify a list of DB Objects using Spring MVC? Question
Using the spring MVC model and without any ORM solution, how am I supposed to treat a large list of database objects without multiplying the database queries?

Research tracks
Track 1

*

*Step 1: SELECT the objects with the DAO and put them in a (big) List with a RowMapper.

*Step 2: deal with my objects within the associated service in Java.

*step 3: loop on the (n-big) List to do n simple UPDATE in the DB

Queries for n objects: 1 + n
Track 2
Write a SQL query in the DAO that directly updates all the corresponding objects without extracting them.
Queries for n objects: 1
Thoughts
As track 2 seems far more efficient, it also seems to straightly go against the Spring MVC model as my services will tend to empty and my DAO will tend to expand.
Maybe there is a generic way to do an UPDATE on a Java List of objects in a database without multiplying the queries?

Simple case
Given this table:
+----+---------+------+
|           MY_OBJECT |
+----+---------+------+
| ID | BOOLEAN | DATE |
+----+---------+------+
|  0 |       0 | NULL |
|  1 |       1 | NULL |
|  2 |       0 | NULL |
|  3 |       1 | NULL |
|  4 |       1 | NULL |
+----+---------+------+

I have a MyObjectDao and a MyObjectService.
I'd like to set DATE to the SYSDATE() for all objects that have the boolean to true.
Should it be full DAO with a query or should the DAO retrieve the objects, the service edit them and then the DAO update them?

A: This is something that would typically be handled by the ORM layer.
If you are using Hibernate (other ORMs are available) then I would delegate to that.
If you have your own home spun ORM layer you can do whatever you want, but as weight to your arguments I would say:

*

*The service should only know the pagination it wants.

*How this is implemented should sit below the service.

A: I did some researches and put a lot of thoughts into this question. What I deduced from my work is that in the majority of cases the process should be:

*

*Pull the data from the DB with the DAO in a generic way

*Edit the objects the way you need it with the service / business layer

*Transmit the objects to the DAO to do a generic batchUpdate
The key element I was missing is the batchUpdate. Without it, updating a big List of elements would take minutes which is unacceptable. The big difference is not the amount of queries executed but how they are transmitted to the DB, avoiding multiple usages of the network layer in the batch update case.


text:
Q: jQuery mobile: get navigation and search toggle position:fixed I´m using jQuery Mobile and my navigation and search panel will slide from the left into the page. So the problem is, that something and I really don´t know what kind of element, is changing the position of the toggle so that it´s not fixed. I´ve defined already data-position:fixed; but that didn´t help.
How can I change the position of the jQuery Mobile toggles to position:fixed; so that they are over the div.ui-panel-dismiss ?
I know that jquery mobile uses translate3d to animate the panel. So if I put this out it will have the position:fixed; but the page will also stay behind the panel, so that is not a solution for me. But I think this question is like:
css3 transform reverts position: fixed


text:
Q: uid does not have android.permission.SEND_SMS I'm trying to send a message (SMS) from one emulator to another:
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eheio.com.exo2">

    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Send message method:
public void sendMessage(View view) {
        EditText number = findViewById(R.id.number);
        EditText message = findViewById(R.id.message);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number.getText().toString(), null, message.getText().toString(), null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "SMS failed, please try again later!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

I'm getting the following exception:

java.lang.SecurityException: Sending SMS message: uid 10082 does not have android.permission.SEND_SMS.

A: For starters, you can inspect what permissions are granted to your apps by doing:
adb shell dumpsys package <your package>

and you'll see something like:
grantedPermissions:
  android.permission.MANAGE_ACCOUNTS
  android.permission.WRITE_SYNC_SETTINGS
  android.permission.RECEIVE_BOOT_COMPLETED

The android.permission.SEND_SMS permission is dangerous protection level. That means as of API 23 you need to prompt the user to accept the permission. It's not enough to declare its use in the manifest. You can read about that here:
https://developer.android.com/guide/topics/permissions/overview#dangerous-permission-prompt

A: The android.permission.SEND_SMS is dangerous protection level. So It's not enough to declare <uses-permission android:name="android.permission.SEND_SMS"/> in the manifest.
So, above API level 23 you need to prompt the user to accept the permission,  when the app is running.
You can try the following code:
SmsManager smsManager = SmsManager.getDefault();
ActivityCompat.requestPermissions(this,new String[] { Manifest.permission.SEND_SMS}, 1);
smsManager.sendTextMessage(strPhoneNo, null, strMessage, null, null);


text:
Q: Establishing security trust between two domains without VPN We have a company we recently acquired and we would like for them to access our SQL Server Analysis Services (via Excel file) on our company's domain. They are external users with separate Windows domains.
I was reading about AD Forest trusts and I don't know if this is the right path. If we set up a trust relationship between the two domains, can I add NewCompany\NewUser to our SSAS security role and they would have access?
It seems like if they're in Azure, following the below would work?
https://docs.microsoft.com/en-us/azure/architecture/reference-architectures/identity/adds-forest
The end result I want is:

*

*for NewCompany\NewUser to refresh the cube/PivotTable in Excel on their PC  without having to VPN (this is the key thing)

*

*edit: Using a jumpbox would be ok too.

Is this possible and if so, is there a high-level overview of the steps needed? Would I be able to add NewCompany\Sam to SSAS security role, for example?
I'm a software developer so don't know much about infrasture/AD. This is mainly for my curiosity - I don't think we'll implement this. Thanks!
My company uses Windows Server 2016. New company uses Azure AD Services.

A: I think there are two questions here. Trusting an acquired company is usually problematic, and you're definitely in VPN territory. If you create accounts for them in your forest, that would obviate the need for a trust to access your application.
How they get network access is a separate worm can.  If it's only for SQL Server, it's possible to access SQL Server over TLS using a certificate, but this would only be secure if it were required at the server - not something everyone is prepared to do. If that were in place, creating a DSN with the credentials and server name/port to access a database in Excel is fairly straightforward using the Microsoft ODBC Driver 17 for SQL Server:
https://www.microsoft.com/en-us/download/details.aspx?id=56567


text:
Q: Seven-sided dice from five-sided dice with finite rolls I have a 5-sided dice, and I want to use it to simulate a 7-sided dice.
Is there a way to do this with a finite number of rolls?

A: There is no way to do it with a bounded number of rolls. This is because if you know you will stop after at most $k$ rolls, the probability of each outcome or combination of outcomes is a multiple of $\big(\frac15\big)^k$, but $\frac17$ isn't.
If you're ok with the number of rolls being unbounded, but finite with probability $1$, you can do this. For example, rolling two dice gives $25$ possible outcomes. Assign three each to the numbers $1$ to $7$, and if one of the other four outcomes comes up, reroll. (More efficient schemes exist.)
The average number of times you roll two dice with this is $\frac{25}{21}$, since the probability of stopping is $\frac{21}{25}$ at each attempt (see wikipedia). So the average number of dice you need is $\frac{50}{21}$.


text:
Q: DateTime in Snowflake Timestamp '23-Jan-2015 23:02:39' is not recognized So I have a varchar that I am converting to a DateTime and I'm using the below syntax but I get the following error in Snowflake "Timestamp '23-Jan-2015 23:02:39' is not recognized". Since I'll be getting my data in this format what do you suggest?
select '23-Jan-2015 23:02:39'::timestamp_tz;

A: Your timestamp string literal is not in a standard format which Postgres can directly use.  Instead, you may use TO_TIMESTAMP to convert:
SELECT TO_TIMESTAMP('23-Jan-2015 23:02:39', 'DD-Mon-YYYY HH24:MI:SS');

In the demo tool I used, this returned: 2015-01-23 23:02:39+00
Demo

A: You need to let snowflake know how to make sense of the literal that you are passing.

*

*Use the to_timestamp() to instruct it to convert to a timestamp

*Give it a way to map the day-month-year while it parses the literal to map it to values

select to_timestamp('23-Jan-2015 23:02:39', 'DD-MON-YYYY HH24:MI:SS');
Please check the supported  Date ,Time , Timestamp etc formats supported by Snowflake here:
https://docs.snowflake.com/en/user-guide/date-time-input-output.html#date-formats


text:
Q: close function of dialog being executed after dialog is closed upon ESC key press (in chrome only) I got a div with a certain class, i have delegated a click event to it so when it is being clicked i toggle its class with another one and open a dialog , Now when the dialog is being closed I toggle the div class back to the original
Now to the interesting part... If i hit the esc button on the keyboard the classes continue to toggle... this happens only in Chrome browser
Instructions to reproduce :
In Chrome:
click the div -> a dialog will be open -> close it -> start hitting esc button -  the color of the div will be changed cause the dialog close function is being executed (and it cause the div classes to toggle)
In FF and IE it works just fine and no esc issues are present
Here is the js code snippet
$(document).ready(function() {
  $(document).delegate(".dashboard_widget", "click", function(){
     $(this).toggleClass('dashboard_widget').toggleClass('dashboard_widget_clicked');
     showDialog();
  });

});
function showDialog(){
    $("#dialogID").dialog({
        buttons: {
            Close: function () {
                $(this).dialog("close");
             }
        },
        close: function (event, ui) {
            $("#myID").toggleClass('dashboard_widget_clicked').toggleClass('dashboard_widget');
        }
    });
}

I reproduced it in jsfiddle
Thanks ahead,
Daniel.

A: solved it , thanks to Rory idea
set the .data with false/true in order to tell when the dialog is open/close
here is the main snippet of the code (js)
$(document).ready(function() {
  $(document).delegate(".dashboard_widget", "click", function(){
     $(this).toggleClass('dashboard_widget').toggleClass('dashboard_widget_clicked');
     showDialog();
  });

});
function showDialog(){
    $("#myID").data('closed',false);
    $("#dialogID").dialog({
        buttons: {
                Close: function () {
                    $(this).dialog("close");
                }
            },
        close: function (event, ui) {
            if($("#myID").data('closed')!==true){
                $("#myID").toggleClass('dashboard_widget_clicked').toggleClass('dashboard_widget');
                $("#myID").data('closed',true);
            }
        }
    });
}

jsfiddle Full Solution

A: It's because the escape key is attached to the close method of the dialog. Because you have hooked your toggleClass to this method, the class is changed on each keypress.
Firefox and IE appear to ignore the esc keypress when the dialog is not opened, Chrome does not, hence the issue.
Without changing the code of the plugin I don't think there is much that can be done to fix this.


text:
Q: ChromeDriver not waiting on `get()`? The JavaDoc of WebDriver.get() says ... the method will block until the load is complete.
Firefox driver waits until all initial JavaScript has finished. However, ChromeDriver seems to return as soon as the HTML is downloaded. This makes testing JS-based web apps difficult as you don't even know if the app is rendered or not when the function returns.
Does anyone know if this is the expected behavior and if so how to check if JavaScript has finished running?

A: We have found with selenium, that putting lots of sleeps between steps solves about 95 percent of problems, and is about the only reliable way to deal with these issues. It makes for slow tests, but really, if you are emulating the browser, it's that slow in the real world as well. Rather than spend tons of time trying to trouble shoot every delay, put in a wait/sleep, and continue on.


text:
Q: Markdown-it not working with Nuxt & contentful, throwing errors I am Building a site using Contentful and have followed different guides and configurations. No matter what I do I can't seem to get a basic example of markdownit working. I keep getting an error:
Property or method "$md" is not defined on the instance but referenced during render.
can't get any examples in the docs working:
https://openbase.com/js/@nuxtjs/markdownit
I have even deleted the whole template and tried simple versions. I have also tried different set ups in the config file below.
I have run 'yarn build', 'yarn add markdown-it'
and neither seem to have helped
here is what I am trying to get to work eventually:

This is one example I am following and it seems to be working here on the live demo:
https://github.com/sdras/contentful-nuxt-netlify/blob/e80e6552eef812320a7bd2dd66ad3fa8ebf5f840/pages/_slug.vue
In context - pages/_id/index.vue
<template>

    Go back to overview

{{post.fields.title}}

      {{post.fields.body}}

</template>

nuxt.config.js
const config = require('./.contentful.json')

module.exports = {
  // ...
  env: {
    CTF_SPACE_ID: config.CTF_SPACE_ID,
    CTF_CDA_ACCESS_TOKEN: config.CTF_CDA_ACCESS_TOKEN,
    CTF_PERSON_ID: config.CTF_PERSON_ID,
    CTF_BLOG_POST_TYPE_ID: config.CTF_BLOG_POST_TYPE_ID
  }
  // ...
}

export default {
  // Target: https://go.nuxtjs.dev/config-target
  target: 'static',

  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'thomasulman',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [

  'nuxt-buefy',

  "@nuxtjs/markdownit"],

  markdownit: {
    runtime: true, // Support `$md()`
    injected: true,
  },

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
  }
}

package.json
{
  "name": "******",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/markdownit": "^1.2.10",
    "contentful": "^8.4.2",
    "core-js": "^3.15.1",
    "markdown-it": "^12.1.0",
    "nuxt": "^2.15.7",
    "nuxt-buefy": "^0.4.8"
  },
  "devDependencies": {}
}

just in case it helps:
index.vue
<template>

{{ person.fields.name }}

        {{ post.fields.title }}
        <nuxt-link :to="post.fields.slug" class="more">Read more ⟶</nuxt-link>

</template>

A: I've achieved to make it work properly as shown here: https://github.com/nuxt-community/markdownit-module#usage
I've added a proper HTML sanitizer too, check the plugins directory.
You can find the working Github repo here: https://github.com/kissu/so-nuxt-markdownit
This configuration was enough so far for me
nuxt.config.js
plugins: [
  '~/plugins/vue-dompurify'
],
modules: [
  '@nuxtjs/markdownit'
],
markdownit: {
  runtime: true, // Support `$md()`
  // preset: 'default',
  // linkify: true,
  // breaks: true,
  // use: [
  //   'markdown-it-div',
  //   'markdown-it-attrs'
  // ]
}

And those 2 files are working properly
index.vue
<template>

    <nuxt-link to="/inline">Inline markdown working too!</nuxt-link>

</template>

inline.vue
<template lang="md">
  # Hello World!

  Current route is: {{ $route.path }}

  <nuxt-link to="/">Back to index</nuxt-link>
</template>

A: The issue with the whole thing was that // module.exports {} was overwriting the export default {} in the config file.


text:
Q: Any idea why hyperlinks to same page anchors stopped working in my markdown file posted as a gist I regularly share markdown pages with my collaborators by uploading them to gist. I usually include a "table of contents" at top with hyperlinks to headers in the page. The hyperlinks are just anchors named after the content of the headings. This worked fine until a few days ago. The anchors are there, you can see them in the page source and they are rendered. Clicking on the links brings you to the right URL (with the anchor in it). But the page doesn't move. Tried this on several browsers.
Here's an example page at https://gist.github.com/ho-ben/a3eaf926f6a91611d575b0256316afe6#more-stuff


text:
Q: Code inside the constructor I have the following Java class:
public class MyClass{
    private List<MyObject> lst;

    public MyClass(){
        //----Starting initial code-----
        MyAdditionalObject obj=new MyAdditionalObject();
        Event e= new Event()
        obj.attacheEvent(e);
        //----initial code end-----
        lst.add(e);
    }
}

Is it a bad practice to put such initial code inside the constructor?

A: Use Initialization block if you have overloaded constructor to avoid repetition of code.
public class MyClass{
   private List<MyObject> lst;

   //Initialization block
   {
       //----Starting initial code-----
       MyAdditionalObject obj=new MyAdditionalObject();
       Event e= new Event()
       obj.attacheEvent(e);
       //----initial code end-----
   }

   public MyClass(){...}

   public MyClass(int i){...}

   public MyClass(String i){...}

}

A: There are two alternative to using a constructor to initialize instance members...
First one is Instance initialization block,
{
    // whatever code is needed for initialization goes here
    MyAdditionalObject obj=new MyAdditionalObject();
    Event e= new Event()
    obj.attacheEvent(e);
}

The reason that instance initialization block is recommended over chaining of constructor is

The Java compiler copies initializer blocks into every constructor.
  Therefore, this approach can be used to share a block of code between
  multiple constructors.

So, approach will be simpler and will reduce the vertical problem.
Second one is to use final method to initialize instance members. A final method cannot be overridden in a subclass.
Example :
class Whatever {
    private varType myVar = initializeInstanceVariable();

    protected final varType initializeInstanceVariable() {

        // initialization code goes here
        MyAdditionalObject obj=new MyAdditionalObject();
        Event e= new Event()
        obj.attacheEvent(e);
    }
}

Reference Java doc for answer : Initializing fields.


text:
Q: Extracting a specified string in a list of strings in Python I have a list in python that contains strings like['abc','defg',xyz','lmnopqrst']. I need to iterate through the list and extract elements in the 2nd and 3rd position and create another list with just those letters
ex : O/P should be a list which has ['bc','ef','yz','mn']

A: You can do like this:
new_list = [ s[1:3] for s in your_list ]

A: Let's use list comprehensions and slice notation:
output_list = [s[1:3] for s in input_list]


text:
Q: Zend_Exception with message 'Registry is already initialized' Using Zend, Extjs, and socialengine4. I am adding users to the user table and they are successfully put into the database with the 'enabled' and 'verified' set at 1. I can add the new users to the table and set those values perfectly fine and when i go to the next page i can click on a link to the user's profile page that i have just created and the information that i have input for their profile is displayed. If i try to click  on the link again i get the following error.
exception 'Zend_Exception' with message 'Registry is already initialized' in /var/www/web15/web/application/libraries/Zend/Registry.php:71
Stack trace:
#0 /var/www/web15/web/application/libraries/Engine/Registry.php(87): Zend_Registry::setInstance(Object(Engine_Registry))
#1 /var/www/web15/web/application/libraries/Engine/Registry.php(104): Engine_Registry::setInstance(Object(Engine_Registry))
#2 /var/www/web15/web/application/libraries/Engine/Registry.php(66): Engine_Registry::init()
#3 /var/www/web15/web/application/libraries/Engine/Registry.php(176): Engine_Registry::getInstance()
#4 /var/www/web15/web/application/modules/User/Model/User.php(231): Engine_Registry::get('database-defaul...')
#5 /var/www/web15/web/application/modules/User/controllers/ProfileController.php(63): User_Model_User->isAdmin()
#6 /var/www/web15/web/application/libraries/Zend/Controller/Action.php(513): User_ProfileController->indexAction()
#7 /var/www/web15/web/application/libraries/Zend/Controller/Dispatcher/Standard.php(289): Zend_Controller_Action->dispatch('indexAction')
#8 /var/www/web15/web/application/libraries/Zend/Controller/Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#9 /var/www/web15/web/application/modules/Core/Bootstrap.php(75): Zend_Controller_Front->dispatch()
#10 /var/www/web15/web/application/libraries/Engine/Application.php(160): Core_Bootstrap->run()
#11 /var/www/web15/web/application/index.php(194): Engine_Application->run()
#12 /var/www/web15/web/index.php(24): include('/var/www/web15/...')
#13 {main}

Once this error is thrown it will reset my table values of 'enabled' and 'verified' to 0. The user will no longer show up on the page or when i click to browse members but its db entry is still there with its changed values.


text:
Q: Method of finding all the classes used by a main class I am provided with a workspace where i have to extract few classes. I know the main classes which have to be extracted. Is there a way in eclipse which lists all the classes used by this main class. Indirect and direct references of this class.
For example:
I have main class A which uses class B and class C. Class C internally uses class D.
So for all the classes used in A should list B,C and D.

A: You can delete the classes folder of your application and compile only the class you want to obtain dependencies for using javac  where you provide the classpath of dependent jars (if any). The java compiler will find all the dependencies of this class and compile them as well:
javac -classpath dep1.jar;dep2.jar path.to.your.class.YourClass.java


text:
Q: I have error on checkout page I have error on checkout page (see the image) .
Continue button is not working. Any luck ?

A: Based on your question i think you uploaded a google script (maybe review script ) , and the way you added the values blocks the current page for proceeding. Use this for delivery country :
 "delivery_country": "<?php echo $googleRatingData['delivery_country'] ?>",

For the delivery date :
 "estimated_delivery_date": "<?php echo $deliveryDate=Date('Y-m-d', strtotime("+12 days")); ?>",

Update the date as you want.
If this doesnt work for you , paste the full script here (without the mercant id ) so we can debug.


text:
Q: Truth value of a Series is ambiguous. Use a.empty(), a.bool(), a.item(), a.any() or a,all() I'm trying to write a code that takes certain (optional) inputs from a .csv file and outputs based on which criteria (inputs) have been given and which have not. I managed to get the code to take optional inputs but I want the program to take certain outputs from certain rows of the file (for example, variable w is the name of the business, I want it to read only that specified row from the .csv and ignore every other, same for every other criteria) so I tried something, here's the code:
#link CSV
    import pandas as pd

    df = pd.read_csv(r'C:\Users\ASUS\Documents\Small businesses.csv',encoding='latin1')

    print(df.to_string())
   #Take input
w=str(input('enter name here'))
x=str(input('enter field here'))
y=str(input('enter desired operation size here'))
z=str(input('enter preferred mode of service here'))
#refine output
#to revert what you did if it doesn't work, remove the df statements and convert
#every second if back to elif
if df.iloc[1,4]:
 if x == "":
    print (y + z)
or df.iloc[1,7]:
 if y == "":
    print (x + z)
or df.iloc[1,11]:
 if z == "":
    print (x + y)
or df.iloc[[1,4],[1,7]]:
 if x == "" and y == "":
    print(z)
or df.iloc[[1,4],[1,11]]:
 if x == "" and z == "":
    print(y)
or df.iloc[[1,7],[1,11]]:
    if y == "" and z == "":
     print(x)
or df.iloc[[1,1]]:
 if w == "":
    print ("accoridng to other guidelines, we find:")

I know the code is wrong but I just don't know how to fix it since I'm new to programming, I got this error: "Truth value of a Series is ambiguous. Use a.empty(), a.bool(), a.item(), a.any() or a,all()"
Any fixes? Thank you
edit:
For all the people asking me to paste a portion of the .csv to help, here it is:
small business.csv screenshot
Here's the full error from the kernel:
File "C:\Users\ASUS\untitled2.py", line 29, in
if df.iloc[[1,4],[1,7]]:
File "C:\Users\ASUS\AppData\Local\Programs\Spyder\pkgs\pandas\core\generic.py", line 1330, in nonzero
f"The truth value of a {type(self).name} is ambiguous. "
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
(sorry I'm new to this)

A: df.iloc[[1,4],[1,11]]

and other such statements return a pd.series, not a Boolean.
In order to evaluate those in an If statement, you have to reduce these multiple values into a single Boolean value using some logic.
Usually, you will want to use .any() or .all() for that.


text:
Q: ASP.NET Core MVC List.Contains(Model) I have this class:
public class UserSet
{
    public int One { get; set; }
    public string Two { get; set; }
    public string Three { get; set; }
}

And a static class:
public static class AllUsers
{
    public static List<UserSet> Usersc = new List<UserSet>();
}

I always create new UserSet and then store it in Usersc. Basically I do this:
Data.UserSet setupSet = new Data.UserSet()
        {
            One = name,
            Two = OsCislo,
            Three = User.Identity.Name
        };

Then I store it.
Data.AllUsers.Usersc.Add(setupSet)

Now what I want to do is:

*

*Define setupSet

*Check if setupSet is in Usersc.

*If one (from my setupSet) is in Usersc then
3a) if setupSet is in Userc and everything is equal then don't do anything.
3b) If something is different then delete old UserSet in AllUsers and insert the new one

In code it will look like this:
Data.UserSet setupSet = new Data.UserSet()
        {
            One = name,
            Two = OsCislo,
            Three = User.Identity.Name
        };

if (Data.AllUsers.Usersc.Select(s => s.One).ToList().Contains(User.Identity.Name))
{
    // Always returns false for some reason
    if (!Data.AllUser.Usersc.Contains(setupSet))
    {
        Data.AllUsers.Usersc.Remove(Data.AllUsers.Usersc.Where(s => s.One == User.Identity.Name).ToList().First());
        Data.AllUsers.Usersc.Add(setupSet);
    }
}
else
{
    Data.AllUsers.Usersc.Add(setupSet);
}

As you can see, problem is in my if statement where I try to get whether setupSet is inside Usersc but for some odd reason it always returns false even though setupSet should be inside it.

A:
even tho setupSet should be inside it

There's a reason static is rarely used in Asp.Net projects, of any kind: there are multiple threads that handle your requests, and if they're all fighting over the same List<>, that's a recipe for disaster.
Either use a synchronized collection (like ConcurrentSet<> or ConcurrentBag<>), or use a crude locking mechanism, or something to make sure you don't trample one thread's list access from another.
Or even better, use a database to store data. That's what it's made for, and most DBMS are transactional, so they handle multi-threaded access safely for you.

A: This is because your line of code Data.AllUser.Usersc.Contains(setupSec) compares references - not values of the properties of objects in the list.
You create your setupSet object at the top without adding it to the list - so this list doesn't contain it. Despite the fact that two objects have exactly the same values of properties for .net these are two different objects. Therefore list.Contains() return false.
So to solve your problem there are 2 ways:

*

*Don't use Contains() method of List - and use LINQ expression comparing properties that are crucial for your understanding equality of 2 objects of your UserSet class

*Definitely better - implement Equals method inside your UserSet class that will tell the CLI what do you understand as EQUAL if it comes to your class.
Take a look at the following code (please bear in mind that this is a naive implementation):
void Main()
{
    var myList = new List<SomeClass>();

    var o1 = new SomeClass{SomeProperty = "foo"};

    myList.Add(o1);

    var o2 = new SomeClass{SomeProperty = "foo"};

    if(myList.Contains(o2))
    {
        "List Contains element".Dump();
    }
    else{
        "List does not contain element".Dump();
    }

}

private class SomeClass{
    public string SomeProperty {get;set;}

    public override bool Equals(object obj)
    {
        var casted = obj as SomeClass;
        if(casted == null) return false;
        if(string.Equals(casted.SomeProperty, this.SomeProperty)) return true;
        return false;
    }
}

Here I told the .NET what it means for me that 2 instances of my SomeClass are equal by overriding the {public bool Equals(object obj)} method.
Inside of that method I write that 2 objects are equal if value of SomeProperty is the same.
if(string.Equals(casted.SomeProperty, this.SomeProperty)) return true;

Therefore in the console, I can see "List Contains element". If you remove that override Equal the console will say "List does not contain the element".
Last but not least as Blindy wrote - use thread-safe collection. It will make your example better (however I don't believe that threads are the problem that you described).
You can also dive deeper into in-memory database in Entity Framework - you will not have to create that static class with a static collection of elements (which is a mock of database of cache I believe). It is super-easy
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                    .UseInMemoryDatabase(databaseName: "My_DB")
                    .Options;
            var context = new ApplicationDbContext(options);


text:
Q: How to concat two response, invoke in sequence. Second http call depends on the value returned by the first? Now I have that code and try to return concerted value from two http Call
defer(() => {
                return this.service.save1(data)
                    .pipe(
                        concatMap((result) => {
                            if (result) {
                                return of({
                                    ...result,
                                    c: this.service.save2(result.id , this.obj).subscribe()
                                })
                            }
                            return of({});
                        }),
                        catchError(err => throwError(err)),
            }).subscribe((result) => {
                if (result) {
                    console.log(result);
                }
            },

In cosnole.log(result) now we have the whole object result + c: as Observable
I'd like to return all fields returned by the first call and c: as an array of objects

A: You don't have to subscribe inside the operators. Instead you could return the observable directly and subscribe where the result is required.

*

*Use filter pipe to ignore undefined responses from the first request. This way the if conditions inside the concatMap and subscription isn't needed.

*Pipe a map to the second observable to combine both the results.

Try the following
return this.service.save1(data).pipe(
  filter((result) => (!!result))   // <-- go ahead only if `result` is defined
  concatMap((result) =>
    this.service.save2(result.id, this.obj).pipe(
      map((c) => ({
        ...result,
        c: c
      }))
    )
  ),
  catchError(err => throwError(err))   // <-- `catchError` is redundant at the moment
);

A: you can format the response by piping the response of observable c. there is no need to subscribe to that observable, it will automatically subscribe to the value with concatMap
 defer(() => {
    return this.service.save1(data)
        .pipe(
            concatMap((result) => {
                if (result) {
                    return this.service.save2(result.id , this.obj).pipe(
                            map((data) => [...data, result]) // all the data is
                                                             // available here, format
                                                             // as you would like
                }
                return of({});
            }),
            catchError(err => throwError(err)),
}).subscribe((result) => {
    if (result) {
        console.log(result);
    }
},


text:
Q: Partially sort an array in descending order using Java Stream API I need to know how to partially sort an array of primitive unique integers in descending order using Stream API. For example, if there is an array like {1,2,3,4,5}, I want to get {5,4,3, 1,2} - 3 biggest elements first and then the rest. Is it even possible using streams? I checked the docs - there are two methods skip and limit but they change the stream content and work from the beginning of the array.
I can sort the whole array like
Arrays.stream(arr)
.boxed()
.sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();

but how to make this sorting partial? I said Stream API because I want it to be written nicely.
Also I intuitively feel that concat may have a go here. Another approach I could think about - is to use a custom comparator limiting the number of sorted elements. What do you think?
P.S. I am not a Java expert.

A: Though the code is longer than the accepted answer, it does a lot less sorting: for big arrays this will matter:
private static int[] partiallySorted(int[] input, int bound) {
    int[] result = new int[input.length];

    int i = -1;
    PriorityQueue<Integer> pq = new PriorityQueue<>(bound, Comparator.naturalOrder());
    for (int x : input) {
        pq.add(x);
        if (pq.size() > bound) {
            int el = pq.poll();
            result[bound + ++i] = el;
        }
    }

    while (!pq.isEmpty()) {
        result[--bound] = pq.poll();
    }

    return result;
}

A:
I need to know how to partially sort an array of primitive integers in descending order using Stream API.

There is no built-in tool that lets you do this in Java. Neither in the Stream API nor in the Collections API. You either need to implement it on your own or change your approach.

I said Stream API because I want it to be written nicely.

Using Java 8 Streams does not mean that your code will be written nicely. Streams are not universal tools. Sometimes they offer enhanced readability and sometimes you have to use something else.

Another approach I could think about - is to use a custom comparator limiting the number of sorted elements.

That can't be done, since Comparator does not know how many elements have been sorted. Simply counting the calls will not give you any meaningful information in this regard.

What I would suggest is implementing something like C++'s std::partial_sort, which is most likely based on the heap approach.

A: Here's an approach using streams.
int[] sortPartially(int[] inputArray, int limit) {
    Map<Integer, Long> maxValues = IntStream.of(inputArray)
                                            .boxed()
                                            .sorted(Comparator.reverseOrder())
                                            .limit(limit)
                                            .collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.counting()));

    IntStream head = maxValues.entrySet()
                              .stream()
                              .flatMapToInt(e -> IntStream.iterate(e.getKey(), i -> i)
                                                          .limit(e.getValue().intValue()));

    IntStream tail = IntStream.of(inputArray)
                              .filter(x -> {
        Long remainingDuplication = maxValues.computeIfPresent(x, (y, count) -> count - 1);
        return remainingDuplication == null || remainingDuplication < 0;
    });

    return IntStream.concat(head, tail).toArray();
}

Above example of course sorts the entire input array, but keeps the order of unsorted elements stable.
Another stream example using priority queue (as others mentioned) reduces the runtime complexity:
Collection<Integer> sortPartially(int[] inputArray, int sortedPartLength) {
    Queue<Integer> pq = new PriorityQueue<>(sortedPartLength);

    Deque<Integer> result = IntStream.of(inputArray).boxed().map(x -> {
        pq.add(x);
        return pq.size() > sortedPartLength ? pq.poll() : null;
    }).filter(Objects::nonNull).collect(Collectors.toCollection(ArrayDeque::new));

    Stream.generate(pq::remove).limit(sortedPartLength).forEach(result::addFirst);

    return result;
}

If there are duplicates in the input array, the order of unsorted elements can change.

A: I  would save the three largest elements in a set and then define my own comparator.
 public static void main(String[] args){
    int[] input = {1,2,3,4,5};
    Set<Integer> set = Arrays.stream(input).boxed().sorted(Comparator.reverseOrder()).limit(3).collect(Collectors.toSet());
    Comparator<Integer> customComp = (a,b) -> {
        if(set.contains(a) && set.contains(b)){ return a.compareTo(b);}
        else if(set.contains(a)){ return 1;}
        else if(set.contains(b)){ return -1;}
        else { return 0;}
    };
    int[] sorted = Arrays.stream(input).boxed().sorted(customComp.reversed()).mapToInt(i->i).toArray();
    System.out.println(Arrays.toString(sorted));
}

A: You won't be able to do this very nicely using streams. Here is one way to do it:
public static void main(String[] args) {

    Integer[] arr = {1, 2, 3, 4, 5};
    List<Integer> originalValues = new ArrayList<>(Arrays.asList(arr));

    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        originalValues.stream().max(Integer::compareTo).ifPresent(v -> {
            list.add(v);
            originalValues.remove(v);
        });
    }
    list.addAll(originalValues);

    System.out.println(list);
    // [5, 4, 3, 1, 2]
}


text:
Q: ICustomTypeDescriptor with display Hi guys I am implementing the interface ICustomTypeDescriptor and binding to a WPF grid. I am having issues with result, was expecting just the single column "Random" but getting something totally different. Any help would be much appreciated. Andy

/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
    //- PROPERTIES --------------------------------------------------------------------------------------------------------------

    #region Properties

    /// <summary>
    /// Component Type
    /// </summary>
    public override Type ComponentType
    {
        get { return typeof(Dictionary<string, TestResultValue>); }
    }

    /// <summary>
    /// Gets whether its read only
    /// </summary>
    public override bool IsReadOnly
    {
        get { return false; }
    }

    /// <summary>
    /// Gets the Property Type
    /// </summary>
    public override Type PropertyType
    {
        get { return typeof(string); }
    }

    #endregion Properties

    //- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------

    #region Constructor

    /// <summary>
    /// Constructor
    /// </summary>
    public TestResultPropertyDescriptor(string key)
        : base(key, null)
    {

    }

    #endregion Constructor

    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Can Reset Value
    /// </summary>
    public override bool CanResetValue(object component)
    {
        return true;
    }

    /// <summary>
    /// Gets the Value
    /// </summary>
    public override object GetValue(object component)
    {
        return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
    }

    /// <summary>
    /// Resets the Value
    /// </summary>
    public override void ResetValue(object component)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
    }

    /// <summary>
    /// Sets the value
    /// </summary>
    public override void SetValue(object component, object value)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
    }

    /// <summary>
    /// Gets whether the value should be serialized
    /// </summary>
    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}
/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Gets the Attributes for the object
    /// </summary>
    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
        return new AttributeCollection(null);
    }

    /// <summary>
    /// Gets the Class name
    /// </summary>
    string ICustomTypeDescriptor.GetClassName()
    {
        return null;
    }

    /// <summary>
    /// Gets the component Name
    /// </summary>
    string ICustomTypeDescriptor.GetComponentName()
    {
        return null;
    }

    /// <summary>
    /// Gets the Type Converter
    /// </summary>
    TypeConverter ICustomTypeDescriptor.GetConverter()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Event
    /// </summary>
    /// <returns></returns>
    EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Property
    /// </summary>
    PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
    {
        return null;
    }

    /// <summary>
    /// Gets the Editor
    /// </summary>
    object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
    {
        return null;
    }

    /// <summary>
    /// Gets the Events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
    {
        List<TestResultPropertyDescriptor> properties = new List<TestResultPropertyDescriptor>();

        //Add property descriptors for each entry in the dictionary
        foreach (string key in this.Keys)
        {
            properties.Add(new TestResultPropertyDescriptor(key));
        }

        //Get properties also belonging to this class also
        //PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);

        //foreach (PropertyDescriptor oPropertyDescriptor in pdc)
        //{
        //    properties.Add(oPropertyDescriptor);
        //}

        return new PropertyDescriptorCollection(properties.ToArray());
    }

    /// <summary>
    /// gets the Properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
    {
        List<TestResultPropertyDescriptor> properties = new List<TestResultPropertyDescriptor>();

        foreach (string key in this.Keys)
        {
            properties.Add(new TestResultPropertyDescriptor(key));
        }
        return new PropertyDescriptorCollection(properties.ToArray());

    }

    /// <summary>
    /// Gets the property owner
    /// </summary>
    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}`public class TestResultValue
{
    private object _value;
    public object Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
        }

    }
}`

This is how I am using it...
var items = new ObservableCollection<TestResultRowWrapper>();
        var row = new TestResultRowWrapper();
        row.Add("Random", new TestResultValue() { Value=1.1});
        items.Add(row);

        dataGrid1.ItemsSource = items;


text:
Q: Why are linux-headers not upgraded by apt-git dist-upgrade After a fresh ubuntu 12.10 installation, I faced some problems installing Nvidia drivers.
After some research discovered that linux-headers are not being upgraded when executing sudo apt-get dist-upgrade. I had to install the new headers manually although linux-image packages are installed.
Anyone knows why is this happening to me? Is it normal or there's something wrong?

A: If you installed linux-headers matching your running kernel version only, for example, linux-headers-3.5.0-18, then they will not be upgraded. Instead, do:
sudo apt-get install linux-headers-generic

The -generic header package will update headers every time linux-image is updated.

A: I recently ran into a similar problem during Nvidia drivers installation. I am not a Linux expert so I didn't really know where to start looking, but one thing caught my attention. When I run uname -r, I get
3.2.0-30-generic-pae

Then, dpkg -l | grep linux-headers:
ii  linux-headers-3.5.0-18                                      3.5.0-18.29                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-18-generic                              3.5.0-18.29                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-19                                      3.5.0-19.30                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-19-generic                              3.5.0-19.30                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-21                                      3.5.0-21.32                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-21-generic                              3.5.0-21.32                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-22                                      3.5.0-22.34                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-22-generic                              3.5.0-22.34                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-23                                      3.5.0-23.35                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-23-generic                              3.5.0-23.35                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-24                                      3.5.0-24.37                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-24-generic                              3.5.0-24.37                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-25                                      3.5.0-25.39                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-25-generic                              3.5.0-25.39                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-26                                      3.5.0-26.42                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-26-generic                              3.5.0-26.42                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-3.5.0-27                                      3.5.0-27.46                               all          Header files related to Linux kernel version 3.5.0
ii  linux-headers-3.5.0-27-generic                              3.5.0-27.46                               i386         Linux kernel headers for version 3.5.0 on 32 bit x86 SMP
ii  linux-headers-generic                                       3.5.0.27.43                               i386         Generic Linux kernel headers
ii  linux-headers-generic-pae                                   3.5.0.27.43                               i386         Transitional package

And finally, dpkg -l | grep linux-image:
rc  linux-image-3.2.0-23-generic-pae                            3.2.0-23.36                               i386         Linux kernel image for version 3.2.0 on 64 bit x86 SMP
ii  linux-image-3.2.0-30-generic-pae                            3.2.0-30.48                               i386         Linux kernel image for version 3.2.0 on 32 bit x86 SMP
rc  linux-image-3.2.0-31-generic-pae                            3.2.0-31.50                               i386         Linux kernel image for version 3.2.0 on 32 bit x86 SMP
rc  linux-image-3.5.0-27-generic                                3.5.0-27.46                               i386         Linux kernel image for version 3.5.0 on 32 bit x86 SMP

Shouldn't the linux-headers and linux-image packages match? That was also the problem when installing the Nvidia drivers: it couldn't find the package linux-headers-3.2.0-30-generic-pae. It seems the updates somehow got messed up. What can I do about it?


text:
Q: jQuery adding custom password rule not working I am new to jQuery and i am using jQuery form validator to validate my form..
The problem is , i have to validate the password as it must contain at-least one digit..
I searched on Google and I found example in here Link to forum.jquery
Here is the snippet of my HTML code
  <form  name="f2" id="f2" method="post" action="hello">

                 Password

             <input type="password" name="pwd" id="pwd"  placeholder="Enter Password" class="text_box">

              <button type="submit" class="submit-button">Register</button>

    </form>

    //jquery script for form validation

Everything works fine until i add the this line to above code rules
pwd:{
    required:true,
    minlength:5,
    mypassword: true
}

I included the additional scripting file which contains the following method
jQuery.validator.addMethod('mypassword', function(value, element)
{
    return this.optional(element) || (value.match(/[a-zA-Z]/) && value.match(/[0-9]/));
},
'Password must contain at least one numeric and one alphabetic character.');

After trying to execute the above code, I got the following error message in my browser console as follows:

Uncaught TypeError: Cannot call method 'call' of undefined  in
  js/jqueryvalidation.js

Why the additional method not working?
Any help or suggestions would be greatly appreciated.

A: Please check the example in the fiddler link : http://jsfiddle.net/NaaEw/
    jQuery.validator.addMethod('mypassword', function(value, element)
    {
       return this.optional(element) || (value.match(/[a-zA-Z]/) && value.match(/[0-9]/));
    });

and message :
    pwd:{
                    required:"Please enter password",
                    minlength:"Please enter minimum characters",
      mypassword: 'Password must contain at least one numeric and one alphabetic character.'

Hope this is what you are expecting.


text:
Q: steering behavior and passed time I'm trying to implement steering behaviors but I have a problem with "including" the passed time in the calculation and then allowing me to control the speed of the game. I have seen various sources of steering behaviors and I've come up with this (Arrive behavior):
var toTarget:Vector2D = new Vector2D( mEntity.targetPosition.x, mEntity.targetPosition.y );
toTarget.subtract( mEntity.position );
var dist:Number = toTarget.length;
toTarget.normalize().scale( mEntity.maxSpeed );
if( dist < slowDownDist ) {
    toTarget.scale( dist / slowDownDist );
}
return toTarget.subtract( mEntity.velocity );

And here's the advanceTime method of MovingEntity:
var steeringForce:Vector2D = mSteering.calculate();
steeringForce.x /= mMass;
steeringForce.y /= mMass;
steeringForce.scale( time );
mVelocity.x += steeringForce.x;
mVelocity.y += steeringForce.y;
x += mVelocity.x * time;
y += mVelocity.y * time;

The steering force should be (at some point) directly opposite to the entity's velocity and thus making it stop. The problem I see and do not understand is that in order to simulate acceleration the force needs to be divided by mass and also to consider the passed time it needs to be multiplied by that time - but this scales the steering force down a lot and causes the entity to overshoot the target spot instead of stopping there so then it returns back which effectively causes oscillation. If I do not multiply the force with the time then the moving entity behaves slightly differently depending on the game speed.

A: By second (?) Newton's law F = m * a where F is force, m is mass and a is acceleration. Force is measured in newtons, mass in kilograms and acceleration in meters per second per second. So, you just need to apply bigger force, and lave the calculation as is.


text:
Q: Ruby 2.3/Rails - net uri not working anymore after update to Ubuntu 16.04 I used to have a working code in my Admin Panel , checking if a url inputed existed and giving a friendly message to the Administrator in case it did not..
def get_url_response(url)
    uri = URI(url)
    request = Net::HTTP.get_response(uri)
    return request
end

url_response = get_url_response("http://www.example.com").code
    if  url_response === "200" || url_response === "304"
       link_to http://www.example.com, http://www.example.com, target: :blank
    else
        status_tag("We have a problem ! Response code: "+url_response, :class => 'red')
    end

It works great when the address ("http://www.example.com" in the example above) exists, that it to say sends back a 200 code, but as soon as I have a non existing address such as http://www.examplenotexistingotallyfake.com, it should send a 404 code and display ""We have a problem ! Response code:" but it fails with the error message:
SocketError: Failed to open TCP connection to examplenotexistingotallyfake.com:443 (getaddrinfo: Name or service not known)
from /home/mreisner/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/net/http.rb:882:in `rescue in block in connect'

I verified this by opening my Rails console (Rails c) and if I type:
 Net::HTTP.get(URI('https://www.examplenotexistingotallyfake.com')).code

I get the same error message:
 SocketError: Failed to open TCP connection to examplenotexistingotallyfake.com:443 (getaddrinfo: Name or service not known)
from /home/mreisner/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/net/http.rb:882:in `rescue in block in connect'

How can it work for correct urls and not for non-existing addreses? it should just work but send me back a 404 code, shouldn't it?
I can only see the upgrade to Ubutun 16.04 i made a few days ago, that might have tampered with some critical dns/localhost settings as the source of this issue but not 100% totally sure.
EDIT
After some suggestions, I now try to avoid the app crashing by rescuing this
def get_url_response(url)
    begin
        uri = URI(url)
          request = Net::HTTP.get_response(uri)
          return request

        rescue SocketError => e
        puts "Got socket error: #{e}"
        end

  end

but the app still crashes with a socket Error message

A: That's the correct behaviour.
The problem there is that examplenotexistingotallyfake.com doesn't exists in the DNSs entries.
If you look at the description of what the 404: https://en.wikipedia.org/wiki/HTTP_404

to indicate that the client was able to communicate with a given
  server, but the server could not find what was requested.

So, in order to get the 404 code you'll need first to be able to communicate with the server in question.
You can double check this behaviour using chrome or even curl, visiting the following urls: examplenotexistingotallyfake.com or google.com/missing
Each will give a different result.
in curl:
$ curl -I examplenotexistingotallyfake.com
curl: (6) Could not resolve host: examplenotexistingotallyfake.com

# google
curl -I google.com/missing
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
Content-Length: 1568
Date: Fri, 12 Jan 2018 09:25:27 GMT

If you want your code to behave in the same way (even though I'd suggest that give the user a different message, you can do the following):
require 'uri'
require 'net/http'
require 'ostruct'

def get_url_response(url)
  uri = URI(url)
  request = Net::HTTP.get_response(uri)
  return request
rescue Errno::ECONNREFUSED => e
  OpenStruct.new(code: 404)
end

A: Its not an issue , the site you are looking for it doesn't exists and can't be reached.
So it will give DNS address is not found issue when you try to hit it directly.Thats why the error:
It directly gives socketError : getaddrinfo: Name or service not known You need to handle this.
But if you want 404 status code, you will get it when the site(address) is present and the page inside that site is not.
To get 404 your address should be valid and error will raise if The requested URL /examples was not found on this server.


text:
Q: Easiest way to scrape Google for URLs via my browser? I'd like to scrape all the URLs my searches return when searching for stuff via Google. I've tried making a script, but Google did not like it, and adding cookie support and captcha was too tedious. I'm looking for something that - when I'm browsing through the Google search pages - will simply take all the URLs on the pages and put them inside a .txt file or store them somehow.
Does any of you know of something that will do that? Perhaps a greasemonkey script or a firefox addon? Would be greatly appreciated. Thanks!

A: See the JSON/Atom Custom Search API.

A: I've done something similar for Google Scholar where there's no API available. My approach was basically to create a proxy web server (a java web app on Tomcat) that would fetch the page, do something with it and then show to user. This is 100% functional solution but requires quite some coding. If you are interested I can get into more details and put up some code.

A: Google search results are very easy to scrape. Here is an example in php.
<?
# a trivial example of how to scrape google
$html = file_get_contents("http://www.google.com/search?q=pokemon");

$dom = new DOMDocument();
@$dom->loadHTML($html);
$x = new DOMXPath($dom);
foreach($x->query("//div[@id='ires']//h3//a") as $node)
{
    echo $node->getAttribute("href")."\n";
}
?>

A: You may try IRobotSoft bookmark addon at http://irobotsoft.com/bookmark/index.html


text:
Q: How would someone discover the Einstein-Hilbert Action? Usually in textbooks or on online resources, when you are learning General Relativity, propose the following:
$$
\mathcal S[g_{\mu\nu}] =\frac{1}{2 \kappa}\int_{\mathcal M} {\mathrm d^4 x \; R\sqrt{-g}}
$$
This is the Einstein-Hilbert Action. All textbooks, in which appears, propose it as something trivial, but how Hilbert arrived to this conclusion? The best I could do, while searching for information, was to find how to vary the action and find Einstein-Field Equations in the vacuum from it. But my question is: what procedure did Hilbert follow to find this formula, how would you derive it (and know this will give EFE in the vacuum)?

A: I don't know the history of how the Einstein-Hilbert action was discovered originally, but from a modern point of view it can be justified in several ways.
First, if you want to represent gravity as geometry of spacetime, and you don't want a fixed "background" geometry, then you need the action for pure gravity to be a scalar built out of the metric and derivatives. By locality, we also want the action to be an integral of a local function. The logic of effective field theory (see also this review) tells us that at low energies, the terms in the action with the smallest numbers of derivatives will be the most important. Then...

*

*At zeroth order in derivatives, the only local scalar function involving the metric is a constant (the cosmological constant)
\begin{equation}
S_{CC} = \int {\rm d}^4 x \sqrt{-g}
\end{equation}

*At first order in derivatives, there are no candidate scalar functions. With one derivative, you would have an unpaired index $\nabla_\mu$ which has nothing to be contracted with.

*At second order in derivatives, there is one candidate scalar function, the Ricci scalar $R$. This immediately gives us the Einstein-Hilbert action
\begin{equation}
S_{EH} = \int {\rm d}^4 x \sqrt{-g} R
\end{equation}

*At fourth order in derivatives, there are three candidate terms, which could appear, generally with arbitrary coefficients
\begin{equation}
S_{4} = \int {\rm d}^4 x \sqrt{-g} \left(c_1 R^2 + c_2 R_{\mu\nu} R^{\mu\nu} + c_3 R_{\mu\nu\rho\sigma} R^{\mu\nu\rho\sigma} \right)
\end{equation}

*There are more possible combinations at higher orders in derivatives (also including covariant derivatives acting on the Riemann curvature tensor) but we expect these to be relatively unimportant (or irrelevant in the lingo) at low energies.

So the Einstein-Hilbert term plus a cosmological constant is a natural guess for a low energy theory of gravity from modern effective field theory logic.
There are also more sophisticated methods to justify the Einstein-Hilbert action. In particular:

*

*The Einstein-Hilbert action is the unique low energy theory of an interacting, Lorentz invariant, local, massless spin-2 particle. This is justified in a series of works, including the Feynman lectures on gravitation, and this classic paper by Deser: https://arxiv.org/abs/gr-qc/0411023.

*In order to have second order equations of motion (which is generally required to avoid ghost instabilities), only special combinations of curvature tensors can be used in the Lagrangian, called Lovelock invariants. The Einstein-Hilbert term (and cosmological constant) are the simplest (lowest order) Lovelock invariants. (And in four dimensions, the only non-trivial Lovelock invariants).

*

*There is also $f(R)$ gravity, where you have an arbitrary function of the Ricci scalar as your action, but this describes a spin-2 particle plus an additional scalar degree of freedom, so adds an extra physical mode relative to general relativity.

A: A physicist is liable to build a theory as the simplest option that does what they want. The truth is we can't "deduce" a unique theory; @Andrew's answer gives a great overview of more complex alternatives. Let's see how far this KISS principle takes us.
One of the earliest findings when working with covariant derivatives on a differentiable manifold is they don't commute. Even under the zero-torsion assumption of general relativity - which fits the data (if there is torsion it's very small), simplifies and uniquely determines such derivatives - we get $[\nabla_a,\,\nabla_b]V_c=R_{abcd}V^d$, with $R_{abcd}$ the Riemann tensor. (If you add in torsion, we get another interesting coefficient tensor, but let's keep it simple.)
Since this tensor quantifies how far we depart from partial derivatives' famous commutativity, and it's made of the metric tensor and derivatives up to its second, scalars made from it are natural candidate terms in the scalar Lagrangian density (a little-used term for Lagrangian density divided by $\sqrt{|g|}$). Next we keep it "simple" in the sense of being linear. The tensor turns out to have such antisymmetries we only have one linear option, namely the Ricci scalar $R=R_{abcd}g^{ac}g^{bd}$.

A: Einstein argued that physical laws should be generally covariant. This can be physically motivated from the argument that the physics of a situation should not be dependent upon how we describe the situation through coordinates. Formalising this leads to the notion of spacetime being described by manifolds and physical laws being covariant wrt to diffeomorphisms of the spacetime manifold. The natural structure on the manifold, after Minkowski's reformulation of SR as a 4d theory of spacetime, is a Lorentzian metric and the natural invariant of this is its curvature.
It's through these and other arguments that Einstein discovered the field equations of GR.
Hilbert took a different route. He searched instead for an action principle. The simplest Lagrangian or action density here is the scalar curvature. When he looked at its Euler-Lagrange eom he discovered Einstein's field equatuons roughly about the same time.
It also turns out that this is the correct action to unify the classical theory of gravity and YM. Roughly speaking, if we look at principal bundle with structure group G over the spacetime manifold amd impose the same action then the variations wrt metric gives Einstein's field equations whilst varying the connection yields the Yang-Mills equations. All this came out of Kaluza, Klien and Nordstrom's work on higher dimensional gravity.


text:
Q: Evaluation of a multiple sum involving $\min\{i_0, i_1+ \cdots+ i_n\}$ with $i_1+ \cdots+i_n\leq x$ How  can I calculate

$\displaystyle\sum_{i_0=0}^x \sum_{i_1,\ldots, i_n=0}^1I_{i_1+
 \cdots+i_n\leq x}\min\{i_0, i_1+ \cdots+ i_n\}$
  as a function of $n,x$?

$I_{i_1+ \cdots+i_n\leq x}$ is indicator function which is 1 if $i_1+ \cdots+i_n\leq x$, else zero.
Also $x<n$.
Now
\begin{eqnarray}
\displaystyle\sum_{i_0}^x \sum_{i_1,\ldots, i_n=0}^1I_{i_1+
 \cdots+i_n\leq x}\min\{i_0, i_1+ \cdots+ i_n\}=\\
  \sum_{i_1,\ldots, i_n=0}^1I_{i_1+
 \cdots+i_n\leq x}\big( \sum_{i_0=0}^{i_1+\cdots+i_n}i_0 + \sum_{i_0=i_1+\cdots+i_n+1}^x i_1+ \cdots+ i_n\big )
\end{eqnarray}
But I can not proceed further due to indicator function.
Kinly give me some hints.


text:
Q: top.window.close() stops working on Google Editor add-on after Chrome 88 update We are using Google Outh2 client provided for google App-script Google-outhClient2 for Authorizing access to our Server.
The library opens the Authorization URL in the next tab and after successful login, it would close the tab with the custom function written by us
setTimeout(function() { top.window.close() }, 1);

However, after the recent Chrome update to 88, the above method has stopped working.
This is the message I receive

"Scripts may close only the windows that were opened by them"

When I read about Chrome 88 changes, I came across Google's policy change on "Tab Hopping"
Any other insight on how to tackle this would be helpful.
Updated the code workflow here
function getDriveService() {
try {
 return OAuth2.createService('service')
      .setAuthorizationBaseUrl(authUrl)
      .setTokenUrl(tokenUrl)
      .setRefreshUrl(tokenUrl)
      .setClientId(Client ID)
      .setClientSecret(Client Secret)
      .setCallbackFunction('authCallback')
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope('user')
      .setExpirationMinutes(0)
      .setParam('access_type', 'offline')
     .setParam('prompt', 'consent')
    }
    catch(e) {

    }
}

function authCallback(request) {
  try {
  var driveService = getDriveService();
  var isAuthorized = driveService.handleCallback(request);
  if (isAuthorized) {
    showFile();
    return HtmlService.createHtmlOutput('Success! <script>setTimeout(function() { top.window.close() }, 1);</script>');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}
catch(e) {
}
}


text:
Q: creating a mosaic with jai I am trying to create a concatenation of multiple images into one, but have been having problems. To isolate this I have created the following POC which I am trying to solution in order that I understand how to use the JAI API.
In the POC, I have two images "image1.gif" and "image2.gif" which are both 256x256. The objective is to concatenate them horizontally into a single image "image3.png" which is 512x256. Here is the code I wrote for this using JAI.
try {
    InputStream stream1 = new FileInputStream("D:\\poc\\image1.gif");
    InputStream stream2 = new FileInputStream("D:\\poc\\image2.gif");
    RenderedImage image1 = ImageIO.read(stream1);
    RenderedImage image2 = ImageIO.read(stream2);
    ImageLayout imageLayout = new ImageLayout(0,0,512,256);
    RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
    RenderedImage finalImage = MosaicDescriptor.create(new RenderedImage[]{image1, image2}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
    FileStoreDescriptor.create(finalImage, "D:\\poc\\image3.png", "PNG", null, null, null);
} catch (FileNotFoundException e) {
    e.printStackTrace();
    return;
} catch (IOException e) {
    e.printStackTrace();
    return;
}

What I get is an image of correct dimensions 512x256, with the first image (image1) in its entirety on the left side of the image, and the right hand side of the image completely black. In other words, it is like I have concatenated the image1.gif with a 256x256 black square.
I have tried changing the MosaicType to MosaicDescriptor.MOSAIC_TYPE_BLEND, but this just creates a similar image only the left half consists of image1 overlaid on top of image2 (or vice-versa) with the right half still completely black.
I have also tried changing the first two parameters of the ImageLayout constructor. This doesn't work either though - for example, I can set the first parameter of ImageLayout to -256, but then image1 is shown on the right half of the image, with the left half of the image black.
Please help!

A: Here is the final  solution I came up with - these generic methods create mosaics of two images to illustrate. You just have to map them to a common co-ordinate space - first create a mosaic of one image (to increase the overall size, as ScaleDescriptor does not work for some reason) and then translate the second one so it can be overlaid with the first.
private static RenderedImage horizontalMosaic(RenderedImage image1, RenderedImage image2) {
    ImageLayout imageLayout = new ImageLayout(0, 0, image1.getWidth() + image2.getWidth(), image1.getHeight());
    RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
    RenderedImage image3 = MosaicDescriptor.create(new RenderedImage[]{image1}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
    RenderedImage image4 = MosaicDescriptor.create(new RenderedImage[]{image2}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
    RenderedImage image5 = TranslateDescriptor.create(image4, (float)image1.getWidth(), 0.0f, null, renderingHints);
    return MosaicDescriptor.create(new RenderedImage[]{image3, image5}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
}

private static RenderedImage verticalMosaic(RenderedImage image1, RenderedImage image2) {
    ImageLayout imageLayout = new ImageLayout(0, 0, image1.getWidth(), image1.getHeight() + image2.getHeight());
    RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
    RenderedImage image3 = MosaicDescriptor.create(new RenderedImage[]{image1}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
    RenderedImage image4 = MosaicDescriptor.create(new RenderedImage[]{image2}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
    RenderedImage image5 = TranslateDescriptor.create(image4, 0.0f, (float)image1.getHeight(), null, renderingHints);
    return MosaicDescriptor.create(new RenderedImage[]{image3, image5}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, renderingHints);
}

A: Here's a more concise way to mosaic two images using JAI.  The basic process is to translate (or warp) the source images into the common image space of the mosaic.  Then you can supply all the translated images to the mosaic operation.  There's no need to perform two mosaic operations.  Since the union of the image spaces of all the input images corresponds with the desired output image space of the mosaic, you do not need to supply an ImageLayout as a RenderingHint.  In this example the input images are created in memory, but they could be read in from a file as is done in the original post.
   public void makeMosaic(String fileName) throws IOException{
        // Make a black image in memory
        RenderedImage blackImage = ConstantDescriptor.create(256f,256f,new Byte[]{0x00,0x00,0x00},null);
        // Make a white image in memory
        RenderedImage whiteImage = ConstantDescriptor.create(256f, 256f, new Byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff},null);
        // Translate the white image to shift it 256 pixels to the right
        RenderedImage translatedWhiteImage = TranslateDescriptor.create(whiteImage, 256f, 0f, new InterpolationNearest(), null);
        // Now you can mosaic the two images.  No need to supply an ImageLayout hint or pre-mosaic the black image.
        RenderedImage mosaic = MosaicDescriptor.create(new RenderedImage[]{blackImage,translatedWhiteImage}, MosaicDescriptor.MOSAIC_TYPE_OVERLAY, null, null, null, null, null);
        // Write out the output image.  Should be 256 pixels tall and 512 pixels wide with black tile on left and white tile on right.
        ImageIO.write(mosaic, "PNG", new File(fileName));
    }


text:
Q: R cronjob wrong date and time I have got a R script that generates a stat for a given time period (1 week). When i run the script from command line everything works as expected. But when i try to generate the stats with a cron job, the date and time functions are not correct.
My crontab:
/usr/bin/Rscript -e "rmarkdown::render('stats.Rmd', output_file = file.path('/tmp/stats.html'))"

The Rmd file:
---
title: "Stats"
output: html_document
---

Stats begin: `r as.Date(as.numeric(Sys.Date())-7, origin="1970-01-01")`
Stats end:   `r Sys.Date()`
[...]

The Stats begin and end time are always the time of the last execution.
I already tried to delete the generated html file and call the Rscript with --vanilla, but I had no success.

A: I found myself a solution:
Instead of the existing crontab i wrote a little R script:
#!/usr/bin/env Rscript
rmarkdown::render('/.../stats.Rmd', output_file = file.path('/tmp/stats.html'))

And updated my crontab
.../stats.R

This solves the strange behavior in my case.