Preencher os parâmetros do Array args sem sair do Eclipse

Question: Eu possuo parâmetros que são passados ao executar o .jar do meu código, em args, como nesse exemplo:
public static void main(String[] args) {
        final File diretorio = new File(args[0]);
        final String extencao = "." + args[1];
        final String origem = "\\"+args[2];
        final String destino = "\\"+args[3];

Quero saber se é possível eu definir os valores que estou passando na linha de comando pelo o Eclipse, sem precisar alterar os valores das variáveis ou chamar separadamente pelo console.
Answer: Conforme retirado desta resposta, as instruções abaixo é para o caso de você já ter executado sua classe que possui o método main ao menos 1 vez dentro da IDE:

No menu, clique em Run , depois em Run Configurations.... Vai aparecer uma tela semelhante a esta:

na lista suspensa na lateral, procure pelo nome da sua classe que quer passar parâmetros no main, no meu caso, é a classe que já está selecionada, MainParametrosTest.

clique na guia Arguments e aparecerá conforme o print abaixo:

No campo Program Arguments, você irá inserir os argumentos que quer passar para o main da sua classe separados por um espaço.
Veja o exemplo abaixo, onde passei argumento1 argumento2 argumento3:
Comment: Muito obrigado, deu certo.


Not defined Or zero

Question: let's say we play a game 9 times and I was asked to find the probability of $F_K$ which means the probability to succeed only at the $k^{th}$ try.
What can I say about $F_K$ for $k<0$ or $k>9$ is it 0 or not defined?
My professor said only one is true but I forgot which one of them and why is that.
Comment: What would it mean to say you first succeeded on the $-3^{rd}$ trial?
Comment: that's what I am asking is it 0 or not defined?
Comment: Well, if you can't say what it means then it is undefined.  By contrast, $F_{43}$ is perfectly well defined.  It is the probability that you lose the first $42$ games and win on your $43^{rd}$ attempt.
Answer: The probability that rolling a single standard die produces a $7$ is $0$. More generally, the probability of an impossible event is $0$. It may however depend on local definitions on what an event is in the given context.
In short, we consider a set of outcomes and an event is a subset of the set of outcomes. For a die, we may let $\{1,2,3,4,5,6\}$ be the set of outcomes and the events "the roll is a six" and  "the roll is an odd number" then are the subsets $\{6\}$ and $\{1,3,5\}$, respectively. Is "the roll is a seven" an event? As stated, it certainly is not $\{7\}$ as this is not a subset of $\{1,2,3,4,5,6\}$. But just as "the roll is odd" was interpreted as $\{1,3,5\}$ and not as $\{1,3,5,7,8,11,\ldots\}$, it is then correct to state that "the roll is a seven" is the empty event $\{\}$. As such it has probability $0$.
Alternatively, we could allow $7$ (and other values) as outcomes but with individual probability $0$. The result would not change - "roll is seven" now becomes the event $\{7\}$ but still has probability $0$.
With this philosophy in mind, the event "succeed only at $k$th try" for some impossible $k$ (negative, too big, not even an integer, ...) is an impossible event and hence has the (defined) probability $0$.

Not defined Or zero


When I try to dynamically load a div, all the classes and ids aren't registering, even with .on

Question: EDIT: REQUESTED MORE CODE:
In my index.html  tags, it contains two divs:

  blabla

Then my java-cheatsheet.html contains:

Java Cheat Sheet

    <input type="button" value="Show Keywords" id="keywordButton">

 To help with remembering, some keywords will be hidden. Simply click or tap the box to reveal the
        important keyword(s). e.g. There are eight bits in a byte. Disable/Enable all the
        hidden words by tapping the button at the top right.

I then have a bunch of code, that is tested and works properly, if I push on the button(with an id of "keywordButton"), it either reveals or hides ALL the span elements with a class of "answer", but if you click on a specific span, it will hide/show that and only that word. This is fully functional on its own. But if I try using this (in my custom.js file):
$("#javaCheatSheet").click(function () {
    $("#java-cheatsheet-placeholder").load('../java-cheatsheet/javaSummary2.html');
    $("#index-banner").hide();
});

it loads the data, but clicking the button or the spans NO longer works, unless I also add

in my java-cheatsheet.html file at the bottom. I of course don't want to do this, and would rather have .on() working with jquery, but if I try what most people have suggested:
$("#javaCheatSheet").on('click', '#keywordButton, .answer', function () {
    $("#java-cheatsheet-placeholder").load('../java-cheatsheet/javaSummary2.html');
    $("#index-banner").hide();
});

it doesn't even load the html into index.html at all >_>.
Comment: Read about [`Event delegation`](https://learn.jquery.com/events/event-delegation/)
Comment: The HTML code you provided in the fiddle is incomplete. For example, there is no `#javaCheatSheet`. Also, please copy your fiddle into a Stackoverflow code snippet
Comment: I have updated my post
Answer: You haven't added jquery. With jquery your code works fine.

see below.

var toggleColorNotVisible = "rgb(0, 0, 0)";
var toggleColorVisible = "rgb(0, 0, 0)";
var backgroundColorVisible = "rgb(255, 255, 255)";
var showAnswersButton = false;

$(document).on('click', '#keywordButton', function() {
  if (showAnswersButton) {
    $(".answer").css("color", toggleColorNotVisible);
    $(".answer").css("background-color", toggleColorNotVisible);
    $(".answer").each(function() {
      this.hideAnswers = false;
    });

  } else {
    $(".answer").css("color", toggleColorVisible);
    $(".answer").css("background-color", backgroundColorVisible);
    $(".answer").each(function() {
      this.hideAnswers = true;
    });
  }
  showAnswersButton = !showAnswersButton;
});

$(document).on('click', '.answer', function() {
  console.log("LOL")
  this.hideAnswers = this.hideAnswers || false;

  if (this.hideAnswers) {
    $(this).css("color", toggleColorNotVisible);
    $(this).css("background-color", toggleColorNotVisible);
  } else {
    $(this).css("color", toggleColorVisible);
    $(this).css("background-color", backgroundColorVisible);

  }
  this.hideAnswers = !this.hideAnswers;
});
.answer {
  font-weight: bold;
  color: #000000;
  background-color: #000000;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
#keywordButton {
  position: fixed;
  top: 10%;
  right: 1%;
  opacity: 0.9;
}

<input type="button" value="Show/Hide Keywords" id="keywordButton">

 Intro

Stuff

To help with remembering, some keywords will be hidden. Simply click or tap the box to reveal the important keyword(s). e.g. There are eight bits in a byte. Disable/enable using button for all!
Comment: I definitely did. I think it might have something to do with materializecss?
Comment: I should say, I most certainly did in my .html, and have been using it quite a bit. On the jsfiddle I didn't. I'm very confused why this isn't working with materializecss framework, I feel like it shouldn't matter.
Comment: Yeah I know I corrected myself, apologies, but with jsfiddle I can't have two HTML files regardless, and the issue is once I call the load, the .click methods don't even fire, because it seems that they don't identify the new added class and id in the body of index.html, which was taken from tutorial.java
Comment: Then use with $(document).on('click', '#button', callback); It should work.
Comment: Could you elaborate on how to use ^, meaning, do I use the callback, or what is #button? I have an id and a class element.
Comment: @VDog your #keywordButton button, see the code snippet.
Comment: @Prs unfortunately that didn't work, it's simply not firing >_>
Answer: Is this what you were looking for?
$("#javaCheatSheet").on("click", "#keywordButton, .answer", function () {
    $("#index-banner").load('../java-cheatsheet/javaSummary2.html');
});

Edit:
$("#java-cheatsheet-placeholder").on("click", "#keywordButton, .answer", function () {
    // Show/hide answers here
});

Comment: Yeah, that's what I wanted to do, but unfortunately when I did this it didn't generate the dynamic code, nor cause any errors. But if I removed the "#keywordButton, .answer" part, it generated the html, but the main issue remained, where .answer and #keywordButton did nothing on click :(
Comment: @VDog You should show us more of your HTML/JS code.
Comment: You got it, I just updated my post providing much more detail, thank you!
Comment: @VDog Have you tried something like this? (edited answer)


Is there a function to create a new column over two columns?

Question: I have the following reservation data:

Site
Reservation
Arrival
Departure
Category

AIRBNB_1
1234
2023-01-01
2023-01-02
GUEST

AIRBNB_1
1234
2023-01-02
2023-01-03
GUEST

AIRBNB_1
1234
2023-01-03
2023-01-07
OWNER

AIRBNB_2
5678
2023-01-15
2023-01-17
GUEST

AIRBNB_3
9123
2023-02-01
2023-02-02
COMP

I need to add a new "Umbrella Category" that takes into account the Category column across the Site + Reservation.

Site
Reservation
Arrival
Departure
Category
Umbrella Category

AIRBNB_1
1234
2023-01-01
2023-01-02
GUEST
OWNER

AIRBNB_1
1234
2023-01-02
2023-01-03
GUEST
OWNER

AIRBNB_1
1234
2023-01-03
2023-01-07
OWNER
OWNER

AIRBNB_2
5678
2023-01-15
2023-01-17
GUEST
GUEST

AIRBNB_3
9123
2023-02-01
2023-02-02
COMP
COMP

Unfortunately, I cannot group because I need all records. Is there a function or possible partition that would allow me to assign an umbrella category based on the category column? I have the below query, but it doesn't allow me to take into account Site + Reservation columns (which is needed because the first three lines are one reservation. Any insight is much appreciated.
select
    [Site],
    Reservation,
    Arrival,
    Departure,
    Category,
    case
        when Category in ('GUEST', 'OWNER') then 'OWNER'
        when Category in ('OWNER', 'COMP') then 'OWNER'
        when Category in ('GUEST', 'COMP') then 'GUEST'
        else Category end as [Umbrella Category]
from #Reservations

Comment: Your posted `CASE WHEN...` logic does not correspond to your expected-results: when will `COMP` be returned? Why are you checking for `'OWNER'` twice?
Comment: I believe I understand your logic. Essentially you want to look at a group/partition of records that share the same `site` and `reservation` and then if that group has both `GUEST` and `OWNER` categories, then the umbrella is `OWNER`. Please confirm if that is correct.
Comment: _"Unfortunately, I cannot group because I need all records"_ - you can, just use a CTE.
Comment: Please explain the structure and contents of your `#Reservations` table. Your post suggests that the `#Reservations` table is denormalized - if so, please describe the normalized source data (and if you can, or cannot, just reference that directly). Also, may I ask why you are using a `#TemporaryTable` here?
Comment: It's a large table, thus the reason I created a small temp table to demonstrate some example records/scenarios. In the case of owner, there is a priority which owner wins if that category is listed with any other category. Does that make sense? And to answer the comp question, it would only be comp if the reservation is a single line with a category = comp.
Comment: BAsed on your last comment, would it be safe to say that in a group/partition of records that `Owner` wins over `Guest` and `Comp`, and that `Guest` wins over `Comp` and then `Comp` only wins when it's by itself?
Comment: I think the real problem here is that your `#Reservations` data is denormalized, which is why you're having problems trying to work with it - is there any way you can get _normalized_ data, with actual primary-keys?
Comment: My apology! When I was building the table in my original post, I forgot to update the arrival/departure dates! No wonder it was confusing. If you look at reservation 1234, it's actually a single reservation (likely because the owner had two friends who stayed one night each). Hopefully that makes sense.
Comment: JNevill, you got it!
Comment: It's a strange schema, but yes you can use window queries with partitioning, by the reservation value. The problem is in the ordering and the concept of "Umbrella" Why does "OWNER" win over "GUEST" and "COMP"? In this case we can use a simple sort, but ideally your `Category` should represent a lookup in another table that provides metadata or a specific value to determine the correct lookup logic.
Answer: From your sample data it looks like you could simply use a windowed aggregate of categories:
select *, Max(category) over(partition by Site, Reservation) Umbrella_Category
from #Reservations;

Answer: Consider a new table to hold the ranking of your categories so you can determine which category wins in a group/partition:
category:
+----------+------+
| category | rank |
+----------+------+
| OWNER    |    1 |
| GUEST    |    2 |
| COMP     |    3 |
+----------+------+

Then you can join to this to get your umbrella rankings:
SELECT
    res2.Site,
    res2.Reservation,
    res2.Arrival,
    res2.Departure,
    res2.Category,
    cat2.Category as Umbrella
FROM
   (
      SELECT cat.Site,
        cat.Reservation,
        cat.Arrival,
        cat.Departure,
        cat.Category,
        MIN(res.rank) OVER (PARTITION BY Site, Reservation) as Umbrella_cat_rank
      FROM Reservations res
       INNER JOIN categories cat
          ON res.Category = cat.category
   ) res2
   INNER JOIN category cat2
       ON res2.Umbrella_cat_rank = cat2.rank

While the SQL is a bit more involved with the subquery and two joins, this gives you a lot of flexibility if in the future you add more categories or need to change ranks. You merely INSERT/UPDATE into your category table as needed and this sql will bring back the correct umbrella category.
Comment: I like this a lot! Thank you!
Answer: Try the following:
SELECT
    [Site],
    Reservation,
    Arrival,
    Departure,
    Category,
    MAX(CASE
            WHEN Category IN ('GUEST', 'OWNER') THEN 'OWNER'
            WHEN Category IN ('COMP', 'OWNER') THEN 'OWNER'
            WHEN Category IN ('GUEST', 'COMP') THEN 'GUEST'
            ELSE Category
        END) OVER (PARTITION BY [Site], Reservation) AS [Umbrella Category]
FROM
    #Reservations

Comment: This is not a good example of `CASE`. `WHEN`...`IN` is only good for mutually exclusive groups, in this case all `'COMP'` values will be converted to `'OWNER'` and all `'GUEST'` values will also be converted to `'OWNER'` making all records `'OWNER'`. This answer therefor confuses people about how `CASE` in a window query works.
Answer: My approach performs the GROUP BY in a CTE (grouped) and each group is examined in a second CTE (umbrellaCategories), where the "Umbrella Category" values are determined exhaustively from separate filtered COUNT expressions in a single CASE... expression. The advantage of this approach is that if the source-data contains unexpected rows (e.g. 2 or more 'COMP' rows for a single Site+Reservation) then that can be explicitly detected and handled, if necessary:
DBFiddle link.
/*
CREATE TABLE reservations (

  Site        nvarchar(50) NOT NULL,
  Reservation int          NOT NULL,
  Arrival     date         NOT NULL,
  Departure   date         NOT NULL,
  Category    nvarchar(50) NOT NULL
);

INSERT INTO reservations ( Site, Reservation, Arrival, Departure, Category ) VALUES
( 'AIRBNB_1', 1234, '2023-01-01', '2023-01-02', 'GUEST' ),
( 'AIRBNB_1', 1234, '2023-01-02', '2023-01-03', 'GUEST' ),
( 'AIRBNB_1', 1234, '2023-01-03', '2023-01-07', 'OWNER' ),
( 'AIRBNB_2', 5678, '2023-01-15', '2023-01-17', 'GUEST' ),
( 'AIRBNB_3', 9123, '2023-02-01', '2023-02-02', 'COMP'  );
*/

WITH grouped AS (

  SELECT
      r.Site,
      r.Reservation,
      COUNT( * ) AS CountRows_All,
      COUNT( CASE r.Category WHEN 'OWNER' THEN 1 END ) AS CountRows_Owner,
      COUNT( CASE r.Category WHEN 'GUEST' THEN 1 END ) AS CountRows_Guest,
      COUNT( CASE r.Category WHEN 'COMP'  THEN 1 END ) AS CountRows_Comp,
      COUNT( CASE WHEN r.Category <> 'OWNER' THEN 1 END ) AS CountRows_NonOwner,
      COUNT( CASE WHEN r.Category NOT IN ( 'GUEST', 'OWNER', 'COMP' ) THEN 1 END ) AS CountRows_Other
  FROM
      reservations AS r
  GROUP BY
      r.Site,
      r.Reservation
),
umbrellaCategories AS (

    SELECT
      g.Site,
      g.Reservation,

      CASE
          /* "owner wins if that category is listed with any other category" */
          WHEN g.CountRows_Owner > 0 AND g.CountRows_NonOwner > 0 THEN 'Owner'
          /* " it would only be comp if the reservation is a single line with a category = comp" */
          WHEN g.CountRows_Comp = 1 AND g.CountRows_All = 1 THEN 'Comp'
          WHEN g.CountRows_Guest > 0 THEN 'Guest' ELSE 'Other'
      END AS "Umbrella Category"
    FROM
      grouped AS g
)
SELECT
    r.Site,
    r.Reservation,
    r.Arrival,
    r.Departure,
    r.Category,
    uc."Umbrella Category"
FROM
    reservations AS r
    INNER JOIN umbrellaCategories AS uc ON
       r.Site = uc.Site
       AND
       r.Reservation = uc.Reservation
ORDER BY
    r.Site,
    r.Reservation;

Gives me these results:


Show that $K(\sqrt{2\sqrt{2}-1})$ is a degree $4$ Abelian extension of $K=\Bbb Q (i\sqrt{14})$

Question: I have to show that $K(\sqrt{2\sqrt{2}-1})$ is a a degree $4$ Abelian extension of $K=\Bbb Q (i\sqrt{14})$.
Now, $a=\sqrt{2\sqrt{2}-1}$ has minimal polynomial $f(x)=x^4+2x^2-7$ over $\Bbb Q$, which can be checked. I have to show that that $f$ is irreducible over $K$ and that the extension is normal. Then it'll follow that it's Galois and hence Abelian since it has degree 4. WolframAlpha tells me that the roots are $\pm \sqrt{2\sqrt2-1},\pm i\sqrt{2\sqrt{2}+1}$. So, the field is also normal as $\alpha \in L \implies \sqrt{2} \in L$ and then $i\sqrt{2\sqrt{2}+1} = {i\sqrt{14} \over \sqrt{2} \alpha} \in L$.
Then the only thing left to prove is that $f$ is irreducible over $K$. Please help me out.
EDIT : Writing $K_1=K(\sqrt{2})$, we get that $[K_1:K]=2$ as otherwise $K_1=K$ and $[\Bbb Q{\sqrt{2}}:\Bbb Q]=2=[K:\Bbb Q]$ mean $K=\Bbb Q{\sqrt{2}}$ but that's absurd as $\Bbb Q{\sqrt{2}}$ is real while $K$ is not. So, we'll be done if we can prove that $[L:K_1]=2$. The obvious choice for minimal polynomial is $x^2+1-2\sqrt{2}$ and it'll be enough if we can show that it is indeed irreducible over $K_1$.
Comment: HINT.-$x_0\in K\iff x=a+b\sqrt{-14}$ and $f(x_0)=(a^4-84a^2b^2+196b^4+2a^2-28b^2-7)+i4\sqrt{14}ab(a^2+1-4b^2)$ from which it is impossible that $f(x_0)=0$. Then $f(x)$ has neither a linear factor over $K$ nor a cubic factor. It remains to prove that $f(x)$ it is not a product of two quadratic factor over $K$.

We have that the corresponding splitting polynomial over $\mathbb C$ is $f(x)=(x-\sqrt{1+2\sqrt 2})(x+\sqrt{1+2\sqrt 2})(x-i\sqrt{-1+2\sqrt 2})(x-i\sqrt{-1+2\sqrt 2})$

Can you finish now?
Answer: You have found that $[\Bbb{Q}(a):\Bbb{Q}]=4$. Because $K$ is Galois over $\Bbb{Q}$, we have${}^1$
$$[K(a):K]<4\qquad\Leftrightarrow\qquad[\Bbb{Q}(a)\cap K:\Bbb{Q}]>1,$$
which is of course equivalent to $K\subset\Bbb{Q}(a)$. Now it suffices to check that $\sqrt{-14}\notin\Bbb{Q}(a)$.

1: It is very much worth while trying to prove a general version of this equivalence; draw a diagram and try to prove when exactly the degree of a compositum of fields is precisely the product of their degrees. See also corollary 3.19 on page 41 of Milne's notes, and the diagram there.
Comment: Why is $\Bbb Q(a)$ Galois over $\Bbb Q$? It looks to me that $\Bbb Q(a)$ has two real embeddings and two (conjugate) complex embeddings, thus cannot be Galois over $\Bbb Q$.
Comment: I knew this result, but was overly complicating everything. Thanks.
Comment: @WhatsUp You are right; I meant to write $K$. Corrected now.
Answer: Let $a=\sqrt{2\sqrt{2}-1}, b=i\sqrt{14}$ and then we know that $[\mathbb{Q} (a) :\mathbb{Q}] = 4$ and $[\mathbb{Q} (b) :\mathbb {Q}] = 2$.
If we assume that these fields are subfields of $\mathbb {C} $ then we can observe that $b\notin \mathbb{Q} (a) $ and hence $[\mathbb{Q} (a, b) :\mathbb {Q} (a)] =2$ so that $[\mathbb{Q} (a, b) :\mathbb{Q}] =8$ and thus $[\mathbb{Q} (a, b) :\mathbb{Q} (b)] =4$ and we are done.


duplicate results with pdo

Question: When adding a list of past episodes to my site using this code:
include.php
class rest {
  public function fetch_all(){
    global $pdo;
    $query = $pdo->prepare("SELECT * FROM podcast");
    $query->execute();
    return $query->fetchAll();
  }
}

index.php
$rest = new rest;
$list = $rest->fetch_all();

Past Episodes

<?php foreach ($list as $rest) { ?>

<?php echo $cast['cast_title']; ?>

<?php } ?>

it displays 2 of the same (latest) title and not the 2 separate titles listed in the cast_title field of the database.
Am I missing something?
I sorted this by adding
   <?php foreach ($articles as $feedback) {
if ($feedback['cast'] === $_GET['id']) { ?>

Comment: What is `$cast`. I do not see where this variable is initialized.
Comment: Just a note: `SELECT *`. Do you really need everything, or just the title? `SELECT cast_title` might suffice.
Comment: thank you. changing it to rest. does the job. but how do i get it to list in reverse order?
Comment: What does it print? : `foreach ($list as $cast) { echo '' . $cast; }`
Comment: just the title @AnotherTest
Comment: @kevstarlive then select only the title ;)
Comment: but it does the same job right?
Answer: class rest
{
    public function fetch_all(){
        global $pdo;

        $query = $pdo->prepare("SELECT cast_title FROM podcast ORDER BY cast_title DESC");
        $query->execute();

        return $query->fetchAll();
    }
}

Then template:
<?php
$rest = new rest;
?>

Past Episodes

<?php foreach ($rest->fetch_all() as $rest) { ?>

    <?php echo $rest['cast_title']; ?>
<?php } ?>

Comment: I have used `ORDER BY` clause for sorting. There is a `DESC` order, which means *descendant*, and You can use `ASC` (or none) for *ascending* order. Or You can order by different columns.

duplicate results with pdo


How to secure Cross-Domain request; allowing third website to POST data

Question: I have done some researches on how to prevent fake cross-origin requests and have found a lot of useful information. However, none of them seems to directly resolve my concerns, and because my application has to deal with this specific situation, I would like to understand it completely.
I have a simple php mailing website: mailsite.com
This site will allow other pre-defined addresses, for instance, user.com, to send POST data to it, and process the information that contains to and mesaage; then send them an E-mail from mailsite.com to to with the message message.
Currently, I am using $_SERVER[ "HTTP_ORIGIN" ] and $_SERVER[ "HTTP_REFERER" ] to check where the requests come from; and process them if it is from the pre-defined domains. However, I've read some articles that say:

HTTP_ORIGIN is not even indexed in PHP documentation, because it is pretty much per-browser sort of thing, so browsers that refuse to send those information will not work. HTTP_REFERER is easy to fake.
Tokens are good in preventing CSRF.

However, the request I allow is coming from a third pre-defined website, how does Tokens work in this situation?
My question is: If I allow specific domains to POST data to my site, how can I make sure (or the most secured way) that those requests are coming from the sites I expected? Is HTTP_ORIGIN not even safe enough to use? I dare to think about allowing third website to POST data to my site because I've seen Facebook allowing people to access their database. There must be some possible solutions for checking where the requests come from.
Comment: Yes @GeorgeCummins I too stand corrected. I took it from OP's [`original post`](http://stackoverflow.com/revisions/23576001/1). Had forgotten the underscore.
Comment: I'm sure you meant `$_SERVER[ "HTTP_REFFERAL" ]` right? You made a typo.
Comment: Yes. I am so sorry for the typo. I typed it from my phone. Thanks a lot for pointing it out.
Comment: Do you need to support browsers that don't support CORS? Otherwise not exactly clear what your concerns are...
Comment: @Fred-ii I'm sure you meant [`$_SERVER['HTTP_REFERER']`](http://www.php.net/manual/en/reserved.variables.server.php) right? ;)
Comment: Hi Alexei. I meant that from my PHP server, how do I know exactly which site is sending request to my site? I currently use HTTP_ORIGIN but it was said to not be supported by all browsers; and HTTP_REFERER is fake-able. If there is no way, I am looking for an alternative solution such as sending custom header or something. I am quite new about cross-domain.
Answer: It sounds like you have multiple solutions possible:

Use a token permission system. Give user.com a private token to add as a hidden value to the input form. Upon submitting this form, the browser will give your server the token, and the user shouldn't have to know about the token. You check the token against your own database. If you find the token, allow the mail to be sent.
Use CORS (Cross-Origin Resource Sharing). When an Ajax request is sent to your server from user.com, there should be multiple Access-Control headers. You check if these exist and what their values are using $_SERVER['HTTP_ACCESS_CONTROL_header'] where header is one of the Access-Control header names. If these values match up to your expectations, respond with multiple header('Access-Control-header: value'); calls so that the browser knows you accepted the preflight request, otherwise don't add any extra headers. The browser will send another request after the preflight, and this is when you'll actually send the mail.
If this is being sent from user.com's server rather than a visitor of user.com, most likely the server's IP address won't change (though it may or may not use a defined range of IPs, so be mindful of that.), so you could verify that the $_SERVER['REMOTE_ADDR'] matches a value in your database. You can keep a table of approved IP addresses in your database for this purpose. If you find the IP address in your table, allow the mail to be sent.

Hope this helps.
Comment: About the third point, I think it won't be a good practice to do so, as what if user.com is on a shared hosting?
Comment: Then it gets a bit more tricky. You could keep a table of approved domain names, and then IP addresses for that domain name. Use a script that executes on a cronjob to periodically do lookups on each domain name and map its IPs into your database, removing older entries for that domain that no longer come up in the lookup, and adding any new IPs that the lookup found. When the request comes in, verify against any of those IPs. You can also add in checking the reverse-DNS of that IP, and see if its DNS is in your approved domain names.
Comment: shared hosting = multiple domain single ip.
Comment: Hi Jailout2000. Thank you so much for the answer. Can I have 2 quick questions? 1) User A visits site.com; is the REMOTE_ADDR returns user A's IP or site.com's IP? 2) Only the CORS seems possible for me now, do you have a very quick and basic example of it from the server side? I've looked it up, but it seems to be just a little more than HTTP_ORIGIN, while HTTP_ORIGIN is not really reliable. The HTTP_ACCESS_CONTROL_header is something that can be coded using Javascript, which mean it is vulnerable, doesn't it?
Comment: @user3622260 answer to your first question is: it will return `site.com`'s IP.


Varying ImageView source according to value

Question: I would like to show something similar to a progressbar by using different images, for example an empty lawn if progress = 0 and a nearly complete house if progress = 95.
I have 30 files named image1.jpg .... image30.jpg
Would it be possible to set the Drawable of an ImageView by using a string for the file name? That way I could just get an int between 1 and 30 from the progress and add that to a string that I use to set the Drawable.
I have read this:
Android: Imageview showing an image according to edittext option
but I don't want to write code for every case as I would like to use this function at different places of a project.
I would be very grateful for any help, either on how I can use strings and filenames for the Drawable or if there is another way of solving this.
Best regards,
Emil
Answer: <code>public void setImageSrc(int i){
    final ImageView iv = (ImageView) findViewById(R.id.naviView);
    iv.setImageResource(getResources().getIdentifier("image"+i, "drawable", "com.example"));
}
</code>
You can retrieve the id if you know the name of the resources and then set the image via the id you determined earlier


Horrible Playback Quaility On Reaper (Distorted Sound)

Question: !!! I found an interesting solution:
I installed the program in portable version and everything works smooth now. !!!

I used to be able to use Reaper with no problems. But one day, I started to get a very distorted sound when I'm playing my recordings on Reaper.
Fact 1: Reaper renders my projects as its supposed to be (not distorted)
Fact 2: I can use Audacity with no problem
Fact 3: I can use EZmix (which I also use with ASIO drivers) with no problem.
*I tried to play with buffer size, but It didn't affect anything.
Do you have any idea? I can upload the screenshots of the Audio-Device-Setup settings if needed.

Sound samples (simple clean chord recorded as dry guitar sound):
1. What Reaper renders
2. What I hear during playback

Screenshots of the settings:
1. Rendering
2. Playback
3. Buffering
4. Audio Device

Thank you very much for all your help,
Comment: Having same issue with GNU\Linux portable version on Debian 11. Using Reaper 6.5/linux-i686 rev 6e5302 (Mar 3, 2022) on direct ALSA on EMU1212 (no breakout box) with no Jack or PulseAudio. Free Ardour for GNU\Linux seems to work fine with this config. Also, for whatever reason, Jack is "Jacked Up" on my box but Ardour on raw ALSA is okay. Rendering in Reaper is good but playback is as Deniz said.
Comment: Strangely, I somehow had a project sample rate of 44 kHz even though Reaper was displaying 48kHz 24 Bit WAV : 2/2 ch 512 spls ~ 10/10ms ALSA EMU1010 16-Bit in the upper right hand corner. When I changed project sample rate from 44kHz to 48kHz, things cleared up quite a bit.
Answer: I think the most likely cause is the audio settings -- have you tried using going to the Reaper preferences under "Audio Device" and setting a different device? I'd recommend trying both WaveOut and ASIO. I'm not sure if you have to restart Reaper after changing the setting or not...
Comment: I normally use Asio4All with this program. And yes, I tried direct sound, Asio4All and the device's own audio driver.
Comment: Did you try "select REAPER (reset configuration to factory defaults) from the Start menu" (from http://forum.cockos.com/showthread.php?t=56723).
Comment: I just reset the settings after reading your comment. It didn't help :(
Comment: If it's not Reaper and it's not ASIO.... could it be the sound card? Do you have an additional one you could swap in? Or an audio interface with audio out? Or are you using a sound card and you could switch to on-board audio?
Comment: I use two of my guitar multi-effects with USB interface for recording and my PC itself when I'm playing the projects which used to work with no issues.
Answer: That sounds very much like the type of distortion that is wanted by guitarists, not a problem with sound card. It's really quite a nice warm distortion.
So, this indicates one of two things:

soft clipping in a gain stage somewhere. It's certainly not a hard clip. And it can't be on input stage, as you have a clean recording there.
Or more likely - a distortion plugin is used...somewhere.

How did you play back your clean track, and what is different between that and playing back your rendered track?
Can you check your audio path for a distortion effect.
Comment: I am with you here: the render version seems like it is bypassing all effects, while the player version sounds like an overdrive effect has been placed, either on the track or on the master. Perhaps an effect was on the master and then saved as a template.
Comment: Well, I actually did not place any effects. The sound card; I used 2 of my guitar processors with USB interface and my PC itself which I used to be able to use without any issues. I actually thought that while playback, the sound is kind of placed into a multiple feedback loop. Because when I stop the playback the track does not stop instantly (or with a reverb kind of thing); it last for a while, then ends.
Comment: That could be a feedback loop: perhaps you are feeding the monitor (output) back into the input.
Comment: Wouldn't resetting all the settings and/or starting a new project have eliminated this possibility?
Comment: I reinstalled Reaper multiple times. I actually found a solution of installing the program in portable version. It seems like it solved the problem.
Comment: Interesting. The portable version would have its own, separate settings from the original version, which might suggest buried somewhere in the settings is the problem. However, if this were the case, resetting to defaults should have fixed things. Very strange. Did you note any obvious differences between the portable install and the original install as far as the settings pages we investigated earlier?
Answer: You should see the answer to this question. Referring to that, guitar tracks sound different upon implementing different recording techniques. For the best results, you should monitor the sound the audio interface receives through headphones plugged into it. If you are connecting the 6.1mm wire from your distortion pedal/processor/amp line-out to the audio interface's input, it would definitely sound different than how it will be if you record it using an instrument microphone to record the rich tone coming out of your amp. You must also check for combinations of different settings on your pedal board (which include selecting the patch as well as effects like delay, echo, reverb, wah; adjusting gain and volume, etc.).
NOT THE BEST SOUND YET? USE PLUGINS IN REAPER!
However, you won't necessarily get the best results out of what settings you have with you. Softwares like Reaper let you use plugins to overlap with the sound of your guitar track. This is similar to using VST plugins to record tracks using a midi keyboard. Watch this video: Using VST plugins in reaper to create and automate guitar rig. This shows how to get best results using plugins as well as overviews some of the ideal settings and I'm sure this could be of some help to you.


Why $|G|$ even implies $|A(G)|$ also even?

Question: Let $G$ be finite group with even order. Why has the set $A(G)=\{g\in G: g\neq g^{-1}\}$ an even number of elements?
Comment: It seems to me that $A(G)$ has an even number of elements irrespective of whether $|G|$ is odd or even. If $g\in A(G)$, then also $g^{-1}\in A(G)$ as $(g^{-1})^{-1}=g$.
Comment: I might be missing something- but $g \in A(G)$ implies that $g^{-1}$ is in $A(G)$
Comment: @JyrkiLahtonen you're right, I guess the hypothesis of $|G|$ even is not necessary..
Answer: For any finite group doesn't your set $A(G)$ have even order, since we can pair each element of $A(G)$ with it's inverse.
On the other hand if $G$ has even order, then I guess $G-A(G)=\{g\in G : g=g^{-1}\}$ has even order.
Comment: @PtF Yeah, but that'd be a circular argument. It *directly* follows for *any* finite group $G$ that $A(G)$ has an even number of elements. The second statement is just a corollary and doesn't have to be used (nor should it be) to again show that $|A(G)|$ is even.
Comment: As to your second statement if $G-A(G)$ has even order then $G=(G-A(G))\cup A(G)$ (disjoint union) implies $|G|=|G-A(G)|+|A(G)|$ hence $|A(G)|$ should also have even order, right?
Comment: Right, I had misunderstood your comment, sorry..


Logarith at base 10 as integration

Question: The logarithmic function with base $e$ is the (set theoretic) inverse of exponential function $e\colon \mathbb{R}\rightarrow (0,\infty)$. This can also be defined using integration as: $\log\colon (0,\infty)\rightarrow \mathbb{R}$, $\log x= \int_1^x \frac{1}{t} dt$.
Question:  Can we define logarithm at base $10$ using integration?
Comment: I think $\log_{10} x=\dfrac{\log_e x}{\log_e 10}$ is already a nice definition.
Answer: The logarithm of base then can be integrated but the base has to be changed to $e$.
When you have a function, lets say $f(x)=logx$ then the base can be changed from 10 to $e$. This is done using the rule $log_mx=(log_nx)/(log_nm)$.
So changing from base 10 to base e would look as follows:
$log_{10}x=(log_ex)/(log_e10)$.
Comment: I didn't understand the point. Can you explain it further?

Logarith at base 10 as integration


Construction of noncommutative torus

Question: In short, how do we get the formula for the NC torus? I find the equations in many places (including here) but I still have no idea for how this comes from the torus. If my understanding is correct, then you take the torus and look at its algebra of (smooth or just continuous?) functions. Then make this noncommutative and that is your noncommutative torus. There are different ways to do this which lead to different anti-symmetric matrices $\theta$ which yield different tori. But how do I do this in practice? And is there any way to go backwards: Is there a way to take the information $UV = e^{2\pi i \theta} VU$ and do some math and say, "hey this is a torus in some sense!"?
When looking at noncommutative $\mathbb{R}^4$ for example, it is easy to explain what it has to do with $\mathbb{R}^4$ and how to get it. Is there no other way to simply explain this for the torus? Perhaps because the algebra of functions on the torus is much more complicated than that of $\mathbb{R}^4$?
I am also curious if there is some way to realize $\mathbb{T}^n_{\theta}$ as a quotient of $\mathbb{R}^4_{\theta}$ by some NC lattice (if such a thing exists). That might provide a nice construction of the NC torus.
A reference would be great. I find a lot of references to papers or books that talk about the NC torus a good way into the text and then it often invokes a lot of background. Maybe it really does take that much set up? Any help would be greatly appreciated. Thank you.
*Note: I put this on MO by mistake earlier, but I feel it's better suited here. I think I deleted the MO one...
Answer: Recall that any $f \in C^\infty(\mathbb{T}^n)$ can be uniquely written as a convergent Fourier series
$$
 f = \sum_{\mathbb{k} \in \mathbb{Z}^n} f_{\mathbb{k}} U_{\mathbb{k}}, \quad f_{\mathbb{k}} := \int_{\mathbb{T}^n} e^{-2\pi i \langle \mathbb{k},t \rangle}f(t)\,dt,
$$
where for each $\mathbb{k} \in \mathbb{Z}^n$,
$$
 \forall t \in \mathbb{T}^n, \quad U_{\mathbb{k}}(t) := e^{2\pi i \langle \mathbb{k},t\rangle}.
$$
Recall, moreover, that the usual pointwise multiplication of functions corresponds to the convolution product of Fourier series:
$$
 \forall f, \; g \in C^\infty(\mathbb{T}^n), \quad fg = \sum_{\mathbb{k} \in \mathbb{Z}} \left(\sum_{\mathbb{k}^\prime \in \mathbb{Z}^n} f_{\mathbb{k}-\mathbb{k}^\prime}g_{\mathbb{k}^\prime} \right)U_{\mathbb{k}}.
$$
In other words, $C^\infty(\mathbb{T}^n)$ is generated by unitaries $\{U_{\mathbb{k}}\}_{\mathbb{k} \in \mathbb{Z}^n}$ satisfying the relations
$$
 \forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad  U_{\mathbb{k}}U_{\mathbb{k}^\prime} = U_{\mathbb{k}+\mathbb{k}^\prime},
$$
which implies, in turn, that
$$
\forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad U_{\mathbb{k}^\prime}U_{\mathbb{k}} = U_{\mathbb{k}}U_{\mathbb{k}^\prime}.
$$
Now, suppose that $\Theta : \mathbb{Z}^n \times \mathbb{Z}^n \to \mathbb{T} := \mathbb{R}/\mathbb{Z}$ is a (normalised) $2$-cocycle, i.e., that it satisfies

For all $\mathbb{k}\in\mathbb{Z}^n$, $\Theta(\mathbb{0},\mathbb{k}) = \Theta(\mathbb{k},\mathbb{0}) = 0$ (normalisation).
For all $\mathbb{p}$, $\mathbb{q}$, $\mathbb{r} \in \mathbb{Z}^n$, $\Theta(\mathbb{p},\mathbb{q}+\mathbb{r}) + \Theta(\mathbb{q},\mathbb{r}) = \Theta(\mathbb{p},\mathbb{q}) + \Theta(\mathbb{p}+\mathbb{q},\mathbb{r})$ ($2$-cocycle condition).

Then you can replace the usual convolution of Fourier series by a deformed convolution of Fourier series to obtain the noncommutative $n$-torus $C^\infty(\mathbb{T}^n_\Theta) := (C^\infty(\mathbb{T}^n),\star_\Theta)$:
$$
 \forall f,g \in C^\infty(\mathbb{T}^n), \quad f \star_\Theta g := \sum_{\mathbb{k} \in \mathbb{Z}} \left(\sum_{\mathbb{k}^\prime \in \mathbb{Z}^n} e^{-2\pi i \Theta(\mathbb{k}-\mathbb{k}^\prime,\mathbb{k}^\prime)}f_{\mathbb{k}-\mathbb{k}^\prime}g_{\mathbb{k}^\prime} \right)U_{\mathbb{k}}.
$$
In terms of our unitary generators $\{U_{\mathbb{k}}\}_{\mathbb{k} \in \mathbb{Z}^n}$, this reduces to defining
$$
\forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad U_{\mathbb{k}} \star_\Theta U_{\mathbb{k}^\prime} := e^{-2\pi i \Theta(\mathbb{k},\mathbb{k}^\prime)}U_{\mathbb{k}+\mathbb{k}^\prime},
$$
which, in turn, implies the commutation relations
$$
\forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad U_{\mathbb{k}^\prime} \star_\Theta U_{\mathbb{k}} = e^{2\pi i \theta(\mathbb{k},\mathbb{k}^\prime)}U_{\mathbb{k}} \star_\Theta U_{\mathbb{k}^\prime},
$$
where $\theta : \mathbb{Z}^n \times \mathbb{Z}^n \to \mathbb{T}$ is defined by
$$
 \forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad \theta(\mathbb{k},\mathbb{k}^\prime) := \Theta(\mathbb{k},\mathbb{k}^\prime) - \Theta(\mathbb{k}^\prime,\mathbb{k}).
$$
As it turns out, $\theta$ is an alternating bicharacter, i.e.,

For all $\mathbb{k} \in \mathbb{Z}^n$, $\theta(\mathbb{k},\mathbb{k}) = 0$ (alternating).
For all $\mathbb{k} \in \mathbb{Z}^n$, $\mathbb{k}^\prime \mapsto \theta(\mathbb{k},\mathbb{k}^\prime)$ and $\mathbb{k}^\prime \mapsto \theta(\mathbb{k}^\prime,\mathbb{k})$ both define homomorphisms $\mathbb{Z}^n \to \mathbb{T}$ (bicharacter).

Conversely, every alternating bicharacter $\theta : \mathbb{Z}^n \to \mathbb{Z}^n$ can be induced in this way from a (normalised) $2$-cocycle $\Theta : \mathbb{Z}^n \to \mathbb{Z}^n$.
Now, what happens when $\Theta$ and $\Theta^\prime$ both induce the same alternating bicharacter $\theta$? It's an old theorem of Kleppner's that this happens if and only if $\Theta$ and $\Theta^\prime$ are cohomologous, i.e., there exists some $T : \mathbb{Z}^n \to \mathbb{T}$ such that
$$
\forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad \Theta^\prime(\mathbb{k},\mathbb{k}^\prime) = \Theta(\mathbb{k},\mathbb{k}^\prime) +  T(\mathbb{k}) + T(\mathbb{k}^\prime) - T(\mathbb{k}+\mathbb{k}^\prime) ;
$$
in other words, $\Theta^\prime - \Theta = dT$. In that case, we can define an explicit $\mathbb{T}^n$-equivariant isomorphism $\Psi_T : C^\infty(\mathbb{T}^n_\Theta) \to C^\infty(\mathbb{T}^n_{\Theta^\prime})$ by
$$
 \forall \mathbb{k} \in \mathbb{Z}^n, \quad \Psi_T(U_{\mathbb{k}}) = e^{2\pi i T(\mathbb{k})} U_{\mathbb{k}}.
$$
Hence, up to equivariant isomorphism, for any alternating bicharacter $\theta$ (or equivalently, by Kleppner, for any class $\theta \in H^2(\mathbb{Z}^n,\mathbb{T})$, where $H^2(\mathbb{Z}^n,\mathbb{T})$ is the second group cohomology of $\mathbb{Z}^n$ with coefficients in $\mathbb{T}$), we can define the noncommutative $n$-torus $C^\infty(\mathbb{T}^n_\theta)$ as the algebra generated by unitaries $\{U_{\mathbb{k}}\}_{\mathbb{k} \in \mathbb{Z}^n}$ satisfying the commutation relations
$$
\forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad U_{\mathbb{k}^\prime}  U_{\mathbb{k}} = e^{2\pi i \theta(\mathbb{k},\mathbb{k}^\prime)}U_{\mathbb{k}}  U_{\mathbb{k}^\prime};
$$
to construct it, we just take $C^\infty(\mathbb{T}^n_\theta) := C^\infty(\mathbb{T}^n_\Theta)$ for any $2$-cocycle $\Theta$ inducing $\theta$.
Let me be more explicit about what appears in the literature. We have an isomorphism
$$
 \{\text{alternating bicharacters $\theta : \mathbb{Z}^n \times \mathbb{Z}^n \to \mathbb{T}$}\} \cong \mathbb{T}^{n(n-1)/2}
$$
given by
$$
 \theta \mapsto (\theta(e_i,e_j))_{1 \leq i < j \leq n},
$$
where $\{e_i\}_{i=1}^n$ is the standard ordered basis for $\mathbb{R}^n$; conversely, the alteranting bicharacter $\theta$ corresponding to $(\theta_{ij})_{1\leq i < j \leq n} \in \mathbb{T}^{n(n-1)/2}$ is given by
$$
 \forall \mathbb{k}, \; \mathbb{k}^\prime \in \mathbb{Z}^n, \quad \theta(\mathbb{k},\mathbb{k}^\prime) = \sum_{1 \leq i < j \leq n} \theta_{ij}(k_i k^\prime_j - k_j k^\prime_i).
$$
Then there are three conventions that tend to appear for constructing $2$-cocycles $\Theta : \mathbb{Z}^n \times \mathbb{Z}^n \to \mathbb{T}$ inducing $\theta$:

For all $\mathbb{k}$, $\mathbb{k}^\prime \in \mathbb{Z}^n$, set $\Theta(\mathbb{k},\mathbb{k}^\prime) := \sum_{1 \leq i < j \leq n} \theta_{ij} k_i k^\prime_j$.
For all $\mathbb{k}$, $\mathbb{k}^\prime \in \mathbb{Z}^n$, set $\Theta(\mathbb{k},\mathbb{k}^\prime) := -\sum_{1 \leq i < j \leq n} \theta_{ij} k_j k^\prime_i$.
For each $1 \leq i < j \leq n$, choose $\tfrac{\theta_{ij}}{2}$ such that $2 \tfrac{\theta_{ij}}{2} = \theta_{ij}$. Hence, for all $\mathbb{k}$, $\mathbb{k}^\prime \in \mathbb{Z}^n$, set $\Theta(\mathbb{k},\mathbb{k}^\prime) := \sum_{1\leq i < j \leq n}\tfrac{\theta_{ij}}{2}(k_i k^\prime_j - k_j k^\prime_i)$.

The first two conventions give you non-alternating bicharacters, which complicates a fair bit of the algebra, but turn out to be far more robust from a group-cohomological perspective; in particular, they give honest-to-goodness splittings of the short exact sequence
$$
 0 \to \ker(\Theta \mapsto \theta) \to \{\text{$2$-cocycles}\} \xrightarrow{\Theta \mapsto \theta} \{\text{alternating bicharacters}\} \to 0.
$$
The third convention gives you alternating bicharacters, which simplifies a fair bit of the algebra, but all the non-uniqueness can give you headaches when dealing with certain technicalities.
Comment: Hi Branimir. Is it true that any alternating bi-character over $ \mathbb{Z}^{n} $ is equivalent to a *non-degenerate* one?
Comment: Given that you're talking about equivalence, I presume you have in mind a non-zero $2$-cocycle $\Theta$ that happens to be an alternating bicharacter itself. By non-degeneracy of $\Theta$, do you mean that $\Theta$ itself is non-degenerate as a bicharacter or that the canonically associated alternating bicharacter $\theta$ is non-degenerate as a bicharacter (i.e., that the cohomology class $[\Theta]$ is non-degenerate)?
Comment: Hi Branimir. If I recall correctly, every $ 2 $-cocycle $ \Theta $ is co-homologous to a bi-character, which may not necessarily be the canonically associated alternating bi-character $ \theta $. In fact, I believe that in general, $ \theta $ is co-homologous to $ \Theta^{2} $ instead of $ \Theta $. We may thus restrict our attention to $ 2 $-cocycles that are bi-characters. Let me then modify my question as follows: Is any bi-character co-homologous to an alternating bi-character that is non-degenerate?
Comment: The answer is no. Let $\alpha \in \mathbb{R}/\mathbb{Z}$ be irrational and consider the bicharacter $\Theta$ on $\mathbb{Z}^3$ defined by $\Theta(\mathbb{x},\mathbb{y}) = \alpha x_1 y_2$, so that the corresponding alternating bicharacter $\theta$ encoding the cohomology class $[\Theta]$ of $\Theta$ is given by $\theta(\mathbb{x},\mathbb{y}) = \alpha(x_1y_2 - x_2y_1)$.
Comment: Then any alternating bicharacter $\Theta^\prime$ cohomologous to $\Theta$ must necessarily take the form $\Theta^\prime(\mathbb{x},\mathbb{y}) = \beta(x_1y_2-x_2y_1)$ for $\beta \in \mathbb{R}/\mathbb{Z}$ with $2\beta = \alpha$, and such $\Theta^\prime$ is clearly degenerate (with $\mathbb{Z}e_3$ in its kernel).
Comment: One minor point, Branimir. I don't think that it's quite right to define an $ n $-dimensional non-commutative torus as a universal $ C^{\ast} $-algebra generated by a sequence $ (U_{\mathbf{p}})_{\mathbf{p} \in \mathbb{Z}^{n}} $ of unitary elements such that $ U_{\mathbf{q}} U_{\mathbf{p}} = e^{2 \pi i \theta(\mathbf{p},\mathbf{q})} U_{\mathbf{p}} U_{\mathbf{q}} $ for all $ \mathbf{p},\mathbf{q} \in \mathbb{Z}^{n} $, where $ \theta $ is an alternating bi-character on $ \mathbb{Z}^{n} $. These commutation relations say nothing about the universal $ C^{\ast} $-algebra being finitely generated.
Comment: Defining universal $C^*$-algebras is always a messy business. In practice I'd much rather deal with explicit constructions via strict deformation quantisation or even with Olesen–Pedersen–Takesaki's dynamical characterisation. But you're right, I'm sweeping something under the rug: I'm clumsily trying to say that a noncommutative $n$-torus as a twisted group $C^*$-algebra of $\mathbb{Z}^n$ (with basically the same issues with completions as in the untwisted case).

Construction of noncommutative torus


Finding how many times I need to perform an action before I have an x% chance of a specific outcome in r

Question: Non-specific question: There is an action that can be performed that has multiple outcomes. Each outcome has a different probably, p, of occurring. How many times, n, do I need to do the action before I have an x% chance of a specific outcome occurring one or more times.
I know in r I can do this and change n until I get the x I'm looking for:
1-dbinom(0, n, p)

and that will show me the probability of the action occurring one or more times. What would be the inverse where I say function(x, n, p)?
Specific question: There is a slot machine. A specific outcome happens 0.02% of the time. How many times would someone spin the slots before they have a 90% chance of that outcome occurring one or more times?
Comment: Hint: $P(\text{at least once in}~n~\text{tries}) = 1-P(\text{never in}~n~ \text{tries})=(1-(1-p)^n)$. Can you think of any way of solving $$0.9 = 1 - (1-0.0002)^n$$ for $n$? Logarithms might help in some way...
Comment: Thank you for the mathematics behind it! In this case n would equal 11511.8. However, I'm more looking for the r function that handles this. qbinom is the inverse of pbinom, but it still doesn't find n, instead n is a parameter of the the function. By the way, no this isn't for homework. I'm interested in solving this for a video game.
Comment: Someone edited my question to add the negative-binomal tag. After searching for solving for those in r, I was able to found the correct function I needed! I appreciate showing the math behind it so I know what's going on behind the scenes.
Answer: Found the r function I was looking for:
Using the numbers from the question above
qnbinom(0.9, 1, 0.0002)


How to switch logo and menu links based on subdomain?

Question: my D7 site will be accessible from 4 different subdomains:
- a.site.com
- b.site.com
- c.site.com
- www.site.com (or just site.com)
I already enabled a domain cookie for .site.com and the login works across all subdomains.
Now I want to be able to show a different logo logo based on the subdomain and I also want to be able to switch the main menu links.
I tried the context module but didn't find a way to detect the subdomain.
I don't want to use the domain access module. I was thinking about modifying the theme to switch the logos. Can I do the same for the menu links?
Does anyone have a  better idea?
Comment: Do you use different themes for each site or one theme for all subdomains ?
Comment: they use the same theme
Answer: I am unaware of any contrib modules that do this (well, other than Domain Access), but it would be pretty trivial to write a little custom code to accomplish it.
Essentially, you would add something to your theme preprocess to detect the domain and tack on body classes.  How to do this depends on whether you are using Drupal 6 or Drupal 7.  Either method, though, would use $_SERVER["HTTP_HOST"] to detect the theme.
Then, in your CSS you would preface your logo rules with body.whatever to choose the correct one.
The menu thing is a little trickier.  You would use essentially the same logic, but set a variable containing the proper menu and print this out in your theme.  To be honest, though, I really would use Domain Access for this if you are using Panels.  The domain shows up as a panel selection rule, so you can do all of this from the UI.
Comment: Glad I could help.  Personally, I always use Panels from the get-go, as it is easier to rework what a panel does than to redo a site to use panels.  A lot of modules that you may want in the future (Domain Access, Mobile Tools, etc) also integrate nicely into Panels.
Comment: thanks. I looked into Domain Access and it worked great but it seemed to be too much for what I try to accomplish. Also, I don't want to use Panels yet, trying to keep things as simple as possible. Thanks again
Answer:
I tried the context module but didn't find a way to detect the
  subdomain.

You need to use the Context Domain module.  I'm not sure about the logos, but maybe you can use Context Reaction Menus for handling the main menu.
Answer: You need this: https://drupal.org/project/domain
& https://drupal.org/project/domain_menu_access
Using domain module you can manage various settings like theme, block for specific domain.
Using domain menu access you can restrict specific menu link to appear in specific domain under menu configuration settings.


Flip a card from an $2N$ sized deck and guess the color, drink every time you are wrong

Question: I saw this game in The Triangle of Sadness (I wasn't the biggest fan of the movie, but YMVM).
Woody Harrelson picks up a card from a deck ($2N=52$), and asks his opponent red or black. If his opponent guesses correctly, then they are safe. If they guess incorrectly, they must drink. It would seem the winning strategy is to count the number of red and black cards remaining in the deck and guess appropriately. But what percentage of the time can we expect his opponent not to drink? This is easy in simple cases (e.g. $N=1$, guess correctly the first time 100%, guess incorrectly, you know the next card for $E[\text{Correct}] = 75\%$).
Short of enumerating possibilities what is a strategy tractable for humans for large Ns? One could try and enumerate all cases, but the possibility tree seems to blow up. I cheated and used a Monte Carlo:

E[Correct]/Total vs N
It makes sense that the counting advantage approaches 0 the larger the deck, but I wanted a bit more intuition.
There are many other card questions, but I did not see this one posted.
Also, in the movie it doesn't matter. Because you can catch Woody Harrelson cheating.
Comment: Should stress:  if you want a guess, my guess is that there is no simple closed form for the solution.  That could certainly be wrong, but that would be my guess.  Best way to find out is to work it out for a lot of $N$ and look for patterns.  Then use the recursion to prove that those patterns hold generally.
Comment: Well, there's a simple recursion:  Let $E[r,b]$ denote the expected number of drinks assuming you start with $r$ Red and $b$ Black cards in the deck.  Then, if $r≥b$ you guess Red and we see that $E[r,b]=\frac r{r+b}\times E[r-1,b]+\frac b{r+b}\times (E[r,b-1]+1)$ with a similar recursive step if $b>r$.  And boundary conditions $E[r,0]=0=E[0,b]$. Should be easy to implement...at least then you could solve the problem exactly for many values of $N$.
Comment: Right, but short of dynamic programming? How do I characterize the curve I posted
Comment: What do you mean?  Looks like a simple decaying exponential.  you could fit parameters to your data.  As you say, for large $N$ you are mostly guessing blind, so you'd expect to be wrong half the time, so maybe it's just $\frac 1N$ for large $N$.  Small $N$ seems a lot harder to get intuition for, but the recursion should help.
Comment: I mean you're guessing at this point. I can solve the problem (and fit the curve), but I posted this looking more for intuition of the closed form. Also the BC is E[0, b] = b (given b >= r)
Comment: I don't understand what you are asking.  I gave you an explicit recursion so you can solve the problem exactly.  Granted, that won't work well as $N$ gets very big, but you can get a lot of exact values easily.  And you can fit a curve to your data if you want, but you don't have to.  And, of course $E[0,b]=0$...each choice is determined so you never have to drink in that scenario.
Comment: Woops. =0 is fine. I meant to defined it as the percentage of the time that you do not drink (I updated the question, that way it also matches the plot). At what point to we determine there is no simple closed form? This is more a question on how to approach this problem.  I can run Monte Carlo or find a explicit recursive definition- but in terms of problem solving approach do I just play around and try to fit the curve and look for patterns?
Comment: Yeah, that's just about all you can do.  If there is a simple closed form, it shouldn't be hard to spot.  I suggest:  Look at patterns in $E[b,r]$, not just in $E[N]=E[N,N]$.  The recursion needs to consider unbalanced decks.  Also...might not be a bad idea to post $E[N]$ for $N≤10$ or so.  Maybe someone else can spot a pattern even if you can't.
Comment: Worth saying:  the reason I think there is not a closed form solution is that this feels quite similar to the famous [red and black card problem](https://math.stackexchange.com/questions/2544045/optimal-stopping-in-red-vs-black-card-game-deck-of-52-cards) which has been studied extensively (and which lacks a closed form).  Of course, the problems are not equivalent.
Answer: It turns out that there is simple a closed-form expression for $\ E(r,r)\ $.  I wrote a Magma script script to calculate the values of $\ E(r,b)\ $ using a version of lulu's recursion.  Here are the values of $\ E(r,r)\ $ for $\ r=1\ $ to $\ r=26\ $:
\begin{array}{|r|l|}
r&E(r,r)\\
\hline
1 & \frac{3}{2}\\
2 & \frac{17}{6}\\
3 & \frac{41}{10}\\
4 & \frac{373}{70}\\
5 & \frac{823}{126}\\
6 & \frac{3565}{462}\\
7 & \frac{7625}{858}\\
8 & \frac{129293}{12870}\\
9 & \frac{272171}{24310}\\
10 & \frac{1139735}{92378}\\
11 & \frac{2376047}{176358}\\
12 & \frac{19743201}{1352078}\\
13 & \frac{40890483}{2600150}\\
14 & \frac{168947957}{10029150}\\
15 & \frac{348259369}{19389690}\\
16 & \frac{11464229693}{601080390}\\
17 & \frac{23547218611}{1166803110}\\
18 & \frac{96587303059}{4537567650}\\
19 & \frac{197831583443}{8836315950}\\
20 & \frac{1618881562939}{68923264410}\\
21 & \frac{3308327420393}{134564468610}\\
22 & \frac{13508555185547}{526024740930}\\
23 & \frac{27554570432479}{1029178840950}\\
24 & \frac{449278087454089}{16123801841550}\\
25 & \frac{915002452786559}{31602651609438}\\
26 & \frac{3724430600965475}{123979633237026}\\
\hline
\end{array}
The numerators of this sequence are given as entry A322755 in the online encyclopedia of integer sequences, and the denominators as entry A322756. The commentaries on these entries tell us that
$$
E(r,r)=r - \frac{1}{2} + \frac{2^{2r-1}}{{2r\choose r}}\ .
$$
They also tell us that an equivalent version of the game had been  proposed as problem number $\ 630\ $ in the College Mathematics Journal. The solution by John Henry Steelman appears in Vol. 30, No. 3 (May, 1999) of the same journal on pp. 234-235.
An approximate value of $\ E(26,26)\ $ is $\
30.04066\ $.
Comment: Super cool! Thanks for the reference. Wow OEIS really does have everything- that's a great suggestion to keep everything symbolic and use it as a reference.


iframe content reloads when there is a DOM manipulation Angular

Question: I have an iframe that is loaded dynamically when a specific condition is met.

The issue I have is that whenever anything in the page - outside of the frame -  changes (Input text, select values, etc), the iFrame content reloads, and I can see all the scripts contained being reloaded in the network tab, and therefore what the user has filled in the iframe disappears.
I am suspecting the ChangeDetectionStrategy since the stack trace of the initiator of the call that loads the files for the iframe goes back to viewRef._detectChanges as you can see from the screenshot:

I tried to add ChangeDetectionStrategy.OnPush but that created other issues on the page.
Answer: I solved the issue by creating a new component that contains only the iframe. I would still want to know why that solved the issue...
Comment: @fishbone thanks for referring that link! Good to see this solution worked for you as well!


iOS: How to implement the mask view event penetrate?

Question: As the following image,I have a collectionView, with a maskView above it.
And a right side view above the maskView.

How to implement the mask view event penetrate?
My PM's idea is that the collectionViewCell is clickable when a mask view above the collectionView. ( a little weird )
The mask view has taken over the collectionView's event.
I think I should override the event responder chain.
I tried to handle the override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
class Mask: UIView {
// ...
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let views = superview?.subviews else {
            return self
        }
        for view in views{
            if type(of: view) == UICollectionView.self{
                return view
            }
        }
        return self
    }
}

Not worked as commanded, the collectionView just scrolls.
How to solve it?

I improved the code a little.
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let views = superview?.subviews else {
            return self
        }
        for view in views{
            if type(of: view) == UICollectionView.self{
                let collectionView = view as! UICollectionView
                for cell in collectionView.visibleCells{
                    if cell.frame.contains(point){
                        return cell
                    }
                }
            }
        }
        return self
    }

It is not very sharp. Some events are abandoned when switching the cells being clicked. Just like Apple did a hitTest event cache.
Answer: If I understood correctly and the mask view is on top of the collectionView and it gets the events you can just set the mask view userInteractionEnabled to false.
This way the event will be sent to the layer below until someone handles it.

iOS: How to implement the mask view event penetrate？


rhdfs - RJavaTools error writing datasets to hdfs

Question: I am running rStudio Server on a hortonworks sandbox version of hadoop.  I have the rhdfs package loaded, but when I try to write a dataset to hdfs using the hdfs.put() command I receive the following error:
<code>hdfs.put(mtcars,"/user/root")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
  java.io.IOException: File c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17.3, 15.2, 10.4, 10.4, 14.7, 32.4, 30.4, 33.9, 21.5, 15.5, 15.2, 13.3, 19.2, 27.3, 26, 30.4, 15.8, 19.7, 15, 21.4) does not exist
</code>
Anyone encountered this issue before?  I am assuming that it is related to using a 32 bit version of Java on a 64 bit operating system.  Any suggestions are much appreciated
Answer: Though its too late to answer, thought people might find this useful.
The command 'hdfs.put' of rhdfs package can be used to transfer files from the local file system to the HDFS. In this case mtcars is built in R data frame which has to be first saved to local disk before moving to hdfs using 'hdfs.put' command.
R Code:
<code># Save built in data set to local disk
save(mtcars, file = "/home/mtcars.RData")

# Move data from local to hdfs
hdfs.put("/home/mtcars.RData", "/in")
</code>


How testing (new data points) works in graph neural network

Question: In machine learning, data is divided into train and test splits. The machine learns weights using training data and we can utilize weights to predict test data.
Similarly, we are also learning weights in GNN. But how is testing performed for new or test data points? The crux behind GNN is its connection of edges and nodes for data points. Given a new data point or test point (let's say for a single point), it does not have any connection with other training data. How does testing work in GNN?
Do we have to give training and testing data both while training itself? What is an efficient way to perform testing?
I am a newbie to GNN.
Comment: This came up in a [video](https://youtu.be/0YLZXjMHA-8?list=PLV8yxwGOxvvoNkzPfCx2i8an--Tkt7O8Z&t=787) I am watching on the topic. The term used is "binary mask" to encode if a node should be considered part of the training or out-of-sample data. (Perhaps there can be a "three-way mask" for a train/test/validation split.)
Answer: For GNNs operating on data where every training/test sample is a separate graph, this is not a problem. Examples include chemical compounds, brain networks etc.
For GNNs operating on large graphs which can evolve through time, like social network, there are approaches to address this problem, by introducing an inductive learning framework by aggregating attributes from the neighbors of the new node. Example of such an approach is GraphSAGE (introduced in a NIPS publication in 2017).


How should an Auditor determine the minimum sample size?

Question: Let's pretend that in a Financial / IT / Construction Audit of a task which the outcome is either Pass(1) or Fail(0).
Suppose that the Auditee should perform this task on a daily basis (365 days in a year), what would be the formula / test that the Auditor can use to find the minimum sample size (in days) that supports such statement:
"The Auditor believes, with 95% confidence, that the Auditee has Passed 90% of daily task performed in 1 year. "
Appreciated if the answer could use the parameters above as example.
Without digging too deep into the formula or tables, my attempt using this tool is as follows:
https://stattrek.com/survey-sampling/sample-size-calculator.aspx
Input
Sampling method: Simple random sampling
Parameter of interest: Proportion
Purpose of research: Test hypothesis
Main goal: Find min sample size, given error
Margin of error: 0.05
Significance level: 0.05
Null hypothesis: Proportion >= 0.95
Total population size: 365
Output
Sample size = 46
Region of acceptance = 0.900 to 1.000
======
Does a sample size of 46 support the statement above?
Comment: I apologize that your question was mistakenly closed.
Comment: @base64, What is the total population size and what is the effect size?
Comment: @DhamnekarWinod Population size is 365 and there is only single group.
Comment: @base64, You have not stated your problem in clear way.
Comment: I reopened the question because, even in its original form, it looked perfectly clear to me.
Comment: @base64,Plug in Null hypthesis =90%, effect size =0and then compute the sample size. Answer will be 102 days
Answer: If audit was conducted 365 times, what is the probability that it would pass 365*0.9 times? The probability can be calculated from Binomial distribution $B(k|365,p)$. The problem is that $p$ is unknown. So, we need a trick.
First, we estimate it by conducting $n$ trials and get $\hat p=\frac{m+1}{n+2}$, where $m$ was the number of times audit passed in $n$ trials. Here, I'm using the Laplace's rule of succession. The reason is that if you have $n$ successes then usual MLE estimate gives $\hat p=1$ and it messes up the bootstrapping step.
Second, we need a sampling distribution of $\hat p$. We can either an approximation or an "exact" one. There are many approximations, e.g.
using Wald method we get the sampling distribution:
$$f(\tilde p)=\hat p+ z\sqrt{\hat p(1-\hat p)/n},$$
where z is the standard normal.
The "exact" method isn't really exact but it's a bootstrapping from $\hat p$: we plug it into the binomial distribution, generate $n$ trials and get $\tilde p=\tilde m/n$, where $\tilde m$ is number of passes. This is what "exact" method is based on.
Third, we convolve $f(\hat p)$, either approximation or "exact", with the binomial distribution:
$$k\sim \int_{0}^1 B(k|365,\hat p)f(\hat p)d \hat p$$
Where $k$ is the number of times passed in 365 audits.
Once you got the distribution, perhaps numerically, you can estimate the probability $Pr[k>365*0.9]$ and get the probability that you were looking for.
Now, you should see that your question doesn't have a unique answer. In other words, you pick any $n$ and produce a probability that auditee would have passed 90% of time in daily audits during the year. The only things that will change is the power of the test, it will increase with $n$, but you didn't specify the required power.
Example: suppose you conducted n=46 audits and 42 of them passed. This means $\hat p=0.896$, and the sampling distribution is $f(\hat p)=\mathcal N(0.896,0.045)$ in Wald method or in "exact" method you get the corresponding Binomial distribution. Monte Carlo simulation with 1000 trials produces the probability of passing 329 or more time in 365 trials is $\pi\approx 47\pm 1.6$% in Wald and $\pi\approx 35\pm 1.5$% in "exact" method. The Monte Carlo uncertainty is $\sqrt{\pi*(1-\pi)/1000}\approx 1.5$%. Here's a cumulative histogram for Wald and "exact" methods:

VERY IMPORTANT CASE: ongoing audit
The previous discussion was based on the notion that you did $n$ trials this year, and planning for the next year audit. What if we're planning the remaining audit? In other words $n$ is a part of 365 days of audit. So we cunducted $n$ audits and now are thinking how many more we need before we're confident that auditee would pass 90% of total 365 audits?
In this case you have to make an important adjustment to the step 3 in the previous discussion. You only generate 365-$n$ trials in Monte Carlo if you're using this method. Here's what I got with "exact" method for this case and the same n=46 and m=43. The estimate of probability is the same $\hat p=0.896$. So we run Monte Carlo with this setting but generate only passes for 365-46 trails and add the passed to earlier 42 passed. Then we build the cumulative distribution of total passes. In this case the probability of 90% passes in total 365 trials changes a bit: $\pi\approx 38\pm1.5$%. Here's a histogram:

This modification doesn't make a lot of difference for low initial trial numbers $n$. However, as $n$ grows it becomes very important. Consider the case where you made already $n=364$ trials with 328 successes. In this case the probability of getting 90% successes is equal $\hat p$, because we have essentially a Bernoulli experiment at hand at this point. Unlike the case where you're planning for the next year, where you didn't run any audit at all yet.
This is how you do it in Excel.
First you calculate the estimated $\hat p$ in cell F6 using the Laplace formula. Then you bootstrap the sampling distribution of $\tilde p$ in column B:

Then for each realization of $\tilde p$ in column B you simulate remianing trials and show obtained passes k in column C:

Finally, you count in how many simulations you passed the required mark of 90% in 365 audits:
Comment: Hi Aksakal, thanks for your in-depth answer. Would your answer vary if k is always coincidentally >= np before such tests are run?
Comment: @base64, do you mean to say that in the past they always passed the threshold? I dont understand your question
Comment: Hi Aksakal, yes, given that they have passed the threshold within the sample. For example, if I sampled 46 days in a year and found that more than 41.4 (e.g. 42) is a "pass", can I safely conclude that 328.5 of 365 days is also a "pass", without looking at the 319 days (the rest of the population).
Comment: @base64, I updated my answer with your example in comments, but the answer is No, it's much lower than 90% probability they'll pass 329 times or more. If they passed 44 times, then we'd be talking! Such a drastic sensitivity tells you that the power of a test is low at n=46
Comment: @Aksakal, Original post is asking what is minimum sample size? Stattrek calculator provided 102 days as a sample size. What is your answer for the required sample size?:-)
Comment: @Aksakal, thanks for your great answer. Can you see if my implementation https://pastebin.com/vXVHZcin at https://repl.it/languages/python3 has same output as yours?
Comment: I also noticed that normal approximation may not work for small population (e.g. 52 weekly task) or estimated p ≈ 1.00. Is there any hints to approach that?
Comment: @base64, the normal approximation can be capped or floored at around 0 or 1. it's an approximation anyways.
Comment: @base64, I edited my answer with adding "exact" method in addition to Wald
Comment: @DhamnekarWinod, there's no unique answer to the question. For instance, even with 60 trials if you get 59 successes then it's over 95% probability that in 365 trials you get 90% successes.
Comment: @Aksakal By N(0.896,0.045) Do you mean a standard deviation of 0.045 rather than a variance of 0.045?
Comment: @base64, yes, corrected it in the text to variance. Also, see my important edit of the answer. It occurred to me that you might be planning the remaining of audit year, not the next audit year
Comment: @Aksakal Thanks. I tried implementing the simulation based on what you described. However, I got 46-50% for the "exact" method https://pastebin.com/edjTHVCK Would share your algorithm regardless of the language?
Comment: @Aksakal After correcting p~=(m~+1)/(n+2) and k~=m~+m, where m~ is from 365-n trials, everything worked out. Thank man!


Can't locate where Commerce Authnet stores the API and Key

Question: I am using Drupal Commerce and the Commerce_authnet module to connected to Authorize.net. I have custom functionality which requires me to make a separate call to the Authorize.net CIM API. I have done so sucessfully by adding a submit handler to the Checkout button, catching the API Login and Key, and used those in my API calls.
$login = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['login'];
$key = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['tran_key'];
define("AUTHORIZENET_API_LOGIN_ID", $login);
define("AUTHORIZENET_TRANSACTION_KEY", $key);
However, I need to create a separate way of users updating their Authorize.net account settings from their user profile form. I have looked in the commerce database tables and in the drupal variable editor to see if I could pull it from the database, but I have not found where its stored.
How can I access this data?
Answer: I'm assuming you're using the latest version of Commerce authnet.
Drupal Commerce payment system (as well as discounts, taxes..) is based in rules, you can see here how the settings form are included: http://cgit.drupalcode.org/commerce/tree/modules/payment/commerce_payment.rules.inc#n250 in the rules UI, so it is basically stored by rules in a rules_config object, specifically in the unserialized data column.
So if you want to see the settings in the database, you can go to rules_config table and check the data db field.
Modifying this from outside rules is another story, I've never done this, but I'm quite sure that rules doesn't provide an API to alter this data field, you'll probably need to use the Database API to access rules_config table and unserialize/serialize the data information to alter it.
It is probably advisable to find an alternative way to do this, i.e providing a new module that runs a slightly modified version of the charge callback of authnet (http://cgit.drupalcode.org/commerce_authnet/tree/commerce_authnet.module#n750)
Answer: I figured out how to retreive the credtials with this post https://stackoverflow.com/a/9996895/1015214.
You can get the rule machine name from the rules_config table.


GMM weighting change during marginalization

Question: Suppose one has a multivariate Gaussian Mixture Model:
$$
\text{pdf}(\vec{x}) = \sum_{i=1}^N w_i \mathcal{N}(\mu^{(i)}, \Sigma^{(i)})
$$
Suppose $\vec{x} = \{\vec{a},\vec{b}\}$ and we marginalize out $\vec{b}$. For a single Gaussian component  we would get:
$$
\mathcal{N}\left(\mu_a \mid \Sigma_a \right)
$$
where $\mu_a$ is the corresponding part of $\mu = [\mu_a, \mu_b]'$ and $\Sigma = \begin{bmatrix}\Sigma_{a} & \Sigma_{ab} \\ \Sigma_{ba} & \Sigma_{b} \end{bmatrix}$.
For the marginalized mixture, does one need to update the weights?:
$$
\text{pdf}(\vec{a}) = \sum_{i=1}^N w'_i \mathcal{N}(\mu_a^{(i)}, \Sigma^{(i)}_a)
$$
In other words, is $w_i' = w_i$ for all of the components?
Answer: Okay, I figured it out.
Marginal probability:
\begin{align*}
pdf(a) & = \int_b pdf(a,b) \> db \\
& = \int_b \sum_i w_i \mathcal{N}(\mu^{(i)},\Sigma^{(i)}) \> db \\
& = \sum_i w_i \int_b \mathcal{N}(\mu^{(i)},\Sigma^{(i)}) \> db \\
& = \sum_i w_i \mathcal{N}(\mu_a^{(i)}, \Sigma_a^{(i)})
\end{align*}
The weights are unchanged.


VB.net Fill Dataset at Application Start

Question: I have a winforms application that has an sql server backend.  I have some tables that have static data, lookup tables, that I would like to fill in my dataset at application start to be used throughout the application when needed.
Normally in a form I would use something like this: Me.TEMSWBSETableAdapter.Fill(Me.EMS_DS.TEMSWBSE)
But I would have to do that in every form that required that data.  The problem is it takes awhile to load that data, so I would like to load the data at startup in a background worker that can be used by any form that requires it.  Basically filling the dataset with that data for use throughout.
I am not sure how to do this.  Can someone point me in the right direction.
Thanks
Comment: If you define your DataTable in a module, it should be globally available. 2-3 mins is a long time, maybe you can optimize your query. I'm not very firm with mssql, but mysql has got many queries that will run much faster if you write it in another way (some queries moved down from minutes to seconds).
Comment: I think, this will depend on how long the loading of the DataTable will last. Maybe a spashscreen would be good (loading the data into a global DataTable).
Comment: right now i do use a splashscreen.  It takes 2-3 mins for the data to load.  Ill look up global datatables.
Comment: It is just a table with a million records.  It is just a simple select statement, no way to optimize.
Comment: Looking into global datasets now.  Trying to find a good example.
Comment: Very hard to read, but I think, this will work.
Comment: I dont know how to format code in comments.
Comment: So is this correct:

    So is this correct:

Module dsglobal

    Public lookupds As EMS_DS

    Public Sub populateDS()
        lookupds = New EMS_DS

        Dim ta As New EMS_DSTableAdapters.TEMSWBSETableAdapter
        ta.Fill(lookupds.TEMSWBSE)

        Dim ta1 As New EMS_DSTableAdapters.TEMSCCTRTableAdapter
        ta1.Fill(lookupds.TEMSCCTR)
    End Sub

End Module
Comment: You are on the right track when you suggest loading a datatable using a backgroundworker or other multi-threading technique - although this may not even be necessary since it may well be that you can't really progress until your cache is loaded anyway, so you might as well wait for it. Show us what you have tried.
Incidentally, do you literally mean a million records or is that a figure of speech? A million records is not a huge number for a db, but it *is* a huge number for a lookup!
Comment: I pretty much did what i posted in my last comment.  Yes, it is like 1.4 million records and yes, big for a lookup, but nothing I can do for that.
Answer: you first need to implement DataReder object that can retrieve data with out creating a database TableAdapter. this will load your data with forward only and read only mode of the ADO.net mechanism.then you can implement ExecuteNonQuery() method to append the changes directly to the database.


Solving a real integral in the complex plane

Question: $\int_0^\infty \frac{\cos(x)}{x^2+1}dx$
Singularities: $x_{1,2}=\pm i$
We want to integrate over the upper half of a circle on the complex plane. So we only consider $x_1=+i$. We can use the residue theorem.
Define $h(z)=cos(z), \ g(z)=x^2+1, \ g'(z)=2x$
Since $g(i)=0, \ g'(i)=2i\neq 0$ and $h()=\cos(i)\neq 0$ we can conclude that $x_1$ is a simple pole and we can use:
$Res(f;x_1)=\frac{h(x_1}{g'(x_1)}=\frac{\cos(i)}{2i}=\frac{e^{-1}+e^1}{4i}$
Now, since the integral is from $0$ to $\infty$ we can conclude that:
$\int_0^\infty f(x)dx=\pi i \cdot (\frac{e^{-1}+e^1}{4i})=\frac{\pi}{4}(e^{-1}+e^1)$
Now, I don't have any solutions but someone told me the solution is probably $\frac{\pi}{2e}$, if that's right - what did I do wrong?
Comment: You didn't estimate the integral over the semicircular arc. (It **doesn't** tend to zero!)
Comment: You are right, I didn't. Haven't done this in a long time, forgot about it! I usually never had to actually estimate it but I could argue differently. Im gonna check that, thanks.
Answer: First of all a general note: never use trigonometric functions in such exercises. They are very hard to bound on half a circle. This is where the problems in your solution started. So instead of that define the complex function $f(z)=\frac{e^{iz}}{z^2+1}$. Because the pole at the point $z=i$ is simple you can find the residue like this:
$Res(f;i)=\lim_{z\to i} (z-i)f(z)=\lim_{z\to i}\frac{e^{iz}}{z+i}=\frac{e^{-1}}{2i}$
So if we call our contour (for a specific radius) $\Gamma$ then $\int_{\Gamma}f(z)dz=\frac{\pi}{e}$ by the residue theorem. On the other hand if you take the radius of the half circle to infinity then you can easily get that on the circle itself the limit is zero while on on the part of the contour which is on the real line the limit equals to $\int_{-\infty}^\infty f(t)dt$. Using the identity $e^{it}=cost+isint$ we can take the real part of the integral and get that $\int_{-\infty}^\infty\frac{cosx}{x^2+1}dx=\frac{\pi}{e}$. This is an even function so the integral from $0$ to $\infty$ is half of that.
Comment: What I usually do is: I choose the upper half-circle with radius R in the complex plane as my path. Then I basically have $\int_{-\infty}^\infty f(z)dz=\int_{\gamma_R}f(z)dz + \int_{\gamma_I} f(z) dz = 2\pi \sum_i Res(f;z_i)$. Then if the integral over the imaginary part of the path converges to 0, we can let $R\to\infty$ and thus basically get the integral in $\mathbb R$. Usually I only had functions, where the numerator is a simple function like $z^2$. So maybe the real question is: How does the function (in the numerator) affect this approach? You hinted to that. Mind explaining that more?
Comment: The problem is that if you take your function to be $\frac{cosz}{z^2+1}$ then the limit on the imaginary part will not be equal to $0$ when $R\to\infty$. Trigonometric functions are very hard to bound. So we use the exponential function. If we define $f(z)=\frac{e^{iz}}{z^2+1}$ like I did then the limit will be equal to zero. Write $z=x+iy$. Then $e^{iz}=e^{ix}e^{-y}$. The absolute value of $e^{ix}$ is $1$ and because we are in the upper half plane ($y>0$) we have $e^{-y}<1$. Hence $|e^{iz}|\leq 1$ in the upper half plane. From here it is easy to conclude that the integral of $f$ goes to zero.
Comment: So we find the integral $\int_{-\infty}^\infty\frac{e^{ix}}{x^2+1}dx$. And then using the identity $e^{ix}=cosx+isinx$ and the fact that we are on the real line we take the real part and get the required integral.
Comment: Thanks a lot, that makes it way clearer! I also noticed that I didn't know about Jordan's Lemma, which you basically used here - np? Very nice, thanks!
Comment: Actually I didn't use Jordan's lemma. I used the most simple bound: the absolute value of the integral is bounded by the length of the contour times the maximum of the function on this countour. So in our case it is bounded by $\pi R*max|\frac{e^{iz}}{z^2+1}|$. As we already know on this contour $|e^{iz}|\leq 1$ and from here it is easy to see that $\pi R*max|\frac{e^{iz}}{z^2+1}|\to 0$ when $R\to\infty$. Now, if we would have an expression like $z-i$ in the denominator then this limit wouldn't be equal to $0$. In that case we would need Jordan's lemma. (so good to know it as well)
Comment: That kind of rings a bell too. Thanks, gonna work over everything again tomorrow! Thanks


Ionic ,Node js build ios error

Question: I am trying to create a basic mobile app using steps provided on
this link
Everything worked fine till step 3. But on step 3
<code>$ ionic build ios
</code>
is giving error as under

✗ (node:9776) fs: re-evaluating native module sources is not
supported. If you are using the graceful-fs module, please update it
to a more recent version.
Error: xcodebuild was not found. Please install version 6.0.0 or
greater from App Store

I am already using the latest version of node.js ie; 6.2.0. Am I missing anything?
Comment: @theaccordance - Well spotted, I overlooked that...
Comment: As per the error, you need to install xcodebuild version 6 or greater.
Comment: You can't compile to iOS using Windows, unless of course someone's written a port of `xcodebuild`
Comment: When the error says "more recent version" it refers to graceful-fs , not Node itself.
Answer: Simply put, you can't compile iOS apps locally using a Windows Machine.  You'll either need to compile those apps using a Mac, or a cloud-compiler service, like PhoneGap Build or Ionic Platform.
Comment: ionic is what i am trying to use...How to build it using ionic?
Comment: You'll have to read how to do it on Ionic's website.  I don't use their cloud compiler because I develop on a Mac

Ionic ,Node js build ios error


Query on Apache load balancer balancer-manager and also on JSESSIONID/Stickysessions

Question: I am setting up Apache with mod_proxy and balancer-manager, and just have two questions on this.
1 Is there any way to color code the status in the balancer-manager? EG green for OK, blue for draining, red for disabled, or something like it? A stpuid question I know, but I find visual aids like colors help.
2 Using JSESSIONID sticky sessions. If I restart the apache load balancer in front, will this reset the users JSESSIONID?
Regards
B
Answer: 1) No. You'd have to make an RFE or modify the code yourself.
2) No, it should have no effect. Apache addes 'routes' to the end of the JSESSIONID that is set by the underlying app server and uses this route when requests are made to determine which underlying service to use.


Help with simplifying trigonometric expression

Question: I need to understand how to obtain $f/g$ and $f/h$ from the following equations:
$$
\frac{f^2\sin^2\alpha}{h^2}+\frac{f^2\cos^2\alpha}{g^2}=f^2/k^2
$$
$$
\frac{f^2\sin^2\beta}{h^2}+\frac{f^2\cos^2\beta}{g^2}=f^2/l^2
$$
Which must lead to the following expressions:
$$
(f/g)^2=\frac{(\frac{f\sin\alpha}{l}+\frac{f\sin\beta}{k})(\frac{f\sin\alpha}{l}-\frac{f\sin\beta}{k})}{\sin(\alpha+\beta)\sin(\alpha-\beta)}
$$
$$
(f/h)^2=\frac{(\frac{f\cos\beta}{k}+\frac{f\cos\alpha}{l})(\frac{f\cos\beta}{k}-\frac{f\cos\alpha}{l})}{\sin(\alpha+\beta)\sin(\alpha-\beta)}
$$
I know the expressions are correct but I get lost in the algebra and can't understand how to go from the first couple of equations to the second couple. Any help will be very appreciated.
Comment: But $f^2$ can be cancelled straightaway
Answer: The first thing I notice is, both in the starting and ending expressions, you can divide both sides by $f^2$, so the variable $f$ plays no role in this calculation other than being along for the ride. Dividing it from the initial equations, we get:
$$
\frac{\sin^2\alpha}{h^2}+\frac{\cos^2\alpha}{g^2}=1/k^2
$$
$$
\frac{\sin^2\beta}{h^2}+\frac{\cos^2\beta}{g^2}=1/l^2
$$
Now, just to give us a break from fractions, let's define $H=\frac{1}{h^2}$, $G=\frac{1}{g^2}$, $K=\frac{1}{k^2}$, and $L=\frac{1}{l^2}$, giving us:
$$
H\sin^2\alpha + G\cos^2\alpha = K
$$
$$
H\sin^2\beta+G\cos^2\beta = L
$$
Now we see that we have linear equations with unknowns $H$ and $G$, and we can solve them by the usual techniques:
$$
H=\frac{K\cos^2\beta-L\cos^2\alpha}{\sin^2\alpha\cos^2\beta-\sin^2\beta\cos^2\alpha}
$$
$$
G=\frac{L\sin^2\alpha-K\sin^2\beta}{\sin^2\alpha\cos^2\beta-\sin^2\beta\cos^2\alpha}
$$
Undoing our substitution for $K$ and $L$, we note that both numerators are differences of two squares, and can be factored accordingly:
$$\begin{align}
K\cos^2\beta-L\cos^2\alpha = \frac{\cos^2\beta}{k^2}-\frac{\cos^2\alpha}{l^2} &= \left(\frac{\cos\beta}{k}\right)^2-\left(\frac{\cos\alpha}{l}\right)^2\\
&= \left(\frac{\cos\beta}{k}+\frac{\cos\alpha}{l}\right)\left(\frac{\cos\beta}{k}-\frac{\cos\alpha}{l}\right),
\end{align}$$
and similarly for the other one.
That just leaves the (identical) denominators to account for. They can also be factored as differences of two squares:
$$\begin{align}
\sin^2\alpha\cos^2\beta-\sin^2\beta\cos^2\alpha &= (\sin\alpha\cos\beta)^2 - (\sin\beta\cos\alpha)^2\\
&=(\sin\alpha\cos\beta + \sin\beta\cos\alpha)(\sin\alpha\cos\beta -
 \sin\beta\cos\alpha)\\
&=\sin(\alpha+\beta)\sin(\alpha-\beta),
\end{align}$$
where the last step uses the identities for $\sin$ of a sum and a difference.
Finally, multiply both sides by $f^2$ again, and you obtain your desired result.
Comment: Thank you very much! Great help
Comment: @G Tony Jacobs is it possible that your first solution for $H$ has the wrong signs? I obtain: $H=\frac{-K\cos^2\beta+L\cos^2\alpha}{-\sin^2\alpha\cos^2\beta+\sin^2\beta\cos^2\alpha}$
Comment: That's the same answer. Just multiply by $\frac{-1}{-1}$
Comment: Yes, thanks, and sorry for bothering.
Comment: No worries! Glad I could help. :)
Answer: Remove common $f^2$ as having no role in problem.
You are asking to just to solve two linear equations with two unknowns.
Let $$ k_1=1/h^2,\, k_2=1/g^2,\, 1/k^2 = x_1,\, 1/l^2 = x_2,\,  $$
$$ k_1 \cos ^2 \alpha+ k_2 \sin^2 \alpha = x_1 \tag1$$
$$ k_1 \cos ^2 \beta+ k_2 \sin^2 \beta = x_2 \tag2  $$
By Cramer's Rule common denominator
$$ D= (\cos \alpha \sin \beta)^2- (\sin \alpha \cos \beta)^2 \tag3 $$
that simplify to common denominator in your last two equations.
and numerators for $k_1,k_2$ are respectively
$$  x_1 k_2 \sin^2 \beta - x_2 k_2 \sin ^2\alpha \tag4 $$
$$  x_2  k_1 \cos^2 \alpha - x_1  k_1 \cos^2\beta \tag5 $$
which again simplify to numerators you  gave in the last two equations after plugging in 1) and 2) for $x_1,x_2$.
Comment: thank you, I didn't know about Cramer's rule so I used the technique of equating coefficients and could understand the results that @G Tony Jacobs also gave me.


