VB.NET - When a button is pressed, do an action, wait a few seconds, and do another action

Question: I want to make it so when I press the button, it performs an action, waits a little bit and do another action. However, when I do this it doesn't do the first action until the Sleep has finished. I have also tried making a Background Thread but it can't access the ListBox. Can someone please explain how I can do this, and why my current one doesn't work? Thank you.
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    ListBox1.Items.Add("Thing1")
    Threading.Thread.Sleep(500)
    ListBox1.Items.Add("Thing2")

End Sub

Answer:
it doesn't do the first action until the Sleep has finished

Not exactly. The action does happen, but the UI doesn't reflect the change until the UI thread becomes available to repaint the UI. However, because you put the UI thread to sleep, this does not happen.
Instead of sleeping, use Task.Delay, which works similarly to a sleep, but the UI thread remains free to perform other work, including refreshing the UI:
Private Async Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    ListBox1.Items.Add("Thing1")
    Await Task.Delay(500)
    ListBox1.Items.Add("Thing2")
End Sub

Notice that for this to work, you need to add Async to the method signature, and Await to the call to Task.Delay().
To understand how the above code works, you may want to read Asynchronous Programming with Async and Await (Visual Basic).


Replace menu's ul li.first a text link with image  link

Question: Drupal 7.
For example no matter what menu block would be added to the header region, how can I make it replace first link (which has .first class) with image link?
So Drupal generates links as
Home
 and then apply some function from template.php which would replace it with something like

I found some code which kind of does that, but it needs to enter path to image via Add link under Title field and I don't really need that, the users of the theme won't understand how that works. And it also applies to any links. While I need to switch the very first text link with image link whose path would be given inside template.php
<?php
/**
* Allows for images as menu items.
* Just supply the an image path in the title. The image path will be replaced
* with an img tag. The description is used as alt text and title.
* Implements theme_menu_link().
* Reference: http://chrisshattuck.com/blog/how-use-images-menu-items-drupal-simple-preprocessing-function
*/
function YOUR_THEME_menu_link($variables) {
  $element = &$variables['element'];

  $pattern = '/\S+\.(png|gif|jpg)\b/i';
  if (preg_match($pattern, $element['#title'], $matches) > 0) {
    $element['#title'] = preg_replace($pattern,
      '',
      $element['#title']);
    $element['#localized_options']['html'] = TRUE;
  }

  return theme_menu_link($variables);
}
?>

I can do that with CSS, but I prefer not (client side reasons).
Comment: What do you mean by "I can do that with CSS, but I prefer not (client side reasons)."?  Are you saying you can't use a CSS background image instead of an actual image element in the markup?
Comment: A CSS background image sounds like the way to go there. Either you load an image from HTML or you load an image via CSS, either way it's an HTTP request to the server. If you combine the background image in a CSS sprite, the CSS option is more performant.
Comment: Or you use css_emimage. And for the CSS selector you can use :first-child, I think the web has evolved enough to make this a viable option.
Answer: You can override theme_menu_tree.  All it does is output UL tags, so you could squeeze in an LI at the beginning, like this:
    function mycustomtheme_menu_tree($variables) {
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';
      return '
' . $home_li . $variables['tree'] . '
';
    }

I've done this exact thing on several sites (but I use nice_menus), here's the code I added to my template.php file in my custom theme:
    function mycustomtheme_nice_menus_tree($variables) {
      $menu_name = $variables['menu_name'];
      $mlid = $variables['mlid'];
      $depth = $variables['depth'];
      $menu = $variables['menu'];
      // Load the full menu array.
      $menu = isset($menu) ? $menu : menu_tree_all_data($menu_name);
      if (isset($menu)) {
        $page_menu = menu_tree_page_data($menu_name);
        $trail = nice_menus_build_page_trail($page_menu);
        unset($page_menu);
      }

      // Allow i18n module to translate strings where available.
      if (module_exists('i18n_menu')) {
        $menu = i18n_menu_localize_tree($menu);
      }

      // Assume depth == 0 by default, overriden if mlid is specified.
      $parent_depth = 0;

      // For custom $menus and menus built all the way from the top-level we
      // don't need to "create" the specific sub-menu and we need to get the title
      // from the $menu_name since there is no "parent item" array.

      // Create the specific menu if we have a mlid.
      if (!empty($mlid)) {
        // Load the parent menu item.
        $item = menu_link_load($mlid);
        // The depth for our parent item, if it exists.
        $parent_depth = ($item['depth']) ? $item['depth'] : 0;

        // Narrow down the full menu to the specific sub-tree we need.
        for ($p = 1; $p < 10; $p++) {
          if ($sub_mlid = $item["p$p"]) {
            $subitem = menu_link_load($sub_mlid);
            // Menu sets these ghetto-ass keys in _menu_tree_check_access().
            $menu = $menu[(50000 + $subitem['weight']) . ' ' . $subitem['title'] . ' ' . $subitem['mlid']]['below'];
          }
        }
      }

      $output['content'] = '';

      if ($menu) {
        // Set the total menu depth counting from this parent if we need it.
        $depth =  ($depth > 0) ? ($parent_depth + $depth) : $depth;
        $output['content'] .= theme('nice_menus_build', array('menu' => $menu, 'depth' => $depth, 'trail' => $trail));
      }

      /* my changes */
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';

      $output['content'] = $home_li . $output['content'];
      $output['subject'] = '';

      return $output;
    }


How to use curl -XGET in python

Question: I have a curl command which i want to use in python version 2.7.
curl -k -XGET '' -d ''
But I am not finding any appropriate function in Request library or pycurl library. I can only find simple curl get command alternates in it. But i need to post a JSON object which is a query to elasticsearch. Any help? Thanks a lot!
Answer: for get request you can use library requests http://docs.python-requests.org/en/master/
import requests

response  = requests.get(url, data=your_data)

your_data is a dict of data in json format.
Comment: The important thing to realize, is that -XGET is just a simple GET. And since GET is the default for curl, you can actually omit it altogether for the curl request. -X in curl is followed by the http verb to use, so in the elastic search doc -XPUT is just a PUT.
Answer: You can use urllib2 for posting json and getting the response back:
import json
import urllib2
data = json.dumps(['a', 'b', 'c'])
url = <define the url to be called>
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
resp = f.read()
f.close()

How to use curl -XGET in python


Simple Inverse Logic

Question: I have the following statement: "Every number besides 0 has a unique multiplicative inverse."
I am curious as to why the following does not work:
$$\forall x \in \mathbb{R_{ \neq 0}} \exists y,z \in \mathbb{R_{\neq 0}} : ((xy = 1) \cap (xz =1)) \iff (y =z)$$
From my understanding, the following is correct, but am told that there needs to be universal quantifier for z instead. Why is this the case?
$$\forall x \in \mathbb{R_{ \neq 0}} \exists y,z \in \mathbb{R_{\neq 0}} :
(xy =1 ) \land (xz = 1) \implies (y = z) $$
I'm assuming the following doesn't hold because (y = z) can be false, while the other predicate is true:
$$\forall x \in \mathbb{R_{ \neq 0}} \exists y,z \in \mathbb{R_{\neq 0}} :
(y = z) \implies (xy =1 ) \land (xz = 1) $$
Comment: I'm not sure why this got a downvote; it's based on a misunderstanding, but isn't that the point of asking?
Answer: $\exists y\exists z~(\varphi(y)\land\varphi(z)\leftrightarrow y=z)$ can be satisfied by the existence of two distinct entities where at least one does not satisfy the predicate $\varphi$.   If there is some $y,z$ where $y\neq z$ and at least $\lnot\varphi(y)$ or $\lnot\varphi(z)$, then these values do satisfy $\varphi(y)\land\varphi(z)\leftrightarrow y=z$.
In short, the fact that $(2\cdot 3=1\land 2\cdot 4=1)\leftrightarrow 3=4$ is valued as true does not suggest that either $3$ or $4$ are the multiplicative inverse of $2$.

You wish to state "For every (non-zero real) $x$, there is some $y$ that is its multiplicative inverse, and there is no other."
$$\forall x\in\Bbb R_{\neq 0}~\exists y\in\Bbb R_{\neq 0}~\forall z\in\Bbb R_{\neq 0}~\big(xy=1\land(xz=1\to z=y)\big)$$
Note: the parenthesis placement is important.
Comment: Indeed. @BrianO
Comment: A nicety: $xy = 1$ doesn't have to be within the scope of the $z$ quantifier, and arguably the sentence is clearer if it isn't:
$$\forall x\in\Bbb R_{\neq 0}~\exists y\in\Bbb R_{\neq 0}~\big(xy=1\land \forall z\in\Bbb R_{\neq 0}~(xz=1\to z=y)\big)$$

Simple Inverse Logic


How to find the Big-O of this function: $\ 2^{\log_2(n)^4} $

Question: The definition of Big-O is
$$u_n = O(v_n) \iff (\exists c \in \mathbb{R}^{*})\,\, (\exists N \in \mathbb{N}) \,\, n > N \implies u_n < c \, v_n$$
Based on that I am trying to find the upper bound for this function
$\ 2^{\log_2(n)^4} $, but I have no idea how to continue.
It seems legit to me though that $\ 2^{\log_2(n)^4} $ = O($\ 2^{\log(n)^4} $)
Is there a way to simplify this Big-O even more? E.g could we say that O($\ 2^{\log(n)^4} $) = O($\ 2^{\log(n)} $)
Comment: Your question is not well-defined. Since the function is in the Big-O of itself. So what exactly are you looking for? A 'simpler' function for the Big-O? Something else?
Comment: @Dimitris No, $2^{\log_2(n)}=n$, which grows much more slowly than $2^{\log_2(n)^4}$.
Comment: @AlexShtof Thank you for your observation. I edited my question. Yes, I am trying to find a way to simplify this even more, if thats possible. Could we say that O($\ 2^{log(n)^4} $) = O($\ 2^{log(n)} $)?
Comment: Thank you everybody.
Answer: What they probably mean is $\left(2^{\log_2 n}\right)^4$.  Because $2^{\log_2 n}=n$ this simplifies to $n^4$.  The conventional way to read $a^{b^c}$ is $a^{(b^c)}$, which in your case would mean the function is $2^{\left((\log_2 n)^4\right)}=n^{\left((\log_2 n)^3\right)}$  This grows faster than any polynomial.
Comment: It can be simplified to $n^{(\log n)^3}$, which makes it more obvious it grows faster than any polynomial.
Comment: @eyeballfrog:  good point


Unbounded functions inside closed intervals

