text:
Q: Is it possible to have a WCF service host not bound to any specific service type? This post is somewhat connected to my previous post.
In short, I am trying to build a reverse polling http binding where the host polls its clients for requests. I am using the code from http://archive.msdn.microsoft.com/duplexhttp as my reference. Now, in this binding the  host is actually a client and the clients are actually servers. Which means, a client using this reverse polling http binding must end up with a hidden Service Host providing the channel pump facility.
Now, the usual pattern of using the ServiceHost type demands the presence of the actual WCF service implementation. In my case, the ServiceHost is open at the client - it does not have the service implementation and rightfully so.
I am wondering what is the best way to solve this problem?
Ideally, this service host needs no service. The polling host sends Message instances, which are not mapped to any service contract. These Messages are requested and replied to by dedicated channels - HttpPollingRequestChannel and HttpPollingReplyChannel respectively. But I need the service host for the channel pump facility it implements.
Edit 1
I guess more background information is necessary to clarify the picture. Our system consists of clients, the server and agents. Clients talk to the server, the latter communicates their requests to the agents, which communicate the results back to the server. All the channels are straightforward HTTP - simple and clear.
However, there is a demand to be able to deploy agents behind firewall with no ability to open inbound ports on it. This means, that the Server --> Agent communication is no longer possible. As I see it, I have two choices:

*

*Redesign the Server --> Agent protocol to make it use polling.

*Implement low level binding, which would use polling internally.

What choice would you make? Although, the second choice is harder to implement this is a one time effort. But it has numerous benefits. Is it possible? I think yes, because polling duplex http binding already exists both for Silverlight and for .NET - see the link in the beginning to this post.
Edit 2
I wish to stress again, that I do not want duplex. In duplex communication, the callback is executed in the context of the request, meaning Agent sends request and the Server performs the callback. My case is different. Agent sends nothing. The server decides out of the blue to communicate with the Agent. There is no active request on behalf of Agent. So, the existing duplex binding is not good for me, but I am trying to learn from it how to implement the polling.
The overall picture is this:

*

*Agent constantly polls the Server

*If Server wants to send a message to the Agent, that message waits for the next polling request and rides to the Agent on top of the polling request reply.

The polling requests are not part of any interface, they are implemented in a low level binding infrastructure.

A: Firstly, I would not use duplex if I were you.
In addition to a whole host of threading issues, if server and client are equivalent in terms of weight and authority, I would use 2 separate interfaces one for server to clients and the other clients back to server.
WCF might not be exactly the way to go if you need full flexibility on the message. CQRS + NServiceBus might be more suitable which defines commands and each message will mandate the action which is required to be done upon it.

A: In my opinion you are wasting your time. The technology is not prepared for that. If you want duplex communication with clients use Publish/subscribe pattern. If you want just server to call clients expose service on clients and user server as client of that services.
Why?

*

*It will save you enormous amount of time and budget

*It will work - it is tested by thousands of real world solutions

*People will understand it and help you if you have troubles.

If you really need to follow your scenarion give up with WCF and use other programming model - probably sockets directly.
Edit:
Ok if you still want to use duplex service I have this idea:

*

*Use WsDualHttpBinding when agent is not behind firewall

*Use PollingDualHttpBinding when agent is behind firewall - to get this binding you must install Silverlight 4 SDK. It is in separate assembly System.ServiceModel.PollingDuplex.dll. You must register binding as new binding extension if you want to use it in config file.

A: Firewalls are the reason why duplex HTTP doesn't work. Given the number of times this very problem comes up, I really wish Microsoft would have never created dualHttpBinding.
The solution for this is to use something like netTcpBinding instead, as that one allows actual duplex communication over a single connection (the one the client creates), thus solving the firewall problem. If for some reason you need to use HTTP though, your only option is to have the agents poll the service.


text:
Q: Filter ObservableCollection when button toggled Currently I have a ObservableCollection<Car> CarList, a WrapPanel, and a ToggleButton. The WrapPanel contains some CarInfo user control, each CarInfo refers to a Car in the CarList.
Basically, when a new Car is added to CarList, a new CarInfo control should be added to WrapPanel. When the ToggleButton is clicked, the WrapPanel should only display CarInfo in which Car.Speed > 70.
I'm now subscribe to CarList.CollectionChanged to update the WrapPanel, and using ICollectionView to do the filtering.
My problem is: how can I trigger the filtering on ToggleButton click?
I'm really new to WPF, so some sample code is highly appreciated! Thank you very much!

A: You should be binding the WrapPanel's ItemsSource to the car collection rather than updating it manually.
To toggle the filter, add this event handler to your toggle button:
    private void toggleFilter_Checked(object sender, RoutedEventArgs e)
    {
        ICollectionView view = CollectionViewSource.GetDefaultView(CarList);
        if (toggleFilter.IsChecked == true)
            view.Filter = car => ((Car)car).Speed > 70;
        else
            view.Filter = null;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solution to LTI system of equations I was wondering if there are any mathematical functions that satisfy both of the following equations:
\begin{align}
\frac{dx_1}{dt} &= x_2\\
\frac{dx_2}{dt} &= -x_1
\end{align}
I know one of the solutions would be:
\begin{align}
x_1 &= \sin(t), \text{ since } \frac{dx_1}{dt} = \cos(t) \\
x_2 &= \cos(t), \text{ since } \frac{dx_2}{dt} = -\sin(t)
\end{align}
Can anyone give any other example that satisfies the two equations? Thank you!

A: The system is linear, so you can scale.
The system is autonomous, so you can time-shift.


text:
Q: I'm trying to make a simple Discord Bot, but it doesn't work I'm trying to make a simple Discord Bot within a Minecraft Mod, and it doesn't work. I do have to say that I am new to coding discord bots in java, as I am more based to javascript.
Here is what I made:
DiscordBot.java
public class DiscordBot
{
    public JDA jda;

    private String token = "----";

    public static DiscordBot instance = new DiscordBot();

    @SuppressWarnings("deprecation")
    public void startDiscordBot() throws LoginException
    {
        jda = new JDABuilder()
                .setToken(token)
                .setStatus(OnlineStatus.DO_NOT_DISTURB)
                .addEventListeners(new DiscordEventListener())
                .build();
    }
}

DiscordEventListener.java
public class DiscordEventListener extends ListenerAdapter
{
    @Override
    public void onMessageReceived(MessageReceivedEvent event)
    {
        if(event.getMessage().getContentRaw().equals("-login"))
        {
            EmbedBuilder eb1 = new EmbedBuilder();
            EmbedBuilder eb2 = new EmbedBuilder();

            event.getAuthor().openPrivateChannel().queue(channel -> {
                eb2.setColor(Color.MAGENTA);
                eb2.setTitle(placeholder-text);
                eb2.setDescription(placeholder-text);
                channel.sendMessage(eb2.build());
            });

The DiscordEventListener takes "-login" and responds with the rest of the code, but the problem is, while the bot does go online, it doesn't do anything when I send -login in the discord server, nor dms. Also no errors occur on launch neither on the event. Also, I have a depricated version of JDA (4.2.1) because I don't understand how to use the new one.
I tried multiple little things but they showed 0 results, so I don't know what is wrong here.
(Also yes, I have initialised the DiscordBot class in the Main one, so I don't think that is the problem)

A: @dan1st figured it out, I forgot to add .queue(); to the end of channel.sendMessage, so thanks to them.


text:
Q: Saving excel file in user's downloads folder producing error (.NET Core Razor Pages) In my razor page application, I have a button that you click which creates an excel file and should automatically save it to your downloads folder.
The code below works great in localhost - I click the button, it saves to MY downloads folder, and I can view it.
However, once I publish and try, I receive an error that states "Could not find a part of the path 'C:\WINDOWS\system32\config\systemprofile\Downloads\PartCommentHistory.xlsx'.".
I would also be perfectly fine changing this code to instead pull up the save file dialog window and allow the user to pick where the file gets saved in the first place - but I'm not sure how. Google isn't helping much, so here we are!
If I physically navigate to this path, I noticed that there is no Downloads folder. I tried adding an if statement in my code that says if the Downloads folder doesn't exist here, create it first and then save the file there. However, that produces another error which is that I don't have access to the path.
public async Task<IActionResult> OnPostExportAsync(string currentFilter)
        {
            string sFilePath = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"),"Downloads");
            string sFileName = @"PartCommentHistory.xlsx";
            string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
            FileInfo file = new FileInfo(Path.Combine(sFilePath, sFileName));
            var memory = new MemoryStream();
            using (var fs = new FileStream(Path.Combine(sFilePath, sFileName), FileMode.Create, FileAccess.Write))
            {
                ExcelPackage pck = new ExcelPackage();
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Worksheet1");

                List<CmtPartComment> commentlist = _context.CmtPartComments.Select(x => new CmtPartComment
                {
                    SupplierNo = x.SupplierNo,
                    PartNo = x.PartNo,
                    Comment = x.Comment,
                    EnterBy = x.EnterBy,
                    EnteredDt = x.EnterDt.ToString("yyyy-MM-dd HH:mm:ss tt"),
                    CompletedDt = x.CompleteDt.ToString("yyyy-MM-dd HH:mm:ss tt")
                }).Include(c => c.System).OrderByDescending(x => x.EnterDt).Where(x => x.PartNo == currentFilter).ToList();

                ws.Cells[1, 1].Value = "SupplierNo";
                ws.Cells[1, 2].Value = "PartNo";
                ws.Cells[1, 3].Value = "Comment";
                ws.Cells[1, 4].Value = "EnterBy";
                ws.Cells[1, 5].Value = "EnterDt";
                ws.Cells[1, 6].Value = "CompleteDt";

                int recordIndex = 2;
                foreach (var item in commentlist)
                {
                    ws.Cells[recordIndex, 1].Value = item.SupplierNo;
                    ws.Cells[recordIndex, 2].Value = item.PartNo;
                    ws.Cells[recordIndex, 3].Value = item.Comment;
                    ws.Cells[recordIndex, 4].Value = item.EnterBy;
                    ws.Cells[recordIndex, 5].Value = item.EnteredDt;
                    ws.Cells[recordIndex, 6].Value = item.CompletedDt;
                    recordIndex++;
                }

                ws.Cells["A:AZ"].AutoFitColumns();

                pck.SaveAs(fs);
            }

            using (var stream = new FileStream(Path.Combine(sFilePath, sFileName), FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
        }

A: Use this method to get a folder path
    Environment.GetFolderPath(Environment.SpecialFolder.Yourspecialfoldernamehere, System.Environment.SpecialFolderOption.None)

For example
    Environment.GetFolderPath(Environment.SpecialFolder.System));

In above example System is a special folder.

A: For your issue, it is caused by that you are creating a temp file in the server side by using (var fs = new FileStream(Path.Combine(sFilePath, sFileName), FileMode.Create, FileAccess.Write)) which may not exist in the server side.
For your requirement, you are trying to create a file and return it to client side. If so, there is no need to create the local file in the server side, you could return the byte of the file like below:
public async Task<IActionResult> OnPostExportByInMemoryAsync(string currentFilter)
{
    string sFileName = @"PartCommentHistory.xlsx";

    using (var pck = new ExcelPackage())
    {
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Worksheet1");
        ws.Cells[1, 1].Value = "SupplierNo";
        ws.Cells[1, 2].Value = "PartNo";
        ws.Cells[1, 3].Value = "Comment";
        ws.Cells[1, 4].Value = "EnterBy";
        ws.Cells[1, 5].Value = "EnterDt";
        ws.Cells[1, 6].Value = "CompleteDt";
        ws.Cells["A:AZ"].AutoFitColumns();
        return File(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
    }
}

A: You can't determine where on the client machine the file can be saved. The only reason it appears to work on your machine is because your machine acts as the server. All you can do is to force a Save or Open dialog when the user downloads the file, which is achieved by setting the content type to application/octet-stream:
Do I need Content-Type: application/octet-stream for file download?


text:
Q: Wordpress & IE specific markup error I have this piece of code within a Wordpress loop that gathers all parent terms of the current post and displays children terms of each parent in an unordered list.
<?php $taxonomyName = "custom_tax";
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false)); ?>

  <?php foreach ($parent_terms as $pterm) :
    $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
      foreach ($terms as $term) :?>

<?php echo $term->name ?>

      <?php endforeach;?>
  <?php endforeach;?>

This works in FF, Chrome, Safari & Opera, however in IE9, I get

Term1

Term2

  ...

I'm sure there is a simple fix, I checked and didn't find any similar issues here or in the WP forum so I'm hoping someone can shed some light on whether this is a known issue.
Thanks in advance.

A: The HTML code generated by you PHP script isn't affected by the browser you are using.
Using output buffering you should save the generated html into a file, to see what html code you script is generating.
Clear the cache in IE and try it again. Does this help?


text:
Q: Find the following composition of the relations given below: (Rosen 7 Ex 36 Chapter 9 if it helps someone) Given R = Set of all real numbers, define the following relations:
R1 = {(a, b) ∈ R^2 | a > b}, the "greater than" relation,
R2 = {(a, b) ∈ R^2 | a ≥ b}, the "greater than or equal to"
relation,
R3 = {(a, b) ∈ R^2 | a < b}, the "less than" relation,
R4 = {(a, b) ∈ R^2 | a ≤ b}, the "less than or equal to"
relation,
R5 = {(a, b) ∈ R^2 | a = b}, the "equal to" relation,
R6 = {(a, b) ∈ R^2 | a != b}, the "unequal to" relation.
Find:
a) R1 ◦ R1 -
My answer: R1
b) R1 ◦ R2. -
My answer: R1
c) R1 ◦ R3. -
My answer: R^2 because if a <= b and b > c, then both a and c might be arbitrary (doubt here)
d) R1 ◦ R4. -
My answer: R^2 because if a < b and b > c, then both a and c might be arbitrary (doubt here)
e) R1 ◦ R5. -
My answer: R1 because if a = b and b > c, then a > c which is R1.
f ) R1 ◦ R6. -
My answer: R^2 because if a != b and b > c, then both a and c might be arbitrary (doubt here)
g) R2 ◦ R3. -
My answer: R^2 because if a < b and b >= c, then both a and c might be arbitrary (doubt here)
h) R3 ◦ R3. -
My answer: R3 because if a < b and b < c, then then a < c
Please correct me if I went wrong.