How can I render a view as JSON inside a template file?

Question: I would like to render a view as JSON, within the page template. I would hide it with CSS and use it with JavaScript.
Is there a way to alter the Format field used when creating a view, which normally shows options like Grid, HTML List?
I did try the Rest Export core module, but it seems to render the view as JSON with no other page content.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/127163/discussion-on-question-by-hayden-thring-how-can-i-render-a-view-as-json-inside-a).
Answer: Though originally I wanted to avoid making subsequent requests to the server, it seems its the easiest way to get around this. Just make some views that output json and load them with ajax.


Ambiguous reference in Stream

Question: This is the webservice method i have
 LoadImageFromDB(int ID, ref Stream streamReturnVal)

I have this on the top of the section using Stream = System.IO.MemoryStream;
Whenever i consume this method(update web reference) from a web application, i get this error
 'Stream' is an ambiguous reference between 'System.IO.Stream' and 'WebReference.Stream'

Any thoughts?
In webservice class
using Stream = System.IO.MemoryStream;
LoadImageFromDB(int ID, ref Stream streamReturnVal);

In web page where above webservice is consumed:
using WebReference;
Stream streamReturnVal = null;
streamReturnVal = new MemoryStream();

WebserviceInstanceName.LoadImageFromDB(100,streamReturnVal );