Question: I'm pretty stuck on the following question:
Let $f$ be an unbounded function from the closed interval $[a,b]$ to $R$. Prove that there exists a point $x$ in $[a,b]$ such that $f$ is unbounded in any neighborhood of $x$.
I understand that this comes naturally from the fact that $[a,b]$ is a closed interval - I'm sure that for any open/half open interval such a point $x$ does not have to exist. But I'm just not sure exactly why this is.
I tried assuming that such a point doesn't exist, which means that $f$ is bounded in any neighborhood of any point in $[a,b]$. The conclusion is that $f$ can't be unbounded (which is the contradiction I'm looking for), but I just can't take that extra step in order to conclude this (naturally I have to somehow derive this conclusion from the fact that the interval is closed).
Can somebody point me in a generally useful direction?
Thanks a lot in advance.
edit:
I think I came up with a general direction for a proof, but I'm not sure if it's the right way to go:
Let's look at the edges - $a$ and $b$. We need to ask - is there a neighborhood of $a$ and $b$ where $f$ is unbounded? If there is - we're done. If there isn't, this means that there is some $\epsilon_1$ neighborhood of $a$ and $b$ where $f$ is bounded, and so we'll define the closed interval $[a + \epsilon_1, b - \epsilon_1 ]$.
Now we'll ask the same question about $[a + \epsilon_1, b - \epsilon_1 ]$ - is there a neighborhood of the two edges where $f$ is unbounded? If there is - we're done. If not, there is some $\epsilon_2$ neighborhood of the two edges where $f$ is bounded, so we'll define the closed interval $[a + \epsilon_1 + \epsilon_2 , b - \epsilon_1 - \epsilon_2 ]$.
We'll continue in such a manner infinitely many times, until we can't do it any further. So (using Cantor's lemma) either we'll reach some single middle point x, or we'll reach some inner interval $[a', b'] \subseteq [a, b]$.
Now I claim that either way - we've found the point we're looking for - either x, a' or b' must be a point with no bounded neighborhoods. (but I'm not sure if there's still another step I need to take in order to show this)
What do you think?
Comment: +1 for a very good question. Especially the fact the result in question does not deal with continuous functions is important as it emphasizes the key aspect of completeness.
Answer: For the sake of argument, suppose for every $x\in[a,b]$, $f$ is bounded in some neighborhood $U_x$ of $x$. Then
$$
[a,b]=\bigcup_{x\in[a,b]} U_x
$$ Now use compactness of $[a,b]$ to get a contradiction.
Comment: I actually don't know what compactness is haha, I'm a complete beginner. could you please explain a bit further?
Comment: Compactness tells you that you can choose finitely many $x_1,x_2,\cdots, x_n\in[a,b]$ such that $[a,b]=\cup_{k=1}^n U_{x_k}$.
Answer: Well, the best approach here is to use the Nested Interval Principle. Since $f$ is unbounded on $[a, b] $, it is unbounded on at least one of the intervals $[a, (a+b) /2]$ and $[(a+b) /2,b]$. Call that interval $I_1$ and repeat the procedure to obtain a sequence of nested closed intervals $I_n$ such that $f$ is unbounded on each $I_n$. Since the length of $I_n$ tends to $0$ by Nested Interval Principle there is a unique point $c$ which lies in all intervals $I_n$. Now any neighborhood of $c$ contains some $I_n$ and hence $f$ is unbounded on any neighborhood of $I_n$.

The problem with your approach is that you never know when you can cover the entire interval by using steps of size $\epsilon$ which can be arbitrarily small. The nature of real line is not so simple to be handled by such naive arguments. You must resort to some form of completeness property of real numbers.
To convince yourself note that the result fails for rationals. The function $f:\mathbb{Q} \to\mathbb{Q} $ given by $f(x) =1/(x^{2}-2)$ is unbounded on the rational interval $I=\{x\mid x\in\mathbb{Q}, 1\leq x\leq 2\} $ but $f$ is bounded on every rational neighborhood (ie neighborhood containing only rational points) of any point in $I$. Your argument remains same even in this case also.
The argument of this answer is based on Nested Interval Principle which does not hold for the system of rational numbers. Thus in effect if we carry the process mentioned in the answer for rational intervals $I_n$ then there is no guarantee of a rational point $c$ which lies in all of $I_n$.
Comment: That's a really cool idea. thanks!
Comment: @GSofer: by the way you should also try to prove this using other forms of completeness like least upper bound property.


update every elements replaceWith partial rails 3.1

Question: I have 3 elements and one form with a button:
<input type="submit" value="Follow All" class="follow_all">

 page 1

 page 2

 page 3

When I click in submit button, the form action, call to the file create.js.erb.
In this file I have:
var $divs = ("#page .pages");
$($divs).replaceWith("<%= escape_javascript(render(:partial => 'replace_all_divs'))%>");

In the partial _replace_all_divs.html.erb I have:
<% @posts.each do |post| %>
<%= post.id   %>
<% end %>

I want replace each div content (page 1, page 2 and page 3) with post id.
The problem is that I get for each div the 3 ids of post.id:
I get a bad result :(:

 123

 123

 123

I want get the next result:

 1

 2

 3

Answer: As you're using "#page .pages" as the selector, the replaceWith method is executed three times, each one with the content produced by _replace_all_divs.html.erb (a loop that concatenates all your ids => "123").
You'd better use "#page" as the selector and replace its content with new divs.
create.js.erb :
$('#page').empty().append('<%= render(:partial => 'replace_all_divs')%>');

_replace_all_divs.html.erb :
<% @posts.each do |post| %>
 <div id="page<%= post.id.to_s.rjust(2, '0') %>" class="pages"><%= post.id %>

<% end %>


Function that is injective in each argument separately

Question: What do you call a function $f(x,y)$ such that for all $a,b$,
$$y\mapsto f(a,y)\quad \text{ is injective, and}$$
$$x\mapsto f(x,b)\quad \text{ is injective.}$$
For example, linear functions: $f(x,y)=2x-3y+5$ over $\mathbb R$, or the Boolean XOR function.
Comment: Asked before (but not answered): https://math.stackexchange.com/questions/3731057/does-this-kind-of-function-have-special-name ... two suggestions there: "bi-injective" and "injective in each argument"
Answer: In case there is no canonical term for such a function, let's gather a list of suggestions:

Component-wise injective
Projectively injective (because you're saying the induced maps you get from the projections of the domain $X \times Y$ onto either component are injective)
Multi-injective or in the case of two arguments biinjective, by analogy with multilinear and bilinear


Why am I getting a Mixin undefined error when compiling my LESS code?

Question: I am new to LESS and am trying to create a complex structure to my LESS files so I can separate the front end framework files from my platform files from my client specific changes.... So to that end I have a structure using @import "filename.less"; like this (all separated into sub folders....)
master.less > platform.less > bootstrap.less > variables.less
                                             > mixins.less
                                             > ............etc

                            > font-awesome.less > ........etc

                            > bootstrap-ui.less > ........etc

                            > platform-variables.less
                            > platform-mixins.less
                              ......... etc

            > site.less > site-variables.less
                          ...............etc..
                          random-page.less

OK so master.less has a import to platform.less and site.less etc....
My question how come I am able to use the mixins defined in mixins.less file.... in random-page.less but not able to use the mixins defined in my custom mixin file in random-page.less (platform-mixins.less) that is called from the platform.less file I'm very confused....   please advise.
The error that I receive is:
>> NameError: .no-padding is undefined in css/site/random-page.less on line 75, column 3:
>> 74   .footer-sidebar {
>> 75           .no-padding;
>> 76   }

Which is true because it does not exist in this file?
However the bootstrap standard mixin works as expected despite the  clear fix mixin/class not existing in this file...
.footer-sidebar {
    .clearfix;
}

Comment: So I can't see any reason why it coould be not visible. I'm afraid it's impossible to suggest anything w/o seeing the whole project. (As you say above Bootstrap mixins defined and used same way work just fine so it must be something very simple - for example don't you try to compile `site.less` separately from `master.less`? That way it won't work of course (countrary `platform.less` can be compiled alone since it includes all used components)). How do you compile all that, btw.?
Comment: To say for sure we need to see how exactly this `.no-padding` is defined (For example is this really a mixin defined in the global scope and not something buried deep deep under other selector(s)?).
Comment: Sure my mixin is super simple:
    .no-padding() { padding:0; }
Just to be certain I checked the compiled code which is as expected:
    .no-padding { padding:0; }
Comment: Thanks for your input... Yes, all files get compiled into one CSS file... not separate files... I will investigate further in the morning and thanks again for your help.
Comment: Thank you for your help the issue is now resolved. It was not a result of the LESS structure shown above this worked fine. But as part of the build i was also generating further CSS files that also had a dependency on site.less file but didn't include the platform.less file DOE. Hence in this context the mixin was not found.
Answer: To understand your structure, I created five files as follow:

master.less:
.master {master:1;}
@import "site";
@import "platform";

platform.less
.platform {platform:1;}
@import "platform-mixins.less";

platform-mixins.less
.platform-mixins {platform-mixins:1;}
.platform-mixin() {color: red;}

random-page.less
.random-page {
    .platform-mixin()
}

site.less
.site {site:1;}
@import "random-page";

After that I run lessc master.less which outputs the following CSS code:
.master {
  master: 1;
}
.site {
  site: 1;
}
.random-page {
  color: red;
}
.platform {
  platform: 1;
}
.platform-mixins {
  platform-mixins: 1;
}

As expected, the .platform-mixin() from platform-mixins.less can be called without errors in random-page.less. So make sure that your mixin exists and that you really import the files you mention.


Bitmap Performance-Optimization Patterns

Question: I found several patterns for optimizing Bitmaps handling in WPF. I do not, however, understand when to use each patterns. As I think this is a common problem, I summarized what I understand and what I guess and ask for your help. If you can add patterns, explain how they differ, explain if they use the CPU or the GPU, and teach when to use each and how to combine them, it'd be a tremendous help!
Context – the Images "Grid" Scenario:
My application has to display many bitmap images. The images are displayed on the screen in a rows-and-columns grid-like organization (not necessarily the Grid or UniformGrid classes, think Window Media Player's Album view). Images might move between different grid cells. Some images at arbitrary cells may be replaced by others. Images should be clickable, should provide a context menu, should be selectable, drag-able etc. In other words, "combine the little buggers into one big bitmap" is not applicable, at least not naively.
Pattern 0: The Hack
Do combine the little buggers into a bitmap (how? drawing context?), and use this as the background. Overlay this with images with empty content that will handle the hits, context menus, events etc.
The advantage is that we're only speaking about two bitmaps here: The currently displayed one and the one that should replace it. This should be really fast. However, my years of experience raise the red flag of danger. Your comments?
Pattern 1: Reduce Image Size
This is a no-brainer when you know in advance the image size to resize to, and when you're prepared to lose details (color) for performance:

Reduce the bitmap size using BitmapImage.DecodePixelWidth
Reduce the color information using FormatConvertedBitmap.DestinationFormat
Set the control's scaling behavior setting Image.Stretch to Stretch.None
Set the SetBitmapScalingMode for the image to LowQuality.
Freeze the bugger

See code here.
Pattern 2: Background pre-fetch
This pattern is applicable when you think you can take advantage of the user gazing at the images on the screen, and prepare ahead the next images to display. The cons for your project, in addition to the memory overhead, is that it has to support the .Net Framework 4 target and not just the client profile, so it might incur an installation on the client's. You yourself will have to suffer the async programming pain.
In this pattern you create exactly the required number of Image controls. When bitmaps need to be added, moved or deleted you only modify the Image controls' BitmapSource(s). A BackgroundWorker task is responsible for pre-fetching the BitmapSource(s) (possibly using the "Reduce Image Size" pattern above) and inserting them into MemoryCache.
For this to work you have to set the BitmapImage's CacheOption to OnLoad, so that the work is off-loaded to the background worker.
Pattern 3: Drawing Context
This was suggested by Sheldon Ziao from Microsoft Support on the MSDN WPF forum here. See page 494, Chapter 15 "2D Graphics" in Adam Nathan's WPF 4 Unleashed for a description of DrawingContext. I can't say I understand it. According to the answer here, I would assume this would improve handling of Geometry drawings, not bitmaps. Next, I don't think this will support the focus and events requirements for the images (my bad for not explaining the requirements better at the forum) Moreover, I'm worried by the book's summary sentence: "Note that the use of DrawingContext doesn't change the fact that you're operating within a retained-mode system. The specified drawing doesn't happen immediately; the commands are persisted by WPF until they are needed." This means that once our even handler re we can't take advantage of parallelism as in "Background pre-fetch".
Pattern 4: Writeable Bitmaps
The MSDN documentation here describes it as a dual buffer system: Your UI thread updates the buffer; the WPF's render thread moves this to video memory.
The intended usage (see here) is for bitmaps that change a lot such in a video movie like display. I'm not sure, but possible this could be hacked and combined with the Background Pre-fetch pattern and used in the grid scenario.
Pattern 5: Cached Bitmap
Not much info on the MSDN (here). On the WPF forum archive (here) it's explained that "The BitmapCache API is designed to cache your content (when rendering in hardware) in video memory, meaning it stays resident on your GPU.  This saves you the cost of re-rendering that content when drawing it to the screen." This seems like a great idea. I'm not sure, however, what are the pitfalls and how to use it.
Pattern 6: RenderTargetBitmap
The RenderTargetBitmap converts a Visual to a bitmap. I'm not sure if it's relevant here. See here.
Edit: Regarding Paul Hoenecke question: I've written that "My application has to display many bitmap iages". I failed to mentions that I need to display about 800 images concurrently.
One can read about the performance issues involved at my SO questions WPF Bitmap performance and How can I make displaying images on WPF more "snappy"?
I've modified the description of pattern 1 to highlight the concept that the image controls aren't created or deleted (unless we want to display a larger or smaller grid). Only their Sources are set to different, new or null BitmapSources.
Edit: This question as posted on the WPF support forum, with some answers from MS personnel.
Comment: How many images are you anticipating? I have made an app that shows a grid of thousands of images before. We used a virtual-mode listbox; as the user scrolls down, the images are loaded in a background thread, frozen and set to the Source of the Image. Clearly, you have put a lot of thought into this... but, maybe knowing more about exactly what you want to accomplish would be better. For example, what problems have you had that make optimizing such a priority?
Comment: @PaulHoenecke Hi Paul, thank you for your answer. The virtual collections help you when you want to display a small number of items out of a large collection. Here, I want to display about 1K items concurrently. Additionally, I'm not sure there exists a virtualizing grid. Lastly, pattern 1 is essentially virtualizing - I'll add en edit.
Comment: Avi, your question looks inappropriate for the described problem. You may want to improve compression ratio for some reason, but then you need to know exactly what kind of images you are displaying. Or, on the other hand, you may want give the user an impression of all the images available, then you might define some sets and display thumbnails or alike. But both things don't have necessarily to do with each other. Maybe you want something like a similarity metric to define sets of look alike images?
Comment: @artsenay Sorry, I did not understand your comments. I want to display a lot of bitmaps on the screen, and I want to display them in a grid, not at arbitrary screen positions. And it's not fast enough, so I want it to appear faster.
Comment: @Avi Is there any reason not to use existing algorithms, e.g. JPEG with low quality settings? It depends on the images you want to compress, of course, but if you have images like diagrams, you could try with PNG and there with one of the numbered algorithms. It doesn't make any sense to discuss how one could shuffle with the binary data in memory if you don't know what you want to do. Probably server caching is your least problem, since the bottle neck will be on the client side or in the transmission.
Comment: @artsenay I think I undertand where the misunderstanding lies. I'm not talking about a web server senario. I'm talking WPF. THere's no transmission of images, they are all on the local computer. And displaying them is slow. Please re-read the interoduction and the context sections.
Answer: I'm unable to find a specific question in your post, other than asking for comments on the approaches below. I won't claim to know everything above but I'll tell you what I do know having worked for a while developing high-performance UIs using WPF and Silverlight.

Pattern 0: The Hack. Combining all into one image

I'd avoid this if possible. It sounds like you want to display a large wrap-panel of thousands of small images. Each image is therefore a thumbnail (as you cannot display 1000s of large images at once). As a result, I'd advocate caching/resize over combination.

Pattern 1: Reduce Image Size

If you are displaying 1,000 images on screen at once, consider the available screen real-estate. The average monitor is 1280x1024 pixels, or just over 1.3MPixels. 1000 images suggests you will get a maximum size of 1300 pixels per image, or 36*36. Lets say your images are 32*32 in size. You should definitely be creating a thumbnail of that image size to render on screen, then on click (or other action) show the full size image.
Also consider not only the render overhead of resizing a large image, but of sending a large image to the GPU to resize. That data requires bandwidth to send. A large image can be several megabytes whereas a thumbnail of size 32*32 could be a few kilobytes.
If you require dynamic sizing, fine, but you'll need to experiment with creating multiple thumbnails or generating them on the fly.

Pattern 2: Background pre-fetch

This is a technique I've not heard of, however it seems plausible. What is the overhead in your application? is it updating the Image.Source property or creating a new Image, tessellating, performing Layout and sending the information to render it to the GPU?
All the above occur on the CPU except for the final render. By reducing the overhead on the CPU side and updating the source you might be on to something. Combine this with WriteableBitmap as a source and you could further gain a performance improvement (see below).

Pattern 3: Drawing Context

Ok, all this does is allow you to queue up retained mode drawing calls using an "OnPaint" style syntax which is nothing like the old GDI OnPaint. In my experience OnRender doesn't improve performance, but it does allow for fine grained flexibility over what is drawn and when. OnRender provides you with a context, which has a DrawImage function, allowing a BitmapSource to be drawn to the rendering pipeline without the need for an Image control. This is good as it removes some overhead, however introduces problems similar to those seen in Pattern0 (you will lose layout and have to compute position of all your images). If you do this, you might as well invoke Pattern 0, which I advised against.

Pattern 4: Writeable Bitmaps

WriteableBitmaps are a little used and extraordinarily powerful subsystem within WPF. I use them to great effect to create a charting component capable of rendering large amounts of data in real-time. I would suggest checking out the WriteableBitmapEx codeplex project Disclosure, I have contributed to this once and seeing if you can combine it with other patterns. Specifically the Blit function which would let you write a cached bitmap to a bitmap source on an image.
For instance, a good technique might be Pattern 1 + 2 + 4.
You could have a grid of N Image controls on the screen at set locations in a grid control. Each of these is static and doesn't get scrolled out of view so there are no creations/deletions going on. Now, on top of this, resize your image and write to a WriteableBitmap which is set as the Source property on each image. As you scroll, get the next/previous thumbnails and update the sources using WriteableBitmapEx.Blit. Pow! virtualized, cached, multi-threaded imaging goodness.

Pattern 5: Cached Bitmap

This is an attempt by microsoft to do 1+2+4 as I discussed above. What it tries to do is after layout (CPU side), tessellation (CPU Side), sending retained mode render instructions to the GPU (CPU side) and rendering (GPU side) it caches a raster image of the rendered element which is re-used on the next rendering pass. Yes a little known fact about WPF is that wonderful GPU powered engine is terribly slow as it does most of its work on the CPU :P
I would experiment with BitmapCache and see how it performs. There are caveats, and they are that when you update your UIElement it has to recreate the cache so static elements will perform far better than dynamic. Also I've not seen a significant improvement in performance from using this whereas WriteableBitmap style techniques can give an order of magnitude improvement.

Pattern 6: RenderTargetBitmap

This final technique lets you render a UIElement to a bitmap - you know that - but what is interesting is this can perform a poor-mans thumbnail generator (or resize). For instance, set an Image with BitmapSource of your full size image. Now set the size of the Image control to 32*32 and render to bitmap. Voila! You have your BitmapSource thumbnail to use in conjunction with some swapping (Pattern 2) and/or writeable bitmaps.
Ok finally, just wanted to say the requirement you have will push WPF to its limits, however there are ways to get it to perform. Like I said, I have build systems which rendered thousands or millions of elements on the screen at once by using the wonderful workaround that is WriteableBitmap. Going down the standard WPF route will result in performance hell so you will have to do something exotic to solve this.
As I said my recommendation is 1+2+4. You must resize a thumbnail, of that I have no doubt. The idea of having a static grid of Image controls and updating the sources is very good. The idea of using WriteableBitmap (specifically WriteableBitmapEx blit function) to update the sources is also one worth exploring.
Good luck!
Comment: That Article link on the WPF Rendering Pipeline is now dead, please see http://jeremiahmorrill.wordpress.com/2011/02/14/a-critical-deep-dive-into-the-wpf-rendering-system/
Comment: Yes I do! See this article: http://jeremiahmorrill.com/2011/02/14/a-critical-deep-dive-into-the-wpf-rendering-system/ This is pretty esoteric stuff, don't feel bad. Most will tell you "Just override OnRender" for performance, or "WPF uses the GPU", but that's the wrong answer. When you realise that WPF does most of its work CPU side (lame!!) then you can begin to optimize for performance.
Comment: Thank you for your answer! An ancient Jewish Passover story describes four sons: Wise, evil, naive and one that doesn't even know which questions to ask. I feel I'm so lacking in background I'm not even capable to ask the correct questions: "tessellating"? Are you aware of any book or article describing the (2D) graphics "pipeline" in WPF? What are the activities, what does the CPU do, what does the GPU do?
Comment: Going through the trail you sent me on, I start getting the feeling that WPF is inherently slow and that one should wait for Direct2D or WinRT...
Comment: @Avi WPF is inherently slow, yes. However WinRT/Xaml apparently is no better. Direct2D is available now, you shouldn't need to wait to integrate this to your application. However if you want rich databinding and quick creation of screens you won't find it in Direct2D!
Comment: @Avi I should add, there are ways to make WPF perform, just takes a little coaxing ;-) Check out http://bit.ly/xv5cVv - which uses a combination of efficient WPF techniques and immediate mode techniques such as Bitmaps/Direct GPU access to get the desired effect


Error: Unable to find entry in pubspec.yaml:C:\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_widget_from_html-0.8.0\test\images\

Question: After updating some dependency in my pubspec.yaml I started receiving this error "Error: unable to find directory entry in pubspec.yaml: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_widget_from_html-0.8.0\test\images". So I don't really know whtat is wrong. Here is my pubspec.yaml

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  badges: ^2.0.2
  cached_network_image: ^3.2.0
  cloud_firestore: ^3.1.6
  dots_indicator: ^2.0.0
  easy_localization: ^3.0.0
  firebase_auth: ^3.3.6
  firebase_core: ^1.3.0
  firebase_messaging: ^11.2.6
  firebase_storage: ^10.2.6
  flutter_web_browser: ^0.16.0
  flutter_html: ^2.1.0
  flutter_widget_from_html: ^0.8.0
  google_fonts: ^2.1.0
  google_sign_in: ^5.0.4
  html: ^0.15.0
  html_unescape: ^2.0.0
  image_picker: ^0.8.1+3
  intl: ^0.17.0
  introduction_screen: ^2.1.0
  launch_review: ^3.0.1
  line_icons: ^2.0.1
  lottie: ^1.1.0
  package_info: ^2.0.2
  path_provider: ^2.0.2
  provider: ^6.0.0
  share: ^2.0.4
  shared_preferences: ^2.0.6
  skeleton_text: ^3.0.0
  fluttertoast: ^8.0.7
  flutter_math_fork: ^0.4.0
  flutter_svg: ^0.22.0
  url_launcher: ^6.0.9
  youtube_player_flutter: ^8.0.0
  youtube_plyr_iframe: ^2.0.7
  rounded_loading_button: ^2.0.5
  firebase_analytics: ^9.1.0
  flutter_facebook_auth: ^4.0.1
  the_apple_sign_in: ^1.1.1
  video_player: ^2.1.10
  flick_video_player: ^0.4.0-dev
  flutter_icons:
    git:
      url: https://github.com/adarsh-technocrat/flutter-icons
  md2_tab_indicator:
    git:
      url: https://github.com/westdabestdb/md2_tab_indicator

  google_mobile_ads: ^1.0.1
  facebook_audience_network: ^1.0.0-nullsafety.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^1.0.0

  flutter_launcher_icons: "^0.9.0"

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/images/icon.png"

flutter:

  uses-material-design: true

  assets:
    - assets/images/
    - assets/animation_files/
    - assets/translations/

  fonts:

    - family: Poppins
      fonts:
        - asset: assets/fonts/Poppins-Light.ttf
          weight: 400
        - asset: assets/fonts/Poppins-Regular.ttf
          weight: 500
        - asset: assets/fonts/Poppins-Medium.ttf
          weight: 600
        - asset: assets/fonts/Poppins-SemiBold.ttf
          weight: 700
        - asset: assets/fonts/Poppins-Bold.ttf
          weight: 800

    - family: Open Sans
      fonts:
        - asset: assets/fonts/OpenSans-Light.ttf
          weight: 400
        - asset: assets/fonts/OpenSans-Regular.ttf
          weight: 500

    - family: Manrope
      fonts:

        - asset: assets/fonts/Manrope-Regular.ttf
          weight: 400
        - asset: assets/fonts/Manrope-SemiBold.ttf
          weight: 500
        - asset: assets/fonts/Manrope-Medium.ttf
          weight: 600
        - asset: assets/fonts/Manrope-Bold.ttf
          weight: 700
        - asset: assets/fonts/Manrope-ExtraBold.ttf
          weight: 900

And here is my flutter doctor -v

[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.18362.53], locale en-US)
    • Flutter version 2.8.1 at C:\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 77d935af4d (7 weeks ago), 2021-12-16 08:37:33 -0800
    • Engine revision 890a5fca2e
    • Dart version 2.15.1

[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    • Android SDK at C:\Users\USER\AppData\Local\Android\sdk
    • Platform android-32, build-tools 32.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 2020.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] Connected device (3 available)
    • itel P651W (mobile) • 062983715I011447 • android-arm    • Android 10 (API 29)
    • Chrome (web)        • chrome           • web-javascript • Google Chrome 97.0.4692.99
    • Edge (web)          • edge             • web-javascript • Microsoft Edge 97.0.1072.62

• No issues found!
Comment: Have you tried deleting the cache directory? Sometimes files get corrupted.
Comment: Yes I have. I did invalid cache and restart, flutter clean.
Answer: You just need to upgrade to v0.8.1+1
Reference: https://github.com/daohoangson/flutter_widget_from_html/issues/618#issuecomment-950555416


Qual status HTTP devo usar para quando estiver faltando um parâmetro no POST?

Question: Tenho um form que será submetido para o servidor via ajax, usando um plugin para isso. Quando o form não é preenchido corretamente (no caso quando estiver faltando um parâmetro obrigatório), quero retornar um JSON com uma mensagem de erro e um status de erro, para que no javascript, o plugin entre no callback de erro ao invés de sucesso.
Sei que deve ser um da família 4xx, mas não sei qual deles.
Não parece ser nenhum desses:

400 - Bad request: o request deu certo, tanto que retornei um JSON
404 - Not found: o recurso existe, tanto que eu posso dar POST pra ele
403 - Forbidden: também acho que não

Qual é o status que devo retornar?
Comment: Aqui vc tem todos os códigos, mas não acho existe um erro para isso, já que não existe uma obrigatoriedade do http q seja passado um post. Talvez vc possa adotar como padrão o 412.  http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Comment: O Laravel, framework do PHP adotou o `422` por padrão, quando há algum dado inválido pela validação do requisição. Faltar o parâmetro seria equivalente a violar a validação `required`.
Answer: O 422 é o mais próximo disso (já comento mais sobre ele).
No 400, é falado sobre "bad syntax", mas este não é o caso (erro de sintaxe).
No 412, é falado sobre "preconditions that the requester put on the request", ou seja, quem contactou o servidor é que tinha uma pré-condição. Mas esse também não é o caso, porque é o servidor (e não o requester) quem vai fazer a validação de fato. Embora, claro, seja possível haver alguma validação também do lado do formulário/cliente.
No 422, ele fala sobre erros de semântica. Ou seja, não tem erro de sintaxe, mas tem alguma informação faltando. Parece ser o mais conveniente.
Answer: As opiniões são divididas. Há uma pergunta equivalente no Stack Overflow em Inglês, em que as pessoas se dividem entre os códigos 400, 412 e 422:
https://stackoverflow.com/questions/3050518/what-http-status-response-code-should-i-use-if-the-request-is-missing-a-required
Neste caso, você teria que avaliar o contexto em que o código será retornado para decidir qual o melhor código a devolver.
Comment: Eu geralmente uso 422 Unprocessable Entity: The request was well-formed but was unable to be followed due to semantic errors.
Answer: Muito interessante o stack apontado pelo @Cigano.
Particularmente eu apoio o uso do 400 pois o servidor estaria respondendo que recebeu uma requisição ruim do cliente.
Mas por quê uma requisição ruim?
Porque alguma coisa que ele necessita para fornecer a resposta ideal e completa estava ausente. E esse alguma coisa pode ser, um argumento de URL (como um token), um campo de controle normalmente armazenado num hidden e etc.
Comment: Ou a falta de um argumento como nome de callback, no caso do `JsonP` :)


Regular expression for two consecutive things in my case

Question: What is the regular expression matches exactly two consecutive tab and new line symbols. \t\n\t\n ? I am using Java.
Comment: Why not just `"\t\n\t\n"`?
Comment: Or `"(\\t\\n){2}"`
Comment: windows line breaks is `\r\n`. So maybe `(\\t(\\r|)\\n){2}`
Comment: I am seeking a way without repeatedly typing "\t\n\t\n"
Comment: `"(\t\n){2}"` if you prefer, but you're not saving yourself any keystrokes.
Answer: Java 8 supports use of \R as a Linebreak matcher that will match any Unicode linebreak sequence.
So you can use it like this:
String str = "\t\r\n\t\r\n";
System.out.printf("Matched: <%s>%n", str.matches("(?:\\t\\R){2}"));

str = "\t\n\t\n";
System.out.printf("Matched: <%s>%n", str.matches("(?:\\t\\R){2}"));

Since we are using this regex in matches() method here hence it will match full string input only.
Output:
Matched: <true>
Matched: <true>

Answer: Your expression will match \t\n\t\n even if it is part of a longer sequence, i.e. not exactly two consecutive occurrences.
If you would like to match the sequence of exactly two \t\ns, use negative look-around:
(?<!\t\n)(\t\n){2}(?!\t\n)

Note the use of parentheses and {2}, it lets you avoid typing the same sequence multiple times.


Leiningen: working with local git repo

Question: I want to change something in incanter, so I created a fork on github and a clone of it on my laptop. Now, when I try to run tests with lein test I get these errors:
/Users/me/work/incanter$ lein test
Could not find artifact incanter:incanter-core:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-io:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-charts:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-mongodb:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-pdf:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-svg:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-latex:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-excel:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-sql:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
Could not find artifact incanter:incanter-zoo:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)
This could be due to a typo in :dependencies or network issues.
If you are behind a proxy, try setting the 'http_proxy' environment variable.
/Users/me/work/incanter$

I have not changed anything in the project.clj yet, here it is:
(defproject incanter "1.5.8-SNAPSHOT"
  :description "Incanter is a Clojure-based, R-like statistical programming and data visualization environment."
  :url "http://incanter.org/"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :scm {:name "git" :url "https://github.com/incanter/incanter"}
  :min-lein-version "2.0.0"
  :dependencies [[incanter/incanter-core "1.5.8-SNAPSHOT"]
                 [incanter/incanter-io "1.5.8-SNAPSHOT"]
                 [incanter/incanter-charts "1.5.8-SNAPSHOT"]
                 [incanter/incanter-mongodb "1.5.8-SNAPSHOT"]
                 [incanter/incanter-pdf "1.5.8-SNAPSHOT"]
                 [incanter/incanter-svg "1.5.8-SNAPSHOT"]
                 [incanter/incanter-latex "1.5.8-SNAPSHOT"]
                 [incanter/incanter-excel "1.5.8-SNAPSHOT"]
                 [incanter/incanter-sql "1.5.8-SNAPSHOT"]
                 [incanter/incanter-zoo "1.5.8-SNAPSHOT"]
                 [org.clojure/clojure "1.5.1"]
                 ]
  :profiles {:dev {:resource-paths ["data"]}
             :debug {:debug true}
             :uberjar {:aot :all
                       :main incanter.main
                       :dependencies [[reply "0.3.0" :exclusions [org.clojure/clojure]]
                                      [swingrepl "1.3.0"
                                       :exclusions [org.clojure/clojure org.clojure/clojure-contrib]]
                                      ]
                       }
             }
  :repl-options {:init-ns incanter.irepl
                 :resource-paths ["data"]
                 :init (do
                         (set! *print-length* 500)
                         (use 'clojure.repl))
                 }
  :jvm-opts ["-Xmx1g" "-Djsse.enableSNIExtension=false"
             ~(str "-Dincanter.home=" (System/getProperty "user.dir"))]
  )

Any help will be greatly appreciated.
Comment: you want to use that libs from your local, I mean from your system? The thing is you don't have those deps in your ~/.m2(maven) you get that exception and leiningen tries to search in clojars.
Comment: Sorry, I'm new to Clojure and not really familiar with maven. Could you please give details of what needs to be done to get the deps in my local maven directory?
Comment: maven is build tool that leiningen uses underneath, I've answered your question if it is not clear I can edit it in detail.
Comment: Did you go `lein install` from the command line at the project root of your Incanter project? That's the usual way, although usually there is one jar per project. But worth a try. Also you should manually look in your .m2 directory to see what's there.
Comment: I recommend to use `develop` branch if you want to submit patches to Incanter. And it supports `sub` & `modules` plugins, so you can do `lein sub test` to perform `test` task for all modules.
Comment: @AlexOtt many thanks for the tips.
Answer: I took a look at the project. You must build any projects under /modules so that the snapshot-version 1.5.8-SNAPSHOT will be builded on your local .m2/
cd modules
cd incanter-core
lein install
...

Then I think it should work. Alternative you can reduce in  the dependencies to 1.5.7.
Answer: You can use this approach:
Create jars of those projects(lein uberjar)
Then use command for each your jar:
mvn install:install-file \
 -Dfile=maven_repository/my-project.jar \ ;;path to your jar(this is example)
 -DgroupId= incanter \
 -DartifactId= incanter \
 -Dversion=0.1.0 \
 -Dpackaging=jar \
 -DgeneratePom=true

Then add deps to your project.clj and refresh leiningen:
[incanter/incanter "0.1.0"]
[groupId/artifactId "your-version"]
...

Comment: Many thanks. Unfortunately, when I run `lein uberjar` I get errors like `Could not find artifact incanter:incanter-core:jar:1.5.8-SNAPSHOT in clojars (https://clojars.org/repo/)` and eventually it says: `Uberjar aborting because jar failed: Could not resolve dependencies`
Comment: Note, the dependencies are submodules  of incanter.
Comment: you can go to https://clojars.org/incanter/incanter-core and search each modules latest versions and update according to that and try to run lein test again? let me know how it goes
Comment: it seems like those versions don't exist anymore
Comment: Thing is, I want to change one of the modules (maybe more), so ideally I'd like lein to build all the modules from the source in the incanter repo (my local clone) and use them, rather than any other version from clojars.
Comment: then you need to download each module(project) and do what I just answered you need the jars.

Leiningen: working with local git repo


Solaris ps output interpretation

Question: I have a program that regularly forks and execs other programs.  Occasionally, the programs that it starts get stuck in their processing and new programs never seem to start processing.  We eventually kill a bunch of stuck programs and restart the program that forks/execs them and the issue seems to clear out.  The ps output of old/stuck programs (pre kill) and new/working (post restart) programs are different.  What can we interpret from the difference between "-ksh -c" and the perl process (pid 6212)?  They were invoked in exactly the same way; why is the ps output different?  Is there some resource we may be running out of?  Virtual terminals?
[me@unixbox1:~]> ps -ef | grep app_bld_rfh2
  appadm 23926     1  0 14:19:34 ?        0:00 -ksh -c /home2/app/eai/app_bld_rfh2.pl  APP.DOC.SERVICE
      me  9232  5237  0 14:38:09 pts/28   0:00 grep app_bld_rfh2
  appadm  2975     1  0 14:30:04 ?        0:00 -ksh -c /home2/app/eai/app_bld_rfh2.pl  APP.DOC.SERVICE
  appadm 17697     1  0 14:14:31 ?        0:00 -ksh -c /home2/app/eai/app_bld_rfh2.pl  APP.DOC.SERVICE
  appadm 11820     1  0 14:09:30 ?        0:00 -ksh -c /home2/app/eai/app_bld_rfh2.pl  APP.DOC.SERVICE
  appadm 29658     1  0 14:25:00 ?        0:00 -ksh -c /home2/app/eai/app_bld_rfh2.pl  APP.DOC.SERVICE
  appadm  6212     1  1 14:35:15 pts/2    0:47 /usr/local/bin/perl /home2/app/eai/app_bld_rfh2.pl APP.DOC.SERVICE

Comment: How do you launch these scripts, precisely ?
Answer: You get the -ksh when it is invoked as the login shell, and my guess is that your perl script /home2/app/eai/app_bld_rfh2.pl starts with the line
#!/usr/local/bin/perl

or
#!/usr/bin/env perl

Invoking ksh -c /home2/app/eai/app_bld_rfh2.pl APP.DOC.SERVICE will in turn execute perl based on the above hash-bang. That is the cause of the difference.
As to why it hangs, my guess is that it needs a pseudo-tty to run, so if you start it through ssh use the -t option to force pseudo-tty allocation.

Solaris ps output interpretation


Why is this solution incorrect?

Question:
Prove that on the axis of any parabola there is a certain point K which has the property that, if a chord PQ of the parabola be drawn through it, then
$\frac{1}{PK^2}
 +
\frac{1}{QK^2}$
is the same for all positions of the chord.

If it would be valid for standard parabola than it would be valid for all parabolas. Thus, proving for $y^2=4ax$.
let the point K be (c,0)
Equation of line PQ using parametric coordinates:
$x=c+rcos\theta$ (Equation 1), $y=rsin\theta$ (Equation 2)
From equation 1 and 2: $(x-c)^2+y^2=r^2$ (Equation 3)
Using Equation 3 and $y^2=4ax$, we get this quadratic in r: $r^2- 4ax -(x-k)^2=0$ (Equation 4)
Roots of this quadratic $(r_1 \ and \ r_2)$ would be the lengths of $PK$ and $QK$
From Equation 4, $r_1 + r_2=0$ and $r_1r_2=-(4ax+(x-k)^2)$
We know, $\frac{1}{PK^2}+\frac{1}{QK^2}=\frac{1}{r_1^2}+\frac{1}{r_2^2}=\frac{(r_1 + r_2)^2-2r_1r_2}{(r_1r_2)^2}=\frac{-2}{r_1r_2}$
As value of $r_1r_2$ is not constant thus $\frac{1}{PK^2}+\frac{1}{QK^2}$ does not turn out to be constant. Hence, this solution is incorrect.
I've seen the correct solution but I wanted to know $\mathbf {why \ this \ solution \ is \ incorrect?}$
Answer:
Roots of this quadratic ($r_1$ and $r_2$) would be the lengths of PK and QK.

This part is incorrect. Roots of this equation correspond to the same value of $x$. P and Q can have different $x$.
Update:
$x=c+r \cos \theta$, $y=r \sin \theta$
$$y^2=4ax \Rightarrow r^2 \sin^2\theta - 4ar \cos\theta - 4ac=0$$
Absolute values of roots of this equation would be the PK and QK.
$r_1+r_2=\frac{4a\cos\theta}{\sin^2\theta}$, $r_1r_2=-\frac{4ac}{\sin^2\theta}$
$$\frac{1}{PK^2}+\frac{1}{QK^2}=\frac{(r_1+r_2)^2-2r_1r_2}{(r_1 r_2)^2}=\frac{16a^2\cos^2\theta+8ac\sin^2\theta}{16a^2c^2}$$
This value does not depend on $\theta$ at $c=2a$. This is the answer.

Why is this solution incorrect?


Roman numeral analysis: Bridge over Troubled Water

Question: I'm trying to create a "universal key" to learn more about the harmony and to be able to practice it easily in every key. Below is the intro for 'Bridge over Troubled Water'.
Generally, I see the harmony as progressing two keys upward the circle of fifths and then back to the main key. Some comments about my thinking:

2.4: VIIo or V7b9 without the root.
3.1: IV6 or an inversion of II-7. But because IV6 resolves to IV, IV6 seemed more
appropriate. The bass can be seen as I/V, a resolution of the previous chord.
4.1: At first I wasn't sure why 3.4 to 4.1 sounded so good, because
you're going from a tertiary dominant to the main subdominant. Then I realized that
IIø7 - V7 resolves naturally to an F minor, and that's the relative minor of this chord.

My question is: is this analysis right? Any major errors, or minor ones?
Comment: It's not clear what your question is
Comment: Oh, I wasn't aware of the chat function. Hmm... so better to delete this post then? (I'm used to Stack Exchange for programming questions, but now that I think about it this generalizes less than those type of questions.)
Comment: Hi @Daan. **Welcome to Music.SE!** Certainly wouldn't want to be unkind in response to any post, especially not your first post. But what is the question here? Are you just asking if we agree with your analysis? If so, this might be better for chat, as it might not be a very useful post for future readers.
Comment: Sorry! Clarified it. (I thought it was implicit.)
Comment: Where should I post this in the chat?
Answer: As a literal depiction of the chords, the analysis is fine and will allow you to transpose to other keys.
If a functional analysis is desired, I would do it this way (answers to your specific questions follow):

beat#

m.#
1
2
3
4

1
C[6-4]*
"
"
V

2
IV
"
IV[6-4-2]
CTo[4-3]/I**

3
I[6-4-2]
I[6-4]
ii[6-5]/ii
V7/ii

4
VI/ii = IV
"
ii/i
"

5
I
"
V7/IV
"

6
IV
"
"
"

*C[6-4] = "Cadential six-four". Also notated V[6-4] or I[6-4].
**CT = "Common-tone"

Specific questions
2.4
I interpret this chord as a common-tone diminished seventh chord attached to the following I chord. For more on common-tone diminished seventh chords see: A chord progression from Leavitt: how to analyze the diminished chord.
3.1
The chord here is a I chord in second inversion, with the C suspended from the previous chord. The suspension resolves on beat 2.
4.1
This one you nailed. In other language, this is a deceptive cadence (V - VI) in the key of ii (F minor), functioning also as IV in the main key. This is known as a "pivot chord": a chord which functions in two different keys simultaneously, facilitating a shift (a "pivot") from one key to the other — in this case, from F minor to Eb major.
Comment: @Daan Good catch. Fixed now.
Comment: Thank you so much! Shouldn't the inversion at 2.3 be [6-4-2]?
Comment: One question about this chord though. I was under the impression that every note had to be accounted for in the chord quality. Hence I went with V7 (although I had my doubts). But you can just call this a IV chord?
Comment: @Daan It's a fair question and a good example of the interpretative aspect of analysis. Your V7 label (more precisely, V[4-2]) is a literal representation of the notes in the chord, but my feeling was that it didn't function like a V chord. It's not exactly a IV chord either, however. It's a passing chord over a pedal Ab in the bass. But since my feeling is that it's serving to "extend" the IV chord, I labeled it as such. (This passing-chord quality would be more clear if the next chord were also a IV chord.)
Comment: Yeah, that makes sense. So I did the redid the notation, basically in line with yours, with one major exception: I did 2.4 to 3.1 as VIIo/V to C64. Look at this, example k: https://myweb.fsu.edu/nrogers/Handouts/Common-Tone_Dim_7_Handout.pdf
Comment: With a double dominant in the bass, and it also being a repeat of 1.1, I like the idea of it being a cadential 6-4 much better.
Comment: @Daan Cool. Glad the answer was helpful.
Comment: One other thing: shouldn't 4.1 be III in F minor?
Comment: @Daan You're correct about F minor being III. I'll need to modify the analysis of the preceding couple of chords, I think, and am working on that....
Comment: This is my final version: https://imgur.com/stwS7GS Not a complete analysis of course, but good enough for playing. :)
Comment: @Daan That looks good, and, as you say, more than good enough for transposing to other keys.
Comment: Thanks. Sadly, I'll have to drop the multiline approach as well. It provides insight into the pivot chords, but it's just not tenable since there are tonicizations every other measure further in the piece. So I'll just use slashes.


How do you override Commerce checkout pane output?

Question: I downloaded the commerce bitcoin module and I'd like to override the current output of the pane. There is no theme_ function to override. How can this be done?
The code is below:
 1 <?php
  2
  3
  4 /**
  5  * Implements base_checkout_form()
  6  * Display the bitcoin address at the checkout
  7  *
  8  */
  9 function commerce_bitcoin_pane_checkout_form($form, $form_state, $checkout_pane, $order) {
 10
 11
 12
 13
 14   $output .= t('Total amount %total BTC', array('%total' => $bittotal)) . '
';                                                                                15   $output .= t('Check Blockchain.info Payment Status') . '
';
 16   $checkout_form['commerce_bitcoin_pane_field_display'] = array(
 17     '#markup' => $output
 18   );
 19
 20   return $checkout_form;
 21 }

Answer: Checkout panes are fieldsets within the context of per-page checkout router form. You can use a hook_form_alter() to modify the contents of the entire page that a form is shown on. For instance, if you want to modify objects that appear on the checkout page (which is the first one in Commerce Core), you'd use this hook:
MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  // Make the customer profile billing pane's locality field a bit smaller.
  $form['customer_profile_billing']['commerce_customer_address']['und'][0]['locality_block']['locality']['#size'] = 20;
}

Where commerce_checkout_form_checkout is commerce_checkout_form_ concatenated with the current checkout router step. See commerce_checkout_router(). Each of the panes within the page exists within this form. As Ryan also points out in the comments, the main form traps errors and other items to present them inline with the checkout pane, so a payment error won't show up at the top of the page, but it will show up above the payment pane for instance.
If you're wanting more info on how to theme checkout, I'd recommend you go review the code for Commerce Responsive UI and mimic what it does.
This includes the complete pane which is still a form. If you want to override the form completely, you can just change the callback that is called when the completion pane is being built:
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['checkout_completion_message']['callbacks']['checkout_form'] = 'MYMODULE_completion';
}