A: Clarifying the doubts:

*

*$R_1 \circ  R_3 = \mathbb R^2$ $$\text{Yes, you are right.}$$

*$R_1 \circ R_4 = \mathbb R^2$ $$\text{Yes, you are right.}$$

*$R_1 \circ R_6 = \mathbb R^2$ $$\text{Yes, you are right.}$$

*$R_2 \circ R_3= \mathbb R^2$ $$\text{Yes, you are right.}$$
And the others are also right. Well done!

A: R2 ◦ R1
b) R2 ◦ R2
c) R3 ◦ R5
d) R4 ◦ R1
e) R5 ◦ R3
f) R3 ◦ R6
g) R4 ◦ R6
h) R6 ◦ R6.


text:
Q: Magento 2.2.3 cron Errors how to solve? we are running website Magento 2.2.3 CE version. We are getting an error in cron.log please advise?

*

*cron.log

Warning: require_once(/srv/public_html/update/vendor/autoload.php):
  failed to open stream: No such file or directory in
  /srv/public_html/update/app/bootstrap.php on line 15

*update.log
We did some R&D and found that vendor directory was missing in /srv/public_html/update/ then we have moved vendor directory to respected path now the above error gone but getting below error.

Update-cron.ERROR: Cron readiness check failure! Found non-writable
  paths

*exception.log

[2019-01-29 06:40:06] main.CRITICAL: No callbacks found
  {"exception":"[object] (Exception(code: 0): No callbacks found at
  /srv/public_html/vendor/magento/module-cron/Observer/ProcessCronQueueObserver.php:278)"}
  []

How to fix these error? Can any one help?
Thanks

A: It seems relate to Magemojo configuration. I got the same issue as your issue and I am contacting to magemojo to support. I have two site one use Stratus and it is getting this issue other site is fine without use Status and same source code.

A: As explained here:
https://devdocs.magento.com/guides/v2.3/comp-mgr/prereq/prereq_cron.html
This error you're facing is related to the Magento Update/Upgrade scripts. At the end of that Magento article they explain what to do when you get this error:

In Composer-based installations, Magento creates the update/ directory when you run composer create-project. Running composer install does not create the update/ directory (if it did not exist before). See Recreate the Magento updater.

In any case, if you do not plan to upgrade your magento this way, you should consider removing the cron line automatically added by magento (the line should look like this):

php /var/www/yourwebsite.com/update/cron.php >> /var/www/yourwebsite.com/var/log/update.cron.log


text:
Q: How can I add a single cell to a Google Spreadsheet using the Sheets API without using batching? A similar question was asked but not answered two and a half years ago.
I have looked at Google's documention on both modifying cells and adding cells using batch updates. However, I am trying to add a single cell without using the batching mechanism, and there seems to be no documented way of doing it.
Here is what I have tried. Note that the entry I am trying to add does not currently have a value, which is why the linked documentation does not allow me to "change" the contents of the cell. In particular, the CellFeed simply does not contain the cell I am trying to add to the value of.
   CellEntry otherEntryFromCellFeed = // Obtained through OAuth and then finding a sheet, a worksheet, and a cellFeed, documented above

   CellEntry cellEntry = new CellEntry(5, 10, "Value");
   cellEntry.setService(otherEntryFromCellFeed.getService());
   cellEntry.update();

Error:
Exception in thread "main" java.lang.UnsupportedOperationException:
Entry cannot be updated at
com.google.gdata.data.BaseEntry.update(BaseEntry.java:635)

A: After another hour of poking through the Javadocs for SpreadsheetService and eventually  GoogleService, I discovered that the insert method will also work for the cell feed, which uses the cellFeedUrl from the incomplete Sheets doc.
   CellEntry cellEntry = new CellEntry(5, 10, "Value");
   service.insert(cellFeedUrl, cellEntry);


text:
Q: Analyzing the proof of Kirszbraun's theorem Kirszbraun's theorem 1934
Let $A \subset \mathbb{R}^n$. If $f \colon A \rightarrow \mathbb{R}^m$ is a $L$-Lipschitz function, then there exists an extension $F \colon \mathbb{R}^n \rightarrow \mathbb{R} ^m$ of $f$ which is also $L$-Lipschitz.
I'm studying that important Lipschitz function extension theorem, better known as Kirszbraun's theorem. The following questions arise through the proof, which I have not been able to solve yet. If anyone has ideas to clearly answer these questions, I would greatly appreciate it.

*

*Why are the sets in the equation $(1)$ compact and why is $K_{\gamma} = \bigcap_{i=1}^{n}{B(y_i , \gamma r_i)} \neq \emptyset$ for any sufficiently large value of $\gamma$?

*Why is it enough to show that $\gamma_{0} \leq L$?