PS: Stream  - is from System.IO.Stream
Comment: having a *using Stream = System.IO.MemoryStream;* doesn't help much, unless you remove *using System.IO* as well.
Answer: So this is caused when you have two namespaces that contain Types with the same name within a single piece of code.
So this section
using Stream = System.IO.MemoryStream;
LoadImageFromDB(int ID, ref Stream streamReturnVal);

should explicitly define what kind of Stream is being passed.
It should probably look something like this
using Stream = System.IO.MemoryStream;
LoadImageFromDB(int ID, ref System.IO.Stream streamReturnVal);

Comment: @msarchet - Thanks, i will let you know after i test.
Comment: @Pauli, that's what I meant, fixing that now
Comment: i know, just wanted to point it out so you could correct it :)
Comment: @msarchet - Thanks, but still i get "Ambiguous reference in Stream" error, any thoughts?
Comment: @Sharpeye500 did you also fix the one in WebRefrence
Comment: @msarchet - Thanks. I was not able to fix this issue, so i converted return type as byte[] & in the front end there is byte to stream conversion, which saved time.
Comment: Hmm, that's odd it's probably something that wasn't visible in the code you showed then, glad it's fixed tho.
Answer: Try moving the using Stream = System.IO.MemoryStream is inside your namespace declaration.
Comment: I have using Stream = System.IO.MemoryStream this inside my webservices.
Comment: Could you post the relevant parts of your source file? Also, I want to be clear that I mean to move the `using` statement from outside (or above) the namespace where you normally put it, to within it (inside the namespace block).
Answer: Do you have using WebReference? That may create a problem.
Comment: @sharpeye500: if your aliasing creates ambiguity, you have little choice - either rename alias or resolve ambiguities with fully qualified class names (include namespaces).
Comment: Please help me to understand by going thro' the code from top section.
Comment: It's not clear what stream must be used in the LoadImageFromDB. If the MemoryStream then: using MStream = System.IO.MemoryStream; LoadImageFromDB(int ID, ref MStream streamReturnVal); Otherwise: LoadImageFromDB(int ID, ref WebReference.Stream streamReturnVal);
Comment: Stream is nothing but reading the image from bytes & sending back in the form of memory stream.
Comment: From your changes to the question, it seems you want to use MemoryStream. In this case, if you declare your method as LoadImageFromDB(int ID, ref System.IO.Stream streamReturnVal); you don't need an alias 'Stream': using Stream = System.IO.MemoryStream; If the alias concept is new to you, it's nothing but a shortcut for not using fully qualified class names