Then, you put your own output into the new callback. Just copy what commerce_checkout_completion_message_pane_checkout_form() does and put your own content in.
Comment: Ah. Okay. Well the same information applies, but there is likely a slightly better way to handle it if you're wanting to change the completion pane. See the update.
Comment: The reason you aren't seeing the dsm() on the checkout page is because the checkout form traps messages to present them inline with their checkout panes. If you're creating a message outside of the context of a checkout pane, it would make sense for it to be "lost" and not appear on the page as expected. In those cases, I just write my debug output to watchdog().
Comment: just tried your hook alter. I did a dsm($form) and it only shows up on pages with a form. I mainly want to theme the checkout complete panes, which are just text and has no forms as shown above.
Comment: nope still doesnt work. i put in a dsm($checkout_panes) in hook_commerce_checkout_pane_info_alte and it doesnt show up on the checkout complete page. however it does show up on every other checkout page. so that isn't the right hook im guessing.
Comment: Checkout complete is checkout/_id_/complete, on your site right?
Answer: It looks like using
 hook_commerce_checkout_pane_info_alter(&$checkout_panes)

or
 hook_commerce_checkout_page_info_alter(&$checkout_pages)

would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary
(hook_commerce_checkout_pane_info() and hook_commerce_checkout_page_info())