*If  $0 \notin \text{conv}\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$, why should there be an $m-1$ dimensional plane separating the origin from $\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$ and why would we have $B(0 , \varepsilon)$ on the opposite side of the plane from $\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$ for all $\varepsilon$ sufficiently small, and why does that contradict the definition of $\gamma_0$?
Here is the proof of the theorem:
Proof
If $m = 1$, the result follows directly from McShane's theorem.
Suppose $m>1$ and consider the family $\mathscr{F}$ of $L$-Lipschitz extensions of $f$ to some set $T$ with $A \subset T$. This collection is non-empty because it contains at least the original function $f$. We define a partial ordering on $\scr{F}$ as follows: suppose that $g_1 \colon T_1 \rightarrow \mathbb{R}^m$ and $g_2 \colon T_2 \rightarrow \mathbb{R}^m$ are both elements of $ \scr{F}$, then $g_1 \preceq g_2$ if and only if $g_2$ is an extension of $g_1$, that is, $A \subset T_1 \subset T_2$ and $g_{1}(x) = g_{2}(x)$ for all $x \in T_1$. (The same partial ordering is defined if we recall that a function from a subset of $\mathbb{R}^n$ to $\mathbb{R}^m$ is a set of elements of $\mathbb{R} ^n \times \mathbb{R}^m$, and we partially order $\scr{F}$ by inclusion). By Hausdorff's maximal principle, $\scr{F}$ has a maximal totally ordered subfamily $\tilde{\scr{F}}$. Let $\tilde{A}$ be the union of the domains of the functions in $\tilde{\scr{F}}$. Let us define the function $F \colon \tilde{A} \rightarrow \mathbb{R}^m$ by $F(x) = g(x)$ where $g \in \tilde{\scr{F}}$ and $x \in \text{dom}(g)$. Clearly $F$ is Lipschitz and $\text{Lip}(F) = L$. We claim that $\tilde{A} = \mathbb{R}^n$. If not, then we can fix $x_0 \in \mathbb{R}^n \setminus \tilde{A}$. A contradiction would be reached if we show that there is $y_0 \in \mathbb{R}^m$ such that $\|y-y_0\| \leq L\|x-x_0\|$ whenever $y=F(x)$ and $x \in \tilde{A}$, that is, if we show that
\begin{equation}\tag{1}
\bigcap_{x \in \tilde{A}}{B(F(x),L\|x-x_0\|)} \neq \emptyset
\end{equation}
Since $(1)$ involves an intersection of compact sets, it suffices to show that
any such finite intersection is non-empty. Accordingly, let $x_1 , x_2, \cdots , x_n \in \tilde{A}$ be fixed. Let $y_i = F(x_i)$, $r_i = \|x_i -x_0\|$, for $i = 1,2, \cdots , n$, and $r^{*} = \sup\{r_1 , r_2 , \cdots , r_n\}$.
We know that for any sufficiently large value of $\gamma$ $$K_{\gamma} = \bigcap_{i=1}^{n}{B(y_i , \gamma r_i)} \neq \emptyset$$
Let $$\gamma_0 = \inf\{\gamma \colon K_{\gamma} \neq \emptyset\}$$
Since \begin{equation}\tag{2}
K_{\gamma_{0}} = \bigcap_{\gamma > \gamma_{0}}{K_{\gamma}}
\end{equation}
and the intersection of any finitely many of the sets on the right-hand side
of $(2)$ is non-empty, we see that $K_{\gamma_0} \neq \emptyset$.
It will suffice to show that $\gamma_{0} \leq L$. We many, of course, assume $\gamma_{0} >0$. Note that $K_{\gamma_{0}}$ must contain exactly one point, because if $k_1 ,k_2 \in K_{\gamma_{0}}$, then
\begin{align*}
\left\|\dfrac{k_1 + k_2}{2} - y_i\right\|^2 &= \dfrac{\|k_1 +k_2\|^2}{4} + \|y_i\|^2 - ( k_1 - k_2) \cdot y_1 \\
&=\frac{\|k_1\|^2}{2} + \frac{\|k_2\|^2}{2} - \frac{\|k_1 - k_2\|^2}{4} + \ |y_i\|^2 - k_{1} \cdot y_i - k_{2} \cdot y_i \\
&= \dfrac{\|k_1 - y_i\|^2 + \|k_2 -y_i\|^2}{2} - \dfrac{\|k_1 - k_2\|^2}{4} \\
&\leq \gamma_{0}^2 r_{i}^2 - \dfrac{\|k_1 - k_2\|^2}{4(r^{*})^2}r_{i}^2
\end{align*}
holds for $i=1,2, \cdots , n$, and $\dfrac{k_1 + k_2}{2} \in K_{\gamma}$ with $\gamma = \sqrt{\gamma_{0}^ 2 - \dfrac{\|k_1 - k_2\|^2}{4(r^{*})^2}} < \gamma_{0}$ contradicting the definition of $\gamma_{0}$.
By translating the coordinate system if necessary, we can assume that $K_{\gamma_{0}} = \{0\}$. Consequently, we have $\|y_i\| \leq \gamma_{0} r_i$, for $i = 1,2, \cdots, n$. We now claim that $0 \in \text{conv}\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$. Were that not the case,
there would exist an $m-1$ dimensional plane separating the origin from $\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$, but then for all sufficiently small $\varepsilon >0$ we would have $B(0 , \varepsilon)$ on the opposite side of the plane from $\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$, again contradicting the definition of $\gamma_{0}$. Thus we can choose non-negative scalars $\lambda_1 , \lambda_2 , \cdots, \lambda_n$ such that $$\|y_i\| < \gamma_{0} r_i \implies \lambda_i = 0$$ and $$0 = \sum_{i=1}^n{\lambda_i y_i} \hspace{0.5cm} \text{con} \hspace{0.4cm} \sum_{i=1}^n{\lambda_i} = 1$$
It follows that
\begin{align*}
   0 &= 2 \left\| \sum_{i=i}^n {\lambda_i y_i}\right\|^2 \\
     &= 2 \sum_{i,j=1}^n {\lambda_i \lambda_j y_i \cdot y_j} \\
     &= \sum_{i,j =1}^n {\lambda_i \lambda_j \left[\|y_i\|^2 + \|y_j\|^2 - \|y_i -y_j\|^2\right]}\\
     &\geq \sum_{i,j=1}^n {\lambda_i \lambda_j \left[\gamma_{0}^2 r_{i}^2 + \gamma_{0}^2 r_{j}^2 - L^2 \|x_i - x_j\|^2\right]}\\
     &= \sum_{i,j=1}^n {\lambda_i \lambda_j \left[2(x_i -x_0)\cdot \gamma_{0}^2(x_j - x_0) + (\gamma_{0}^2 - L^2)\|x_i - x_j\|^2\right]}\\
     &=2 \left\|\gamma_{0} \sum_{i=1}^n{\lambda_i (x_i - x_0)}\right\|^2 + (\gamma_{0}^2 - L^2)\sum_{i,j=1}^n {\lambda_i \lambda_j \|x_i - x_j\|^2} \tag{3}
\end{align*}
If there were but one non-zero $\lambda_i$, then the second term in $(3)$ would
vanish and the first would be positive, a contradiction. Thus there are at
least two non-zero $\lambda_i$'s and the second term in $(3)$  must be non-positive,
forcing $\gamma_{0} \leq L$, as desired.
$\square$

A: *

*The sets in $(1)$ are closed balls in $\mathbb{R}^n$, so they are compact because they are closed and bounded. The reason why $K_{\gamma}$ is non-empty for large enough $\gamma$ is because for any point $p \in \mathbb{R}^n$ and any $i \in \{1,\ldots, n\}$, if we choose $\gamma > \frac{\|y_i - p\|}{r_i}$ then $\|y_i - p\| < \gamma r_i$ and hence $p \in B(y_i, \gamma r_i)$. If we want $p$ to be in all sets $B(y_i, \gamma r_i)$ we just have to choose $\gamma > \max\limits_{i}\frac{\|y_i - p\|}{r_i}$ and we get $p \in K_\gamma$.

*At that point in the proof we have shown that $K_{\gamma_{0}} \neq \emptyset$, so we have a point $y_0$ such that $(1)$ is true with $L$ replaced by $\gamma_{0}$. We could try to show that $\gamma_{0} = L$, but the result would also follow if $\gamma_{0} \leq L$, because if the intersection in $(1)$ is non-empty, replacing $\gamma_{0}$ by $L$ only increases the radii of the balls, so the intersection with $L$ contains the intersection with $\gamma_{0}$ as a subset (in other words, $\|F(x)-y_0\| \leq \gamma_{0}\|x-x_0\|$ implies $\|F(x)-y_0\| \leq L\|x-x_0\|$).

*The existence of such a hyperplane is given by the hyperplane separation theorem, specifically by the version where you have two disjoint nonempty closed convex sets, at least one of which is compact. Here our two sets are $\{0\}$ and $\text{conv}\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$. That version also guarantees the existence of a separating plane with positive distance to both sets, so we can choose a small $\epsilon$-ball around $0$ that is still fully separated from $\text{conv}\{y_i \colon \|y_i\| = \gamma_{0} r_i\}$ by that plane. The reason why this leads to a contradiction is because it allows us to choose a smaller scaling factor $\gamma' < \gamma_{0}$ that still satisfies $K_{\gamma'} \neq \emptyset$, which is impossible as $\gamma_{0}$ was chosen to be minimal in that regard. To see how, first note that $0$ is an inner point of those balls with $\|y_i\| < \gamma_{0} r_i$, so we can scale them down slighty and their intersection would still contain a neighborhood of $0$. For the other balls with $\|y_i\| = \gamma_{0} r_i$ we know that as we move from the origin to the orthogonal projection of the origin onto the separating hyperplane, the distance to all the $y_i$ decreases, so that the segment between $0$ and the projection of $0$ is contained in all those $B(y_i, \gamma r_i)$. Again we can scale those balls down slightly so that we still have points from that segment in the intersection, close enough to $0$ to make sure that they're also contained in the balls with $\|y_i\| < \gamma_{0} r_i$. This gives us a smaller scaling factor with a non-empty intersection and thus a contradiction.


text:
Q: How to pass request type as an argument to retrofit API This is how i define methods in API interface of retrofit.
@POST
@Headers("platform: Android")
Call<JsonObject> getRegisterUserData(
        @Url String url,
        @Header("User-Agent") String userAgent,
        @Header("x-dsn") String dsn,
        @Header("x-appversion") String appVersion,
        @Body JsonObject jsonObject
);

I want to know any possibility to pass request type GET or POST as a a parameter to a method, instead of passing it as an annotation.


text:
Q: Boostrap carousel show 3 images per slide truncated I'm trying to set up a Bootstrap 3 carousel to show 3 images per active slide, I want the next and previous images to be truncated but the centre image full width, similar to this example: https://thescene.com/.
I've played around with this for quite a while but can't seem to get the truncated effect? My initial idea is to have the containing div full width to show all 3 images in full with an overflow:hidden property to get the effect, but the carousel itself needs to be 1280px wide. Codeply is here: http://www.codeply.com/go/6eBfBskTsV

A: Why not grab one online? This component seems has a partial nearby image effect...
http://www.jssor.com/index.html
The bootstrap carousel is just a simple implementation rather than a universal solution, which means it can be cumbersome to tweak to achieve some complicated presentation. I guess unless you are just practising your skills, you won't like to make one by yourself.


text:
Q: Keeping state of UISwitch in TableViewCell: Swift I have an issue, I have a tableview setup, users can add and delete new items but also can check them in and out. What I mean by that, is that with every cell that is added there comes a UISwitch in that cell that the user can turn on and off. "on" being checked in and "off" being checked out.
so, with that, I am very new to programming and would like to know how I could save the state(whether it is off or on) of the UISwitch so that every time the user leaves the application the switch stays the same. Thank you for your help.
Current Code:
current cell code

