How do I show/hide elements on a page using jquery?

Question: I am trying to hide check-box selectors in the custom search module when the page initially loads and then have a clickable link to show them. I have the clickable link working but the check-boxes are initially in a visible state. How can I hide the check boxes when the page/module loads? I tried placing the following code in my THEME_form_alter(&$form, &$form_state, $form_id) function
drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types")[0].hide(); });', 'inline');

and
drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types").hide(); });', 'inline');

But neither worked. Any help would be appreciated. thanks
Answer: the easiest way of adding custom javascript-snippets is to create a custom.js file in your themefolder and declare it in your theme.info file like scripts[] = custom.js. Add all your snippets there.
In your JS file you can hide the elements.
If you have multiple checkboxes create an array and hide them with a for each loop.
example
// create array with stuff you want to hide
    checkboxes = [
        '#checkbox1',
        '#checkbox2',
    ];

// Hide arrays
    for (i = 0; i < checkboxes.length; i++) {
        jQuery(checkboxes[i]).hide();
    }

Answer: For Drupal 7
drupal_add_js('(function ($) { $("#edit-custom-search-types").hide(); }(jQuery));', 'inline');

Working with JavaScript and jQuery
Comment: Why did this get down votes?
Comment: worked perfectly, thanks! here is my final code:
`drupal_add_js('(function ($) { $("#edit-custom-search-types").css("visibility","hidden"); }(jQuery));', 'inline');
drupal_add_js('(function ($)
{
$("#adv_search_link").click(function()
{
if( $("#edit-custom-search-types").css("visibility") == "hidden" )
{
$("#edit-custom-search-types").css("visibility","visible");
}
else
{
$("#edit-custom-search-types").css("visibility","hidden");
}});}(jQuery));', 'inline');
`


Existence of primitive for continuous function on an open interval $(a,b)$

Question: Show that any continuous function on an open interval has a primitive on that interval.
My approach: This result is elementary if we replace open interval by closed interval.
Fact: Indeed, if the function $f$ is continuous on $[a,b]$ then the function $F:[a,b]\to \mathbb{R}$ defined by $x\mapsto \int_{a}^{x}f(t)dt$  is continuous on $[a,b]$ and $F'(x)=f(x)$ on $[a,b]$.
Assume that our function $f(x)$ is continuous on $(0,1)$. For each $\delta\in (0,1/2)$ we know that $[\delta,1-\delta]\subset (0,1)$ and $f(x)$ is continuous on $[\delta,1-\delta]$. Hence by fact it has a primitive $F_{\delta}:[\delta,1-\delta]\to \mathbb{R}$ such that $F_{\delta}$ is continuous on $[\delta,1-\delta]$ and $F'_{\delta}(x)=f(x)$ on $[\delta,1-\delta]$.
For each $x\in (0,1)$ there are infinitely many $\delta>0$ such that $x\in (\delta,1-\delta)$. So by Axiom of Choice for each $x\in (0,1)$ we can assign $\delta(x)>0$ such that $x\in (\delta(x),1-\delta(x))$.
Thus define the function $F:(0,1)\to \mathbb{R}$ by $x\mapsto F_{\delta(x)}(x)$ and this function has all desired properties.
I was wondering is this solution correct?
At least I cannot find any mistakes in my reasoning.
So I'd be vert grateful if you can take a look and check it.
EDIT: Suppose that $f$ is continuous on $(0,1)$. Take $r>0$ such that $[r,1-r]\subset (0,1)$ and $f$ being continuous on $[r,1-r]$ has a primitive say $G(t)$, i.e. $G(t)$ is continuous on $[r,1-r]$ and $G'(t)=f(t)$ on $[r,1-r]$.
For any $x\in (0,1)$ we assign $\delta_x>0$ such that $x\in (\delta_x,1-\delta_x)$. This can be done by Axiom of Choice.
On each such closed interval $[\delta_x,1-\delta_x]$ the function $f$ has a primitive $\hat{F}_{\delta_x}$. We note that $\hat{F}_{\delta_x}-G\equiv c_x$ on $[\alpha,1-\alpha]$, where $\alpha=\max\{r,\delta_x\}$ and $c_x$ is a constant but it "depends" on $x$.
Define a function $F_{\delta_x}:[\delta_x,1-\delta_x]\to \mathbb{R}$ by $F_{\delta_x}:=\hat{F}_{\delta_x}-c_x$.
I guess our primitive is gonna be the function $P:(0,1)\to \mathbb{R}$ defines as $P(x):=F_{\delta_x}(x)$. However, I have some technical issues to prove that it continuous on $(0,1)$ and its derivative is $f$ for all $x\in (0,1)$.
Answer: Your construction is almost there, but not quite. It is not yet certain that $F$ is indeed the primitive of $f$.

For example, take $f(x)=1$ on $[0,1]$.
Then, take $$F_{\delta(x)} = \begin{cases}x\mapsto x& x\geq \frac12\\ x\mapsto x+1&x<\frac12\end{cases}$$
If your choice of $F_{\delta(x)}$ is the one described above, then $F$ is not continuous at $x=\frac12$, and so it is not differentiable on $(0,1)$, and it is not the primitive of $f$.

You need some more work in actually selecting $F_{\delta(x)}$. Not a lot more, you just need to make sure all the primitives "line up", which you can do since you have a constant factor to play around with.

Edit:
Your new solution's construction looks better, and avoids the problem I describe above. Now, as you say, all you need is to prove that $P$ is continuous.
But this is simple, because think about what you created by your new construction.
Take, for example, any two values $x_1, x_2\in(0,1)$. Then there exists some $\delta_1, \delta_2$ such that $x_i\in(\delta_i, 1-\delta_i)$ for $i=1,2$. Without loss of generality, let's assume $\delta_1<\delta_2$.
Then, it should be simple to see that $F_{\delta_1}|_{(\delta_2, 1-\delta_2)} \equiv F_{\delta_2}$, that is, the two functions are identical. You can see that because

both functions are primitives of the same function, which means they may only differ by a constant
the two functions match on at least one point (by construction).

This means that on any interval $(\delta, 1-\delta)$, the function $P$ is identically equal to the function $F_{(\delta, 1-\delta)}$, and so in particular, that means $P$ is continuous at all points of $(0,1)$.
Comment: @ZFR I provide an example where the function $x\mapsto F_{\delta(x)}(x)$ is not continuous. That's what my whole answer is about.
Comment: I am really confused. To be honest I do not see any connection of your example with my reasoning yet. I am defining my function $F:(0,1)\to \mathbb{R}$ in the following way: $F(x):=F_{\delta(x)}(x)$ for each $x\in (0,1)$. I guess that $F(x)$ is continuous because it is determined in terms of $F_{\delta}(x)$ which is continuous. What is wrong with this reasoning?
Comment: I think that I got your example but let me illustrate more expanded version: firstly it is better to take the function $f:(0,1)\to \mathbb{R}$ defined by $f(x)=1$.

For each $x\in (0,1/2)$ we can find $\delta(x)>0$ such that $x\in (\delta(x),1-\delta(x))$ and $f$ being continuous on $[\delta(x),1-\delta(x)]$ it has a primitive $F_{\delta(x)}$ on $[\delta(x),1-\delta(x)]$. And we сan take $F_{\delta(x)}:[\delta(x),1-\delta(x)]\to \mathbb{R}$ which is defined by $F_{\delta(x)}(t)=t$.
Comment: The same we can do when $x\in [1/2,1)$ but taking $F_{\delta(x)}:[\delta(x),1-\delta(x)]\to \mathbb{R}$ defined by $F_{\delta(x)}(t)=t+1.$ Then by my reasoning we obtain function $F$ on $(0,1)$ defined by $x\mapsto x$ for $x\in (0,1/2)$ and $x\mapsto x+1$ for $x\in [1/2,1)$ which is not continuous at $1/2$. Am I right?
Comment: @ZFR Yes, my point is that your construction does not guarantee you will not get something like you describe.
Comment: Please take a look at my edit.
Comment: Maybe now you can show the correct solution?
Comment: @ZFR See my edit.
Comment: Thanks a lot! I will take a look at this. I see you have shown that $P$ is continuous on $(0,1)$ and that is good. But what about $P'(x)=f(x)$ on $(0,1)$?
Comment: Can you show this also, please?
Comment: @ZFR The method should be very similar to the one showing continuity.
Comment: Thank you so much! After some thoughts I realized that one can consider a function $F:(0,1)\to \mathbb{R}$ defined by $F(x)=\int_{1/2}^{x}f(t)dt$. Is this assumption correct?
Comment: @ZFR Sure, if you already know what definite integrals are, but I like your original approach more, it feels neater because it assumes less :)
Answer: First, following the completeness of $\mathbb{R}$, we can always find some $r\in(a,b)$. Then for any $x\in(a,b)$, the closed interval $[x,r]$ or $[r,x]$ are subset of $(a,b)$, thus $f$ is continuous on them and we can define
$$\mathcal{F}(x)=\int_{r}^{x}f(t)\mathrm{d} t$$
with the identity $\int_{x}^{r}f(t)\mathrm{d} t=-\int_{r}^{x}f(t)\mathrm{d} t$, this function is defined for all $x\in(a,b)$. Now we prove it is continuous on $(a,b)$ and $\mathcal{F}'(x)=f(x)$:
\begin{align*}
 &\mathcal{F}(x+h)-\mathcal{F}(x)=\int_{r}^{x+h}f(t)\mathrm{d} t-\int_{r}^{x}f(t)\mathrm{d} t\\
 =&\int_{r}^{x}f(t)\mathrm{d} t+\int_{x}^{x+h}f(t)\mathrm{d} t-\int_{r}^{x}f(t)\mathrm{d} t\\
 =&\int_{x}^{x+h}f(t)\mathrm{d} t
\end{align*}
Let $\Delta(t)=f(x)-f(t)\Rightarrow f(t)=f(x)-\Delta(t)$. Since $f$ is continuous on $(a,b)$, we claim that
$$\lim_{t\to x}f(t)=f(x)\Rightarrow\lim_{t\to x}\Delta(t)=\lim_{t\to x}\left(f(x)-f(t)\right)=0$$
Therefore
\begin{align*}
 &\int_{x}^{x+h}f(t)\mathrm{d} t=\int_{x}^{x+h}\left(f(x)-\Delta(t)\right)\mathrm{d} t\\
 =&\int_{x}^{x+h}f(x)\mathrm{d} t-\int_{x}^{x+h}\Delta(t)\mathrm{d} t\\
 =&f(x)\cdot h-\int_{x}^{x+h}\Delta(t)\mathrm{d} t