I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files
Comment: that only gets the $checkout_panes data passed in, but what if you also wanted the $order data in the hook alter also? how do u pass that in?
Answer: Here's an example to modify the output of the commerce_payment review pane:
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_pane) {
  $checkout_pane['commerce_payment']['callbacks']['review'] = 'MYMODULE_commerce_payment_pane_review';
}

/**
 * Replacement callback function for the commerce_payment review pane.
 */
function MYMODULE_commerce_payment_pane_review($form, $form_state, $checkout_pane, $order) {
  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.checkout_pane');
  $html = commerce_payment_pane_review($form, $form_state, $checkout_pane, $order);
  // Add our custom HTML, could use theme() here to be nice.
  return $html . "
More data here...
";
}


MySQL case when in stored procedure not working as expected

Question: This is a stored procedure that has 3 possible cases.  I can't figure out how to get the 3rd case to run.  If I swap 2 and 3, 3 will run fine and 2 won't run, which leads me to believe it's not the actual code within each case.
CREATE DEFINER=`user`@`ip` PROCEDURE `api_userLogin_new`(IN _userType int,IN _clientId varchar(45),IN _username varchar(50))
    BEGIN
        CASE WHEN _userType = 1
           THEN
              *do stuff that works*
        WHEN '2'
           THEN
              *do other stuff that works*
        WHEN '3'
           THEN
              {this won't run, but does if I swap it out with 2}
        ELSE BEGIN END;
        END CASE;
    END;

It doesn't give an error, but it just doesn't do anything no matter which code is in the last of the 3 positions (i.e. move "WHEN '3'" and it's code up to where WHEN '2' is, and then 2 wont' run or error).
Comment: Use the full expression. `_userType = '2'  WHEN _userType = '3'`
Answer: You mixed the two possible CASE WHEN syntax descibed on the MySQL documentation. You can use the following solution using the variable only on the CASE:
CREATE DEFINER = `user`@`ip` PROCEDURE `api_userLogin_new`(IN _userType INT, IN _clientId VARCHAR(45), IN _username VARCHAR(50))
BEGIN
  CASE _userType
    WHEN 1 THEN
      -- do something
    WHEN 2 THEN
      -- do something
    WHEN 3 THEN
      -- do something
    ELSE
      BEGIN END;
  END CASE;
END;

... or the following solution using the variable on every WHEN (instead once on the CASE):
CREATE DEFINER = `user`@`ip` PROCEDURE `api_userLogin_new`(IN _userType INT, IN _clientId VARCHAR(45), IN _username VARCHAR(50))
BEGIN
  CASE
    WHEN _userType = 1 THEN
      -- do something
    WHEN _userType = 2 THEN
      -- do something
    WHEN _userType = 3 THEN
      -- do something
    ELSE
      BEGIN END;
  END CASE;
END;

Answer: Use the full expression:
CREATE DEFINER=`user`@`ip` PROCEDURE `api_userLogin_new`(IN _userType int,IN _clientId varchar(45),IN _username varchar(50))
    BEGIN
        CASE WHEN _userType = 1
           THEN
              *do stuff that works*
        WHEN _userType = '2'
           THEN
              *do other stuff that works*
        WHEN _userType  = '3'
           THEN
              *do other stuff that works*
        ELSE BEGIN END;
        END CASE;
    END;

Side note: Your scenario was occurring since '2' and '3' evaluate to TRUE in MYSQL.
Comment: Thank you!  Missed that you could not mix when syntaxes.
Answer: I can only speak to code which I can see, not that I can't, but I see a few potential problems with your code.  First, every predicate of the CASE expression should end with a delimiter.  Also, if you don't have an ELSE condition, then don't include one.  So I recommend this version:
CREATE DEFINER=`user`@`ip` PROCEDURE `api_userLogin_new`(IN _userType int,IN _clientId varchar(45),IN _username varchar(50))
    BEGIN
        CASE _userType WHEN 1
             THEN *do stuff that works*;
             WHEN 2
             THEN *do other stuff that works*;
             WHEN 3
             THEN {this won't run, but does if I swap it out with 2};
        END CASE;
    END;


Why does CLT converge quadratically?

Question: CLT states that the standard deviation of the error falls as
1/sqrt(N), where N is the number of trials. Why does this imply that the convergence is quadratic?
In particular, I am confused about this passage from Sutton & Barto's Reinforcement Learning book:
Comment: Sounds weird.would check another book.
Answer: Let us define
$$ S = \sqrt{n} \left( \frac{X - \mu}{\sigma} \right) \xrightarrow{d} N(0,1) $$
We can use Edgeworth series to approximate the probability distribution in terms of cumulants:
$$ G(x) = P(S \leqslant x) = \Phi(x) + n^{-1/2}p(x) \phi(x) + O(n^{-1}) $$
where $\Phi(x)$ is the cdf of the normal distribution, $\phi(x)$ its pdf and $p(x)$ is an even quadratic polynomial of $x$.
The leading term if we substract the true CDF of the normal distribution is $n^{-1/2} = 1/\sqrt{n}$, therefore the CLT converges with a rate of $\sim n^{-1/2}$.
Comment: Yes: but to almost all the world, "quadratic" convergence is $O(n^{-2}),$ not $O(n^{-1/2}).$  That is the crux of the matter.

Why does CLT converge quadratically?


Unity Moving Platform Interaction Between Rigidbodies

Question: I have a coroutine that continuously moves platform using its Reigidbody, here's the code:
private IEnumerator MovePlatform(Vector3 startPosition, Vector3 endPosition)
{
    float i = 0;
    float rate = 1f / speed;

    while (i < 1f)
    {
        i += Time.deltaTime * rate;
        rigidbody.MovePosition(Vector3.Lerp(startPosition, endPosition, i));

        yield return null;
    }

    StartCoroutine(MovePlatform(endPosition, startPosition));
}

rigidbody.MovePosition is the correct way to move platform if I want my Rigidbodies to interact.
But here's the problem:
If platform moves vertically then object on top of platform continuously jumps while moving.
If platform moves horizontally then object on top of platform slides back and forth.
Obviously that is not what I want them to do.
I want object on platform stay still.
What I tried:

Setting velocity of object manually - not what I want
Using Physic Material with a high friction - not what I want

How can I achieve naturally good interaction between moving platform and object?
P.S. PLEASENOPARENTMETHODTHANKS
Answer: I have recently completed a project that accomplishes getting the rigidbody to stick to platforms that are changing both position and rotation. It takes lots of work, but I'm going to try to lay out a summary really quick.
The whole system relies on creating completely separate physics scenes (https://docs.unity3d.com/Manual/physics-multi-scene.html) for each moving platform, which is used to simulate the physical relationship between the moving platform and the rigidbody rider.  The only difference between the simulation and the real scene is that in the simulation, the moving platform is not moving!
More detail:
At first, this simulation scene contains only a copy of the moving platform, except it does not move. When the rigidbody rider in our main scene collides with the moving platform, a copy of the rigidbody rider is added to the simulation at the same position/speed relative to the moving platform. Then, disable the controller on the main rigidbody rider so that it doesn't respond to player input. Do not disable the controller on the simulated rigidbody rider - it should continue to respond to the controller and freely move around on the simulated (non-moving) platform.
The simulated rigidbody rider is now walking around on a simulated non-moving platform. Now use MovePosition() and MoveRotation() to move/rotate the main rigidbody rider to match the simulated rigidbody character's position and rotation relative to the simulated platform. This way, when the simulated rigidbody character moves, the main rigidbody character will as well.
At this point, we have a functioning moving platform. As long as the rider to rider transformations are done with respect to the platform(s), it doesn't matter how the main platform is moving or rotating - the main rigidbody rider will stick to it perfectly.  Though it will not be natural - for example, if the moving platform suddenly changes speed, the rider will change with it exactly.
When the main rigidbody rider is no longer colliding with the moving platform, we delete the simulated rigidbody rider from the simulation scene, and add full control back to the main rigidbody rider.
Comment: Here is a video of this system in motion:  [link](https://www.youtube.com/watch?v=O0_21aA4PxY&t=1s)


Monitor Linux services with Nagios 4

Question: I'm trying to monitor a few RHEL7 services via Nagios. I'd like to monitor if the services are running or stopped and receive an alert when stopped. I haven't any out of the box option with Nagios 4 and nagios-stat, which is the way we were doing it on our old Nagios server hasn't been updated for years.
EDIT: I decided to go with NRPE but can't figure out a working command for virt-who. The ps info for virt-who is this:
root     60804  0.3 29.2 921684 548544 ?       S    Oct09   5:13 /usr/bin/python /usr/share/virt-who/virt-who.py -b
Comment: I don't see why you couldn't keep running nagios-statd everywhere, if that's what you're comfortable with. It hasn't been updated in 9 years, though...
Comment: I'm not comfortable with it, it was done by someone else that is no longer part of the team. I prefer to avoid if there is another way to do it.
Comment: What type of service.  You just need to come up with a command line script tool that will test if something is good or not then returns a useful exit code.  Making your own scripts is really easy.  Though there huge numbers of example scripts to be found on the internet if you just search for 'nagios check {service name}'.
Comment: The service in question is virt-who but I'll apply the same check to monitor other services.
Comment: `systemctl show ` will give you all the information you could possibly want in an easy to parse format.
Answer: You may try installing the NRPE together with the nagios plugins in the monitored server.
The simplest way to check whether a process is running is to add something like the following line inside nrpe.conf:
command[check_myprocess]=/usr/lib/nagios/plugins/check_procs -c 1: -C myprocname -a stringinmyprocargs

Then you can add the following inside your Nagios server conf:
define service{
        use                             local-service
        host_name                       myservername
        service_description             myprocess
        check_command                   check_nrpe!check_myprocess
        }

This should definitely work for Nagios version 3 and 4.
Comment: But this will tell me if the process is running, it will not tell me the status of my service, correct?
Comment: I'm trying your method but Nagios is returning an unknown response. Maybe I'm not using the right process name, this is the virt-who details:
`root     60804  0.3 29.2 921684 548544 ?       S    Oct09   5:13 /usr/bin/python /usr/share/virt-who/virt-who.py -b`
Comment: Then you can use something like: /usr/lib/nagios/plugins/check_procs -c 1: -C python -a virt-who
Comment: it returns "unable to read output"

Monitor Linux services with Nagios 4


Violin - Notation for writing sliding fingers?

Question: On the violin, you slide your fingers forward on a string (the D string as an example), and make a noise that sound something like this. What would be sheet music notation for writing that?
Comment: Xilpex - please stop deleting your questions just because you get a downvote. You are likely to trigger automated question bans if you do this.
Comment: @DoktorMayhem I'm so sorry... I didn't know.
Comment: @Xilpex Generally, we reserve deletion for more extreme circumstances, never simply because of downvotes. I like this question (though it's been asked before); I think it belongs on this site. Also, the system itself records self-deleted posts for this very reason, as User Doktor Mayhem has noted. I try never to delete my own posts unless I did something egregious like posting on the wrong site by mistake. The moderation/review queues will handle most minor issues.
Comment: What I'm trying to do is called a *Portamento*. On sheet music portamento would look like this: [![Portamento](https://i.stack.imgur.com/fTVn8.png)](https://i.stack.imgur.com/fTVn8.png) This portamento indicates sliding fingers from G (On the E string) down to E (Open E string)
Comment: Actually thia is not really a duplicate question, because the other question is about the difference between portamento and glissando while singing. But this question is about how to notate a glissando in sheet music for violin.
Comment: What is the point of asking a question and then posting the answer to your own question in a comment? Your comment is the answer to your question.
Answer: Sliding the fingers is called 'portamento' and the notation looks like this:

A glissando is similar but notated with a wavy line. The differences are discussed in this question: What is the difference between portamento and glissando? (the answer with the most upvotes is good, not the accepted one).


How to properly program AJAX links?

Question: I have a custom module that uses AJAX. Everything works fine the way it is. I'm just wondering if it's the proper way to do it in Drupal. I'm new to Drupal 8 and 9 programming
This is a line from my code
$link ='Test AJAX';

Is this ok to do or should I be building my link? If so, why and how?
EDIT
I currently build non-ajax links like
  $url = Url::fromRoute('entity.node.canonical', array('node' => $record->nid));
  $title_link = Link::fromTextAndUrl($record->title, $url);
  $title_link =$title_link->toRenderable();
  $title_link=render($title_link);

Comment: dump out $title_link->toRenderable(); then see if you can set the class  attribute and add use-ajax , if not see https://api.drupal.org/comment/63439#comment-63439
also lol you were using my comment https://api.drupal.org/comment/62725#comment-62725
Comment: So I would use ```$content = array(...```
Comment: Thanks for the comment assist before! ;)
Comment: Try this https://www.drupal.org/project/ajax_links_api
Answer: If you just need to add the classes I believe it can be done like so
$url = Url::fromRoute(
  'entity.node.canonical',
  ['node' => $record->nid],
  ['#attributes' => ['class' => ['btn', 'btn-default', 'use-ajax']]]
);

 $title_link = Link::fromTextAndUrl($record->title, $url);

At that point $title_link should be able to be rendered in the template as is!
// php
$variables['title_link'] = $title_link;

// twig
{{ title_link }}

Comment: So I gather the answer is that it's best to build links as opposed to specifying the links. And I use the build + attributes to specify AJAX and other classes.
Comment: Its subjective - but yes probably the most "Drupal way" would be to build the links as above.
Comment: Is there a reason why the "Drupal way" is better than just specifying links?
Comment: I'm probably not really qualified to answer that - but here is Drupal's page about using render arrays and Drupal's renderable elements https://www.drupal.org/docs/drupal-apis/render-api/render-arrays
Comment: Thanks. I get it now, I think. It's so you can easily alter content (maybe in a separate module) as opposed to trying to alter the non-built link.

How to properly program AJAX links?


Expected number of attempts to get 2 out of 50 results at least once?

Question: I looked at some material, such as markov chains and inclusion-exclusion, but was unable to wrap my head around them with my only cursory understanding of probability.
I'm trying to find the solution to a problem where there are 50 possible unique results of equal probability; you could imagine a deck of cards with the one-eyed jacks removed. How many times do I have to draw, with replacement, before I draw both two-eyed jacks (which are also replaced) at least once?

My initial intuition is that we can start with an expected 100 attempts, because it is $1/p$ or 50 expected attempts for the first jack and then you have the same deck you started with for +50 expected attempts for the other jack, but I suspect that I need to subtract some amount for the chance that the second jack was already drawn before the first.
I also tried to do what this answer suggests and treated the problem like a 3-sided die where... $$p(1) = 48/50\qquad p(2) = p(3) = 1/50$$
...treating the 1-result as every other card in the deck, and the 2-result and 3-result as the desired draws. This, I guess, gives me an expected outcome of... $$4H_4-\frac{48}{50}\cdot4$$
...but I don't know how to account for the 0.04% chance that I get the 2-result and 3-result right away. That alone wouldn't be a problem as I doubt it changes the expected number of draws enough to matter, but I also don't know what $H_4$ means to do the calculation.
Any help you can offer to complete either of my two approaches (or to enlighten me on why these approaches don't work for my question) would be greatly appreciated.

I looked at these related questions, but the methods don't seem to work for this problem since they want each result at least once, and I only want two results (or perhaps I just don't understand the answers well enough to apply them to my question):

Expected number of trials before I get one of each type
Expected number of rolls for an unfair die to get all possibile values at least once
Comment: For anyone wondering, the application of this question is related to D&D and trying to find the expected number of Wild Magic Surges before two desired outcomes are reached. Related to [this answer](https://rpg.stackexchange.com/a/168037/41726) on RPG StackExchange.
Answer: This is related to my answer here. For this question, at the start, the probability of drawing the first (as yet undetermined) two-eyed jack is $\frac2{50}$, so $\frac{50}2$ draws are expected to get it; once that has been drawn, there is a $\frac1{50}$ chance of drawing the other two-eyed jack, so $\frac{50}1$ draws are expected to get it. The expected total number of draws is then their sum: $\frac{50}2+\frac{50}1=75$.
In general, if you are waiting for $k$ specific results from repeating a draw on $n$ objects with replacement, the expected number of draws needed is $n\sum_{i=1}^k\frac1i$.
Comment: @DavidCoffron Yeah, sorry, I might make these silly mistakes from time to time. It's been corrected.


Algebra (inequalities)

Question:
Let $\{a,b\}\subset\mathbb{R}$. Show that:
  $$a^2+b^2+ \frac{1}{a^2}+ \frac{b}{a} \geq \sqrt{3}$$

I am unable to apply AM-GM inequality in the given problem.
Comment: What do you mean by "Root under 3" ? Do you mean $\sqrt{3}$ ?
Comment: yes,I mean sqrt(3).
Comment: Excuse me! I made a mistake in my calculation..
Answer: it is equivalent to
$$\left(ab+\frac{1}{2}\right)^2+\left(a^2-\frac{\sqrt{3}}{2}\right)^2\geq 0$$
Answer: One could do as follows as well, if some calculus were allowed.
Consider the function $ f(a,b) = a^2 + b^2 + \frac{1}{a^2} + \frac{b}{a}$.
As we are looking for a lower bound, we could calculate $ \frac{\partial f}{\partial b} = 2b + \frac{1}{a}$ and, upon setting to zero, look along the domain restriction $$ b = -\frac{1}{2a}$$ only.
Substituting yields the expression $$a^2 + \frac{3}{4a^2} = \frac{2a^2 + \frac{3}{2a^2}}{2} $$ after which we can apply the AM-GM inequality $$\frac {x+y}{2} \geq \sqrt {x y}$$ upon setting $x=2a^2$ and $y = \frac{3}{2a^2} $, concluding that the given expression is equal or greater than $$ \sqrt{  2a^2 \frac{3}{2a^2}} = \sqrt{3}$$
Answer: We need to prove that
$$b^2+\frac{1}{a}\cdot{b}+a^2+\frac{1}{a^2}-\sqrt3\geq0,$$
for which we need $\Delta\leq0$ or
$$\frac{1}{a^2}-4\left(a^2+\frac{1}{a^2}-\sqrt3\right)\leq0$$ or
$$4a^2+\frac{3}{a^2}\geq4\sqrt3,$$ which is AM-GM:
$$4a^2+\frac{3}{a^2}\geq2\sqrt{4a^2\cdot\frac{3}{a^2}}=4\sqrt3.$$
Done!

Algebra (inequalities)


Why did Kevin Durant switch to the Golden State Warriors?

Question: Kevin Durant switched from the Oklahoma City Thunder to the Golden State Warriors for the 2016-17 NBA season. I was wondering why he moved and would really like to know more about it. Why couldn't he just stay on the Thunder?
Answer: All we can really tell you here is what Durant himself said about the move. Quoting from this ESPN article, Durant said:

"The primary mandate I had for myself in making this decision was to have it based on the potential for my growth as a player - as that has always steered me in the right direction, but I am also at a point in my life where it is of equal importance to find an opportunity that encourages my evolution as a man: moving out of my comfort zone to a new city and community which offers the greatest potential for my contribution and personal growth. With this in mind, I have decided that I am going to join the Golden State Warriors."

Reading between the lines, I would interpret "my growth as a player" as "chance to win a championship".


Changing code to render carriage return and new line characters

Question: I have a text in SQL Server database that has new line character and carriage return character in it.  When I assign this value into a string variable, I can see these newline and carriage return as show in first screenshot. But when it is rendered these values are not present (as shown in second screenshot).
How can we render the newline and carriage return characters with the following code in gridview?
CODE
protected void Page_Load(object sender, EventArgs e)
{

    List<Account> result = new List<Account>();
    string value = DisplayTest("Daily Tax Updates:\r\n");

    Account acc = new Account(){Description = value};
    result.Add(acc);

    grdFinancialAmount.DataSource = result;
    grdFinancialAmount.DataBind();

}

public class Account
{
    public string Description { get; set; }
}

private static string DisplayTest(string searchValue)
{
    string test = String.Empty;
    string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        string commandText = @"SELECT AccountType,*
                          FROM Account
                          WHERE AccountType LIKE @input ESCAPE '\'";
        using (SqlCommand command = new SqlCommand(commandText, connection))
        {
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.AddWithValue("@input", "%" + searchValue + "%");

            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {

                        test = reader.GetString(0);
                    }
                }
            }
        }
    }

    return test;

}

MARKUP
<asp:GridView ID="grdFinancialAmount" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="Text">
            <ItemTemplate>
                <%# Eval("Description")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Variable value from Database

Rendered Value
Comment: You could try a `String.Replace()` on `\r\n` with ``.
Comment: put it in a
Answer: Replacing the \r\n with \\r\\n should work fine.
I mis-interpreted this, I though you wanted to show \r\n instead of the character return but as a comment says, replace with
.
string.Replace("\r\n", "
");

Answer: Your rendered value is html. Putting \r\n in html might well change the source html, but will have absolutely no effect on what gets rendered.
You can verify this by doing a "view source" on your rendered window.
One approach here would be, before you render, to replace all occurrences of \r\n with
, a hard line break.
Or you could add a
 tag to the front of your string, and add a
 tag to the end of your string, then replace all \r\n occurrences with

, i.e. split it into paragraphs. This is probably the more elegant approach of the two.
There will be other options here too, you just need to be aware that you need to translate your crlf characters into something html can understand.


Adicionar um programa de terceiro a um instalador

Question: Estou utilizando o InnoSetup para gerar um instalador de uma aplicação Delphi.
Porem essa mesma aplicação depende o programa R, gostaria de saber se é possível acoplar o instalador do R ao meu instalador.
Answer: Sim, é possível.
Basicamente você pode adicionar o instalador 'R', como um recurso no seu próprio instalado, e tratar para que o seu processo aguarde a instalação do 'R'
Segue um exemplo, onde o dotnetfx35 é necessário:
[Files]
Source: D:\dsv\projetos\geral\Instalador\nfe\dotnetfx35_sp1.exe; DestDir: {#MyAppDirIns}; Flags: ignoreversion
[Run]
Filename: {#MyAppDirIns}\dotnetfx35_sp1.exe;
Comment: mas eu não posso acoplar o instalador do r, para o cara ser obrigado a instalar quando já estive instalando meu programa?
Comment: é isso que vai acontecer. Quando executar o seu instalador, se essa rotina vier primeiro, ele vai abrir o exe obrigando o usuario a instalar o R, apos isso, vai seguir na instalação do seu App.
Comment: Muito bom funcionou corretamente.
Answer: Boa noite,
Apenas reforçando com outro exemplo, vou mostrar parte do script de instalação do ERP da minha empresa:
[Files]
Source: "..\..\..\SetupSystec\Systec\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs promptifolder; Languages:  brazilianportuguese; Permissions: system-full
Source: "..\..\..\SetupSystec\Componentes\*"; DestDir: "{app}\Componentes\"; Flags: ignoreversion createallsubdirs recursesubdirs

[Run]
Filename: {app}\Componentes\TDBGrid7.0.0285_patch.exe
Filename: {app}\Componentes\psqlodbc.msi; Flags: shellexec waituntilterminated

Neste exemplo, a pasta "Componentes" recebe arquivos de terceiros. Colocando os programas na mesma, na tag [Run] é só indicar como vc quer que os os programas sejam executados. Para sua instalação continuar apenas depois do X programa instalado, colocar a flag "Flags: shellexec waituntilterminated"
Comment: parabéns pela atitude, vai ajudar os outros.
Comment: @GuilhermeLima Obrigado!


Bug ao usar Select2 em um form-group do Bootstrap

Question: Estou com uma dificuldade em corrigir um bug que acontece ao utilizar o Select2 em um input-group. O problema é que ao selecionar um option com nome muito extenso, o input-group não respeita a largura do elemento pai.

    <select class="select2">
        <option></option>
        <option>Nome extenso Nome extenso Nome extenso Nome extenso Nome extenso</option>
    </select>

        <button class="btn btn-sm btn-default" type="submit">

    </button>

O que acontece é que o input-group acaba ficando com um width maior do que 200px, não respeitando o elemento_pai. Alguém que já passou por isso achou uma solução?
Exemplo do problema no JSFiddle
Issues sem solução:

https://github.com/ivaynberg/select2/issues/2472
https://github.com/t0m/select2-bootstrap-css/issues/42
Comment: Acho que falta o elemento-pai no seu exemplo do Fiddle.
Comment: @RenatoDinhaniConceição no exemplo do JSFiddle não precisa do elemento_pai, basta diminuir o tamanho da janela do seu navegador e você irá perceber que o select não vai respeitar a largura. Esse `elemento_pai` foi apenas para ilustrar.
Answer: Uma solução:
.select2-container .select2-choice > .select2-chosen{
  white-space: normal;
}

Exemplo JSFiddle
Answer: Não sei se é a melhor resposta mas pelo o que eu encontrei pra solucionar seu caso, você deve colocar o primeiro <option> com o texto pequeno
Exemplo:

  <form class="form-inline">

      @

      <select id="lunch" class="selectpicker form-control" data-live-search="true" title="Please select a lunch ...">
        <option value="1">Nome extenso Nome extenso Nome extenso Nome extenso Nome extenso Nome extenso Nome extensoNome extenso Nome extenso</option>
        <option selected>Select 1</option>
        <option>Select 2</option>
        <option>Select 2</option>
        <option>Select 2</option>
        <option>A really really long option made to illustrate an issue with the live search in an inline form</option>
      </select>

  </form>

Achei a resposta aqui.
Comment: Antony, a questão está relacionado ao uso do Select2 com `input-group`, essa sua resposta não resolve o meu problema, mas obrigado pela intenção.


Assign different taxonomy terms to translations of content

Question: I've got some custom content translated with entity translation with custom taxonomy also translated.
Actually taxonomy terms are correctly shown inside the content page.
The problem is I need different taxonomy terms for different translation.
When I change the taxonomy terms in the translation edit page every translation of the content gets updated with the terms variation.
The logic behind would be:
- content A (english) --> taxonomy term 1 (english)
- content A (french)  --> taxonomy term 2 (french)
- content B (english) --> taxonomy term 2 (english)
- content B (french)  --> taxonomy term 3 (french)

Answer: If you don't want the node translations to share the terms they are tagged with you need to make the Taxonomy term reference field translatable. Then you will be able to enter different values into that field depending on which language you're editing.
You can enable the translations for Fields under Configuration > Regional and language > Content language and translation (/admin/config/regional/content-language).
Tick the box for your Taxonomy field and hit the "Save configuration" button at the bottom of the page.
After that you'll be able to save the translations with different values for that field than the original. The translations in languages other than the default one will probably have that field empty before you edit them, they will not "inherit" the values from the default translation out-of-box.
Comment: I'm not finding this setting page you are suggesting. Maybe because taxonomy are translated with entity translation. There will be any conflicts enabling multilingual modules for taxonomy translation?
Comment: I assumed it was about D8.  I have noticed incompatibilities between Entity translation and Multilingual select module. Do you have them both enabled? Have you followed the instructions for the Entity Translation module configuration? https://www.drupal.org/docs/7/modules/entity-translation/configure-content-types-for-entity-translation


iteration over array for rendering dynamic data without div element

Question: { Object.keys(props.data).map((key, value) => {

  return(

{key}

{props.data[key]}

        )
  })}

The above code creating the following:
Key
Value

when hardcoding the above without the div wrapper element i'm getting:
Key           value

the full code chunk:

                        {props.title}

A

A

So my issue id the div wrapper element, is there a way to use map for rendering dynamic data without returning the div wrapper element?
Comment: You can use [`React.Fragment`](https://reactjs.org/docs/fragments.html) to wrap your elements.
Answer: Thinking semantically, it would be good idea to wrap with dl:
return(

{key}

{props.data[key]}

)

But looking at the code you're already defining dl and inside that you're using the component?
If you don't like the above solution only then you should use React.Fragment: (Use the above as far as possible)
return(
  <> {/* alias for React.Fragment */}

{key}

{props.data[key]}

  </>
)

Ah, you also need to provide key props:

Or, using Fragment:
<React.Fragment key={key}>

The following is invalid use: (shorthand method doesn't support any props)
<key={key>
</>

Comment: still the same issue...
Comment: Updated my answer.