A: You should use a data persistance to save your configuration (state on and off) and then get them back. There are many options here Core Data (local database), UserDefault, SQLite or even Property Lists. below a helpful link where you can start. Good luck.

A: If you were new with iOS development,NSUserDefaults is easier to use.Just save data like this:[[NSUserDefaults standardUserDefaults] saveObject:data forKey:@""];And read data like this:[[NSUserDefaults standardUserDefaults] objectForKey:@""]


text:
Q: Move a sentence 20px every 3 seconds with setInterval I'm trying to simply move a sentence 20px on the y-axis every 3 seconds by using setInterval(). My code will only move the sentence one time. What's going on?
var yAxis = 20;

setInterval(function() {
    $('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + yAxis + ')');
 }, 3000);

fiddle

A: You can use offset() method to get offset of current element from left and from top. At first, get current offset from top and then override it with new value, which will be "oldOffset + 20px" in your case. Here is the working example:

setInterval(function() {
    var el = $('.sentence');
    var currentOffset = el.offset();
    el.offset({ top: currentOffset.top + 20, left: currentOffset.left})
}, 3000);

Text Text Text

A: The CSS directive you give is always the same - transform .sentence from its original position to 20points lower.
Use:
var yAxis=0;
setInterval(function() {
$('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + (yAxis+=20) + ')'); }, 3000);

instead

A: Your transform does not add 20 to the existing Y. It simply sets the Y to 20. You need to store the state of the previous transformation then update that value before applying it to the next transform.

let yAxis = 0;

setInterval(function() {
  yAxis += 20;
  $('.sentence').css('transform', 'matrix(1, 0, 0, 1, 0,' + yAxis + ')');
}, 500);

This is a sentence.


text:
Q: How to set up a repo so that when cloned it has two different adresses for pushing and fetching? I have a git repository living at git://server.local/repo.git
Cloning with git clone git://server.local/repot.git sets up origin like this:
$ git remote -v
origin  git://server.local/repo.git (fetch)
origin  git://server.local/repo.git (push)

But I would like this instead:
$ git remote -v
origin  git://server.local/repo.git (fetch)
origin  ssh://server.local/realrepopath/repo.git (push)

I want this to be done automatically when cloning (without changing manually the remote URL).
Is that possible ?
Edit:
I don't want to have to run any command or script after the cloning is done. I would like to configure the remotes URL on the server so that I don't have to manually change them after cloning a repository.

A: Looks like the gerrit solution is still the accepted one.  Check out this answer to see how it can be done with a simple script.

A: Once the repository is cloned you can execute
git remote set-url origin git://server.local/repo.git
git remote set-url --push origin ssh://server.local/realrepopath/repo.git

Unfortunately, there doesn't seem to be a way to run scripts or hooks on a new git clone (as far as I know).

A: The command
git config --global url."ssh://server.local/realrepopath/".pushInsteadOf git://server.local/

should do the trick.


text:
Q: Dynamic query params for React Native Navigation? I have a phonebook app in which I'm implementing a search bar.
I am trying to use the useNavigate hook to take a string {term} and navigate to the search page along with the term the user typed in.
So for example if the user typed in David the address bar would be
http://localhost:3002/search?q=David
At the moment when I type David into search bar I get this result in address bar
http://localhost:3002/search
The parameter was not passed along to the search page.
I followed the instruction here which said I should do following
navigate('search', {term}) but this did not work for me
https://reactnavigation.org/docs/params/
Any help appreciated
Searchbar.js
import "./Searchbar.css"
import { useState } from "react"
import { useNavigate } from "react-router-dom"

export default function Searchbar() {
    const [term, setTerm] = useState('')
    const navigate = useNavigate()

    const handleSubmit = function(e) {
        e.preventDefault()
        navigate('search', {term})
        console.log(term)

    }

    return (

           <form onSubmit={handleSubmit}>
           Search Contacts
           <input
           type="text"
           onChange={(e) => setTerm(e.target.value)}
           value={term}>
           </input>
           </form>

    )
}

Navbar.js
import { Link } from "react-router-dom";

import "./Navbar.css"
import Searchbar from "./Searchbar";

export default function Navbar() {
  return (

        <Link to="/" className="brand">
Phonebook
</Link>
        <Searchbar></Searchbar>
        <Link to="/create">Create Contact</Link>

  )
}

A: Some thing like this should work.
navigate({
  pathname: "search",
  search: {
    q: term,
  },
});

For more you can have a look here


text:
Q: Sequential execution of functions using promises I want to sequentially execute some asynchronous functions based on an array.
I thought this would do it :
var Promise = require("bluebird");
Promise.cast([1,2,3]).reduce(function(_,i){
    console.log("Launching  " + i);
    return Promise.delay(Math.floor(Math.random()*1000)).then(function(){
        console.log("Executing  " + i);
    });
},0);

but I get
Launching  1
Launching  2
Launching  3
Executing  2
Executing  1
Executing  3

instead of the desired result which would be
Launching  1
Executing  1
Launching  2
Executing  2
Launching  3
Executing  3

How can I ensure wholly sequential execution here ?
Note that I know how to do that without promises, I'm only interested in full promises solutions.

A: You are using an old version of Bluebird. The behavior of .reduce was changed in v1 to work this way:

Like .map and .filter, .reduce now allows returning promises and thenables from the iteration function.

( from the changelog )
Please update to the most recent version. This will cause the code to run correctly.


text:
Q: How to draw 2d object and 3d object on the same screen I am trying to draw a button so that later I could click on it. But i am having some problems, namely when i UNcomment the selected part in the Draw2d function, the screen goes black and my 3d object disappears. Any ideas why and how to solve this? I want to add that with the commented part the button shows in a different area (left,top screen) and if i comment it just like its here, then its shown in the center of my 3d object and it doesnt have its borders. Only the label.
void Draw2D()
{
   glPushMatrix();
   glDisable(GL_DEPTH_TEST);
   //glMatrixMode(GL_PROJECTION);
   //glLoadIdentity();
   glOrtho(0, winw, winh, 0, -1, 1);
   //glMatrixMode(GL_MODELVIEW);
   //   glLoadIdentity();
   ButtonDraw(&MyButton);
   glPopMatrix();
   glEnable(GL_DEPTH_TEST);
}

and here's my source code:
Source.cpp
I would also like to ask if anyone knows how to create an Input field? An easy way appreciated since i am still learning.

A: It it not clear how your draw loop looks, and where in it you are setting the matrices, drawing 3d stuff and drawing 2d stuff. But from the code shown so far, I can still explain why it might have an effect: There is a matrix stack per matrix type (modelview, projection, texture).
What your code does is pushing the currently selected matrix onto the stack (probably GL_MODELVIEW). Then, you appy an ortho matrix to it. Since the matrix is unlikely to be identity here, the ortho will not have the results you expect, and the image is wrong. Also, the old projection matrix is still unchanged, which will further effect the transformarions. You then restore the original matrix and rendering goes on unchanged.
If you uncomment the code, you switch first push, then switch, set the ortho matrix as projection and set identity for modelview - but only the modelview matrix is to be restored, and the projection matrix will still have the ortho set.
What you really need to do is:
glMatrixMode(GL_PROJECTION);
glPushMatrix(); // save current projection matrix
glLoadIdentity();
glOrtho(0, winw, winh, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix(); // save current modelview matrix
glLoadIdentity();
// ... draw
glMatrixMode(GL_PROJECTION);
glPopMatrix(); // restore PUSHed projection matrix
glMatrixMode(GL_MODELVIEW);
glPopMatrix(); // restore PUSHed modelview matrix

This assumes that intially when calling this, glMatrixMode(GL_MODELVIEW) is set, and also restores it to this. This can also be optimized to
// assume `GL_MODELVIEW` is the current matrix mode
glPushMatrix(); // save current modelview matrix
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix(); // save current projection matrix
glLoadIdentity();
glOrtho(0, winw, winh, 0, -1, 1);
// ... draw
glPopMatrix(); // restore PUSHed projection matrix
glMatrixMode(GL_MODELVIEW);
glPopMatrix(); // restore PUSHed modelview matrix
// now `GL_MODELVIEW` is selected again

which is slightly less calling overhead, but not as clear as the initial variant.


text:
Q: Ajax call return whole page instead of replacing a div tag I am learning Ajax with MVC 5, it return whole partial view instead of replacing div tag? I don't know why
Here is the page where form submit
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}

Index

Hello from our View Template!

INSERT

 @using (Ajax.BeginForm("NewInsert","Home", new AjaxOptions
 {
   HttpMethod = "GET",
   InsertionMode = InsertionMode.Replace,
   UpdateTargetId = "formSection"
 }))
 {
   <input type="text" name="textToInsert" />
   <input type="submit" value="Insert It" />
 }

Hello

Here is the LayoutPage with script
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />

        @RenderBody()

Here is the partial view

@ViewBag.TheText

Here is the controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace Northwind.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            ViewBag.Message = "New page yeah";
            return View();
        }

        public ActionResult TestBeginForm()
        {
            return View();
        }
        public PartialViewResult InsertText(string text)
        {
            ViewBag.TextToDisplay = text;
            return PartialView();
        }
        public ActionResult GetText(string q)
        {
            ViewBag.TheText = q;
            return PartialView();
        }

        public ActionResult NewInsert(string textToInsert)
        {
            ViewBag.TheText = textToInsert;
            return PartialView("_NewInsert");
        }

        [HttpPost]
        public ActionResult PostInsert(string p)
        {
            ViewBag.TheText = p;
            return PartialView();
        }
    }
}

And ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are true in webconfig

A: You are missing one javascript library which does the Asynchronous form posting for you. Add that to your page (Layout) and your asynchronous form posting should work fine.

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />


text:
Q: New Skype URIs for video calling is not working in IOS I am IOS developer. I have developed one application which use Skype for voice calling and video calling. I can make a voice call through my application easily but in video call it's not working.
For video call:
 skype:skypeUserName?call&video=true
I am using new Skype URIs functionality.
Skype URIs :  https://developer.skype.com/skype-uris/reference
Please help me to solve this issue.
Many Thanks

A: It seems that currently even
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];

which I brought from official tutorial is not working on current Skype iOS app version.