\end{align*}
Since $t\in[x,x+h]$, we have
$$h\to 0\Rightarrow f(x+h)\to f(x)\Rightarrow f(t)\to f(x)\Rightarrow \Delta(t)\to 0$$
which means $\Delta(t)$ is an infinitesimal of $h$, so we write
$$\mathcal{F}(x+h)-\mathcal{F}(x)=\int_{x}^{x+h}f(t)\mathrm{d} t=f(x)\cdot h-\alpha(h)\cdot h$$
This simultaneously indicates that (1) as $h\to 0$, $\mathcal{F}(x+h)-\mathcal{F}(x)\to 0$, so $\mathcal{F}(x)$ is continuous at $x$ (hence continuous on $(a,b)$, even though may not be uniformly continuous); (2) $\mathcal{F}'(x)=f(x)$ because this is exactly the definition of derivative.
It is quite obvious that select a different $r_{1}$ results in a primitive that differs from this one by the constant $\int_{r}^{r_{1}}f(t)\mathrm{d}t$


Blazor equivalent to @Url.Action or @Html.ActionLink

Question: In ASP.NET MVC, whenever you have a controller and an action in it, you could dynamically generate a link to it in a razor page like:
Url.Action("ProductController", "Index", new { id = "123" })

and this would return a string containing the path to that action with the specified route values:
/Product/123

Isn't there a similar method in Blazor where you could give it the component's name and route values:
Url.Component("ProductPage", new { id = "123" })

and get the path?
/Product/123

Answer: Check out NavigationManager: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager?view=aspnetcore-6.0. Inject that and you can do it. I am not sure if you can pass the route values as an object, though or if you'll need to make something like a NameValueCollection and use the Tostring() method on it.
In short, something like:
@inject NavigationManager NavManager;

// Markup here

@code {

    public void MyMethod() {
        var nameValueCollection = new NameValueCollection();
        var myUrl = "https://localhost:5000/somewhere/";
        // fill data
        NavManager.NavigateTo(myUrl + nameValueCollection.ToString(), false);
    }

}


Does hot spare limit write speed in ZFS?

Question: Let's say I have a ZFS pool with a fast SSD and I want to add a magnetic hot spare.
Will the pool slow down to the hot spare's speed?
Answer: Yep, totally.
It's not worth having dissimilar disks in the same data pool. I wouldn't even mix and match SATA and SAS disks as data drives in a single pool. You should stick with a like-model SSD if you want to have a hot-spare. I'd recommend using it as a cold-spare, assuming hot-pluggable disks, though.
Comment: A spare by definition isn't accessed during normal operation, so how could the speed of the spare possibly have any influence of the performance of the pool?
Comment: Because it wouldn't make sense if it came into use. I wasn't giving a direct answer to the question because the premise was wrong.
Answer: No, unless it gets used. You can try this and everything is fast and smooth until a drive breaks in the main pool, then you're back to slow land (resilver can be snappy though, if you can avoid fragmentation).


Formato JSON em campo LocalDate

Question: Pessoal tenho o sequinte registro sendo retornado por uma consulta usando SpringData:
page = grupoService.findByNomeStartingWithOrderByNomeAsc(2, pageable);

Se eu executar o seguinte código:
System.out.println(page.getContent().get(0));

Ele imprime:
Grupo{id=2, dtOperacao='2016-08-26'}

Porém quando eu converto para JSON (para ser enviado ao frontend):
return new ResponseEntity<String>(new Gson().toJson(scSelect), headers, HttpStatus.OK);

O mesmo converte a data para:
{"id": 1, "dtOperacao":{"year":2016,"month":8,"day":26}}

Ele porém deveria retornar assim:
dtOperacao='2016-08-26'

Alguém sabe como resolver isso? Lembrando que preciso continuar usando o Gson.
Answer: Acredito que seja o Serializer. Como não tenho certeza da Classe de Data que vc está usando, caso seja um Date, vc pode usar da seguinte forma:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

EDIT:
LocalDate ... sorry
use um serializer
JsonSerializer<Date> localDateSerializer = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext contex) {
    return return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
  }
};
Gson gson = new GsonBuilder()
   .registerTypeAdapter(LocalDate.class, localDateSerializer)
   .create();

Answer: Eu resolvi utilizando essa função no front-end:
 function convertLocalDateToServer (date) {
        if (date) {
            return $filter('date')(date, 'yyyy-MM-dd');
        } else {
            return null;
        }
    }

E depois só chamo ela antes do post para corrigir a data:
 method: 'POST',
            transformRequest: function (data) {
                if(data.grupo){
                    data.grupo.dtOperacao = DateUtils.convertLocalDateToServer(
                            //This convertion is necessary cause the component scselect returns an object date
                            new Date(data.grupo.dtOperacao.year, data.grupo.dtOperacao.month, data.grupo.dtOperacao.day)
                    );
                };
                return angular.toJson(data);

Formato JSON em campo LocalDate


How to change the View Mode based on theme?

Question: I am using the ThemeKey module to change the theme for mobile users. I have a custom View Mode called Mobile to display different content. I would like to have when my mobile theme is loaded for the node to use the Mobile View Mode that I created instead of the Default View Mode.
I would like to do this in the theme. Either hooking into the theme with a module or just placing the php in a template override.
Thanks!

Ok I found a few items that get my closer to what I am needing. I just can't seem to get it to work. I am testing this idea with the teaser for now.
<?php
$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
?>

By using the node number I am able to get it to print in the page.tpl.php file fine. But I am wanting to get the node I am on and convert the view mode from full to teaser.
<?php
$rendered_teaser = render(node_view(node_load(2), 'teaser'));
?>

I found that information be reading the links below. I am still not able to get it to work but close. For some reason I get errors. I think it has to do with me placing it in the node.tpl.php and the page.tpl.php template file.
http://drupal.org/node/985022
http://drupal.stackexchange.com/questions/36028/getting-the-auto-summary-from-a-node-bodyhttp://drupal.stackexchange.com/questions/23961/print-result-of-a-node-load

And I got it working. Any comments appreciated. I placed this on the top of the page.tpl.php.
<?php
$nid = $node->nid;
if ($nid) {
 $nid = $node->nid;
 $rendered_view = node_view(node_load($nid), 'teaser');
}
?>

And I placed the print rendered_teaser where I wanted the node view to be printed.
<?php
if ($nid) {
 print render($rendered_view);
}
 else {
  print render($page['content']);
 }
?>

Comment: If I use a node number (2) instead of $nid it works perfectly in the page.tpl.php.
Comment: By using $nid = $node->nid; I am able to get the current node ID.
Answer: Since your mobile theme is a different theme a viable alternative is to just use the same display modes everywhere and then theme that display mode differently by overriding the node.tpl.php file differently in each theme.


Remove all special characters from a phone number string entry except + occurring only at first place

Question: I want to remove all special characters from a phone number string entry except + symbol. That too, if it is occurring only at first place.
Example : +911234567890 should be valid but +91+1234#1234 should be invalid.
Comment: you haven't tried anything
Comment: Plz can u provide ur code.
Answer: You can use something like:
String number = "+91+1234#1234"
number=number.replaceAll("[\\D]", "")

This will replace all non digit characters with space but then for your additional "+" in the beginning ,you may need to add it as a prefix to the result.
Hope this helps!
Answer: The best way is to use regular expression:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
    public static void main(String[] args)
    {
    String sPhoneNumber = "+911234567890";

    Pattern pattern = Pattern.compile("^[+]\\d*");
    Matcher matcher = pattern.matcher(sPhoneNumber);

    if (matcher.matches()) {
        System.out.println("Phone Number Valid");
    } else {
        System.out.println("Phone Number must start from  + ");
    }
 }
}

Comment: yeah I tried this matcher and I am able to detect that the string has symbols but I am not able to replace them.
Answer: Scanner scan=new Scanner(System.in);
        String input=scan.next();
        String onlyDigits = input.replaceAll("[^0-9]+","");
        System.out.println(onlyDigits);

Answer: Try this
public static void main(String arg[]){

String num="+45*#545454*j";
String edited="";

for (int i=0;i<num.length();i++){

char c=num.charAt(i);
    if (i==0&&c=='+'){
        edited+=c;
    }
    else if (Character.isDigit(c)){
        edited+=c;
    }

}
System.out.println(edited);
}
}