Ambiguous reference in Stream


Calculate the sum $\sum_{n=1}^{\infty}\Big((2n-1)\Big(\sum_{k=n}^{\infty}\frac{1}{k^2}\Big)-2\Big) $

Question: Calculate the sum $$\sum_{n=1}^{\infty}\Big((2n-1)\Big(\sum_{k=n}^{\infty}\frac{1}{k^2}\Big)-2\Big) $$
The only thing I can think of is that $\sum_{n=1}^{\infty}\frac{1}{k^2}=\frac{\pi^2}{6}.$ However, I can't go any further.
Comment: You should include the link and write down what you have learnes so far.
Comment: If it is active, this question will be deleted (most probably).
Comment: @metamorphy It would seem the [olympiad](https://iuhd.edu.tm/competition/7) is over but the solutions are not posted yet.
Comment: Where does this task come from?
Comment: @ms._VerkhovtsevaKatya From a contest
Comment: @ms._VerkhovtsevaKatya My source is my friend :) He sent me this for my help, but I couldn't deal with this one
Comment: Interesting link for the _Basel problem_ :https://math.stackexchange.com/q/8337/721644
Comment: @metamorphy My friend says that that contest is called "The 3rd Open Mathematical Olympiad for University Students" and it's not that famous.
Comment: @metamorphy No, it is not. It has ended approx. 3-4 days ago
Comment: Hint: $$\sum_{n=1}^N (2n-1)\sum_{k=n}^\infty \frac1{k^2} = \sum_{k=1}^\infty \frac1{k^2} \sum_{n=1}^{\min\{k,N\}} (2n-1) = \sum_{k=1}^N 1 + \sum_{k=N+1}^\infty \frac{N^2}{k^2}.$$
Answer: For $ n\in\mathbb{N} $, define the sequence $ \left(u_{n,k}\right)_{k} $ as follows : $ u_{n,k}=\left\lbrace\begin{aligned}\frac{2n-1}{k^{2}\left(4k^{2}-1\right)},\ \ \ \textrm{If }k\geq n\\ 0,\ \ \ \ \ \ \ \ \ \ \ \ \ \textrm{If }k<n\end{aligned}\right. $
Since $ \sum\limits_{n=1}^{+\infty}{u_{n,k}}=\frac{1}{k^{2}\left(4k^{2}-1\right)}\sum\limits_{n=1}^{k}{\left(2n-1\right)}=\frac{1}{4k^{2}-1} $, and $ \sum\limits_{k=1}^{+\infty}{\frac{1}{4k^{2}-1}}=\frac{1}{2}\sum\limits_{k=1}^{+\infty}{\left(\frac{1}{2k-1}-\frac{1}{2k+1}\right)}=\frac{1}{2} $, the family $ \left(u_{n,k}\right)_{\left(n,k\right)\in\left(\mathbb{N}^{*}\right)^{2}} $ is summable, and Fubini's theorem allows us to write the following : \begin{aligned} \sum_{n=1}^{+\infty}{\sum_{k=1}^{+\infty}{u_{n,k}}}&=\sum_{k=1}^{+\infty}{\sum_{n=1}^{+\infty}}{u_{n,k}}\\ &=\sum_{k=1}^{+\infty}{\frac{1}{4k^{2}-1}}\\ \sum_{n=1}^{+\infty}{\sum_{k=1}^{+\infty}{u_{n,k}}}&=\frac{1}{2} \end{aligned}
But since \begin{aligned} \sum_{n=1}^{+\infty}{\sum_{k=1}^{+\infty}{u_{n,k}}}&=\sum_{n=1}^{+\infty}{\left(2n-1\right)\sum_{k=n}^{+\infty}{\frac{1}{k^{2}\left(4k^{2}-1\right)}}}\\&=\sum_{n=1}^{+\infty}{\left(2n-1\right)\sum_{k=n}^{+\infty}{\left(\frac{4}{4k^{2}-1}-\frac{1}{k^{2}}\right)}}\\ &=\sum_{n=1}^{+\infty}{\left[\left(2n-1\right)\left(2\sum_{k=n}^{+\infty}{\left(\frac{1}{2k-1}-\frac{1}{2k+1}\right)}\right)-\left(2n-1\right)\sum_{k=n}^{+\infty}{\frac{1}{k^{2}}}\right]}\\ \sum_{n=1}^{+\infty}{\sum_{k=1}^{+\infty}{u_{n,k}}}&=\sum_{n=1}^{+\infty}{\left(2-\left(2n-1\right)\sum_{k=n}^{+\infty}{\frac{1}{k^{2}}}\right)} \end{aligned}
We get, $$ \sum_{n=1}^{+\infty}{\left(\left(2n-1\right)\left(\sum_{k=n}^{+\infty}{\frac{1}{k^{2}}}\right)-2\right)}=-\frac{1}{2} $$