text:
Q: Open various text files and copy columns into master workbook I am looking to write an efficient macro to ultimately save a lot of time when working with research data.  Goal is to create one Master workbook with consolidated data.
Here is the situation:

*

*I have 40 research subjects that all have an output file titled with their subject number in the format "Subject 1_OUTPUT.txt" (where "1" in the example ranges from 1 to 40).

*Within each of these output text files, there are ~30 columns of subject-specific data... and the column headers are the same, and in the same order, between all 40 subject files (ex: Column A is titled "OutputDataObject1" in Subject 1's file, Subject 2's file, etc.).
Ultimate Goal:  Create one Master Excel file that has a tab named for each column header from the subject files (ex: OutputDataObject1, OutputDataObject2, etc.) and within each tab, a column for each Subject with their data listed within the column.  Therefore, each tab would have apples-to-apples data for all 40 subjects on one tab.
Logic for the Macro:

*

*Open each Subject txt file (Subject #1 through Subject #40)

*Copy each column from the subject txt file to tab on the Master Workbook with the same name for the data object... and into the appropriate Master column on that tab, depending on the subject number (Subject 1 through 40)

I know this is do-able but I am struggling with how to create nested loops to open, match the column to the tab-name, and then find the subject's specific column to paste into the Master workbook.
UPDATED 10-16-15:  I RESOLVED THE ISSUE WITH MY LOOP -  BELOW WITH WORKING CODE :)
Dim MasterWB As Workbook
Dim OpenWB As Workbook
Dim cur_subjectname As String
Dim cur_filename As String
Dim cur_source_column As Integer
Dim cur_subject_number As Integer
Dim MasterWB_sheetcount As Integer 'to cycle through MasterWB
Dim cur_sheetnumber As Integer 'to cycle through MasterWB
Dim S As Integer
Dim I As Integer 'to cycle through MasterWB
Dim cur_subjectoffset As Integer
Dim Cell As Range

Application.DisplayAlerts = False
Application.ScreenUpdating = False
cur_source_column = 0
cur_subject_number = 1 'tied to master WB column #
cur_sheetnumber = 3 'first tab to populate subject data
cur_subjectoffset = 0 'to move down "Subject_List" tab of subjects

Set MasterWB = ThisWorkbook
MasterWB_sheetcount = MasterWB.Worksheets.Count - 3

MasterWB.Worksheets("Subject_List").Activate 'first subject number in A2
cur_subjectname = Sheets("Subject_List").Range("A1").Offset(cur_subject_number, 0).Value

'Outside Loop - open each workbook, starting with Subject #1
For S = 1 To 45 'Change for Total # of Subjects
    cur_filename = ThisWorkbook.Path & "/" & cur_subjectname & "_OUTPIV.xlsx" 'Change for different data types
    If Len(Dir(cur_filename)) = 0 Then

    Else 'load data to MasterWB (ThisWorkbook)
        Set OpenWB = Workbooks.Open(cur_filename)
        For I = 1 To MasterWB_sheetcount
            OpenWB.Sheets(1).Range("B6:B110").Offset(, cur_source_column).Copy
            MasterWB.Sheets(cur_sheetnumber).Range("A2").Offset(, cur_subject_number).PasteSpecial
            cur_source_column = cur_source_column + 1
            cur_sheetnumber = cur_sheetnumber + 1
        Next I
        OpenWB.Close
    End If
    'Reset values and Move to next Subject
    cur_subject_number = cur_subject_number + 1
    cur_source_column = 0
    cur_sheetnumber = 3
    MasterWB.Worksheets("Subject_List").Activate 'first subject number in A2
    cur_subjectname = Sheets("Subject_List").Range("A1").Offset(cur_subject_number, 0).Value

Next S


text:
Q: SQL query to order by sum of sums Thanks in advance for any help.
The easiest way to explain my question is probably with an example, so I set up a sandbox database with two tables and the following contents:
Categories:
 supercategory | category
---------------+----------
 fruit         | apple
 fruit         | orange
 fruit         | banana
 vegetable     | carrot
 vegetable     | onion
 vegetable     | celery
 grain         | rice
 grain         | wheat
 grain         | barley

Baskets:
 category | amount
----------+--------
 apple    |      2
 carrot   |      4
 wheat    |      1
 orange   |      5
 celery   |      4
 orange   |      3
 barley   |      2
 barley   |      5
 apple    |      1
 carrot   |      2
 rice     |      5
 wheat    |      3
 onion    |      2

What I want to do is query the sum of each category, like this:
SELECT
    categories.superCategory, baskets.category,
    SUM(baskets.amount::numeric) AS categorySum
FROM
    baskets
LEFT OUTER JOIN
    categories ON categories.category = baskets.category
GROUP BY
    categories.superCategory, baskets.category
ORDER BY
    superCategory;

Which returns:
 category | supercategory | categorysum
----------+---------------+-------------
 apple    | fruit         |           3
 orange   | fruit         |           8
 barley   | grain         |           7
 rice     | grain         |           5
 wheat    | grain         |           4
 carrot   | vegetable     |           6
 celery   | vegetable     |           4
 onion    | vegetable     |           2

That resulting table is exactly what I want, except for the ordering. I'd like to order by each supercategory by sum, and then within each supercategory order each category by its sum. So the order I want this table in would be:

barley | grain     | 7      <---- The total for the "grain" supercategory is 16, so put it first
rice   | grain     | 5
wheat  | grain     | 4
carrot | vegetable | 6      <---- The total for vegetables is 12
celery | vegetable | 4
onion  | vegetable | 2
orange | fruit     | 8      <---- The total for fruits is 11
apple  | fruit     | 3

I'm not experienced enough about SQL to know how best to accomplish this. I had tried some nested SELECT functions, but wasn't figuring out how to get that to work right, or if that is even the best approach.

A: Are you looking for this :
select superCategory, category , categorySum from (
SELECT
    categories.superCategory, baskets.category,
    SUM(baskets.amount) over ( partition by categories.superCategory,baskets.category) AS categorySum
FROM
    baskets
LEFT OUTER JOIN
    categories ON categories.category = baskets.category
) X
group by superCategory, category , categorySum
ORDER BY SUM(categorySum) over ( partition by superCategory) DESC,categorySum desc

A: You can do it with the window function SUM() in the ORDER BY clause:
SELECT b.category,
       c.superCategory,
       SUM(b.amount::numeric) AS categorySum
FROM baskets b LEFT OUTER JOIN categories c
ON c.category = b.category
GROUP BY c.superCategory, b.category
ORDER BY SUM(SUM(b.amount::numeric)) OVER (PARTITION BY c.superCategory) DESC,
         categorySum DESC;

See the demo.
Results:
> category | supercategory | categorysum
> :------- | :------------ | ----------:
> barley   | grain         |           7
> rice     | grain         |           5
> wheat    | grain         |           4
> carrot   | vegetable     |           6
> celery   | vegetable     |           4
> onion    | vegetable     |           2
> orange   | fruit         |           8
> apple    | fruit         |           3

A: Try this and use JOIN and subquery:
SELECT T.category
     , T.superCategory
     , T.Sums AS categorySum
  FROM
       (
        SELECT categories.superCategory
             , baskets.category
             , SUM(baskets.amount) AS Sums
         FROM baskets
         JOIN categories ON categories.category = baskets.category
        GROUP BY categories.superCategory, baskets.category
      )T
 JOIN (
       SELECT categories.superCategory
            , SUM(baskets.amount) AS Sums
         FROM baskets
         JOIN categories ON categories.category = baskets.category
        GROUP BY categories.superCategory
      )TA ON T.superCategory = TA.superCategory
ORDER BY TA.Sums DESC, T.Sums DESC

See result in this sqlfiddle


text:
Q: Run jps -l command in java program and fetch output I have to run jps -l command in my java program and fetch output. I have tried below mentioned code but it didn't work.
Runtime rt = Runtime.getRuntime();
proc = rt.exec("jps -l");

Runtime rt = Runtime.getRuntime();
proc = rt.exec("cmd.exe /c start jps -l");

Runtime rt = Runtime.getRuntime();
proc = rt.exec("powershell.exe jps -l");

Every time program output was :
Cannot run program "jps -l": CreateProcess error=2, The system cannot find the file specified

Is there any way to run "jps -l" and fetch output?

A: Very likely jps is not on the system path. You can still run that executable, just provide the absolute path, e.g.
"c:\Program Files\Java\openjdk-17.0.2\bin\jps.exe" -l

Mind the fact that 'Program Files' contains a whitespace which needs escaping.

A: You need to set the Environment variables for Java, refer how to set java path on how to set it.

Proof:

package com.example.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("jps -l");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        // Read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // Read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
        System.out.println("Done");
    }
}

Output:
Here is the standard output of the command:

17556 jdk.jcmd/sun.tools.jps.Jps
13320 com.example.demo.Test
22636 Eclipse
Here is the standard error of the command (if any):

Done

Environment Variable:


text:
Q: Where are Xdebug configurations set outside of the php.ini? (Windows 10) Running PHP 8 with PhpStorm version 2020.3.3, on Windows 10. When I use Xdebug3 as my debugger, I am able to use breakpoints successfully, but I get an annoying message every time:
Xdebug: [Config] The setting 'xdebug.remote_enable' has been renamed, see the upgrading guide at https://xdebug.org/docs/upgrade_guide#changed-xdebug.remote_enable (See: https://xdebug.org/docs/errors#CFG-C-CHANGED)
Xdebug: [Config] The setting 'xdebug.remote_host' has been renamed, see the upgrading guide at https://xdebug.org/docs/upgrade_guide#changed-xdebug.remote_host (See: https://xdebug.org/docs/errors#CFG-C-CHANGED)
Xdebug: [Config] The setting 'xdebug.remote_mode' has been renamed, see the upgrading guide at https://xdebug.org/docs/upgrade_guide#changed-xdebug.remote_mode (See: https://xdebug.org/docs/errors#CFG-C-CHANGED)
Xdebug: [Config] The setting 'xdebug.remote_port' has been renamed, see the upgrading guide at https://xdebug.org/docs/upgrade_guide#changed-xdebug.remote_port (See: https://xdebug.org/docs/errors#CFG-C-CHANGED)