Answer: Here is an answer for you.But please give a try and then ask the question so that you can improve yourself. At least give a try to understand the code without directly use it
public static boolean isValid(String number) {

        if(number.startsWith("+")){
            number=number.substring(1);
        }
        try {
             Integer.parseInt(number);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

Comment: hey, I agree I havent posted the code but it doesnt mean I havent tried anything. also, I asked for replacing the characters, NOT for finding it by catching exceptions. thnx anyways for your suggestion:)
Answer: Use a MaskFormatter to constrain the input, something like this
    MaskFormatter formatter = null;
    try {
        formatter = new MaskFormatter("+###");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    JFormattedTextField tf = new JFormattedTextField(formatter);

The string "+###" in the constructor defines what can be typed in the textfield; in this case the first character needs to be '+' and the following three needs to be digits. See the API for details.


Need help converting date format

Question: I have a csv file where the dates look like this: Jan 31, 2017
I would like it be 2017-01-31
I've been searching the site and I found a lot of similar questions but none with my strange date format.
EDIT: Was unclear. I need to change a lot of dates so doing it manually won't work. Thanks for suggestions, reading the help function of lubridate and strptime now.
Comment: `?strptime` will tell you all you need to know
Answer: Use the lubridate library:
library(lubridate)
date <- "Jan 31, 2017"
date2 <- mdy(date)

date2
[1] "2017-01-31"

Comment: @AlbertAlshamn then do it for the column: `df1$newDate <- mdy(df1$oldDate)`
Comment: Thank you for the very quick answer. I was a bit unclear though, I need to change all the dates in my file, doing it manually like this will be too time consuming.

Need help converting date format


HTML Email - Can't restrict width

Question: I'm charged with 'rebranding' our IT department communications. I wanted to do our email notifications in pure HTML / CSS to ensure it's portability.
Below is the code, which looks exactly how I want it to in Outlook, however as soon as content is added to the main  the words wont wrap correctly and if any content goes further than about 90% of the main content window, the other table components start to stretch!
I've tried all sorts of combinations of 'word-wrap' and 'overflow' at all levels in the table but I can't seem to have it.
My end goal is to have the entire table fixed width, with any long format information expanding down.

        i
        Information

company name

Information Systems

      This is the main TD

        IT Helpdesk     |    Ext :  XXXX    |    Email :  Link    |     Portal :  Link

Any help is greatly appreciated, this one minor issue is taking me way to long to overcome!
Good:

Bad (this is just random, wordwrapped text):
Comment: Have you tried changing colspan="99" to colspan="3"?
Comment: The other thing you could try is removing colspan entirely and using another nested table for your first column instead.
Comment: I sent it to my hotmail account and viewed it the online outlook and it looks fine.
Comment: colspan="3" does nothing different, I had it at 99 as I was playing with a couple different layouts and didn't want to have to change it every time, it was a tip from some website, not sure if it's valid or not.

It def appears to be a COLSPAN issue however. I'm looking into using more nested tables to accommodate for the different column numbers instead of spanning it.

I'l also clean the code up as there is a lot of extra stuff while I've been testing this issue.
Answer: You have a few errors in your html:

you don't need a nested table for the right header section. Just the
 portions are enough.
you should set widths for the 'Information' and 'Company name'  cells to prevent arbitrary wrapping.
your colspan value should be colspan="4", not colspan="99"

Anyways, to solve your problem you can add style="table-layout: fixed;" to your main table element, to allow yourself to set a more predictable table layout.
https://css-tricks.com/fixing-tables-long-strings/
Comment: I'll have to clean the code and re-enter it, a lot of the stuff you have pointed out are things I've put in to try and work around this width issue.

My first thought was I had messed up the header so I was trying to restrict that.

It def looks like an issue with COLSPAN though.

I've also used style="table-layout: fixed;" with no noticeable difference
Answer: In the end it was definitely related to the use of COLSPAN.
Instead I replaced the 'heading' piece with a nested table and that resolved the issue.
The specific code I used:

            i
            Information

                  company name

                  Information Systems

        IT Helpdesk     |    Ext :  XXXX    |    Email :  Link    |     Portal :  Link

It is certainly painful but unfortunately working with in the constraints of not only Outlook, but also our helpdesk application which doesn't allow direct HTML code. The only way is to directly copy a table in (which is why I've tried to contain it all in a single table!)

HTML Email - Can't restrict width


2 arrays UPDATE mysql query. 1 array contains values to update other array contains the unique ID to be updated

Question: I have the following two arrays:
$array1 = (-5, -1, 9, 0, 5);
$array2 = (22, 19, 13, 11, 4);

NOTE: There is lots of code in between, which means the final output of the arrays are comma separated, as would be expected in an SQL query. E.G:
echo $array1;

output:
-5, -1, 9, 0, 5

I want to do something along the lines of this:
$UpdSQL ="UPDATE tbl_test SET ing_ml=('$array1') WHERE ing_id IN ('$array2')";

The order of both arrays match.  So what I would like to happen is the following:
ID  | ing_ml
22  | -5
19  | -1
13  | 9
etc | etc

However, I just can not figure out how to do it.  Any assistance would be much appreciated.
Comment: Create a prepared UPDATE statement and execute it in a loop.
Answer: Use array_combine():
$array1 = [-5, -1, 9, 0, 5];
$array2 = [22, 19, 13, 11, 4];

$combined = array_combine($array2, $array1);

print_r($combined);

/* outputs:
Array
(
    [22] => -5
    [19] => -1
    [13] => 9
    [11] => 0
    [4] => 5
)
*/

foreach ($combined as $key => $value) {
  echo "UPDATE tbl_test SET ing_ml = '$value' WHERE ing_id = '$key';";
}

/* outputs:
UPDATE tbl_test SET ing_ml = '-5' WHERE ing_id = '22';
UPDATE tbl_test SET ing_ml = '-1' WHERE ing_id = '19';
UPDATE tbl_test SET ing_ml = '9' WHERE ing_id = '13';
UPDATE tbl_test SET ing_ml = '0' WHERE ing_id = '11';
UPDATE tbl_test SET ing_ml = '5' WHERE ing_id = '4';
*/

Comment: `array_combine()` is a good suggestion, But you should use a prepared  statement and define it outside the loop. For the sake of security and performance.
Comment: It was a demonstration for how the OP could use array_combine.
Comment: That's fine.. But you can improve your answer.
Comment: This does exactly what I am after. However, when I try to execute it, only the first record is updated, the rest error with:  `Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19'' at line 1`


Syncopation in Greensleeves?

Question: Can anyone explain if there's syncopation in Ralph Vaughan Williams' (To sir with love version) of Fantasia on Greensleeves.
Comment: Are you asking about any specific part?
Comment: You might get a more useful answer if you edit to explain why you're looking for syncopation in it.
Answer: There's no syncopation at all in the piece.
Comment: There was an ongoing debate among my musical colleagues in my college (university) days about whether a dotted rhythm counts as syncopation.  The argument was that the short note, because it's not on the beat, meets the definition.  That wasn't my position, so I agree with this answer, but it is worth mentioning that there are people who would disagree with it -- or at least there are four or five people who would have disagreed with it when they were around 20, give or take a couple of years.
Comment: @phoog See https://music.stackexchange.com/q/131773/78419
Comment: @phoog I'm aware that some people consider dotted rhythms to be syncopation. If the poster were asking whether the dotted rhythms were syncopation then the question would be a duplicate: https://music.stackexchange.com/questions/131544/syncopation-and-dotted-rhythms?rq=1

Syncopation in Greensleeves?


Is there an HTTP status code for (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)?

Question: if there isn't, I need to know how to capture that error in my applicaion and display a suitable message to the user. I am using mvc5
Answer: If the error is because the server is misconfigured, or something else server side, that would be a 500 series error, or just the basic 500 "server messed up" error. This suggests there's nothing the user can do to fix this error.
If the error is because of something that the client is passing in the request, then it's a 400 series error, ideally with some text telling the user what they can change to make the request process properly.
Comment: I used the following code in the web.config file to redirect the user to the corresponding error page and it still didn't redirect him properly.


Como colocar o número da última linha de uma tabela MySQL numa variável

Question: Gostaria de saber como pegar a última linha de uma tabela MySQL, e colocar este número dentro de uma variável PHP.
Tentei assim:
require_once "../../models/conex.php";

$sql = "SELECT * FROM tabela ORDER BY id DESC LIMIT 1";
$query = $mysqli->query($sql);
$ultimaLinha = $query;
$mysqli->close();

Mas o var_dump retorna boolean false...
Comment: Você está fechando a conexão antes de pegar o resultado, faltou o `fetch()`. Ou sua consulta real tem algum erro, pq a ideia é essa mesma ordenar por id de forma decrescente e retorna uma linha.
Comment: Não esqueça de ver se exise algum erro na consula `$query = $db->query($sql) or die($db->error);`
Comment: @rray, `$db` no caso é o link de conexão? no meu caso `$mysqli`?
Comment: @rray além de esquecer do `fetch`, tinha um erro na consulta mesmo, tava passando o nome do campo errado. Depois que coloquei o  `$query = $mysqli->query($sql) or die($mysqli->error);`que vc sugeriu, apareceu o erro `Unknown column 'id' in 'order clause'` e aí bingo.... Ficou assim:
`require_once "../../models/conex.php";

$sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
$query = $mysqli->query($sql) or die($mysqli->error); while ($dados = $query->fetch_assoc()) {
    print_r($dados['idcerto']);
}`
Comment: Cria uma resposta,
Answer: Implemente desta forma e não esqueça de recuperar o erro, pode estar havendo alguma exceção e você não está recuperando.
Tente isso:
$leitura = "SELECT * FROM php_teste"; <== seu select
$resultado =mysqli_query($leitura) or die (mysqli_error());
if(mysqli_num_rows($resultado) <=0){
    echo 'não tem nada';
} else {
    while($mostra = mysqli_fetch_assoc($query)){
        print_r($mostra);
    }
}

Comment: Então, não funcionou... pelo que vi aqui o `mysqli_query` pede também o link de conexão como parâmetro, e o `mysql_error` pede a variável da `query`... e no `while` acho que seria `while($mostra = mysqli_fetch_assoc($resultado))` né (está `$query`)...  mas mesmo colocando `mysqli_query($conn, $leitura) or die (mysqli_error($leitura));`, e mudando o `while` não funcionou, e não aparece nenhum erro... Até acho que é algum erro bobo que to cometendo aqui... +1 pela força... abraço.
Comment: Faça o seguinte abra o phpAdmin e execute esta query diretamente nele, certifique-se que existam dados. Já aconteceu comigo e não vir o resultado e o problema era simples, não tinha mesmo resultado. Faça isso.... sucesso
Answer: Só pra constar, o problema era que, além de esquecer do fetch (o que foi  apontado pelo @rray), também tinha um erro na consulta, pois estava passando o nome do campo errado.
Depois que coloquei o
$query = $mysqli->query($sql) or die($mysqli->error);

por sugestão do @rray, apareceu o erro:

Unknown column 'id' in 'order clause'

Então foi apenas incluir o while com o fetch, e corrigir o nome do campo.
Ficou assim:
require_once "../../models/conex.php";
$sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
$query =    $mysqli->query($sql) or die($mysqli->error);
while ($dados = $query->fetch_assoc()) {
print_r($dados['idcerto']);
}

UPDATE

Seguindo a orientação do @DanielOmine nos comentários, troquei o while pelo if, por duas razões:

como só vai retornar um resultado, não precisa do while;
colocando o if ele verifica se o resultado não retorna vazio;

O código normalizado:
    require_once "../../models/conex.php";
    $sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
    $query =    $mysqli->query($sql) or die($mysqli->error);

    if ($dados = $query->fetch_assoc()) {
        $idcerto = (int)(($dados['idcalc']) + 1);
        echo $idcerto;
    }
    else{

        echo "erro na obtenção da id";

    }
    ?>

Comment: isso! coloca um if() pois também pode vir vazio.
`if ($dados = $query->fetch_assoc()){print_r($dados);}else{echo 'vazio';}`
Comment: pode ser dentro do if(). `if ($dados = $query->fetch_assoc())`
Comment: não precisa do laço de repetição pois retornará apenas um resultado.
Comment: @DanielOmine trocando por um `if` funcionou tbm... é mais correto assim, por ele fazer uma verificação (se `$query->fetch_assoc()` for true...), ou passando assim é melhor: `$idcerto = NULL;
    $dados = $query->fetch_assoc();
    $idcerto = (int)(($dados['idcalc']) + 1);
        echo $idcerto;` (funciona tbm) Não rola uma resposta?
Comment: Legal, se animar faz uma resposta... valeu! @DanielOmine
Comment: é que fica sem sentido responder. Edite a sua resposta com o if(), removendo o while()  aí fica manero!
Comment: Ok Valeu! Só mais uma dúvida, eu declaro a variável direto dentro do if, ou declaro depois faço o if, assim: `$dados = $query->fetch_assoc();
    if ($dados = $query->fetch_assoc()) {
    $idcerto = (int)(($dados['idcalc']) + 1);}`? @DanielOmine
Answer: Coloque:
$linha = $query->fetch_array(MYSQLI_ASSOC);
$variavel=$linha["NOME DA COLUNA DESEJADA"];


Item analysis Skewness and Kurtosis True False Question

Question: I made a test with 15 true/false Questions and about 100 people answered these questions.
Now I'm doing the item analysis in R with the package sjPlot and the function sjt.itemanalysis().
Amongst other things this function returns skewness and kurtosis. Does it make
sense in my scenario to interprete them? In this case the skewness does not tell me more than the mean/item difficulty, does it?
Answer: If you have a binary variable where the values are typically assumed to be independent - like getting a particular question right (1) or wrong (0) - and you look at the average (the proportion of 1's) over a number of observations, you have something completely defined by two numbers (though the information can be expressed several different ways). For example, $p$, the sample proportion of 1's and the total number of values will be sufficient (as would the total number of 1's and the total number of 0's); naturally you can readily convert between pairs of values that carry the information.
Anything calculated from the sample of 0's and 1's can also be calculated directly from the sample proportion, $p$ and the sample size $N$. So a sample skewness or kurtosis is simply a function of $p$ and $N$. Given $N$ as known, and the assumption of independence (so that the order of 0's and 1's is irrelevant, for example), there's no additional information beyond $p$ itself.
That's not to say you can't be interested in knowing skewness or kurtosis, even though they're completely determined by $p$ and $N$.


Spring Jpa Entity - EntityManager.getReference

Question: I have a Spring Boot application using Spring JPA, and what I'm trying to do is to save a new entity that has some foreign keys by just providing the IDs of those child entities. So, like:
@Table(name = "PERSON")
public class Person {
@Column(name = "PET_GUID")
public Pet pet;
}

Using this, I'd like to be able to have my PersonRepository that implements CrudRepository save a Person by just providing the guid of the Pet. Using straight up hibernate I can do that using EntityManager.getReference. I know that I can inject an EntityManager into my Entity or Repository and do something that way, but is there an easier way? I tried just doing person.setPet(new Pet(myPetsGuid)), but I get a "foreign key not found" when doing that, so that does not seem to work.
Answer: First, you should add @ManyToOne relation to the pet property:
@Entity
@Table(name = "PERSON")
public class Person {

    //...

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "pet_guid")
    privat Pet pet;
}

It says to Hibernate to use a foreign key to the Pet entity (and its table).
Second, you should use the method getOne of your PersonRepository to get a reference to the Pet entity, for example:
@Service
public class PersonService {

    private final PetRepository petRepo;
    private final PersonRepository personRepo;

    //...

    @NonNull
    @Transactional
    public Person create(@NonNull final PersonDto personDto) {
         Person person = new Person();
         //...
         UUID petId = personDto.getPetId();
         Pet pet = petRepo.getOne(perId);
         person.setPet(pet);
         //...
         return person.save(person);
    }

}

Comment: Ah yes, the getOne call is what I was missing. That's what I needed! Thanks!


Não faz INSERT aos dados na base de dados

Question: Boas pessoal, tenho este código, e o que se passa é que desde que inseri a parte para fazer upload de uma imagem ele não envia nada para a base de dados. Nem uma linha nova cria, nada mesmo. Alguém me pode ajudar?
<?
    require('../cdn/lib/config.php');

    if(isset($_POST['submit'])){

        if(strlen($_POST['username']) < 3){
            $error[] = 'Username is too short.';
        } else {
            $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
            $stmt->execute(array(':username' => $_POST['username']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['username'])){
                $error[] = 'Username provided is already in use.';
            }
        }

        if(strlen($_POST['password']) < 3){
            $error[] = 'Password is too short.';
        }

        if(strlen($_POST['passwordConfirm']) < 3){
            $error[] = 'Confirm password is too short.';
        }

        if($_POST['password'] != $_POST['passwordConfirm']){
            $error[] = 'Passwords do not match.';
        }

        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $error[] = 'Please enter a valid email address';
        } else {
            $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
            $stmt->execute(array(':email' => $_POST['email']));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if(!empty($row['email'])){
                $error[] = 'Email provided is already in use.';
            }

        }

        if(!isset($error)){

            // Proteger a password
            $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

            // Criar código de activação
            $activasion = md5(uniqid(rand(),true));

            try {

        $file       = $_FILES['img'];
        $numFile    = count(array_filter($file['name']));

        //PASTA
        $folder     = 'cdn/uploads/avatars/';

        //REQUISITOS
        $permite    = array('image/jpeg', 'image/png');
        $maxSize    = 1024 * 1024 * 1;

        //MENSAGENS
        $msg        = array();
        $errorMsg   = array(
        1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
        2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
        3 => 'o upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo'
            );

    if($numFile <= 0){
        echo '';
    }
    else{
        for($i = 0; $i < $numFile; $i++){
        $name   = $file['name'][$i];
        $type   = $file['type'][$i];
        $size   = $file['size'][$i];
        $error  = $file['error'][$i];
        $tmp    = $file['tmp_name'][$i];

        $extensao = @end(explode('.', $name));
        $avatar = rand().".$extensao";

        if($error != 0)
            $msg[] = "$name : ".$errorMsg[$error];
        else if(!in_array($type, $permite))
            $msg[] = "$name : Erro imagem não suportada!";
        else if($size > $maxSize)
            $msg[] = "$name : Erro imagem ultrapassa o limite de 1MB";
        else{

        if(move_uploaded_file($tmp, $folder.'/'.$avatar)){

                $stmt = $db->prepare('INSERT INTO members (username,password,email,active,avatar) VALUES (:username, :password, :email, :active, :avatar)');
                $stmt->execute(array(
                    ':username' => $_POST['username'],
                    ':password' => $hashedpassword,
                    ':email' => $_POST['email'],
                    ':active' => $activasion,
                    ':avatar' => $avatar
                ));

     }else{
     $msg[] = "$name : Desculpe! Ocorreu um erro...";

       }
      }
     }
     }

                // Inserir dados na base de dados

                $id = $db->lastInsertId('memberID');

                // Estrutura do email
                $to = $_POST['email'];
                $subject = "Registration Confirmation";
                $body = "Thank you for registering at site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n\n Regards,\n Administration \n\n";
                $additionalheaders = "From: <".SITEEMAIL.">\r\n";
                $additionalheaders .= "Reply-To: $".SITEEMAIL."";
                mail($to, $subject, $body, $additionalheaders);

                header('Location: register.php?action=joined');
                exit;

            } catch(PDOException $e) {
                $error[] = $e->getMessage();
            }

        }

    }
    ?>

        <form role="form" method="post" action="" autocomplete="off">

                    <?php
                    // Verificar erros
                    if(isset($error)){
                        foreach($error as $error){
                            echo '
'.$error.'
';
                        }
                    }

                    // Mensagem de sucesso
                    if(isset($_GET['action']) && $_GET['action'] == 'joined'){
                        echo "
Registration successful, please check your email to activate your account.
 ";
                    }
                    ?>

        <input type="text" name="username" id="username" class="register" placeholder="Username" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1" maxlength="15">

          <input type="file" class="register" id="avatar" name="img[]" />

        <input type="email" name="email" id="email" class="register" placeholder="Email Address" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="2">

        <input type="password" name="password" id="password" class="register" placeholder="Password" tabindex="3">

        <input type="password" name="passwordConfirm" id="passwordConfirm" class="register" placeholder="Confirm Password" tabindex="4">

        <input type="submit" name="submit" class="submit" value="Register" class="register-submit" tabindex="5">

        </form>