Going to the doc gives me helpful notes of configurations that have changed in Xdebug with Xdebug 3, however, I am not able to find these settings in my PHP 8 php.ini. In the PHP 8 php.ini, the Xdebug section's configs seem to match those recommended in the documentation:
[xdebug]
zend_extension="C:\PHP\php 8\ext\php_xdebug-3.0.4-8.0-vs16-nts-x86_64.dll"
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.start_with_request=trigger

When I run phpinfo() on a file, the output on the XDEBUG section reads below:
Version => 3.0.4
Support Xdebug on Patreon, GitHub, or as a business: https://xdebug.org/support

           Enabled Features<br/>(through 'xdebug.mode' setting)
Feature => Enabled/Disabled
Development Aids => ✘ disabled
Coverage => ✘ disabled
GC Stats => ✘ disabled
Profiler => ✘ disabled
Step Debugger => ✔ enabled
Tracing => ✘ disabled

Debugger => enabled
IDE Key => 18658

Directive => Local Value => Master Value
xdebug.auto_trace => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.cli_color => 0 => 0
xdebug.client_discovery_header => no value => no value
xdebug.client_host => 127.0.0.1 => 127.0.0.1
xdebug.client_port => 9000 => 9000
xdebug.cloud_id => no value => no value
xdebug.collect_assignments => Off => Off
xdebug.collect_includes => (setting removed in Xdebug 3) => (setting removed in Xdebug 3)
xdebug.collect_params => (setting removed in Xdebug 3) => (setting removed in Xdebug 3)
xdebug.collect_return => Off => Off
xdebug.collect_vars => (setting removed in Xdebug 3) => (setting removed in Xdebug 3)
xdebug.connect_timeout_ms => 200 => 200
xdebug.coverage_enable => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.default_enable => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.discover_client_host => Off => Off
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.file_link_format => no value => no value
xdebug.filename_format => no value => no value
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.gc_stats_enable => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.gc_stats_output_dir => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.gc_stats_output_name => gcstats.%p => gcstats.%p
xdebug.halt_level => 0 => 0
xdebug.idekey => no value => no value
xdebug.log => no value => no value
xdebug.log_level => 7 => 7
xdebug.max_nesting_level => 256 => 256
xdebug.max_stack_frames => -1 => -1
xdebug.mode => debug => debug
xdebug.output_dir => C:\Windows\Temp => C:\Windows\Temp
xdebug.overload_var_dump => (setting removed in Xdebug 3) => (setting removed in Xdebug 3)
xdebug.profiler_append => Off => Off
xdebug.profiler_enable => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.profiler_enable_trigger => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.profiler_enable_trigger_value => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.profiler_output_dir => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.remote_autostart => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_connect_back => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_enable => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_host => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_log => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_log_level => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_mode => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_port => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.remote_timeout => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.scream => Off => Off
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.show_mem_delta => (setting removed in Xdebug 3) => (setting removed in Xdebug 3)
xdebug.start_upon_error => default => default
xdebug.start_with_request => trigger => trigger
xdebug.trace_enable_trigger => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.trace_enable_trigger_value => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.trace_output_dir => (setting renamed in Xdebug 3) => (setting renamed in Xdebug 3)
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.trigger_value => no value => no value
xdebug.var_display_max_children => 128 => 128
xdebug.var_display_max_data => 512 => 512
xdebug.var_display_max_depth => 3 => 3

Is there another place that these configs are set, where I can change them to get rid of the annoying error messages??


text:
Q: Dependency Property stops updating after target property changes due to edit in UI I have a custom dependency property on my control like so (boilerplate to implement the control left out):
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value",
    typeof(String),
    typeof(BindingTestControl),
    new PropertyMetadata(null));

public static void SetValue(UIElement element, string value)
{
    element.SetValue(ValueProperty, value);
}
public static string GetValue(UIElement element)
{
    return (string)element.GetValue(ValueProperty);
}

I created a page with code-behind to bind to with relevant xaml like so (with x:Name="root" on the page):
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <local:BindingTestControl Value="{Binding ElementName=root, Path=StringItem}"/>
    <Button Width="200" Height="100" Tapped="Button_Tapped" FlowDirection="RightToLeft"/>
</Grid>

With code-behind like so (again, only relevant parts shown):
private string stringItem = "";
public string StringItem
{
    get
    {
        return stringItem;
    }
    set
    {
        this.stringItem = value;
        OnPropertyChanged("StringItem");
    }
}

int i = 0;
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
    //i++;
    this.StringItem = "Test" + i;
}

This works fine the first time, but if I update the value in the Textbox, the binding won't overwrite the new value.  If I uncomment the i++; then the binding overwrites every time.  I'm assuming this happens this way because the value that is being sent with INotifyPropertyChanged is the same as the previous one despite the value in the Textbox no longer being the same.
Is there a way to force the value through the binding even if it hasn't changed?

A: You could change your setter to something like -
set
{
    this.stringItem = null;
    this.stringItem = value;
    OnPropertyChanged("StringItem");
}

Which should force the PropertyChanged event to fire as a change in value has occurred.


text:
Q: How to find $\int {t^n \, e^{t}}\mathrm dt$? Consider:$$\int {t^n  e^{t}}\ \mathrm dt$$
is there any closed formula for this?
W|A gave me this but I don't know what is Gamma function:
$$\int {t^n e^t\ \mathrm dt} = (-t)^{-n}\ t^n\ \Gamma(n+1, -t)+ \text{constant}$$

A: Hint: Assuming $n$ is a positive integer, there is a closed formula including a sum
$$\int t^n e^t \mathrm{d}t = n!e^t\sum_{k=0}^n (-1)^{n-k}\frac{t^k}{k!} + C $$
I got it by using the formulas (1) and (2) for the incomplete Gamma function. Once you have it,  it can be verified by taking the derivative or you can try proving it with mathematical induction.

A: It is easily proved by induction and integration by parts that
$$
\int {t^n  e^{t}}\,dt = p_n(t) e^t
$$
where $p_n$ is a polynomial of degree $n$ and
$$
p_{n+1}(t) = t^{n+1}-(n+1)p_n(t)
$$
This will give you the formula mentioned by gammatester.


text:
Q: Is record replicated in postgres cluster? We use Postgres as database for our project and found that streaming replication fit our needs which works asynchronous. We have one server in write only mode (MASTER) and others in read only (SLAVES).
In most cases we send data to MASTER and forget about it. But sometimes we want to be sure that current chunk is synchronised between master and slave before continue. For new rows (INSERTS) it is trivial, script can check is new row appeared by simple SELECT query. But for UPDATEs it becomes problem.
So, is there any simple and legal way to check does slave catch up master or not? I know that every record should have own internal id but not sure that it will be the same between servers.
We use Postgres 9.2 with very similar configuration described in this great article.

A: So, finally I found solution by myself. So far postgres stores all changes is special log files, and then replicates changes over slave servers. Same time postgres has rich set of API methods that allows to read state of different internal processes. So in the end I use this queries:
-- On MASTER server current xlog location:

SELECT
  pg_xlog_location_diff(pg_current_xlog_location(), '0/0') AS offset;

-- On SLAVE server current offset of received and applied changes

SELECT
   pg_xlog_location_diff(pg_last_xlog_receive_location(), '0/0') AS receive,
   pg_xlog_location_diff(pg_last_xlog_replay_location(), '0/0') AS replay;

Getting this values from MASTER and SLAVE I can decide how big difference is between servers. And when I need to be sure that both servers are in the same state I can wait till offset on SLAVE becomes equal or bigger than on MASTER.
Probably this query can also be handy if you have the same problem:
-- Check is current server in cluster

SELECT
  pg_is_in_recovery() AS recovery;

-- False — server is MASTER
-- True — server is SLAVE


text:
Q: BINANCE API - Get Aggregated Book via WebSocket I'm developing an application to read the Binance Order Book as following:
        data = dict()
        data["method"] = "SUBSCRIBE"
        data["params"] = []
        for symbol in self.ws_subscriptions:
            data["params"].append(symbol + "@depth5@100ms")
        data["id"] = self._ws_id
        self.log_event(f"Contracts to be subscribed: {data}")
        try:
            self.ws.send(json.dumps(data))
            self.log_event(f"WebSocket {data['method']} to {self.ws_channel_book} update")
        except Exception as e:
            self.log_event(f"ERROR: WebSocket error while {data['method']} {self.ws_channel_book} {e}")

It works perfectly but I have a specific need that is basically to "aggregate" the positions coming from the stream.
Is there a way to request via API a specific aggregation data set?
Let me explain with two simple images:
standard order book obtained via API
aggregated order book that I need
Thanks to all of you will spot the light to help me.


text:
Q: Repertoire method in solving recurrence I don't know, how should I start solving this:
$$a_1 = 2 \\ a_n = 2a_{n-1} +7$$
using the repertoire method.
Could anyone give me an algorithm or explain, how to use this method in this case?


text:
Q: How to sort vuetify v-data-table by item value rather than template slot displayed value I have a v-data-table that has an alphanumeric ID with JSON key name aid (ie, AZ-0001). I also have a field in the JSON array called id which is basically just the numeric version (ie, 0001). When I sort the datatable it always puts the A's first and is not really numerically sorting which is what I want so I created a v-slot template to adjust what is displayed so that ID is the item slot and AID is whats actually displayed in the v-slot template. However, even doing this when pressing the sort icon for ID column it still sorts alphanumerically on what is actually being displayed (AID) so A's first rather than numerically just going by id which is the actual value for that column. I have another column similar to this that displays the date as Calendar year or Fiscal Year (ie, CY2022 and FY2022) so I run into a similar issue with this alphanumberic sorting doing alphabetically. So the simple example I show below I am hoping to use it for multiple fields. I plan to use the solution to this problem on another column I am running into a similar issue that I did not include in this example. My code is as follows:
<v-data-table
  :headers="headerset"
  :items="filteredData"
  :search="searchTable"
  height="inherit"
  :loading="loading"
  loading-text="Loading... Please wait"
  style="cursor: pointer"
>
  <template v-slot:item.id="{ item }">
    {{ item.aid }}
  </template>
</v-data-table>

A: I will try to explain @Takezoshi answer.
Assume you have a v-data-table:
<v-data-table
  :headers="headers"
  :items="desserts"
  :items-per-page="5"
></v-data-table>

The solution is to place custom sort function into your headers array. This way, by example:
data () {
  return {
    headers: [
      {
        text: 'Identifier',
        value: 'id',
        sort: this.customIdSort,
      },
      { text: 'Calories', value: 'calories' },
      ...
    ],
    desserts: [
      {
        id: 'AZ-0001',
        calories: 159,
        ...
      },
      {
        id: 'AB-0004',
        calories: 237,
        ...
      },
      ...
   ]
 }
}

Then you need to define this custom function. Unfortunately, I'm not clearly understand your sort logic, but you can write your own if this will not suit you:
methods: {
  customIdSort(a, b) {
    let aId = a.substring(3)
    let bId = b.substring(3)
    return aId.localeCompare(bId)
  }
}

Test this solution at CodePen.

A: You can provide a sort function in your headers that specify how your items should be sorted for a given column.
From there you should be able to implement the sort function you want.
export interface DataTableHeader<T extends any = any> {
  text: string
  value: string
  align?: 'start' | 'center' | 'end'
  sortable?: boolean
  filterable?: boolean
  groupable?: boolean
  divider?: boolean
  class?: string | string[]
  cellClass?: string | string[]
  width?: string | number
  filter?: (value: any, search: string | null, item: any) => boolean
  sort?: DataTableCompareFunction<T>
}


text:
Q: Learning from distance matrices I have a task to build multi-task classification model based on distance (similarity) matrix only. They are already precalculated and no changes here can be applied.
Can you, please, recommend me where to look for more? articles, packages? any approach that start from distance matrix and set of classes?
I tried to do that with kNN via approach mentioned in this question, but results are not very satisfactory. I would be glad to use SVM-like and/or ANN-like algorithm. They are mostly better than kNN.


text:
Q: Instantiating a New View/ViewModel Instance Using Prism/MVVM I'm new to WPF/MVVM and I'm working on a project where I've integrated Dragablz tab controls in such a way where I need the equivalent of new OEEView() to instantiate a new Window into the content area of a new tab object.
However, in the ctor of the view I'm using (OEEView), it needs a viewModel passed to it. I tried creating a new OEESelectionViewModel within the tab instantiation code and pass it to the new OEEView() but its default ctor looks like public OEESelectionViewModel(IDialogService dialogService, IOEELogger oeeLogger, ISettingsManager settingsManager) and I'm not sure how these I-objects are passed. From what I've gathered this is the responsibility of Prism and resolving dependencies using dependency injection. I've also tried creating a default(no-arg) constructor for OEEView and create a new OEESelectionViewModel within that, but I'm still stuck in terms of how to use Prism's DI.
        public OEEView(OEESelectionViewModel viewModel)
        {
            InitializeComponent();
            DataContext = viewModel;
            _viewModel = viewModel;
        }

        public OEESelectionViewModel(IDialogService dialogService, IOEELogger oeeLogger, ISettingsManager settingsManager)
        {
            ...
        }

        public TabView()
        {
            InitializeComponent();

            var tab = new HeaderedItemViewModel
            {
                Header = new HeaderWithCloseViewModel
                {
                    Header = "OEE Chart #1"
                },
                Content = new OEEView()
            };

            var viewModel = new TabViewModel(tab);

            DataContext = viewModel;
            _viewModel = viewModel;
            this.Show();
        }

I'd expect to be able to resolve a new instance and begin using it as if I used the new keyword but it isn't able to resolve itself automatically.
_container = new Container();
_container.Register<OEEView>(Reuse.Singleton);
OEEView client = _container.Resolve<OEEView>();

Additional information: Unable to resolve StationControl.ViewModels.OEESelectionViewModel as parameter "viewModel"

A: Normally, you would follow these steps:

*

*ensure that your viewmodel implements an interface, i.e. IOEESelectionViewModel

*map (register) your new interface (IOEESelectionViewModel) to a concrete type (OEESelectionViewModel) in the DI container's type registration process

*when you create a new view, use the IOC (DI) container to resolve the interface to a concrete instance of the viewmodel

When using PRISM, your lines of code that resolves the new concrete instance will look something like this:
var myVM = myIocContainer.Resolve<IOEESelectionViewModel>();
var myView = new OEEView(myVM);

Of course if you wanted to be super pure you could also look to have your view resolved and created via the DI container.
When you resolve the concrete instance of the interface, the DI container will create that instance and also auto resolve (and create) the dependencies specified in the constructor. That is part of the beauty of using a DI framework - once you've registered the mappings, magic happens. A lot of repetitive complexity is removed by using IOC patterns and a DI container.

A:
However, in the ctor of the view I'm using (OEEView), it needs a viewModel passed to it.

No, it does not. That's bad style and should be used as a last resort. The view connects to the view model through bindings from xaml, exclusively, unless you face really exceptional conditions.
What you want to do is to use the ViewModelLocator.AutowireViewModel=true attached property. This will take care that the view is magically assigned a resolved view model, without you having to put anything in code-behind.
There's a convention in place per default, but you can change it, if necessary to adapt to your situation. Or you can register a mapping from view to view model (-type) manually for each view.


text:
Q: How can I convert IQueryable expression object into LINQ expression? I need to be able to create LINQ's Where conditions/filters dynamically from a controller. Then, I want to pass these filters to a repository's method that will query the database after applying the dynamic filters using LINQ's Where extension.
Here is the code that I execute in my controller which dynamically creates filters using the IQueryable object
IQueryable<StageModel> stage = null;

if(model.ClientId != null)
{
    stage = stage.Where(s => s.ClientId == model.ClientId);
}

if (model.CategoryIds != null && model.CategoryIds.Any())
{
    var stageIds = new List<int>{ 1, 2, 3 }; // this will be dynamically generated

    stage = stage.Where(s => stageIds.Contains(s.Id));
}

Stages = unitOfWork.Stages.GetStagesPagedList(1, PerPage, stage.Expression as MethodCallExpression);

...
...

Finally, in my repository I have this method that takes Expression<Func<StageModel, bool>> expression in the third argument and passes it to the Where extension if it isn't null.
public IPagedList<StageModel> GetStagesPagedList(int pageNumber, int pageSize, Expression<Func<StageModel, bool>> predicate = null)
{
    IQueryable<StageModel> stages = CastedContext.Stages;

    if (predicate != null)
     {
         stages = stages.Where(predicate);
     }

     return stages.OrderBy(stage => stage.Name)
                  .ToPagedList(pageNumber, pageSize);

}

But I am getting an error on the following line
unitOfWork.Stages.GetStagesPagedList(1, PerPage, stage.Expression as MethodCallExpression)

This is what the error shows

Error 3   Argument 3: cannot convert from 'System.Linq.Expressions.MethodCallExpression' to 'System.Linq.Expressions.Expression>'

I also tried not casing the expression like so
unitOfWork.Stages.GetStagesPagedList(1, PerPage, stage.Expression)

Error 3   Argument 3: cannot convert from
  'System.Linq.Expressions.Expression' to
  'System.Linq.Expressions.Expression>'

How can I correctly do the conversion? Is this isn't possible, how can I dynamically create filters and pass them to my repository?

A: Simply have GetStagesPagedList accept the IQueryable that you have, rather than an Expression.
public IPagedList<StageModel> GetStagesPagedList(IQueryable<StageModel> stages,
    int pageNumber, int pageSize)
{
     return stages.OrderBy(stage => stage.Name)
         .ToPagedList(pageNumber, pageSize);
}

I don't know that that's doing enough to really warrant another method, but you're free to use it if you want.
Also your caller has a major bug in that you initialize the IQueryable to null, when you need to initialize it to the data context's table:
IQueryable<StageModel> stages = CastedContext.Stages;

//...

Stages = unitOfWork.Stages.GetStagesPagedList(stages, 1, PerPage);

A: Using fake IQueryable to build predicate is not a good idea. The chained Where technique is applicable when you have the actual IQueryable. In order to build predicate expression, all you need is some predicate builder helper utility.
For instance, you can take my own PredicateUtils class from Establish a link between two lists in linq to entities where clause. It perfectly fits because handles null predicates.
Copy/paste the class to your project, then use something like this (basically replace stage = stage.Where with predicate = predicate.And):
var predicate = PredicateUtils.Null<StageModel>();

if(model.ClientId != null)
{
    predicate = predicate.And(s => s.ClientId == model.ClientId);
}

if (model.CategoryIds != null && model.CategoryIds.Any())
{
    var stageIds = new List<int>{ 1, 2, 3 }; // this will be dynamically generated

    predicate = predicate.And(s => stageIds.Contains(s.Id));
}

Stages = unitOfWork.Stages.GetStagesPagedList(1, PerPage, predicate);

...
...

A: You need to manually create an Expression like this:
var parameter = Expression.Parameter(typeof(StagedModel), "s");
Expression stage = null;
if (model.ClientId != null)
{
    stage = Expression.Equal(Expression.PropertyOrField(parameter, "ClientId"), Expression.Constant(model.ClientId));
}
if (model.CategoryIds != null && model.CategoryIds.Any())
{
    var stageIds = new List<int> { 1, 2, 3 };
    Expression contains = null;
    foreach (var id in stageIds)
    {
        var equals = Expression.Equal(Expression.Constant(id), Expression.PropertyOrField(parameter, "Id"));
        contains = contains == null ? equals : Expression.OrElse(contains, equals);
    }

    stage = stage == null ? stage : Expression.AndAlso(stage, contains);
}
var lambda = Expression.Lambda<Func<StagedModel, bool>>(stage, parameter);
Stages = unitOfWork.Stages.GetStagesPagedList(1, PerPage, stage);


text:
Q: Firebase getCurrentUser method explanation required Can any one tell me that what does get Current User do?
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
progressDialog = new ProgressDialog(this);
    firebaseAuth = FirebaseAuth.getInstance();
    if (firebaseAuth.getCurrentUser() != null){
        //start profile activity
        finish();
        startActivity(new Intent(getApplicationContext(),Profile.class));
    }

I am confused on which user get Current User pick?

A: FirebaseAuth.getInstance().getCurrentUser() returns the currently logged in user in firebase. The user which whith whom the credentials you made the login from your android emulator. If a user isn't signed in, getCurrentUser returns null.