Comment: Você tem certeza que ele chega a executar o insert? Qual a mensagem de erro?
Comment: O problema e mesmo esse, mao aparece nada, da SUBMIT e diz que ta tudo bem..
Comment: Coloque `ini_set('display_errors', true); error_reporting(E_ALL);` no início do código e veja quais erros aparecem.
Comment: nao aparece nenhum erro, e sim, coloquei isso no incio do ficheiro
Comment: O arquivo após o upload está sendo movido para a pasta cdn/uploads/avatars? Se não estiver, não entra no INSERT.
Comment: nao move a imagem para a pasta nem faz INSERT do username, email, avatar, NADA..
Answer: Bom dia.
Parece-me que pode estar aí um erro a causar esse problema. Forms com upload de arquivos devem ter uma definição que falta nesse HTML:
<form (...) enctype="multipart/form-data">

Depois, sugiro usar o método die / echo / print_r para ajudar a fazer debug. Com esses métodos é fácil perceber se realmente o código de um dado if está ou não a ser executado.
Comment: Bom dia, resolveu o meu problema e vou ja dar a resposta como certa! Mas tenho mais um erro com este codigo, quando mostra o `echo "Registration successful, please check your email to activate your account. ";` tambem mostra o formulario e nao era suposto :ss
Comment: @thecreator a forma de evitar que isso aconteça é ter um if antes de mostrar o form que verifica se está definido $_GET['action']. como o php redirecciona para uma página com o parametro 'action' quando o registo é bem sucedido, o form só deve ser mostrado se esse campo 'action' não estiver definido.
Comment: pode ajudar-me? :ss é que eu nao estou a ver como fazer isto visto que tenho muitos if's e else's
Comment: @thecreator antes do form deve ter: if(!isset($_GET['action'])) { [(...)imprimir form(...)] }


How to make a dynamic circle on the map?

Question: I have a point on the map (a custom pushpin, which does not grow according to the zoom), and I want to have a circumference based on the accuracy of GPS, that will change size according to the zoom. Any idea how to create this circle?
Answer: These two articles show how to create shapes on top of a map.
They do a bit more than you need but I'm sure there's more than enough for your needs there.
Answer: This post is more focused on drawing shapes on bing maps control.
http://awkwardcoder.blogspot.com/2011/10/drawing-shapes-on-top-of-bing-maps-in.html


Find length of a chord of a circle with radius $13$ cm given position of a point located on the chord.

Question: A point located on a chord of a circle is 8 cm from one endpoint of the chord and 7 cm from the center of the circle. If a radius of this circle is 13 cm long, how long is the chord, in cm?
Please help! I'm not sure where to start.
Comment: Can you check if the answer is 23cm?
Answer: Hint:
Applying the Pythagorean theorem twice
$$h^2 = 7^2 - x^2 = 13^2 - (8+x)^2$$
where you have one right angled triangle
with sides $x$ and $h$ and hypotenuse $7$ and
another right angled triangle
with sides $8+x$ and $h$ and the radius of
$13$ is the hyptenuse.
chord $= 2 \cdot (8+x)$
Comment: Or you can directly find out by Law of Cosines.


Maintaining accurate f.name through rename operation in Python w/o dropping lock