A: firebaseAuth.getCurrentUser() is used get a FirebaseUser object, which contains information about the signed-in user.
If it returns null the user has not signed in else it will be redirected to Profile.class...(In your above code)


text:
Q: @PathVariable Validation in Spring 4 How can i validate my path variable in spring. I want to validate id field, since its only single field i do not want to move to a Pojo
@RestController
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(@PathVariable String id) {
        /// Some code
    }
}

I tried doing adding validation to the path variable but its still not working
    @RestController
    @Validated
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(
            @Valid
            @Nonnull
            @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters")
            @PathVariable String id) {
    /// Some code
    }
}

A: You need to create a bean in your Spring configuration:
 @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
    }

You should leave the @Validated annotation on your controller.
And you need an Exceptionhandler in your MyController class to handle theConstraintViolationException :
@ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public String handleResourceNotFoundException(ConstraintViolationException e) {
         Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
         StringBuilder strBuilder = new StringBuilder();
         for (ConstraintViolation<?> violation : violations ) {
              strBuilder.append(violation.getMessage() + "\n");
         }
         return strBuilder.toString();
    }

After those changes you should see your message when the validation hits.
P.S.: I just tried it with your @Size validation.

A: To archive this goal I have apply this workaround for getting a response message equals to a real Validator:
@GetMapping("/check/email/{email:" + Constants.LOGIN_REGEX + "}")
@Timed
public ResponseEntity isValidEmail(@Email @PathVariable(value = "email") String email) {
    return userService.getUserByEmail(email).map(user -> {
        Problem problem = Problem.builder()
            .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
            .withTitle("Method argument not valid")
            .withStatus(Status.BAD_REQUEST)
            .with("message", ErrorConstants.ERR_VALIDATION)
            .with("fieldErrors", Arrays.asList(new FieldErrorVM("", "isValidEmail.email", "not unique")))
            .build();
        return new ResponseEntity(problem, HttpStatus.BAD_REQUEST);
    }).orElse(
        new ResponseEntity(new UtilsValidatorResponse(EMAIL_VALIDA), HttpStatus.OK)
    );
}


text:
Q: AAG databases not getting backed up I am using the following code with Ola Hallalengren's script to run copy only backups on a 3 node AAG setup. I have configured to run backups using the "prefer secondary" option .   When I triggered the job from the primary replica, only db's outside the AAG are backing up and when I trigger it from one of the secondary only AAG db's are backing up.
The priority for backups has been given like so
Primary - 50%
Secondary - 50%
Secondary1 - 40%
What am I missing?Please suggest. Thanks!
sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d master -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = 'USER_DATABASES', @Directory = N'\\SQL02\Backups', @CopyOnly = 'Y', @BackupType = 'FULL', @Verify = 'Y', @CleanupTime = NULL, @CheckSum = 'Y', @LogToTable = 'Y'" -b

A:
I have configured to run backups using the "prefer secondary" option.

Prefer Secondary - Will backup on secondary with highest priority. If no secondary's are available, it will backup on primary.

When I triggered the job from the primary replica, only db's outside
  the AAG are backing up and when I trigger it from one of the secondary
  only AAG db's are backing up.

First of all i would like to say that i am try to explain in concise way but due to function logic , elaborate a bit more.
Once you have your backup preferences and priority established, then it is time to set up a SQL Server Agent Job to perform the backups. Thankfully Microsoft has provided us with a system function called sys.fn_hadr_backup_is_preferred_replica. This function will return 0 if the current instance is not the preferred backup location or 1 if it is the preferred replica for backups according to the preference and priority settings.
IF (NOT sys.fn_hadr_backup_is_preferred_replica(@DBNAME))
BEGIN
      Select 'This is not the preferred replica, exiting with success';
      RETURN 0 – This is a normal, expected condition, so the script returns success
END
BACKUP DATABASE @DBNAME TO DISK=<disk>
   WITH COPY_ONLY;

As per MSDB BOL Here To take the automated backup preference into account for a given availability group, on each server instance that hosts an availability replica whose backup priority is greater than zero (>0), you need to script backup jobs for the databases in the availability group. To determine whether the current replica is the preferred backup replica, use the sys.fn_hadr_backup_is_preferred_replica function in your backup script. If the availability replica that is hosted by the current server instance is the preferred replica for backups, this function returns 1. If not, the function returns 0. By running a simple script on each availability replica that queries this function, you can determine which replica should run a given backup job.
Scripting a backup job with this logic enables you to schedule the job to run on every availability replica on the same schedule. Each of these jobs looks at the same data to determine which job should run, so only one of the scheduled job actually proceeds to the backup stage.
Note:-There is no enforcement of AutomatedBackupPreference. The interpretation of this preference depends on the logic, if any, that you script into backup jobs for the databases in a given availability group. The automated backup preference setting has no impact on ad-hoc backups.

As,i would like to say that as when you are configuring auto backup of
  AAG through maintenance Plan in 'Primary Replica' & when your Backup
  preferrence will be 'Preferred Secondary Replica' in that case also
  the Non AAG databases will be backup in primary replica backup
  location, after the execution of Maintenance plan schedule backup. And
  Availability databases you shall not find out in the backup location
  in Primary Replica . But When you shall check the 'Synchronization
  state' through ' Show Dashboard' you shall find out, the both Replica
  in 'Synchronized state'.

For reference i am writing the last script, which had ran in my server (as on dated '15-10-2016') through 'maintenance plan backup'. Which script was as follows:-
DECLARE @preferredReplica int

SET @preferredReplica = (SELECT [master].sys.fn_hadr_backup_is_preferred_replica(''Database1''))

IF (@preferredReplica = 1)
BEGIN
    BACKUP DATABASE [Database1] TO  DISK = N''H:\SQLSRV-N01_Backup_Files\Automatic Backup\Database1_backup_2016_10_15_000001_6209992.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N''Database1_backup_2016_10_15_000001_6209992'', SKIP, REWIND, NOUNLOAD,  STATS = 10
END

GO
DECLARE @preferredReplica int

SET @preferredReplica = (SELECT [master].sys.fn_hadr_backup_is_preferred_replica(''Database2''))

IF (@preferredReplica = 1)
BEGIN
    BACKUP DATABASE [Database2] TO  DISK = N''H:\SQLSRV-N01_Backup_Files\Automatic Backup\Database2_backup_2016_10_15_000001_7520058.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N''Database2_backup_2016_10_15_000001_7520058'', SKIP, REWIND, NOUNLOAD,  STATS = 10
END

GO
DECLARE @preferredReplica int

SET @preferredReplica = (SELECT [master].sys.fn_hadr_backup_is_preferred_replica(''Database3''))

IF (@preferredReplica = 1)
BEGIN
    BACKUP DATABASE [Database3] TO  DISK = N''H:\SQLSRV-N01_Backup_Files\Automatic Backup\Database3_backup_2016_10_15_000001_7770006.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N''Database3_backup_2016_10_15_000001_7770006'', SKIP, REWIND, NOUNLOAD,  STATS = 10
END

GO
BACKUP DATABASE [Database4] TO  DISK = N''H:\SQLSRV-N01_Backup_Files\Automatic Backup\Database4_backup_2016_10_15_000001_8030022.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N''Database4_backup_2016_10_15_000001_8030022'', SKIP, REWIND, NOUNLOAD,  STATS = 10

GO
BACKUP DATABASE [Database5] TO  DISK = N''H:\SQLSRV-N01_Backup_Files\Automatic Backup\Database5_backup_2016_10_15_000001_8280125.bak'' WITH  COPY_ONLY, NOFORMAT, NOINIT,  NAME = N''Database5_backup_2016_10_15_000001_8280125'', SKIP, REWIND, NOUNLOAD,  STATS = 10

GO

Here I have only changed the database name otherwise everything is as it's the script.
As you can see the above code Database1,Database2 & Database3 are AAG Databases. That's why
automatically it check through 'Scalar-value Functions' (i,e; sys.fn_hadr_backup_is_preferred_replica).
And For the database4 & database5 , it does not check through that function, because these databases are Non AAG Databases.
So, after execution of my 'primary server replica''maintenance plan schedular backup'' only i have found out the Non AAG Databases in specified backup location.
So, I can say that you are not missing anything in Ola Hallalengren's script.
For your Ref Backing Up SQL Server Databases Participating In AlwaysOn Availability Groups and Active Secondaries: Backup on Secondary Replicas (Always On Availability Groups)

A: You can configure multiple steps in a agent job to backup databases AG and NON AG separately.
1.the first step of the job should check for the preferred replica.  If the preferred replica is true it should go to Second step and if preferred replica is false it should go to third step

*if the job comes to second step the script your are already using should be handy. because it must backup all the databases along with  AG

*if the job comes to third step u can exclude the AG databases and backup only NON AG databases by modifying the @databases in thescript to @Databases = 'USER_DATABASES, -AVAILABILITY_GROUP_DATABASES',  this will exclude the AG databases and backup only non AG databases,
Note - If the Full backup happens in Secondary server it will be a copy_only backup. SO make sure you are checking correctly. and also dont configure incremental if the preferred is secondary.


text:
Q: Can waves move the object in the opposite direction of their movement? I'm trying to explain the gravity by the waves, which are emitted by an objects with mass. Can the wave move an other objects to the wave source? Under what conditions?

A: That's not really the conventional explanation fo gravity these days.
This may interest you.
http://phys.org/news/2015-10-sonic-tractor-video.html


text:
Q: How to handle enum while transferring service layer to business layer? I am using enum in my service layer. All doing good if i set value of enum vice versa i am not going to set its value than it gives me an error
Error :
The underlying connection was closed: The connection was closed unexpectedly.

I have used enum in DataContract Class which will be used while database operation.
I am using WCF Services to connect with DB with the use of Data Model. In some of the method i am using enum but in some methods i am not.
DataContract Class :
[DataMember]
public Enums.SearchType SearchType { get; set; }

Enum Declaration:
 public enum SearchType
    {
      Search = 'S',

      Export = 'E',

      Undefined = 0
    }

So what should i do in this case?? If anyone have any idea about this than please help me in this...
Thanx in Advance............

A: Ensure your enum type has a default value (0)
public SearchType
{
   Undefined = 0,
   ...
}

Enums are Int32 (unless specified otherwise). default(Int32) is 0. default(Enums.SearchType) will also be 0. If 0 is not defined in the enum, data contract deserialisation will fail.