Question: I have a file which I'm atomically replacing in Python, while trying to persistently retain a lock.
(Yes, I'm well aware that this will wreak havoc on any other programs waiting for a lock on the file unless they check for the directory entry pointing to a new inode after they actually receive their lock; that check is happening in practice).
import os, os.path, tempfile, fcntl

def replace_file(f, new_text):
    f_dir = os.path.dirname(f.name)
    with tempfile.NamedTemporaryFile(dir=f_dir) as temp_file:
         temp_file.write(new_text)
         temp_file.flush()
         os.fsync(temp_file.fileno())
         dest_file = os.fdopen(os.dup(temp_file.fileno()), 'r+b')
         fcntl.flock(dest_file.fileno(), fcntl.LOCK_EX)
         os.rename(temp_file.name, f.name)
         temp_file.delete = False
    # ...and after more paranoia, like fsync()ing the directory it's in...
    return dest_file

f = open('/tmp/foo', 'w')
f = replace_file(f, "new string")
print f.name # name is <fdup>, not /tmp/foo

I'm hard-pressed to find a workaround for this that doesn't involve dropping the lock even temporarily after the rename has taken place.
Comment: (re: obvious question -- why use atomic renames *and* flock? -- there are multiple edit modes available; in some cases we're doing appends that should be treated as atomic [hence flock], and in others we're replacing the file in full, and don't want to allow data loss even in event of a power loss [hence replace-and-rename]).
Comment: `os.rename` is an atomic operation if source and destination are on the same filesystem (only node rename). Why do you need locking?
Comment: @LaurentLAPORTE, see the very first comment on the question. The locks aren't needed for this case, but for scenarios where we're doing in-place updates.
Answer: If your code is under Linux, here's a way to get filename from a file descriptor:
...
f = replace_file(f, "new string")
print os.readlink('/proc/self/fd/%d' % f.fileno())

Reference: https://stackoverflow.com/a/1189582/2644759
Comment: Hmm. So the proposal is to take all code that references `f.name`, and do a lookup via procfs instead? Inasmuch as using this answer requires modifying everything that uses the `replace_file` function, not the function itself, I'd almost be tempted to build a wrapper for the file object's type and return that.
Comment: ...actually, that wrapper could do it better: By allowing the `file` attribute to be overridden explicitly (it's read-only on the base type), it wouldn't need the procfs lookup at all, but could accept it as an assertion by the code doing the creation.
Comment: BTW -- are you sure the procfs lookup would return `/tmp/foo`, not `/tmp/random-tempfile-name (deleted)`?
Comment: @CharlesDuffy I'm not sure since I didn't test it. It seems you have a high throughput system that there's not too much can be touched in `replace_file` function. Or you can just close the old `fd` and re-open a fresh new one when returning.
Comment: Closing and re-opening drops the lock.
Comment: @CharlesDuffy I see. Also I tested `readlink` after renaming, the file path did get updated so you don't need to worry it won't return the correct file path. Write a light weight wrapper seems like a much good idea.
Answer: A simplicity-focused solution is to use an entirely separate lockfile with a different name (ie. <filename>.lck).

Using a separate lockfile means that the code performing the write-and-rename operation doesn't need to be involved in locking at all, as the rename operation doesn't interact with the lock.
Using a separate lockfile avoids the need to jump through hoops to avoid breaking clients which might find that they've successfully grabbed a lock, but hold it on a now-deleted file rather than the version currently bound to the directory.


Is this a modal composing technique?

Question: Suppose that I went to Wikipedia and got a list of all the dominant seventh chords. Then I composed by doing them in any order I wish:
CEG and Bflat was my first chord  [note that I dont know how to do subscripts]
E then Gsharp then BD was my second chord.
And so on in whatever order I wished as long as it was a dominant seventh.
Here I am not thinking of the tonic or numbers related to the tonic. Or the key. I am only thinking of using a characteristic - that of the quality of dominant sevenths in our case; I could use other qualities from a different list.
Would this be a type of modal composing? Or something else?
Comment: What some call "Modal" harmonies and melodic lines in my experience tend to avoid major/minor melodies and harmonic  I IV V progressions. What you are describing is usually called "Secondary Dominants" and is probably the opposite of what some would consider Modal music.  The Dominant / Tonic relationship is a very Major oriented sound.
Comment: I considered putting in an answer, but I think it is too much an opinion since I'm not sure what is currently considered "modal".  There is enough of a difference between early English Renaissance modal forms, Jazz modal music, and pop/rock (al la the Beatles) modes that I don't feel I can make a qualified answer other than Secondary Dominants probably aren't it.
Comment: Can't see how different this is from taking  one note at a time, randomly from the list of 12 , randomly taking an octave for it, randomly taking a note length, moving on to the next, and so on. 'Music' generally speaking, has a thread running through, making some sense to the way notes (and harmonies) follow each other. Rather like someone speaking in sentences that make sense, not uttering random words. Couldn't be called modal though. This question may well be closed as personal opinion comes in too strongly.
Comment: You might have been better writing that as a reply rather than a comment.
Comment: I also wondered if it could be a kind of serialism. Tonal serialism? Using a list of dominant chords and at random having an order?
Comment: Worth adding that I do compose using this technique. But I have presented a very simplified example here; I wouldn't expect anyone new to unusual composing methods to get my more complex ways of doing it.
Comment: 'Better - fact or opinion?
Comment: I cannot see how there is an element of opinion here. Indeed I have been careful to NOT have opinion; I am presenting a method. I am not batting for the method.
Comment: 'More complex' - writing a symphony isn't simple. Not *your* opinion. Those of answerers.
Comment: That is plain pedantic; this is a valid question.
Answer: I think that your motivation for seeing this as a modal technique is that you are focused on the character of dominant 7th chords, and using that character as a compositional device. But that isn't enough to make this a modal approach.
A dominant 7th chord isn't a mode, and you could associate a number of modes with such a chord, which is to say that you need more than a 7th chord to establish modality.
Dominant 7th chords want to move, and modal harmony tends to be more static. Certainly some sequences of dominant 7th chords will include secondary dominants, tritone substitutions, chromatic mediants, or other functional relationships that will be hard to ignore, making those sequences more functional than modal in character. So, arbitrary sequences of dominant 7th chords will not be modal in character.
Often modal pieces slow down the harmonic motion by extending the durations of the chords. This helps to frustrate the tendency to hear chords functionally; this would probably be an important feature for a sequence of dominant 7th chords to be heard modally.
By itself, I don't see how arbitrarily sequencing dominant 7th chords could be seen as a technique for creating modal compositions. It could be seen as a tool to aid in creating modal compositions; that would require that the composer keep the goals of modal harmony in mind, and use other techniques to facilitate those goals.

Is this a modal composing technique?


How to aggregate nodes in XSLT 1.0?

Question: I often need to aggregate a sequence of nodes using XSLT 1.0 but I always struggle to find a clean solution.
This is a typical example;
Input
<x>Foo/Red</x>
<x>Foo/Green</x>
<x>Foo/Blue</x>
<x>Bar/Hello</x>
<x>Bar/World</x>

Desired output
<y s="Foo">Red, Green, Blue</y>
<y s="Bar">Hello, World</y>

I always end up in a mess with this type of problem. Is there an elegant XSLT 1.0 solution to the above?
I'm using PHP's libxslt so I do have the exslt:node-set() function available to use if necessary.
Answer: Here an adaption of muenchian grouping to your example. For more info look e.g. here.
If you ones have understand how it work and tried to adapt it to changing grouping issues it becomes quite handy.
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="kXprev" match="x" use="substring-before(text(),'/')"/>

    <xsl:template name="y">
        <xsl:param name="s" />
        <y s="{$s}">
            <xsl:for-each select="key('kXprev', $s)">
                <xsl:if test="position()>1" >
                    <xsl:text> </xsl:text>
                </xsl:if>
                <xsl:value-of select="substring-after(text(),'/')"/>
            </xsl:for-each>
        </y>

    </xsl:template>
    <xsl:template match="/*">
        <out>
            <xsl:for-each select="x[count( . | key('kXprev',substring-before(text(),'/') )[1] ) =1]" >
                <xsl:call-template name="y">
                    <xsl:with-param name="s" select="substring-before(text(),'/') "/>
                </xsl:call-template>
            </xsl:for-each>
        </out>
    </xsl:template>
</xsl:stylesheet>

Answer: In general:  Read up on Muenchian grouping.
For this specific problem (but also useful advice in general):  break it up into smaller pieces.
One way to break it up:  You want to produce one y element for each distinct value of the expression substring-before(.,'/') for the x elements in the input.  Or possibly for each occurrence of x where that substring differs from the corresponding substring for its immediately preceding sibling.  First write a stylesheet which just produces the correct number of y elements, with the appropriate value for the s attribute.  So the output is
<y s="Foo"/>
<y s="Bar"/>

How can you do that?
Once you've done that, you need to provide content for the y element:  for each x in the input which shares the same prefix, print out the string value.  In the final version you'll want commas and spaces, but getting them right involves some fussy details, so write the next version of your stylesheet to produce a sequence of z elements as children of y:
<y s="Foo"><z>Red</z><z>Green</z><z>Blue</z></y>
<y s="Bar"><z>Hello</z><z>World</z></y>

The z elements need to appear inside the y element.  So the template that's producing the y element changes to read:
<xsl:template match="...">

  <xsl:element name="y">
    <xsl:attribute name="s">
      <xsl:value-of select="..."/>
    </xsl:attribute>

  </xsl:element>
</xsl:template>

What should the code for producing z elements look like?  Within a y element for a given prefix value $prefix, we want one z element for each x in the input that shares that prefix.  So one simple way to do the job is to call apply-templates on just that set of y elements.  To avoid interference with the templates which match x elements and produce y elements, give it a mode.  The call to apply-templates might look like this:
<xsl:apply-templates mode="z-production"
  select="//x[substring-before(.,'/') = $prefix]"/>

Now write the template for x elements in mode z-production.
Finally, change the stylesheet to generate the commas and blanks instead of the z elements.
There are other ways to break the problem down into smaller pieces; sometimes it's helpful to walk the tree from sibling to sibling instead of from parent to siblings.

How to aggregate nodes in XSLT 1.0?


MySQL - create trigger before insert to replace date

Question: I'm having a small issue.
I want to do an insert in a table with a timestamp field called date in MySQL.
if I do a regular insert using a query with str_to_date, it works nicely.
however, my program does not support using functions in the queries.
so I need to find another way doing it, I was thinking about using a trigger, such as :
DELIMITER //
CREATE TRIGGER audit_oracle_date
BEFORE INSERT ON audit_oracle FOR EACH ROW
BEGIN
SET NEW.date = STR_TO_DATE(NEW.date, "%d %b %Y %H:%i:%s");
END
//
DELIMITER ;

but it does not work. the trigger is created, but when trying to enter a query like :
insert into audit_oracle values("20 Jan 2017 18:01:25","IFOMCP00","sdfdsfds","zerzerez","aaaa","SYSDBA","1","'select * from bla'","ddd","eee","2")

it gives me an error message saying "date field cannot be NULL"
any idea on how to code this trigger please ?
a regular, working query (with str_to_date) is for example :
insert into audit_oracle values(str_to_date("20 Jan 2017 18:01:25", "%d %b %Y %H:%i:%s"),"IFOMCP00","sdfdsfds","zerzerez","aaaa","SYSDBA","1","blabla","ddd","eee","2")

thanks again !
regards,
Comment: Why don't you fix your program to send the data across "correctly"? (which of course could include the embedded call to `str_to_date` if needed)
Comment: hi, because I didn't write the program myself, it's called syslog-NG (it's a well-known log management program, able to write to MySQL databases, but it's very limited)
Answer: For better or worse, the conversion to date occurs when MySQL processes VALUES.  The problem is that MySQL doesn't recognize the date format.
My recommendation would be to do the conversion on the spot, as in your last example.
If you really want to do this using a trigger, you can add another column which is a string, insert into that column, and then use the trigger:
insert into audit_oracle(datestr, . . .)
     values('20 Jan 2017 18:01:25', 'IFOMCP00', 'sdfdsfds', 'zerzerez', 'aaaa', 'SYSDBA', '1', '''select * from bla''', 'ddd', 'eee', '2');

Then your trigger would look like:
DELIMITER //
CREATE TRIGGER audit_oracle_date
BEFORE INSERT ON audit_oracle FOR EACH ROW
BEGIN
    SET NEW.date = STR_TO_DATE(NEW.datestr, "%d %b %Y %H:%i:%s");
END
//
DELIMITER ;

Comment: thanks, it works nicely with the additional column ! I will use this solution (as I cannot do the conversion directly in the insert query due to the program restrictions, syslog-NG) thanks again !


How to add action menu on specific position

Question: As per title. A new action menu is automatically added to the bottom of the list. Is there a way to force them to appear on specific index or just before/after a specific action ?

Thanks in advance
Answer: In Automation Steps screen, in Actions tab you can find the button REORDER ACTIONS, this may help you.
Answer: PXGraph class has an action collections declared as:
public readonly PXActionCollection Actions;

It is a class deriving from .Net framework OrderedDictionary.
You can access it directly in your class deriving from PXGraph:
this.Actions

In the context of a graph extension deriving from PXGraphExtension it is available though Base member:
Base.Actions

Look at the public methods exposed by Actions, I think Move might be able to swap the Actions order in the menu. Here is some usage examples:
public PXAction<APInvoice> release;
public PXAction<APInvoice> prebook;

// Resolving name with static check
Base.Actions.Move(nameof(release), nameof(prebook));

// Using action display name with runtime check
Base.Actions.Move("Release", "Pre-book");


Alternate App Icons appear blurry within app despite using Apple's sample code

Question: I am looking to add alternate app icons to my iOS app but am encountering an issue where they are displaying as blurry in the app's view - but are crisp and clear when set as the app icon.
I am following Apple's Configuring Your App to Use Alternate App Icons developer documentation. Using Apple's Sample Code and running it in Xcode Preview and the Simulator both result in blurry app icons being shown in the view. The alternate app icon functionality works perfectly, and the app icon on the Home Screen appears correctly.
I closely adapted Apple's sample code within my own app and encounter the same blurry app icons - both in the Xcode Preview, Simulator, and on a real device.
See an example of the blurry app icons
I'm using Xcode 13.4.1 and targeting iOS 15.4.
I could add another image asset and just use that as the preview app icon - but I'd rather not bulk up the app with additional assets when each AppIcon has multiple sizes up to 1024x1024.

Below is a snippet of the key parts of the code from Apple's sample code for implementing alternate app icons - you can get it yourself here.
<code>// Main View
struct IconChooser: View {
    @EnvironmentObject var model: Model

    var body: some View {
        let columns = [
            GridItem(),
            GridItem(),
            GridItem()
        ]

        VStack {
            HStack {
                Text("Select an icon:")
                    .font(.title)
                IconImage(icon: model.appIcon)
                    .frame(maxHeight: 100)
            }
            ScrollView {
                LazyVGrid(columns: columns) {
                    ForEach(Icon.allCases) { icon in
                        Button {
                            model.setAlternateAppIcon(icon: icon)
                        } label: {
                            IconImage(icon: icon)
                        }
                    }
                }
            }
        }
    }
}
</code>
<code>// Sub-view for the individual app icon previews
struct IconImage: View {
    var icon: Icon

    var body: some View {
        Label {
            Text(icon.rawValue)
        } icon: {
            Image(uiImage: UIImage(named: icon.rawValue) ?? UIImage())
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(minHeight: 64)
                .cornerRadius(10)
                .shadow(radius: 10)
                .padding()
        }
            .labelStyle(.iconOnly)
    }
}
</code>
<code>// Model
enum Icon: String, CaseIterable, Identifiable {
    case primary    = "AppIcon"
    case blue       = "AppIcon-Blue"
    case green      = "AppIcon-Green"
    case orange     = "AppIcon-Orange"
    case purple     = "AppIcon-Purple"
    case pink       = "AppIcon-Pink"
    case teal       = "AppIcon-Teal"
    case yellow     = "AppIcon-Yellow"

    var id: String { self.rawValue }
}

class Model: ObservableObject, Equatable {
    @Published var appIcon: Icon = .primary

    static func == (lhs: Model, rhs: Model) -> Bool {
        return lhs.appIcon == rhs.appIcon
    }

    /// Change the app icon.
    /// - Tag: setAlternateAppIcon
    func setAlternateAppIcon(icon: Icon) {
            // Set the icon name to nil to use the primary icon.
            let iconName: String? = (icon != .primary) ? icon.rawValue : nil

            // Avoid setting the name if the app already uses that icon.
            guard UIApplication.shared.alternateIconName != iconName else { return }

            UIApplication.shared.setAlternateIconName(iconName) { (error) in
                if let error = error {
                    print("Failed request to update the app's icon: \(error)")
                }
            }

            appIcon = icon
    }

    /// Initializes the model with the current state of the app's icon.
    init() {
        let iconName = UIApplication.shared.alternateIconName

        if iconName == nil {
            appIcon = .primary
        } else {
            appIcon = Icon(rawValue: iconName!)!
        }
    }
}

</code>
Answer: -Using Xcode 14.0

In the Assets folder, each icon has multiple sizes.
Open Attributes Inspector and change (in iOS) All Sizes to Single Size. This will result in having only 1 image at 1024pt. Blurry image no more.

Cheers


Port iOS GPUImageBilateralFilter to Android

Question: I developed iOS app using GPUImage including GPUImageBilateralFilter.
Now I am going to port the iOS app to Android, but I've found there is no GPUImageBilateralFilter in Android GPUImage library.
How can I port this filter in Android?
Answer: Well, you do have the entire source code for that filter right here. I talk a little more about that here and here, but it's a relatively simple bilateral blur. It uses a hardcoded set of 9 Gaussian samples about a central pixel, split into horizontal and vertical passes.
All you need to do is take the vertex and fragment shaders from the GPUImage repository and write your own implementation of a two-pass filter that does this within whatever Android framework you're using. If they've already got a separated Gaussian blur, that shouldn't be too hard to do.
Comment: Thanks. let me check the links. btw I am still curious why there is no GPUImageBilateralFilter in Android. can you let me know why it does?
Comment: @ttotto - I don't know. I have nothing to do with any of the attempted ports of this to Android (I don't do any Android development myself), and I think the two I've seen only got a small fraction of the framework ported over before they stopped.


Suppose U is an orthogonal matrix.

Question: Suppose $U$ is an orthogonal matrix.
Show that $T : M_{22} → M_{22}$ defined by $T(A) = UAU^{−1}$ is an isometry.
I know that a linear operator is an isometry if and only if it sends some orthonormal basis to an orthonormal basis.
But I have no idea how to start this.
Comment: Which scalar product is there on $M_{2,2}(\Bbb R)$?
Comment: Hint: $U$ orthogonal $\implies U^{-1}=U^T$, where $U^T$ is the transpose of $U$. Can you take it from here?
Answer: I'm assuming you're using the standard inner product to define a norm, $\langle A,B\rangle = \text{tr}(A^TB)$. In this case, $\|A\| = \text{tr}(A^TA)$, and we have
$$ \text{tr}((UAU^T)^T(UAU^T)) = \text{tr}(UA^TU^TUAU^T) = \text{tr}(UA^TAU^T) = \text{tr}(U^TUA^TA)=\text{tr}(A^TA)$$
where we used the cyclic property of the trace and the fact that for orthogonal $U$ we have $U^{-1}=U^T$, showing that your map is indeed an isometry.

Suppose U is an orthogonal matrix.


CakePHP 2.x HABTM saveAll with Add view associated model optgroups

Question: I have a CakePHP Add Photo View that is using optgroups so that the HABTM related Tag model's data is shown in grouped fashion in the view.  In the Photo controller I send the related Tag model data as  follows to get the optgroups grouping of Tags by Tag Category:
//fields shown to create optgroups eg group tags by category
$this->set('tags', $this->Photo->Tag->find('list', array(
    'fields' => array('Tag.id', 'Tag.tagname', 'Tag.category'),
    'conditions' => array(
        'Tag.account_id' => $this->Session->read('Auth.User.account_id')))));
}

The view shows the Tags nicely grouped by Category. So that part works perfectly.
However, after adding a new Photo and selecting one or more Tags to assign to it, it does save the Photo properly but not the assigned Tags.
I believe that CakePHP saveAll is expecting a data array as would be delivered without the optgroup Category > Tag hierarcy, and is therefore not saving Tag data when new Photo is added and Tags are assigned to the Photo.
What do I need to do to give it the proper array to save the related Tags?  Will it be in the controller after Create() where I 'remove' the Category grouping?
A bit of background on this from CakePHP http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
"If you would like to generate a select with optgroups, just pass data in hierarchical format. This works on multiple checkboxes and radio buttons too, but instead of optgroups wraps elements in fieldsets:"
$options = array(
    'Group 1' => array(
    'Value 1' => 'Label 1',
    'Value 2' => 'Label 2'
   ),
  'Group 2' => array(
  'Value 3' => 'Label 3'
  )
);
echo $this->Form->select('field', $options);

Output:
<select name="data[User][field]" id="UserField">
    <optgroup label="Group 1">
        <option value="Value 1">Label 1</option>
        <option value="Value 2">Label 2</option>
     </optgroup>
     <optgroup label="Group 2">
         <option value="Value 3">Label 3</option>
    </optgroup>
</select>

Answer: Ok so this problem had nothing to do with the array structure.
It turns out I had 'Photo.Tag' instead of just 'Tag' in the Add Photo View.  Here is the old Add Photo View code that didn't work:

<?php echo $this->element('admin_nav'); ?>

    <?php echo $this->Form->create('Photo'); ?>
        <fieldset>
            <legend><?php echo __('Add Photo'); ?></legend>
        <?php
            echo $this->Form->input('account_id', array('type'=>'hidden'));
            //echo $this->Form->input('filename', array('type'=>'hidden'));
            echo $this->Form->input('filename', array('type' => 'file', 'label' => 'Upload photo'));
            echo $this->Form->input('desc');
            echo $this->Form->input('Photo.Tag' , array('label'=>'Tags', 'multiple'=>'checkbox'));

        ?>
        </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>

Here is the new Add Photo View code which now saves the new photo with the tags selected:

<?php echo $this->element('admin_nav'); ?>

    <?php echo $this->Form->create('Photo'); ?>
        <fieldset>
            <legend><?php echo __('Add Photo'); ?></legend>
        <?php
            echo $this->Form->input('account_id', array('type'=>'hidden'));
            //echo $this->Form->input('filename', array('type'=>'hidden'));
            echo $this->Form->input('filename', array('type' => 'file', 'label' => 'Upload photo'));
            echo $this->Form->input('desc');
            echo $this->Form->input('Tag' , array('label'=>'Tags', 'multiple'=>'checkbox'));

        ?>
        </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>

While the Cakephp documentation on Saving Data makes references to how the array should be formatted, this appears to refer to all of the other relationships excluding HABTM.  HABTM relationships can be saved in one action with the save on the parent model, in this case the Photo model eg:
   $this->Photo->save($this->request->data)

will save the new Photo being added, plus any of the selected Tags, and they will be saved in the join table photostags.
What is a bit unusual, is that $this->Photo->save($this->request->data) appears to work same as $this->Photo->saveAll($this->request->data).


Generating test cases to abuse a BNF grammar automagically

Question: I am wondering if there is a tool or technique which, given a BNF grammar, adjusts it randomly(but intelligently) and generates a stream of output for use in detecting cases that slip past the BNF (but shouldn't).
edit: Fuzz testing a parser, in other words.
Thanks
Answer: Spending some tender time with Google, I found that automated grammar-based fuzz testing is hard, and a subject of current research. In particular, P. Godefroid at Microsoft Research is working on a piece of software called SAGE.
I dug up a research paper by him.
Automated Whitebox Fuzz Testing (joint work with Michael Y. Levin and David Molnar) Proceedings of NDSS'2008 (Network and Distributed Systems Security), pages 151-166, San Diego, February 2008.
I also found the XML-based Peach software, but it is unclear to me on a casual reading how I might leverage it in an afternoon of work for a non-security application.
So my conclusion is: "It's a subject of current (Apr '10) research and there's no quick-use tool out there".
Answer: Not strictly a BNF fuzzing tool, but american fuzzy lop employs artificial intelligence methods and can walk around the lack of BNF knowledge quite well. It already found bugs in many open source parsers, so it might be the right tool for yours as well.


Is there a name for this kind of number?

Question: A perfect number is a number that is the sum of its proper divisors:
$$28 = 1 + 2 + 4 + 7 + 14$$
Is there a name for numbers whose only proper divisors are $1$, $2$, and $N/2$? For example
$6$ is divisible by $1$, $2$, and $3$
$8$ is divisible by $1$, $2$, and $4$
$34$ is divisible by $1$, $2$, and $17$
Is there a name for these numbers?
Comment: Also known as "twice a prime, or 8".
Comment: I suppose 8 is twice a prime in the sense of Grothendieck (the same sense in which 57 is prime).
Comment: I guess you would call them even semiprimes, or 8. http://en.wikipedia.org/wiki/Semiprime
Answer: Aside from 8 and arguably 2, these are the even semiprimes, Sloane's A100484.


Como verificar se a url é verdadeira

Question: Fiz esse código simples para codificar urls, mas gostaria de que ele funcionasse apenas com url verificando se o protocolo e o hostname estão corretos ou se o link magnético está correto:
http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:  //url magnético

function codificar() {
    var valor = document.getElementById("teste").value;
    var encode = window.btoa(valor);

    document.getElementById("saida").innerHTML = encode;
}

Clique no botão para codificar a url.

<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>

<textarea style='width:150px; resize: none;' id="saida"></textarea>
Comment: Você quer verificar se as `url` possuem os padrões que você citou?
Comment: Sim exatamente isso
Answer: Você pode estar verificando se suas strings pertencem a um padrão utilizando regex. Segue um exemplo de uma er (expressão regular) e como ficaria seu uso:
  var re = new RegExp("^((http(s?):\/\/(www.)?[a-z]+.com\/)|(magnet:\?xt=urn:btih:))")

  var term = "http://www.exemplo.com/"

  if (re.test(term)) {
    alert("Valid");
  } else {
    alert("Invalid");
  }

Da forma que essa er foi construida, ela irá aceitar qualquer string que comece com esses padrões:
http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:

Ou seja, se tiver esse padrão no inicio da string, qualquer coisa que estiver depois do .com/ nos casos da url e de btih: no caso do magnet link, ele irá aceitar. Como por exemplo:
http://www.exemplo.com/qualquercoisaaquiassim/?-thiagorespondeu

Answer: Você pode usar esse código completo abaixo caso precise de .net .org .xyz etc.. e está funcionando perfeitamente com o url magnético. Ele vai verificar a expressão, caso seja inválida irá retornar uma alerta.
Caso precise adicionar ftp adicione aqui (ftp|http|https), o "| ou ||" é o operador logico correspondente a ou.

function codificar() {
 var reg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?|magnet:\?xt=urn:btih:/
 var valor = document.getElementById("teste").value;
 var encode = window.btoa(valor);

 if (reg.test(valor)) {
  document.getElementById("saida").innerHTML = encode;
 } else {
  alert("Url Invalido");
 }
}

Clique no botão para codificar a url.

<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>

<textarea style='width:150px; resize: none;' id="saida"></textarea>

Como verificar se a url é verdadeira


Sync Framework -When is tombstone updated?

Question:
I use SQL Server 2014 for all databases and Sync Framework 2.1 in all layers.
The weird thing is suddenly records are deleted from somewhere without user interaction. I thoroughly suspect that this happens due to synchronization but cannot figure it out. I know when the tombstone is set to 1, records will treated as deleted hence the record is deleted. How could this deletion may happens? Please help me with this.
Answer: the tracking tables (records what has changed) are updated via triggers on the table you're synching. so the deleted flag will only get set if someones delete a row that you're synching. you may want to check other apps/user accessing your database who may be potentially deleting rows.
Comment: thank Junet, this deleting happens on a specific data set which were inserted by executing a SQL script in Branch 1. I found that ,these set of data (about 200 records) are not synced to any other Branch also (no records in Tracking tables in other Branches) , and if any update done in Branch 1, when the sync starts, it tries to delete the updated record.
Comment: @user1220497 Did you find the solution, we have encountered same issue.


How to populate an Object[] with items

Question: I'm trying to use a Swing Dialog so that the user can choose an item from a list of options with poolTeams being the name of that list. Like this:
String team = (String)JOptionPane.showInputDialog(frame, "Please choose a team:\n",
    "Choose Team", JOptionPane.PLAIN_MESSAGE, null, poolTeams, "");
According to the documentation, poolTeams needs to be of type Object[] so I can't use ArrayLists or anything like that.
The problem is; the items in poolTeams will vary so I can't just populate it like
Object[] poolTeams = {"a", "b", "c"};
Is there a way I can make the program populate it automatically? If not, is there a different way I can offer the user a list in the dialog box?
Thanks!
Answer: List<Object> options = new ArrayList<Object>();

options.add(...);
options.add(...);
options.add(...);
Object [] selections = options.toArray()

Answer: You can very easily turn an ArrayList to an array using the toArray() method. Build up your ArrayList, then turn it into an array when you need it.

How to populate an Object[] with items


Finding correlation of Max and Min of two IID random variable in U[0,1]

Question: I have a hw problem and can't figure out how to do it. Basically, $X,Y$ are iid $U[0,1]$, we need to find the correlation between max$(X,Y)$ and min$(X,Y)$. My thought is to find the pdf of $U=$max$(X,Y)$ and $V=$min$(X,Y)$ and then find pdf of UV and use the definition of Variance to find the correaltion. But this seems way to substantial to do. I wonder if there is some simpler method.
Comment: "Find the PDF of U=max(X,Y) and V=min(X,Y) and then"... compute E(UV), E(U) and E(V).
Answer: Let $W=\max\{X,Y\}$ and $Z=\min\{X,Y\}$. We can write the following:
$$
F_W(w)=P(\max\{X,Y\}\le w)=P(X\le w \text{ and } Y\le w)=w^2 \\
F_Z(z)=P(\min\{X,Y\}\le z)=1-P(X\ge z \text{ and } Y\ge z)=1-(1-z)^2
$$
Now, you can compute, e.g.
$$
E[W]=\int_0^1w(2w)\, \mathrm{d}w = \frac{2}{3}\\
E[W^2]=\int_0^1w^2(2w)\, \mathrm{d}w = \frac{1}{2}\\
\sigma_W=\sqrt{E(W^2)-[E(W)]^2}=\sqrt{\frac{1}{2}-\frac{4}{9}}=\sqrt{\frac{1}{18}}
$$
(and similarily for $Z$). The last piece is to figure out $\mathop{cov}(W,Z)$:
$$
\mathop{cov}(W,Z)=E[WZ]-E[W]E[Z]
$$
where $E[WZ]=\frac{1}{4}$ (why??).
Now you can finish the calculation:
$$
\rho(W,Z)=\dfrac{E[WZ]-E[W]E[Z]}{\sigma_W \sigma_Z}=\dfrac{1/4-(1/3)(2/3)}{(1/\sqrt{18})(1/\sqrt{18})}=\dfrac{1}{2}.
$$
Here are the useful shortcuts - think a little about why they should hold:

$E[W]+E[Z] = 1$
$\sigma_W^2=\sigma_Z^2$
$E[WZ] = 1/4$
Comment: Any reference textbook for the useful shortcuts?
Answer: Here is a possible answer that avoids using calculus (as it is always asked in some quant interviews, calculus would introduce heavy calculations).
Following @baudolino's notations, we also define $W=\max\{X,Y\}$ and $Z=\min\{X,Y\}$. Then, by symmetry, we have $E[W] = E[W-Z] = 1-E[W]-E[Z]$.
Also note that $E[W] + E[W-Z] + 1-E[W]-E[Z] =1$. Thus, $E[W] = \frac{1}{3}$ and $E[Z]= E[W] + E[W-Z] = \frac{2}{3}$.
In terms of $E[W^2]$, also by symmetry, $E[W^2] = E[1-Z^2]$.
Note that, $E[W^2]+ E[W^2-Z^2] + E[1-Z^2]=1$, and
$E[W^2-Z^2] = E[(W+Z)(W-Z)]$, implying
$E[(W+Z)(W-Z)] = E[(X+Y)(|X-Y|)] = \frac{1}{2}E[X^2-Y^2|X>Y]+\frac{1}{2}E[Y^2-X^2|X<Y] = 0$. The last equation is also by symmetry.
Thus, $2E[W^2]=1$, $E[W^2] = E[Z^2]=\frac{1}{2}$.
Finally,  $E[WZ] = E[XY] = E[X][Y]= \frac{1}{4}$. The last equation is by the independent of X and Y.
Putting what we obtained above into the definition of corrlation, we have
$\rho(W,Z)=\dfrac{E[WZ]-E[W]E[Z]}{\sqrt{E[W^2]- E[W]^2}\sqrt{E[Z^2]- E[Z]^2}} = \frac{1}{2}$.


connect a mac or windows pc to a eon612 speacker

Question: I have a eon612 speaker and I would like to have it play tracks from my PC windows pc 3.5mm jack.
Do I need an amplifier between the pc and eon612? Is there a low cost solutions? can it be done with a simple ts to xlr cable.
Answer: In1 and In2 on the eon612 are dual XLR/jack sockets.  So use the jack option.  Switch the Mic/Line selector to Line.
You need a cable with a stereo 3.5mm jack on one end, two mono 1/4" jack plugs on the other.    You might find this easier to arange with a stereo 3.5mm jack to two phono plugs cable, plus a couple of phono to jack adapters.   Your eon612 is a powered system, so no further amplificxation is needed.


Scala: How to create a new list from operation on adjacent elements of a list

Question: If I have a list like List(1,2,3,4), I want to create a new list that will be equivalent to,
List(1+2, 3+4) = List(3,7)
I need some opeartion to add adjacent numbers in a list and create new list from it. I looked at map, reduceLeft, foldLeft operations but could not find something that would accomplish this.
Answer: The method you're looking for is grouped, which partitions the list into sublists of a given size. For example:
scala> List(1, 2, 3, 4).grouped(2).map(_.sum).toList
res0: List[Int] = List(3, 7)

Note that grouped returns an iterator, so you need to call something like toList if you want a collection. Also note that if your list doesn't have an even number of elements (or more generally isn't evenly divisible by the argument to grouped), the final list returned by the iterator may contain fewer elements than the rest.


Trouble using qt function for P(-t<x<t)

Question: I have found very little information regarding this. I am new to statistical analysis and Rscript, so I am having trouble getting this to.
I am trying to find t for P(-t<X<t) = 0.96 where X ~t(11) using the qt function
I've gone and found P(X<t) which gave me 1.928427, qt(0.96,11) but when I try to find P(x<-t) I get NaN. (I'm trying to solve 1-P = P(x<-t) and then find the difference from P(X<t) and P(X<-t)
Am I approaching this from the wrong way all together?
Answer: The t(11) distribution is symmetric, so you just need to find the point where half your probability lies below the lower threshold. For example
t <- abs(qt((1-0.96)/2, 11))
t
# [1] 2.32814

And you can verify that give the correct answer with
# P(T < t) - P(T < -t)
pt(t, 11) - pt(-t, 11)
# [1] 0.96

Comment: Well, since you are doing `P(-t<X<t)`, then `t` needs to be positive.
Comment: Thanks, this helped me understand a lot better. Just wondering, why are we using the absolute function here? Is it because t can't be a negative value?

Trouble using qt function for P(-t<x<t)


Como referenciar variável de instância com mesmo nome de uma variável local em C++?

Question: Em C++, como eu posso referenciar uma variável de instância que tem o mesmo nome que uma variável global? Por exemplo, em um método set da seguinte classe:
class Person
{
private:
    string name;

public:
    void setName(string name)
    {
        //Em java eu faria: this.name = name;
    }

    string getName()
    {
        return name;
    }
};

Comment: Com `this->name ` https://stackoverflow.com/q/6779645/4438007 ; `this` é um ponteiro para o objeto atual
Comment: Exatamente como o @JeffersonQuesado disse, `this->name = name;`
Answer: Em C++, existe a palavra chave this. Ela é reservada para contextos em que um objeto está tendo seu método sendo executado.
Esse this se comporta como uma constante, constante essa que é um ponteiro da classe de onde o método está sendo executado. Claro, precisa ser um método de instância, métodos estáticos não podem referenciar ao próprio objeto.

Para ser mais exato, this é um prvalue

Na verdade, toda referência a um método de instância ou atributo dentro do objeto é tratado como tendo uma chamada implícita para this->. No seu exemplo:
string getName()
{
    return name;
}

Se usado de modo totalmente explícito ficaria:
string getName()
{
    return this->name;
}

Entre outras funções, chamar explicitamente o this serve para desambiguar. Por exemplo, no seu setter, há um parâmetro chamado de name, nome de parâmetro esse que "joga uma sombra" sobre a variável de instância name.

Em inglês, diz-se que "the parameter shadows the member with the same name"

Para resolver essa situação, pode-se usar usar o this de modo que fique tudo não ambíguo:
void setName(string name)
{
  this->name = name;
}

(Anti-)Padrões C++ de nomenclatura
Devido a problemas desse tipo, algumas escolas de C++ pregam que variáveis de instância devem começar com "_". Então se usaria _name para a variável e name para o parâmetro. De modo geral, seu código ficaria assim (se fosse seguir as diretrizes dessa escola):
class Person
{
private:
    string _name;

public:
    void setName(string name)
    {
        _name = name;
    }

    string getName()
    {
        return _name;
    }
};

Eu particularmente acho essa saída pragmática mas feia. Não usaria ela.
Outro uso seria em construtores; para o caso de Person ter um construtor que receba como argumento uma string referente ao nome:
Person::Person(string name) {
  _name = name;
}

Porém esse estilo de codificação não usa os recursos mais elegantes do C++ para se construir objetos.
Usando inicializador no construtor
Saindo do mundo em que há "_" antes do nome das variáveis internas, você pode muito bem usar inicializadores no construtor. Por exemplo, no construtor que receba uma string e inicializa o atributo name do objeto:
Person::Person(string name) : name(name) {
}

Nessa sintaxe, o atributo name é inicializado com o valor entre parênteses, que nesse contexto é o parâmetro name. De modo geral, esse inicializador pode ser entendido mais ou menos assim:
<assinatura construtor> : <atributo> ( <valor de inicialização> )

Onde:

<assinatura construtor> é a assinatura do construtor (Person::Person(string name))
<atributo> é o nome do atributo que será inicializado (o primeiro name, que vem antes dos parênteses)
<valor de inicialização> é o valor que será atribuído ao atributo (no caso, o name dentro dos parênteses, que corresponde ao parâmetro do construtor)

Algumas fontes adicionais de pesquisa:

essa pergunta no SOen
essa resposta do @Maniero


java.lang.NoClassDefFoundError - Generating Executable Jar

Question: I have created my JAR on Windows 2000 having java version 1.5 which contains following directories/files:

manifest.txt
com
lib

lib contains all JARS which I want to make part of my JAR. com contains my class files and below is manfiest.txt file
Main-Class: com.as.qst.result.ResultTriggerSchedular
Class-Path: lib/axis.jar lib/c3p0-0.9.1.1.jar lib/commons-discovery-0.2.jar lib/commons-logging-1.0.4.jar lib/jaxrpc.jar lib/log4j-1.2.16.jar lib/medplus-hub-8.2-wsclients.jar lib/medplus-hub-13.1-jaxws-clients.jar lib/quartz-2.2.1.jar lib/quartz-jobs-2.2.1.jar lib/saaj.jar lib/slf4j-api-1.6.6.jar lib/slf4j-log4j12-1.6.6.jar lib/ wsdl4j-1.5.1.jar lib/xercesImpl.jar com\as\qst\result

I used following command to generate my JAR
  jar cvfm test.jar manifest.txt com lib

It has successfully created a JAR file but when I try to run it with
java -jar test.jar

it does not execute and throws above exception. I used the same process for Windows 7 which has version 1.7 and it did work out even without class files path in manifest.txt com\as\qst\result. Is something more to do with class-path besides defining in manifest? and why is it working in Windows 7?
Comment: where is the exception trace?
Comment: It throws exception as `Exception in thread "main" java.lang.NoClassDefFoundError: com/ad/qst/result/ResultTriggerScehdular`, nothing else
Comment: Did you copy and paste that or retype it? Because it has multiple typos.
Comment: Can you try "./" before lib and let us know if that works
Comment: sure but it is even unable to find my main class...
Comment: Shouldn't be the file called MANIFEST.MF, all uppercase, and this file should be stored inside META-INF folder inside your jar?
Comment: @Hirak it didn't work.
Comment: @Luiggi Mendoza when I opened my jar this hierarchy of manifest file was created by tool.
Answer: You do not need the class file path in your class path entry. So instead of adding com\as\qst\result to your class-path.
More over you must not package other jar files in your runnable jar.
Other required jars must be provided in the same folder as your jar file (may be in separate folder) and Add current directory "." (without quotes) to your class-path.
Hope this helps.
EDIT
Just found this Stackoverflow Link. This might give you more insight. Please read through it.
Comment: I did change my class-path to add `./` to all jars and not package these jars to my jar. but it still gives same exception. I read link too which says that when main class name in manifest was completed, at least tool was able to find main class which is not happening in my case. It will read others jar after finding my main class.
Comment: did you add current directory to your class-path?


How to remove the gradle nested dependancies, where child and siblings are same

Question: I have few dependancies in my project where Child library is same as the sibling library. How do I remove the child? for e.g

compile - Dependencies for source set 'main'.
\--- org.springframework.security:spring-security-config:3.1.3.RELEASE
     +--- org.springframework.security:spring-security-core:3.1.3.RELEASE
     |    \--- aopalliance:aopalliance:1.0
     \--- aopalliance:aopalliance:1.0

So How can I remove/exclude "--- aopalliance:aopalliance:1.0" who is there asa child element of "org.springframework.security:spring-security-core:3.1.3.RELEASE" in the tree
Answer: Once you know the dependencies you need (presumably using gradle dependencies), you can manage your own by setting transitive to false:
apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.springframework.security:spring-security-config:3.1.3.RELEASE'
    compile 'org.springframework:spring-core:3.0.7.RELEASE'
    compile 'aopalliance:aopalliance:1.0'
}

configurations.compile.transitive = false

For example:
$ gradle dependencies
compile
+--- org.springframework.security:spring-security-config:3.1.3.RELEASE
+--- org.springframework:spring-core:3.0.7.RELEASE
\--- aopalliance:aopalliance:1.0