How can I select every other line with multiple cursors in Sublime Text?

Question: In Sublime Text 2, is it possible to instantly select every other (or odd/even) line and place multiple cursors on those lines?
Thanks.
Comment: Don't you want to accept an answer?
Answer:
Find: Ctrl+F
If regular expressions are not already enabled, enable them: Alt+R
Type in the expression .*\n.*\n
Find all: Alt+Enter
Press left arrow to get rid of the selections, leaving just the cursors: ←
You now have a cursor at the start of every odd-numbered line. If you wanted even-numbered lines, press down: ↓
Depending on the file, there might be one cursor missing right down the bottom of the file. Using the mouse (damn!) scroll to the bottom, hold down Ctrl, and click where the missing cursor should be to add it in.
Comment: You can also use `(.*\n){10}` for every 10 lines
Comment: [As a new improvement](http://stackoverflow.com/a/15598633/1238019) : `(.*(\n|$)){2}`
Comment: nice! @zessx's `(.*(\n|$)){2}` solution includes the last line
Comment: Just to note, in Sublime 2 running on OS X 10.11.5, the shortcut for RegEx search is Alt + Command + R. You can also enable RegEx search by pressing Command + F and then clicking the icon that looks like this: [ .* ]
Answer: You can do it easily :

Select all your lines, or the whole document Ctrl+A
Add multiple selectors : Ctrl+Shift+L (and in Mac: Command + Shift + L)

EDIT :

Or use the great Joe Daley method with (.*(\n|$)){2} expression
Comment: though not the right answer for this question, this is what i wanted. thanks for sharing
Comment: This solution is what I needed but not what the OP wants.
Answer: I was searching for a way to select alternate lines in sublime.
Thanks to Joe Daley for a very good answer.
Though I realised that, if you use regex it would not select the last line in the file if there is no new-line at the end of the file.
I wanted to improve that answer but I don't seem to have enough reputation at the moment to comment on the answer above.
You can use the following search string with the regex turned on, and then press alt+enter. Followed by a left arrow. This would put a cursor each on alternate lines (same steps as explained by Joe Daley)
^.*\n.*$

Comment: This comment from 2014 just saved my morning. Thanks.
Answer: You can try with a plugin: Tools/New Plugin...
import sublime_plugin

class ExpandSelectionToOtherLinesCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.window().run_command("expand_selection", {"to": "line"})
        start_region = self.view.sel()[0]
        self.view.window().run_command("select_all")
        self.view.sel().subtract(start_region)

Save this file in your Packages/User.
Then, add the key binding for that plugin:
{ "keys": ["super+alt+l"], "command": "expand_selection_to_other_lines" }

This command will select all other lines. When you have other lines selected, you can use Split selection into lines command (Ctrl+Shift+L, Cmd+Shift+L on Mac).
If you want to have everythnig in a single shortcut, you can modify the plugin like this:
import sublime_plugin

class ExpandSelectionToOtherLinesCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.window().run_command("expand_selection", {"to": "line"})
        start_region = self.view.sel()[0]
        self.view.window().run_command("select_all")
        self.view.sel().subtract(start_region)
        self.view.window().run_command("split_selection_into_lines")
        self.view.window().run_command("move", {"by": "characters", "forward": False})

The last line is only to remove selection, leaving multiple cursors at the beginning of selected lines.
Comment: Wow this looks promising - I'm gonna try this as soon as I can!
Comment: Thank you very much! I'm fairly new to the plugins. Should be fun. Begin able to select every other line would be just fantastic. Cheers!
Answer: I also wrote a plugin to do that, but I'm too lazy to publish it, so you can just create a SelectEveryNthLine.py file in Packages/User and put this code inside:
import sublime
import sublime_plugin

class SelectEveryNthLine( sublime_plugin.TextCommand ):
    def run( self, edit ):

        def on_done( n ):
            n = int( n )

            selections = self.view.sel()

            # if there is nothing selected, then select everything
            if len( selections ) == 1 and selections[0].size() == 0:
                selections.add( sublime.Region( 0, self.view.size() ) )

            new_selections = []

            for sel in selections:
                for i in range( self.view.rowcol( sel.begin() )[0], self.view.rowcol( sel.end() )[0] + 1, n ):
                    line_region = self.view.line( self.view.text_point( i, 0 ) )
                    if not sel.contains( line_region ):
                        continue
                    new_selections.append( line_region )
            selections.clear()
            for sel in new_selections:
                selections.add( sel )

        # firstly ask for the N
        sublime.active_window().show_input_panel( "Enter N to select ever N-th line:", "", on_done, None, None )

You can also create file SelectEveryNthLine.sublime-commands and put following code inside, to make it accessible from Command Palette:
[
    {
        "caption": "Select every N-th line",
        "command": "select_every_nth_line"
    }
]

Answer: If it's not a huge amount of lines, you can also of course just hold Ctrl (Cmd on Mac) and click on each line where you want a cursor.
For smaller numbers of lines, this is quicker and easier than running regex commands or adding plugins.


Principal Part and little o notation

Question: The function is $f(x) = 2x + e^{x+x^{4/3}} -1$ and the question wants the principal part with respect to $g(x)=x$ as $x$ goes to $0^+$.
I solved it using MacLaurin expansion and I got $3x$, but should it also have the little $o$ notation with the answer, like $3x + o(x)$?
Answer: As $x\to 0^+$,
$$e^{x+x^{4/3}}=1+(x+x^{4/3})+O(x^2)=1+x+O(x^{4/3}).$$
with Big O notation. Therefore you may write
$$f(x)=3x+O(x^{4/3})\quad\mbox{or}\quad f(x)=3x+o(x^{a})$$
with any $1\leq a<4/3$.

Principal Part and little o notation


How to create username unique with respect to database?

Question: I have one field named
username:_________
now i want to add manuaaly username to the database
if once added and i add same next time it must automatically show invalid username right side of  textbox i am searching same code on net and tried too many solution but not working.
This i want to performed in php and mysqli
Comment: what you have tried ? post your coding... with out coding we can't give a solution
Comment: I have not started yet I have just given unique constraint to the username field in my table
Answer: Just mark it as UNIQUE.
<code>CREATE TABLE User
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
</code>
And in PHP script do something like this:
<code>$query = mysqli_query($con, "SELECT id FROM user WHERE username='$username'");

if(mysqli_num_rows($query) > 0){

    echo "Username already exists";
}else{
    // do something
    if (!mysqli_query($con,$query))
    {
        die('Error: ' . mysqli_error($con));
    }
}
</code>
And if you want to check in realtime if username is available (like @Arun pointed) maybe this would help a bit.
Comment: you have to try in  Jquery and Ajax
Comment: I want to display to the user as soon as he finished typing the username and go to the next field it must displayed to him duplicate username enter different like message
Comment: please refer this link http://www.sanwebe.com/2013/04/username-live-check-using-ajax-php for username availablity


Number Theory excercise

Question: please I need your help with this problem
Let $p$, $q$ prime numbers, $ p<q$, $p$ divides $q-1$. Show that exist an integer $k$ such that $k \not\equiv 1$ mod $q$ and $k^p \equiv 1$   mod $q$.
Comment: What have you tried? Have you looked at small values of $p$ and $q$ where $p$ divides $q-1$ and tried to find $k$ with the desired properties? How about when $p=3$ and $q=7$? Do you already know Fermat's Little Theorem, which says that for any integer $a$, $a^{q-1}\equiv1\mod q$?
Comment: (In Fermat's Little Theorem, I left out the necessary requirement that $a$ not divisible by $q$.)
Answer: Take a look at Fermat's Little Theorem and the Euler Fermat Theorem.
Answer: Using Discrete Logarithm wrt some primitive root $g\pmod p$ on $\displaystyle k^p\equiv1\pmod q,$
$\displaystyle p\cdot$ind$_gk\equiv0\pmod{q-1}$
which is true for all integer $k$ as $p|(q-1)$

Number Theory excercise


How to record audio and write audio data to file in android

Question: I want to record audio and write audio data to file in android.
I have to use these parameters this function for recording audio.
AudioRecord: AudioSource:VOICE_COMMUNICATION, sampleRate : 48000 ChannelConfiguration : channel_in_mono, PCM_16bit.
buffer = ByteBuffer.allocateDirect(960);
audioRecord.read(ByteBuffer buffer, int capacity);

And then I have to write audio data to write file and then play it by using AudioTrack.
Answer: There is a really nice tutorial on Android Developers webpage.
https://developer.android.com/guide/topics/media/audio-capture.html
When creating MediaRecorder object, you can set sampling rate to it by doing this:
mediarecorder.setAudioSamplingRate(int x)
Im pretty sure you can set the other parameters too, just follow the link above and its sub-links.
I dont know if this is your desired way of solving your problem, hopefully it will lead you to the right track. Good luck!


Problemas com logica do insert

Question: Estou com um problema. Estou fazendo um sistema de controle de acesso de eventos, criei uma tabela que grava os dado id,codigo,data,hora,sit, o campo sit será 1 e 2, mas preciso que o meu sistema entenda o seguinte. Quando o ultimo registro do banco for 1 ele irá inserir o sit 2 e quando for 2 irá inserir o sit 1, segue abaixo minha estrutura.
<?php
    include"conect_db.php";

    $string_sql = mysql_select_db("evento"); //seleciona o banco de dados

    //Abaixo atribuímos os valores provenientes do formulário pelo método POS
    $string_sql = ("select * from checkout where codigo='06181121978' order by id desc limit 1");
    mysql_query($string_sql,$conn); //Realiza a consulta

    if ($string_sql==$string_sql) {
        $teste = ("INSERT INTO checkout (id,codigo,data,hora,sit) VALUES (null,'06181121978',CURDATE(),curtime(),'1') <> (select * from checkout where codigo='06181121978' AND SIT='2' order by id desc limit 1");
        mysql_query($teste,$conn);
    }
    else{
        $teste2 = ("INSERT INTO checkout (id,codigo,data,hora,sit) VALUES (null,'06181121978',CURDATE(),curtime(),'2')");
        mysql_query($teste2,$conn);
    }
?>

Fiz assim , não deu erro mais tbm não registrou
$string_sql = mysql_select_db("evento"); //seleciona o banco de dados

//Abaixo atribuímos os valores provenientes do formulário pelo método POS

$string_sql = ("select * from checkout where codigo='06181121978' order by id desc limit 1");
 mysql_query($string_sql,$conn); //Realiza a consulta

$resultado = mysql_query($string_sql, $conn);

$dado = mysql_fetch_assoc($resultado);

if ($dado['sit'] == '1') {
    // insere sit 2
    "INSERT INTO checkout (id,codigo,data,hora,sit) VALUES (null,'06181121978',CURDATE(),curtime(),'2')";
}
else {
    // insere sit 1
    "INSERT INTO checkout (id,codigo,data,hora,sit) VALUES (null,'06181121978',CURDATE(),curtime(),'1')";
}

Comment: `if ($string_sql==$string_sql) {` ? Faltou pegar o resultado da consulta e aplicar no if, cade o `mysql_fetch_assoc()` :P
Answer: Existem alguns erros na sua lógica. A função mysql_query() deveria ser atribuída a uma variável que recebe seu resultado, por exemplo:
$resultado = mysql_query($string_sql, $conn);

Logo abaixo, no IF, você compara uma variável com ela mesma, enquanto deveria verificar se o resultado da consulta anterior o campo "sit" é 1 ou 2, por exemplo:
$dado = mysql_fetch_assoc($resultado);
if ($dado['sit'] == '1') {
    // insere sit 2
}
else {
    // insere sit 1
}

Não sei se entendi muito bem sua necessidade, caso não esteja claro, comente que atualizo a resposta.
Comment: fiz assim , não deu erro mais não gravou nada.
Answer: Bom, neste caso é interessante você fazer uma query de update com condição, sem precisar impor lógica dentro do escopo do seu script.
Um exemplo:
UPDATE sua_tabela
SET sit = CASE
WHEN (SELECT sit FROM sua_tablea WHERE sua_condicao ORDER BY id DESC LIMIT 1 ) = 1 THEN 2
ELSE 1
END

Neste exemplo eu executo o update, ao definir valor do campo eu executo um sub select, onde nele pego o último SIT, se for 1 eu coloco 1, se for 2 coloco 1.
Comment: mais vou usar em um formulario que ira receber o cidigo de barras, vai funcionar?
Comment: Não entendi sua dúvida, Fernando. Na query de UPDATE eu apenas executei um sub select pegando o SIT do último registro e fazendo um IF ELSE para o valor do field. Basicamente eu retirei todo esse script que você fez para executar 3 querys para fazer isso, deixei a cargo do MYSQL.
Comment: Olá, consegui fazer, o problema era que quando criei a condição eu não tinha criado uma variável para o insert dentro do if e else, por isto não gravava os dados.

if ($dado['dados'] == '1') {
    // insere sit 2
  $query ="INSERT INTO lanca (id,dados) VALUES (null,'2')";
    $resultado = mysql_query($query) or die('Error, query failed');

}
else {
    // insere sit 1
 $query ="INSERT INTO lanca (id,dados) VALUES (null,'1')";
    $resultado = mysql_query($query) or die('Error, query failed');

}

Problemas com logica do insert


J2ME Tamil(UniCode) Character Display

Question: I tried a many way to print tamil character in J2ME application
 வ whose unicode value U0BB5.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;

/**
 * @author arun kumar non ascii
 */
public class SampleMidlet extends MIDlet {

    Display display;
    Form form = null;
    String ms = null;
    NewClass obj;

    public void startApp() {
        display = Display.getDisplay(this);
        form = new Form("Unicode Test");
        byte[] b = new byte[2];
        b[0] = 0x0b;
        b[1] = (byte) 0xb5;
        try {
            form.append("type0" + "வ");
            form.append("type1" + new String(b, "UTF-16"));
            form.append("type2" + new StringItem("", "\u0bb5").getText());
            form.append("type3" + "\u0bb5");
            form.append("type4" + new StringBuffer("\u0bb5"));
            form.append("type5" + new StringBuffer().append((char) Integer.parseInt("2997", 10)));
            form.append("type6" + ((char) Integer.parseInt("0bb5", 16)));

            char[] text = new char[]{'\u0bb5'};
            form.append(new String(text));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        display.setCurrent(form);

    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

but all the time it shows  white box alone as shown.

where as in Netbeans emulator also shows the same, I'm targeting configuration for CLDC 1.1 and MIDP 2.0 .How to display that character without using Bitmap font (Image)file of that character ?
Answer: Square boxes normally mean that the Font is unable to display that character. The encoding is fine, but you need a different Font.
This link explains how to change the Fonts on the emulator: http://www.devarticles.com/c/a/Java/J2ME-and-Unicode/1/
Comment: As far as I was told, J2ME only supports a subset of the unicode characters. So Tamil might very well just not be supported. When/if you see Tamil in apps/games, they're most probably created using bitmap fonts. That means, a PNG file containing all the characters + some code to render a String using those characters. It's not that difficult to code. Sadly though, I don't think you can use a bitmap font on a highlevel app (meaning one that uses Forms). I think you'll need to use Canvas/GameCanvas when using Bitmap fonts.
Comment: of course its unable to display that character,My question is how to display that one on mobile.
Comment: have added link to answer. Not sure how you get new fonts on to the phone though, but that should work with the emulator.
Comment: I already came across that link  it works for japanese,Arabic on emulator not for Tamil,but though tamil is unicode why it is not supporting.don't you seem the code where merely same
Comment: Why the down vote? Seems a little harsh. Fonts are the problem, and weren't mentioned in the question.
Comment: question is about displaying Unicode character ,font or visual glyph are inter related to the question,
Comment: @arun I have no idea how you expect to *display* a character without a *visual* glyph.
Comment: did i said anything without visual glyph? i just need to display character in any feasible way.
Answer: As with comment proper bitmap file can capable to produce the font on j2me app.
MJbookmaker is capable tool which produce desire format for j2me application

J2ME Tamil(UniCode) Character Display


Reading An Image And Saving It, Increases the Image Size

Question: I've loaded an image using CV2.imread, and saved it using cv2.imwrite() and scipy.misc.imsave(). In both these cases output image size is bumped. Why is this?
Both input and output images are of file type .jpg
img = cv2.imread(img_src)
scipy.misc.imsave(img, "scipy_original.jpg")
cv2.imwrite("cv2_original.jpg", img)

Input file size is 309kb
Output file size in cv2 is 690kb
output file size in scipy is 399kb
this is the image if you want reference: https://i.stack.imgur.com/9qMe0.jpg
Comment: It is using it's default values if we don't specify anything.
refer: https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html
Answer: OpenCV has different compression levels for jpg, from 0 to 100. The default is 95.
This question discusses it, and this site has examples.
Saving with parameters like this:
cv2.imwrite("cv2_original.jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) where jpg_quality < 95 will reduce the file size.
Comment: @Beeti: An 8-bit image doesn't have a bit rate of 8 in a JPEG file. Compression causes the bit rate to drop, for example you can get 0.5 bits per pixel. The compression quality dictates this. The lower the quality, the more data gets lost and the lower the bit rate will be. In a 16-bit image you start off with more bits per pixel, but you can still go down to a very low bit rate. In your case, the input JPEG has a lower quality than the output JPEG, and hence a lower bit rate.
Comment: But isn't that going to change the quality of the output image? And how does compression affect the image size, I thought using different bit-rates like 8-bit, 16-bit are the causes for increasing in size. Please clarify this point.
Comment: Yes it will change the output quality. Generally more compression == less size == less quality.
Comment: Bit rates also contribute to size, but the compression algorithm and compression level contribute too. I think they make more of a difference than bitrates but I'm not sure about that
Comment: @CrisLuengo That makes sense, so openCV and scipy by default save the image with higher bit rate while encoding? Can we know the bit rate of an image by any means? Thanks for your answer.
Comment: I'm currently using this formula to calculate bit rate or bpp (bits per pixel) =>  (image file size in bits) / (image height pixels * image width pixels * no of channels). But the results come out to be less than 1, it doesn't make sense. Aren't bitrate supposed to be 4-bit 8-bit 16-bit?
Comment: @Beeti: You're calculating bits per sample (rather than bits per pixel, but that's OK too). As I said, bit rates are much less than 8 or 16 in a JPEG image. If you compress the data to 10% of its size, an 8-bit per sample image comes out at 0.8 bits per sample after compression. In memory you have 8 bits per sample, but on file you have only 0.8 bits per sample. This is the whole point of compressing the image.


Extract fields from complicated server response

Question: I have a server response that has this format:
{"bankAccounts":[
                  {"id"     :"wfasfsd",
                   "balance":{"amount":90, "currency":"GBP"}
                  }
                ]

I cant find out how to parse through it efficiently
For a similar response with of simpler format this post helped me (Extract JSONObject and iterate through HashMap field)
The picture shows exactly how the server response looks like. I need to extract this into JSON and in the end, I need to  have a HashMap with keys id, amount, currency
Comment: What do you mean by - parse through efficiently? Note, that `bankAccounts` here is an array, so you can get multiple `id` fields
Comment: Any way I could get the fields would be great. Especially if it was possible to put them all in a HashMap, like with keys, id, amount, currency
Answer: You can use json-simple library to read and write json objects.
Here you can see how to use it.


Silently passing exceptions with Future objects

Question: I have a problem with silently passing exceptions in tornado while using futures in situations, when I am not explicitly waiting result from future coroutines (yield some_future_obj), such as infinite loop coroutine:
@gen.coroutine
def base_func():

    @gen.coroutine
    def tail_something():
        raise
        while True:
           yield some_other_coroutine

    base_func()

I have also noticed that this topic was already discussed: refer to here or here.
The problem is that if we don't wait for future completion explicitly, future.result() never be called and exception will never be raised. But tornado.concurrent is committed to use concurrent.futures package.
Now I just hang ioloop.add_future on current loop and simply execute log.exception(future.result()). But I don't like this approach, since it is a bit noisy (redundant lines in production code).
Please, contribute your ideas or may be a real answer.
Answer: The reason Futures "hide" exceptions is that you have to decide where you want the exception to show up.  If you want to be able to handle the exception in your code, you must access its result somewhere (which in a Tornado coroutine means yielding it).  If you just want to log the exception, you can ask the IOLoop to do it for you:
IOLoop.instance().add_future(fut, lambda fut: fut.result())

Note that I'm just calling result() instead of logging its value.  This ensures that we don't log anything when there is no error, and the exception (with traceback) is logged by IOLoop's normal unhandled-exception machinery.
Comment: In that case you may need to insert a non-coroutine shim between RabbitMq and your real coroutine so you can get the coroutine's Future result and add it to the IOLoop.
Comment: Thank you, very nice answer, Ben. I forgot that we can simply subscribe to any future's result.
Comment: what if coroutine is callback, that should be called every time when some data is ready to be processed. For instance, RabbitMq async consumer consumes messages from specified queue and receive all messages to some callback method like ``on_message`` which in turn must call some async code and wait for its reply. In such situation ``on_message`` is coroutine, but no way to handle exceptions there.


"Viewport" by META tag in HTML ... if iPad = X and if iPhone = Y?

Question:
Working good with iPad but not iPhone
Any code can I direction to iPad and iPhone
for iPad
<meta name="viewport" content="width=1040px, minimum-scale=0.5, maximum-scale=1.0" />

for iPhone
<meta name="viewport" content="width=440px, minimum-scale=0.5, maximum-scale=1.0" />

Comment: im done with

Answer: iPhone max-width is 480px not 440px
<meta name = "viewport" content = "user-scalable=no, width=device-width"/>

<meta name="apple-mobile-web-app-capable" content="yes"/>

This sets the viewpoint with the scaleable option off
<link media="only screen and (device-width: 768px)" rel="stylesheet" href="css/ipad.css" type="text/css" title="no title"/>

This is a css file for only iPad
<link media="only screen and (max-device-width: 480px)" rel="stylesheet" href="css/small-device.css" type="text/css" title="no title"/>

This is a css file for only iPhone
They are conditional comments so they will only apply to specific devices with specified max-widths.
Comment: This answer makes no sense at all :/


BEAST (Browser Exploit Against SSL/TLS) Vulnerability on Port 25 for Postfix

Question: I am failing a PCI Compliant scan. I have successfully used RC4 ciphers for Apache setup but my Postfix configuration is still not fixed. What TLS configuration should i use in my main.cf file.
my current configuration is as follows
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
tls_preempt_cipherlist = yes
smtpd_tls_protocols = !SSLv2
smtpd_tls_mandatory_protocols = !SSLv2, SSLv3
smtpd_tls_cipherlist = RC4-SHA:+TLSv1:!SSLv2:+SSLv3:!aNULL:!NULL
smtp_tls_cipherlist = RC4-SHA:+TLSv1:!SSLv2:+SSLv3:!aNULL:!NULL
smtpd_tls_security_level = encrypt

Comment: just a note: `smtpd_tls_cipherlist` is obsolete since 2.3, but should work.
Comment: Don't process email on your public facing web server, or any server which is also processing customer information.
Answer: Your auditor is aware that the B in BEAST stands for BROWSER right?
It is pretty impractical (though yes, not entirely impossible) for a non-browser client like a MUA to leak enough information to compromise security.
That said, you should be able to use the various _cipherlist parameters as you did for Apache.  You should make sure you do not offer any vulnerable ciphers (I believe you currently do with that cipher list, but I'm not looking at the expanded lists so I could be wrong).
You may also want to turn off tls_preempt_cypherlist in case that's causing problems with cipher negotiation.

As others have pointed out your mail server should be an isolated piece of infrastructure (and thus generally outside the scope of a PCI audit anyway.
If your auditor is poking around it's probably easier to just patch it to shut them up, but if your mail server is not an island unto itself you really need to re-architect so that it is. That's just standard security best practices.
Comment: Thanks for your elaborated explanation. The deal is that I am using EC2 instance and using postfix to relay emails to google apps account. I am not storing customer information on my server, however hosting SSL forms which post sensitive data to authorize.net servers. What are my possible options?
Comment: @AbdulHaseeb In that particular case I would eliminate postfix for handling inbound mail (point your MX records directly at Google Apps). If you *need* postfix in the loop spin up another EC2 instance to run it on (a micro would probably be fine) -- you *really* shouldn't run a mail server on a system that's involved with taking customer data (even if you're just showing them a form that posts elsewhere) - I think it's technically OK for PCI standards, but it's definitely a breach of isolation and not the best way to work...
Comment: yes, I am going with eliminating postfix for inbound mails. If I would need a mail server then I will use another EC2 instance for that.
Thanks, it helped a lot :)


Discriminants of number fields

Question: As I understand it discriminants are supposed to easily prove statements like $\sqrt r \not\in \mathbb Q (\sqrt p, \sqrt q)$ for $r,p,q$ distinct odd primes.
You can easily calculate a discriminant like $$D_{\mathbb Z[\sqrt p, \sqrt q]/\mathbb Z} (1,\sqrt p, \sqrt q, \sqrt p \sqrt q)=2^8 p^2q^2$$
Let $\mathscr O$ be the ring of integers of $\mathbb Q (\sqrt p, \sqrt q)$ over $\mathbb Q$.
Apriori you don't know a basis for the ring of integers, but you do know that the discriminant $ D_{\mathscr O/\mathbf Z}$ generated by $a \in \mathbb Z$ should satisfy
$ak^2 = 2^8 p^2q^2$ for some integer $k \in \mathbb Z$.
So if $z$ is any prime with $z|a$ then $z|2pq$.
If you assume to the contrary that $\sqrt r \in \mathbb Q (\sqrt p, \sqrt q)$ and you can show that $z|2rq$ and $z|2pq$ so it must be that $z=2$ so $a=2^m$ for some $m$. It seems like $p$ should divide $a$ so that this should be a contradiction. Does $p|a$? How do you see that?
Answer: There is a relation for the tower of discriminants. Let $A$ be a Dedekind domain with field of fractions $F$. Let $F''/F'/F$ be a tower of field extensions with $A'$ (resp. $A''$) the integral closure of $A$ in $F'$ (resp. $F''$). Then the discriminants satisfy
$$
D_{A''/A} = \mbox{Norm}_{A'/A}(D_{A''/A'}) D_{A'/A}^{[F'':F']}
$$
so in particular $D_{A'/A} | D_{A''/A}$. So in the above example we have that the discriminant of the ring of integers in $\mathbb Q(\sqrt p)$ is $4p$ so that $4p|a$.
http://math.stanford.edu/~conrad/676Page/handouts/transdisc.pdf

Discriminants of number fields


Set ng-selected in angular-ui select

Question: My HTML code:

      Select State

        <ui-select name="lenderBusinessState" ng-model="lenderInfo.modelState.selected" theme="select2" class="form-control">
          <match placeholder="Select Lender State">{{$select.selected.stateName}}</match>
          <choices repeat="state in states | filter: $select.search">

          </choices>
        </ui-select>

          <button type="button" ng-click="lenderInfo.modelState.selected = undefined" class="btn btn-danger">

          </button>

My JS code:
$scope.selectState = function(stateIdPassed)
{
    console.log(stateIdPassed);
    if(stateIdPassed == $scope.stateId){
        return 'selected';
    }
}

I want to prefill my ui-select input. I am using ui-select. If i don't use ui-select input and just use  tags, then its working. But, not with  tags.
What are the possible solutions? Please help me out as i have used  in my application.
Answer: just set lenderInfo.modelState.selected with the value you want preselected.
here is some code for you to try just throw these lines where you setup the controller
$scope.lenderInfo.modelState = {};
$scope.lenderInfo.modelState.selected =  {"stateId":1,"stateName":"Florida"};

Answer: You need to have the state you want prefilledto be available in the states array.
If that doesn't fix it, make a plunker/fiddle and I'll look into it :)
Comment: This should be a comment and not an answer.

Set ng-selected in angular-ui select


How to get all node ids from same content type

Question: I am using Drupal 8 and I want to create related content, but the problem is that I can't figure it out, how I can get all node IDs(except current one) for a specific content type.
Comment: Why not use Views for this task?
Answer: This is a basic query that returns last 10 changed nodes (published) of type 'article'. Modify for your needs.

<code>$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'article')
  ->range(0, 10)
  ->sort('changed', 'DESC');
$nids = $query->execute();
</code>
Comment: I think you need to add in a condition to exclude current node id.


Two representations one-dimensional are equivalent if only if they are equal

Question: Let $\phi , \psi : G \to \mathbb{C}^{*} $ be one-dimensional representations. Show that $\phi$ is equivalent to $\psi$ if and only if $\phi = \psi.$
Well, if $\phi \sim \psi$ (equivalent), then there exist a vector space isomorphism $T : \mathbb{C} \to \mathbb{C}$ where ${\psi}_{g} = T{\phi}_{g}T^{-1}$, for all $g \in G$. Also, since $\phi$ and $\psi$ have dimension 1 (which is the size of the vector space $\mathbb{C}$) then such representations are irreducible, that is, $\lbrace 0 \rbrace$ and $V$ are the only G-invariant subspaces under $V$.
I want to show that $\phi = \psi$, that is, that $\phi_{g}(a) = \psi_{g}(b)$ for all $g \in G$. I thought of taking $a = T^{-1}(b)$ and using the equality $\phi_{g}(a) = \phi_{g}T^{-1}(b)$ but did not succeed.
Answer: Hint: $T$ is one dimensional and one dimensional matrices (i.e. complex numbers) commute
Comment: In this approach will I not even need to go into the definition of irreducibility?
Comment: Every 1 dimensional representation is irreducible...
Comment: Since $\phi$, $\psi$ and $T$ are one-dimensional, then applied to any element of $\mathbb{C}$ are scalar and therefore commutate. That is:
$ (\Rightarrow ) \phi \sim \psi \Rightarrow \phi_{g} = T^{-1}\psi_{g}T \Rightarrow T\phi_{g} = \psi_{g}T \Rightarrow T\phi_{g} = T\psi_{g} (comute) \Rightarrow \phi_{g} = \psi_{g}.\\
(\Leftarrow ) \phi_{g} = \psi_{g} \Rightarrow T\phi_{g} = T\psi_{g} \Rightarrow T\phi_{g} = \psi_{g}T (comute) \Rightarrow \phi_{g} = T^{-1}\psi_{g}T.
$
This is correct?


Route::get with options and function not working properly in laravel

Question: I wan to use Route::get with route options, function and where. following is my route code:
Route::get('/view/{id}', array('uses' =>'BookController@view','as' => 'book.view'), function($id)
{
    die('hello');

})->where('id', '[A-Za-z]+');

so when i call url view/4 it will open 404 page and when i call view/abc it will run controller code but in neither case function code is not executing.
How can i fix this?
Comment: Sorry just noticed why did you attach controller as well as callback function.
You should use either callback or controller
Comment: Can you display the controller logic
Comment: there is nothing in controller right now. let's say `echo 'hi';`
Comment: @Deepak I am planning to put some code in controller and i don't want add much length in route file and that's why i don't want to put controller code in route file (if i can avoid) otherwise i need to do the same. is there any way i can do that?
Comment: Remove the callback first and test it
Comment: @DeepakKumarTP if i remove call back then it will redirect to 404 and i don't want to redirect to 404, i want to open custom url/code.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185363/discussion-between-dipen-and-deepak-kumar-t-p).
Comment: That looks "confusing". Why not use two seperate routes?
Answer: For routing you already put restriction in "id" variable and it should be string only "->where('id', '[A-Za-z]+');"
So there is no problem here in case you use number it should get you 404
And for controller issue you code it wrongly because you add controller and in same time you write Closure and you have to write only one.
So try this
Route::get('/view/{id}', ['uses' =>'BookController@view','as' =>'book.view'])->where('id', '[A-Za-z]+');

and for using number try this
Route::get('/view/{id}', ['uses' =>'BookController@view','as' =>'book.view']);

Thank you
Comment: @Dipen Why don't you just use _one_ case, either `closure` or `controller` and decide/check there if `$id` is numeric or alpha?
Comment: @kerbholz My primary goal to avoid controller code from route if it's possible and if we can use id validation in route i don't want to do that in controller. so if condition flied i want to redirect to another url or some custom code and if condition match then execute controller code.
Comment: Yes these both will work but my requirement is different. I want to run custom code when `where()` condition return false. means in my current case if some try interger then function code should work instead of 404 page


Is it easy to update ubuntu beta to ubuntu final release?

Question: At this moment I am preparing a virtual server to host a web application which needs php5.3
The virtual server base image is always Hardy (8.04 LTS). There is no php5.3 until the upcoming release in a few days: Lucid (9.04 LTS).
I am seeing to options:
 - waiting until the final version is released and then start preparing this server
 - Now upgrading to the beta (do-release-upgrade --devel-release) and when the final release has come upgrading to that
For time constraints I would prefer the second option. I only can't find whether it will be easy to upgrade from a beta to the 'clean' final release. Is this possible in an easy way. Will it have any drawback for security or will there be any traces left of it being ever a beta release?
Note: the server will not go into production before the LTS is really installed.
Answer: Lucid it's 10.04 LTS ;) (that is april 2010 so i'd just wait a couple of days).
btw it should be no problem upgrading from beta to stable release...
Actually could be less hassle than upgrading directly from 8.04.


Transformation of box constraints after PCA

Question: I have a $n\times m$ data matrix  where $n$ is the number of records and $m$ number of dimensions. Running principal component analysis (PCA) and selecting first $k<m$ components, I get an $n\times k$ matrix.
Consider I had a box constraints on the original data, say $x_{\min},x_{\max}\in\mathbb{R}^{m}$. How to construct new constraints for the first $k$ components?
The motivation is the following: I want to optimize an unknown function $f:X\to\mathbb R$ where $X$ is the hyperbox given by $x_{\min},x_{\max}$. I need to construct the function $\hat f$ from data. For practical reasons, I need PCA on the data. How to transform the set $X$?
Comment: Please be more precise. What the new constraints should do? If X data is constrained to some range PCs are also constained. Do you want some other constraint for their range?
Answer: It is a little bit hard to answer withouth further information : why would you like to impose box constraints after the PCA ? Did you impose them before the PCA or is it something you observed in the data ?
Indeed, there is no guarantee that the output of the PCA (i.e. the coordinates of the points on the principal axis)  will follow the initial box constraints.
So you will have to rescale the output of your PCA to match the box constraints, just as you would do (did?) it before the PCA.


Multiple exogenous IV 2sls in Stata

Question: In my model I have two exogenous variables which I want to use as instruments.
Can you please help me with Stata code for it?
I assume it should be something like this:
ivregress 2sls inf exp_inf gap (brent gas = oil_lag1 gas_lag1)

where first instrument is brent=oil_lag1
and second is gas=gas_lag1
Am I right? I just got strange results so I want to make sure.
Answer: The endogenous variables that you want to instrument for go on the left of the equal sign and the instruments go on the right side in the parenthetical part.
The intuition behind 2SLS is that you are using the instruments to predict the endogenous variables, and using the predictions from that model as regressors in place of the endogenous variables themselves. In the first stage, the endogenous variables are the outcome variable and instruments are the explanatory variables or regressors. The parenthetical part represents that first stage.
Comment: Thank you very much!

Actually, I am trying to instrument variable by it`s lag. I run Lag-order selection statistics and it strongly suggests me that I should use first lag for my model. However, when I include this lag, all the variables become insignificant. So model doesn't tell me anything.

Can you suggest something?
Thanks for your time.
Comment: @VictoriiaAlekhina I don't really understand your model and this is not my area of expertise. There's also not very much detail in your questions, so you are unlikely to get much useful advice from anyone else. I suggest asking a new question on the [econ SE site](http://economics.stackexchange.com/), where you provde some additonal details (what is the outcome, what is the source of endogeneity, why are the isntruments relevant and exogenous, how did you implement the lag selection, etc.)

Multiple exogenous IV 2sls in Stata


Comment with email or social networks

Question: I am developing my personal site in drupal 7. Actually i am searching for a module which allows anonymous users commenting with their email or any social n/w like twitter,facebook or google+. Is there any good module available or is drupal 7 supports  anonymous users commenting with their email address ?
Answer: You can achieve that using the OpenID Selector module

This module integrates Javascript OpenID Selector with Drupal's OpenID client.
This module substitutes Drupal's default OpenID form with Javascript OpenID Selector widget, so users do not even need to know what OpenID URL is.
Comment: Thanks, with this module first user has to register & then do comment ?
Because i dont want users to register & do commenting
Answer: We can achieve that using the Disqus module

Comment with email or social networks


Improving bass transcription skill

Question: I'm trying to get in the habit of transcribing music. I don't have a lot of experience, so my ear isn't very good yet, and in particular I often have trouble distinguishing parts of the bass line from similar-sounding instruments like bass drum and guitar. What practices or tools can I use to develop this skill?
It seems like a good A–B repeater and equalizer might help with this, perhaps other tools as well. If you have software or hardware recommendations, please note that I use Apple computers and tablets.
I have only tried a few pieces so far, mostly riff-based rock like Silversun Pickups, or Pink Floyd's "Money," where it is relatively easy to follow the bass. I also try to follow bass rhythms with my fingers while I'm in the car, which is how I noticed how difficult it can be to separate bass guitar from kick drum in rock styles. I mostly listen to modern rock, some classic rock and trip hop, occasionally blues, jazz, soul, funk. I especially like to play blues and soul.
Comment: [Amazing Slow Downer](http://www.ronimusic.com/amsldox.htm) Simple & effective.
Comment: I would say that you will typically find it easier to pick out the basslines on blues, jazz, funk stuff, as the bass parts are usually rather separate from other parts, though the bass and kick will often line up in funk and soul.  A lot of more hiphop based stuff will often have the bass follow the kick and the tone is muddier, such as the classic 808 bass sounds, which tend to blend right into the kick.  When I have difficulties, I will often just try to play with the track and listen to how my playing blends in.  If it fits right in, you're probably pretty close.  Sounds bad, probably wrong
Comment: What type of music are you trying to transcribe? This can make a very big difference. For instance, a lot of rock music will have the bass line follow the guitar part to the extent that they basically function together as one part. Similarly, lots of genres will often have the bass drum and the bass follow each other rhythmically, so it can cause some issues hearing all of the specific notes of the bass. Additionally, there are differences in the way tone is set up for electric bass in different genres that can round out the sound enough that frequencies of the bass are harder to perceive.
Comment: @Basstickler Question updated.
Answer: I always use Audacity for transcribing music. It's a free audio editor (for Mac and Windows). If necessary you can change the tempo, and you have a lot of other useful options. However, I've been transcribing music for many years and I've come to the conclusion that in most cases you just need to be able to select the difficult bit and be able to loop it until you start hearing what's going on. I hardly ever slow down or use any other processing. Since you can select arbitrarily short pieces, you can track down each and every note, even in fast passages. When transcribing complex harmonies it helps (me) to have an instrument at hand playing a single note while the chord sounds to be able to judge whether that single note is part of that chord or not. Anyway, if you're a beginner I would start with transcribing single note melodies (or bass lines).
As a final note, general ear training helps a lot for transcribing. Of course, transcribing itself is also ear training but if it's too difficult in the beginning you might want to go through some basic ear training exercises before starting the more difficult transcriptions.
Comment: Thanks for the tips! I used this approach today with the Amazing Slow Downer for iPad to learn Muse's "Supremacy." My setup makes it easier to use a tablet than my laptop, so if you know of any apps as good for AB looping as Audacity I'd like to know. The Amazing app makes it easy to learn a measure at a time but the interface is not quite up to isolating individual notes or chords.
Answer: I guess you could put some time and effort into ear training. It will definitely help you transcribe more accurately, but it will also boost most of your other musical skills. Not the funniest type of practice, but absolutely essential.
Answer: Posted as an answer at the OP's request - though I'm not really sure I deserve the points for a 'point & shoot' software link ;-)
Amazing Slow Downer Can adjust speed & pitch independently, & also select short segments to loop, allowing you to hammer away til you figure it out.
Not free, $50
Sceenshot -

Edit:
One trick I've used in the past for working out bass lines, is to not use a bass whilst working them out, as you can cover the very thing you're trying to hear. I've used everything from acoustic guitar, piano, synth - just something I can work through the notes yet stay out of the way of what I'm trying to listen to.
Comment: Thanks! This would be even more helpful if you had tips for how best to use the software. Are there any settings especially helpful for isolating bass? Some of them might also work well with the software tools I already have.
Comment: Oh hey, there is an iOS version too! $15 instead of $50. That's pricy for an app but a lot more palatable than the computer version.
Comment: tbh, I've never actually used it, other than as a demo many many years ago. I would normally loop a bit in Cubase, without usually changing speed or pitch, but ASD just seemed designed to do precisely what you asked (& is nowhere near the price of Cubase ;)
Comment: The iPad app was tremendously helpful. You can AB loop a section of a song, say 16 or 32 measures, then cut it down and walk through 2 or 4 measures at a time, then open it back up to the whole passage. I learned Muse "Supremacy" that way today, very handy. I'm going to accept Matt L's more comprehensive answer, but this was very, very helpful! Thanks!
Comment: I up voted his answer too, mine was just a one-liner :)

Improving bass transcription skill


Bootstrap collapsed navbar not expanding

Question: I'm new to Bootstrap and just trying to get the collapsed dropdown nav bar to behave. It resizes perfectly, all the way up to the point that the window is so small that it triggers all the nav bar items being removed and placed inside the little data-toggle button. Because when I click that lil' data-toggle button, it does not expand and show the items in a drop down list like its supposed to.

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-collapse">
                     Toggle navigation

                  </button>

Home

Family Law

Criminal Law

Conveyancing

About

Contact

I've used this identical code on all pages, however for some reason it only works on the home page of this site. The only difference between the home page and other pages is that beneath the  tags there is another div of content containing the main text for that page & an image. That said, when I delete the entire code for this div from my page, the problem persists so I don't think its that....
I may also be (over)using redundant classes, but thats a story for later...
Answer: With >5 you have to use "data-bs-target" instead of "data-target" for the button.
This:
  <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

Instead of:
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

Answer: Most of the time, its because jQuery isn't linked to the page correctly. Or bootstrap.js is referenced before jQuery.js. Make sure you have those linked correctly.
Answer: I used the same code and it is working perfectly, check at http://jsbin.com/henume/2/edit?html,output
You mentioned that it resizes properly, so i assume that the bootstrap.css is working. Please make sure the jQuery.js and boostrap.js are included in the page.
Comment: Thanks! Interesting.... I actually saw other answers about jQuery to this effect, but assumed because I did have a jQuery in the html this wasn't the issue. But apparently the bower template I used linked it in such a way that doesn't guarantee it loading..

The bower template puts jQuery at the bottom of the body, and the bootstrap js stuff after that still. So something about that ordering means that the jQuery doesn't load in time? When i follow your jsbin and put the include in the head, then it works perfect.
Answer: Changing data-toggle to data-bs-toggle and data-target to data-bs-target fixed it for me. CSS caching is a mystery sometimes leaving me to wonder when I made the breaking change. Hope this helps.
Answer: As nasirkhan mentioned, the code is working perfectly on live domain. At times this issue can be caused by just the local domain name as was in my case and the same code was renderering fine on live site.
Answer: I had the same problem, confirm that you are including these two files.
First one is for Bootstrap(css) and second one is for Bootstrap(javascript).
In my case included the css one correctly but you know what I did at the time of including second one I included is as a stylesheet but it's a script.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Answer: Addition of these three lines helped me.

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Answer: I was using firstname.lastname@example.com instead of 4.6.0, as in my tutorial.
Guess things have changed in the new version.
Answer: I am using Bootstrap 5.1 and had the same issue. It only happens if you do not have the reference to the bootstrap.js file before the end of the body tag.


Hilt ViewModel has no zero argument constructor

Question: Cannot create an instance of class com.comp.app.winners.WinnersViewModel
Caused by: java.lang.InstantiationException: java.lang.Class<com.comp.app.winners.WinnersViewModel> has no zero argument constructor

Getting an error when trying to resolve a viewmodel on a fragment using hilt
// Proj
ext.hilt_version = '2.32-alpha'
ext.lifecycle_version = "2.2.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"

// App
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha03'
implementation "androidx.fragment:fragment-ktx:1.1.0"

@HiltAndroidApp
class MyApplication : Application()

@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {
    @Provides
    fun provideService(): MyService = MyServiceImpl()
}

@AndroidEntryPoint
class HomeActivity : AppCompatActivity() {

    // Fragment is added here
    private fun openFragment(fragment: Fragment) =
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.container, fragment)
            addToBackStack(null)
            commit()
        }
}

@AndroidEntryPoint
class WinnersFragment: Fragment() {
    private val viewModel: WinnersViewModel by viewModels()
}

@HiltViewModel
class WinnersViewModel @Inject constructor(
    private val service: MyService
) : ViewModel()

Is there something else to be done with the fragment?
Do i need to provide the viewModel somehow?
NOTE: This is a crash/runtime-error, not a compile error
Comment: try this: https://stackoverflow.com/a/73041253/13216976
Answer: My issue was nothing to do with my ViewModel, but to do with the fragment it was being applied to.
My ViewModel looks like
@HiltViewModel
class MyViewModel @Inject constructor(repository: MyRepository): ViewModel() {

This is correct, but I still got the exception Caused by: java.lang.InstantiationException: java.lang.Class<com.myapp.MyViewModel> has no zero argument constructor
However, I'd missed the AndroidEntryPoint annotation on the fragment. Adding this back in fixed the problem for me, i.e.
@AndroidEntryPoint
class MyFragment: Fragment() {

    private val viewModel: MyViewModel by viewModels()

    ...
}

Answer: If getting this error while using compose, it might be because you are using a NavHost and NavHostController. According to official documentation:

If your @HiltViewModel annotated ViewModel is scoped to the navigation graph, use the hiltViewModel composable function that works with fragments or activities that are annotated with @AndroidEntryPoint.

hiltViewModel is part of a dedicated Hilt + Compose Navigation dependency:
dependencies {
    // 1.0.0-beta01 at time of this writing.
    // official docs linked above appear to auto update the version
    implementation("androidx.hilt:hilt-navigation-compose:[version]")
}

Here is a contextualized example of the call to hiltViewModel provided in the same documentation:
// import androidx.hilt.navigation.compose.hiltViewModel

@Composable
fun MyApp() {
    NavHost(navController, startDestination = startRoute) {
        composable("example") { backStackEntry ->
            // Creates a ViewModel from the current BackStackEntry
            // Available in the androidx.hilt:hilt-navigation-compose artifact
            val exampleViewModel = hiltViewModel<ExampleViewModel>()
            ExampleScreen(exampleViewModel)
        }
        /* ... */
    }
}

Answer: You need to upgrade to Fragment 1.2.0 or higher.
As per the Lifecycle 2.2.0 release notes, the new ViewModelProvider APIs that Hilt uses under the hood only apply when using Fragment 1.2.0 or higher. When using an older version of Fragments, those APIs are not connected to fragments and therefore your Hilt enabled ViewModel factory is not used when you use by viewModels().
You should upgrade to Fragment 1.2.5 (the last version of the Fragment 1.2.X set) or to Fragment 1.3.0, both of which contain the necessary API hooks to get Hilt working.
Comment: Looks like Hilt is not as safe as it is advertised


Number of cells in a bounding hexagon (of a hex p-mino)

Question: I am reading an article about counting hexagonal p-minos.
In page 3 (of the pdf) we define a boundoing hexagon for a p-mino,
In page 6 the article claims that delta - the number of cells inside and on the boundry of the bounding hexagon equal to $s1+s3+s5$ choose $2$ -...
Does anyone have any idea for why this is true ? I have no clue to even why it looks like something in the form of a choose b -...
Answer: The formula comes from combining two ideas:

In a triangular lattice, an equilateral triangle with $k$ lattice points in the first row contains a total of $$k+(k-1)+(k-2)+\dots+1=\binom{k+1}{2}$$ lattice points: $k$ in the first row, $k-1$ in the second row, and so on.
The hexagon can be thought of as taking one larger triangle and cutting a small triangle off of each of the corners (figure $8$ in their paper).  The larger triangle has $(s_1+1)+(s_5+1)+(s_3+1)-2=s_1+s_3+s_5-1$ points in the first row ($(s_1+1)$ points from the triangle of side $s_1$, etc., then subtract $2$ since we counted two vertices twice).  The triangles we subtract off have $s_1$, $s_3$, and $s_5$ points in their first row.
Comment: Thank you vey much, so "the number of cells" means the number of lattice points ? maybe you also understand why K<=C ?(and what is the meaning of K..I looked up the word 'skew' and didn't find a meaning that suits)
Comment: $K$ represents the difference between opposite sides -- how far the hexagon is from being a symmetrical one where opposite sides are equal.  Geometrically, you can think of the $K \leq \min\{A,B,C\}$ here as representing that the sides of a hexagon can't change too quickly if the angles aren't too small.  Every time we move (for example) to the right by one unit, the height of the hexagon in the corresponding vertical slice can change by at most $1$.  So the difference in the leftmost and rightmost vertical slices ($K$) can be at most as large as the horizontal width of the hexagon ($B$).
Comment: On cells vs. points: To each cell the article associates a set of coordinates $(x,y,z)$.  It's natural to think of these as points in a triangular lattice (the actual lattice underlying this is the dual lattice formed by associating to each hexagonal cell its center and connecting the centers of adjacent hexagons).  Counting the number of hexagons intersecting a region then corresponds to counting the number of lattice points in a region.


how to use hook_forms()

Question: I'm trying to get multiple forms for a content type at one page
so, I went by hook_forms($form_id,$args), but when use it, I receive a not full populated form array
I have
hook_menus()
$items['user/%user/administracion/saldos-vacaciones-admin'] = array(
    'type'=>MENU_LOCAL_TASK,
    'title'=>'Saldos admin',
    'page callback'=>'pezgordo_saldos_dias_feriado_form',
    'page arguments' => array(1),
    'access arguments' => array('maneja personas'),
    'file' => 'saldos_dias_feriado_form.inc',
    'file path' => drupal_get_path('module', 'pezgordo').'/includes/user',
);

includes/user/saldos_dias_feriado_form.inc
function pezgordo_saldos_dias_feriado_form($persona=NULL){

$saldos = array_of_nodes();//this is the array of nodes I want their edit forms

$cuenta_forms = 0;
if($saldos){
    foreach($saldos as $ks=>$s){
        //$form_state[$ks]['build_info']['args'] = array($s);

        dpm("$cuenta_forms $ks");

        /*here! if I changes one statemet by the other,
        I can see using A $form[$ks] is an array of 29 elements,
        using B I get an aray of 53 elements, all node related items
        are gone, so form doesn't show at all*/

        //A
        //$form[$ks] = drupal_get_form('saldo_dias_feriado_node_form-'.($cuenta_forms),$s);
        //B
        $form[$ks] = drupal_get_form('saldo_dias_feriado_node_form', $s);

        //dpm($form['$ks]);

        $cuenta_forms++;
    }//fin para cada saldo
}//fin hay saldos

return $form;

}

pezgordo.module
function pezgordo_forms($form_id, $args){
$forms = array();
// Check if the form id is of the pattern add_to_collection_form-[NUMBER]
if(preg_match('/^saldo_dias_feriado_node_form-\d+$/', $form_id)){
    $forms[$form_id]['callback'] = 'saldo_dias_feriado_node_form';
    //$forms[$form_id]['callback arguments'] = $args;
}
dpm($forms);
return $forms;
}

please any help ? thanks
Comment: This is still not working for me. Despite I can see every form has an unique identifier id, the submission of any form doesn't work. When I submit I receive a message: "El contenido de esta página ha sido modificado por otro usuario o usted ya ha enviado modif..."

Also, the field I changed at one form is updated (not in db, just in form) in all forms, not just the one I've changed

I can see a hidden field named "form_id", inside every form, the value of this field is the same on every form, HOW I CAN CHANGE THIS HIDDEN FIELD TO TRY IF THIS IS CAUSING THE PROBLEM ?? ... please ... help !!
Answer: You need to call the forms with a unique ID each time. You can do this:
$i = 0;
foreach($saldos as $ks=>$s){
  $form[$ks] = drupal_get_form('saldo_dias_feriado_node_form-' . $i, $s);
  $i++;

Comment: thank you @jaypan, I'm doing that. As I comment in my code, I'm calling drupal_get_form in two ways (A and B) alternatively . Using the A way, is resulting in a form array that **lacks of many node related items** (if not all). I've also tried passing $form_state as argument to hook_forms(), but no luck. Please, what else may I do to get this ?, thanks

how to use hook_forms()


When is the supremum of a function on a subset equal to the supremum on a set?

Question: Let $f$ be a continuous, real function on a set $X$. Suppose the set $D \subset X$ is dense in $X$, and the set $S \subset X$ is closed and has empty interior, i.e. it is nowhere dense. Moreover, $S\cap D$ is nonempty.
Are there any known conditions for when $\sup(f(S))=\sup(f(S\cap D))$?
I would like to treat $X$ as a general topological space, but feel free to make any assumptions you need.
Comment: @Renard not in general, but I'd still be interested in a proof under the assumption that D is countable!
Answer: Your conditions allow $S\cap D$ to be a singleton, which isn't much better than allowing $S$ and $D$ to be disjoint; you'll need a lot more interaction between $S$ and $D$ to get equality of the suprema. Suppose, in fact, that $S\cap D$ is not dense in $S$, and let $H=\operatorname{cl}(S\cap D)\subsetneqq S$. Fix $p\in S\setminus H$. If $X$ is Tikhonov, there is a continuous real-valued function $h:X\to[0,1]$ such that $h(p)=1$ and $h[H]=\{0\}$; clearly $\sup h[S]=1>0=\sup h[S\cap D]$.
This shows that if $X$ is at all nice in terms of the existence of real-valued functions, you'll need $S\cap D$ to be dense in $S$, and in that case you do of course get equality of the suprema.
Comment: Since $S$ has empty interior, this implies that we must have that $S \subset D$ right? This is what I'm afraid of...
Comment: @Tyler6: No, it doesn't. If $S$ is the middle-thirds Cantor set, for instance, the set of endpoints of the deleted intervals is a dense subset of $S$, and by a cardinality argument $D\subsetneqq S$.
Comment: If $D$ is closed, then must it be that $S \subset D$? This is what I thought and what I'm hoping isn't the case.
Comment: @Tyler6: Yes, if you want the space to be at least Tikhonov: if $S\cap D$ dense in $S$, and $D$ is closed, then $D\supseteq S$. The only alternative that I can see would be to have some restrictions on the functions that you're considering, but what they might be would depend pretty heavily on $S$ and $D$.
Comment: I see thank you! My space is Tikhonov, I will work on trying to appeal to my function in particular in that case.
Comment: @Tyler6: You're welcome! And good luck with it!


Compare unique values in one column but not the other Pandas

Question: What's the best way to find values in one column but not in another column?
df1:
col1  col2
A     5
B     7
C     8
D     10

df2:
col3  col4
C     5
D     8
E     10
F     9

How can I find the unique values in df1.col1 but not df2.col3?
Expected output: A, B
and values in df2.col3 but not in df1.col1?
Expected output: E,F
Comment: Use `isin`. `df1.col1[~df1.col1.isin(df2.col3)].unique()`
Answer: You can try set.difference()
res = list(set(df1['col1']).difference(df2['col3']))

print(res)

['B', 'A']


Query MySQL agrupando os resultados no case

Question: Tenho a seguinte consulta:
SELECT
 DAY(o.data_fechamento) AS DIA,
 u.nome AS TEC,
 COUNT(*) AS TOTAL
  FROM
    ocorrencias AS o
        LEFT JOIN sistemas AS a ON a.sis_id = o.sistema
        LEFT JOIN localizacao AS l ON l.loc_id = o.local
        LEFT JOIN instituicao AS i ON i.inst_cod = o.instituicao
        LEFT JOIN usuarios AS u ON u.user_id = o.operador
        LEFT JOIN usuarios AS ua ON ua.user_id = o.aberto_por
        LEFT JOIN `status` AS s ON s.stat_id = o.status
        LEFT JOIN status_categ AS stc ON stc.stc_cod = s.stat_cat
        LEFT JOIN problemas AS p ON p.prob_id = o.problema
        LEFT JOIN sla_solucao AS sls ON sls.slas_cod = p.prob_sla
        LEFT JOIN prioridades AS pr ON pr.prior_cod = l.loc_prior
        LEFT JOIN sla_solucao AS slr ON slr.slas_cod = pr.prior_sla
        LEFT JOIN script_solution AS sol ON sol.script_cod = o.oco_script_sol
        LEFT JOIN prior_atend AS prioridade_atendimento ON prioridade_atendimento.pr_cod = o.oco_prior
     WHERE
          o.status IN (4)
          AND MONTH( o.data_fechamento) = MONTH(NOW())
          AND YEAR( o.data_fechamento) = YEAR(NOW())
          AND u.nome NOT IN ('ADMINISTRADOR')
          GROUP BY  u.nome,DAY(o.data_fechamento)

Ela retorna da seguinte forma:
DIA NOME    TOTAL
24  MARCOS   1
3   MAURICIO 1
3   PEDRO    1
4   PEDRO    1
6   PEDRO    1
7   PEDRO    3
10  PEDRO    2
24  PEDRO    1
3   ALINE    1
4   ALINE    6
6   ALINE    5
7   ALINE    3
10  ALINE    2
12  ALINE    1
13  ALINE    4
18  ALINE    1
19  ALINE    3
24  ALINE    2
25  ALINE    3
26  ALINE    9
3   CARLOS   13
6   CARLOS   3
10  CARLOS   3
11  CARLOS   11
12  CARLOS   11
13  CARLOS   1
17  CARLOS   2
20  CARLOS   2
24  CARLOS   3
27  CARLOS   12
3   JOAQUIM  1
4   JOAQUIM  1
10  JOAQUIM  1
17  JOAQUIM  1
18  JOAQUIM  1
24  JOAQUIM  1
26  JOAQUIM  3
3   JOAO     12
4   JOAO     12
5   JOAO     1
6   JOAO     3
7   JOAO     4
10  JOAO     3
11  JOAO     4
12  JOAO     5
13  JOAO     4
19  JOAO     3
20  JOAO     5
24  JOAO     1
25  JOAO     2
26  JOAO     5
27  JOAO     4
3   DIEGO    2
6   DIEGO    2
12  DIEGO    6

Preciso que ela retorne os dias em linhas e total abaixo dos dias, consegui chegar até essa query:
SELECT
 u.nome AS TEC,
(CASE DAY(o.data_fechamento) WHEN 1  THEN COUNT(*) ELSE 0 END) AS '1',
(CASE DAY(o.data_fechamento) WHEN 2  THEN COUNT(*) ELSE 0 END) AS '2',
(CASE DAY(o.data_fechamento) WHEN 3  THEN COUNT(*) ELSE 0 END) AS '3',
(CASE DAY(o.data_fechamento) WHEN 4  THEN COUNT(*) ELSE 0 END) AS '4',
(CASE DAY(o.data_fechamento) WHEN 5  THEN COUNT(*) ELSE 0 END) AS '5',
(CASE DAY(o.data_fechamento) WHEN 6  THEN COUNT(*) ELSE 0 END) AS '6',
(CASE DAY(o.data_fechamento) WHEN 7  THEN COUNT(*) ELSE 0 END) AS '7',
(CASE DAY(o.data_fechamento) WHEN 8  THEN COUNT(*) ELSE 0 END) AS '8',
(CASE DAY(o.data_fechamento) WHEN 9  THEN COUNT(*) ELSE 0 END) AS '9',
(CASE DAY(o.data_fechamento) WHEN 10 THEN COUNT(*) ELSE 0 END) AS '10',
(CASE DAY(o.data_fechamento) WHEN 11 THEN COUNT(*) ELSE 0 END) AS '11',
(CASE DAY(o.data_fechamento) WHEN 12 THEN COUNT(*) ELSE 0 END) AS '12',
(CASE DAY(o.data_fechamento) WHEN 13 THEN COUNT(*) ELSE 0 END) AS '13',
(CASE DAY(o.data_fechamento) WHEN 14 THEN COUNT(*) ELSE 0 END) AS '14',
(CASE DAY(o.data_fechamento) WHEN 15 THEN COUNT(*) ELSE 0 END) AS '15',
(CASE DAY(o.data_fechamento) WHEN 16 THEN COUNT(*) ELSE 0 END) AS '16',
(CASE DAY(o.data_fechamento) WHEN 17 THEN COUNT(*) ELSE 0 END) AS '17',
(CASE DAY(o.data_fechamento) WHEN 18 THEN COUNT(*) ELSE 0 END) AS '18',
(CASE DAY(o.data_fechamento) WHEN 19 THEN COUNT(*) ELSE 0 END) AS '19',
(CASE DAY(o.data_fechamento) WHEN 20 THEN COUNT(*) ELSE 0 END) AS '20',
(CASE DAY(o.data_fechamento) WHEN 21 THEN COUNT(*) ELSE 0 END) AS '21',
(CASE DAY(o.data_fechamento) WHEN 22 THEN COUNT(*) ELSE 0 END) AS '22',
(CASE DAY(o.data_fechamento) WHEN 23 THEN COUNT(*) ELSE 0 END) AS '23',
(CASE DAY(o.data_fechamento) WHEN 24 THEN COUNT(*) ELSE 0 END) AS '24',
(CASE DAY(o.data_fechamento) WHEN 25 THEN COUNT(*) ELSE 0 END) AS '25',
(CASE DAY(o.data_fechamento) WHEN 26 THEN COUNT(*) ELSE 0 END) AS '26',
(CASE DAY(o.data_fechamento) WHEN 27 THEN COUNT(*) ELSE 0 END) AS '27',
(CASE DAY(o.data_fechamento) WHEN 28 THEN COUNT(*) ELSE 0 END) AS '28',
(CASE DAY(o.data_fechamento) WHEN 29 THEN COUNT(*) ELSE 0 END) AS '29',
(CASE DAY(o.data_fechamento) WHEN 30 THEN COUNT(*) ELSE 0 END) AS '30',
(CASE DAY(o.data_fechamento) WHEN 31 THEN COUNT(*) ELSE 0 END) AS '31'
    FROM
    ocorrencias AS o
        LEFT JOIN sistemas AS a ON a.sis_id = o.sistema
        LEFT JOIN localizacao AS l ON l.loc_id = o.local
        LEFT JOIN instituicao AS i ON i.inst_cod = o.instituicao
        LEFT JOIN usuarios AS u ON u.user_id = o.operador
        LEFT JOIN usuarios AS ua ON ua.user_id = o.aberto_por
        LEFT JOIN `status` AS s ON s.stat_id = o.status
        LEFT JOIN status_categ AS stc ON stc.stc_cod = s.stat_cat
        LEFT JOIN problemas AS p ON p.prob_id = o.problema
        LEFT JOIN sla_solucao AS sls ON sls.slas_cod = p.prob_sla
        LEFT JOIN prioridades AS pr ON pr.prior_cod = l.loc_prior
        LEFT JOIN sla_solucao AS slr ON slr.slas_cod = pr.prior_sla
        LEFT JOIN script_solution AS sol ON sol.script_cod = o.oco_script_sol
        LEFT JOIN prior_atend AS prioridade_atendimento ON prioridade_atendimento.pr_cod = o.oco_prior
     WHERE
          o.status IN (4)
          AND MONTH( o.data_fechamento) = MONTH(NOW())
          AND YEAR( o.data_fechamento) = YEAR(NOW())
          AND u.nome NOT IN ('ADMINISTRADOR')
          GROUP BY  u.nome

Que me retorna da seguinte forma:
MARCOS        0 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0   0
PEDRO         0 0   0   0   0   0   0   0   0   0   0   0   2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
ALINE         0 0   0   0   0   9   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
CARLOS        0 0   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
PAULO         0 0   40  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
JOAQUIM       0 0   61  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
MAURICIO      0 0   9   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
EDER          0 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   2   0   0   0   0   0   0   0
JOAO          0 0   0   0   0   0   0   0   0   0   0   68  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
SANDRO        0 0   0   0   0   10  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
LUCAS         0 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   2   0   0   0   0
DIEGO         0 0   0   0   0   0   0   0   0   0   0   0   8   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Quase deu certo, porém os meus resultados estão acumulando em dias únicos,esses totais: 40,61,9,68,10 é do mês todo e não apenas dos dias mostrados, o que estou fazendo de errado e o que poderia fazer para acertar ?
Comment: Cara acho que pelo que entendi, você deveria primeiramente utilizar o PIVOT no lugar do case. Da uma estudar nesse link: http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/
Answer: Acho que o problema é o count, experimente fazer assim:
SUM(CASE DAY(o.data_fechamento) WHEN 22 THEN 1 ELSE 0 END) AS '22'

Em MySQL isso pode funcionar também, mais elegante:
SUM(o.data_fechamento = 22) AS '22'

Comment: Sua primeira resposta resolveu meu problema, já essa retornou vazia: SUM(o.data_fechamento = 22) AS '22, Obrigado!


if $p(x)$ is irreducible show $cp(x)$ also is irreducible

Question: If $p(x)$ is irreducible in $K[x]$ and $c \ne 0$, $c \in K$ $\Rightarrow cp(x)$ is irreducible in  $K[x]$.
I would start saying that $p(x)=a(x)b(x)$ with $a(x)$ a unit $\lambda \in K$,
without loss of generality,
$\Rightarrow p(x)=\lambda b(x)$  $\Rightarrow cp(x)=(c\lambda) b(x)$, because     $c \lambda \in K \Rightarrow cp(x)$ is irreducible.
I'm not sure if it shows the statement.
Comment: Yeah but is it an integral domain, a field, etc.?
Comment: What is $K$? ${}$
Comment: the set that contains the coefficients for the polynomials.
Comment: an Integral domain.
Comment: If $K$ is an integral domain and not a field then the statement is not true. Take $x \in \mathbb{Z}[x]$, it is irreducible but $2x$ is not.
Comment: @AnuragA depends on the definition of irreducibility in $K[x]$. I've seen the (absolutely godawful) definition that a *polynomial* is irreducible if it doesn't factor as the product of two *positive degree* polynomials.
Comment: @jgon you are correct but I was going with the standard one.
Comment: That being said, I haven't finished reading the question to see if I can tell which the OP is using. Sure, I prefer the standard one too, but it doesn't help a person who uses the other definition.
Comment: The definition I use is that $p(x)$ is irreducible in $K[x]$ if whenever $p(x)=a(x)b(x) \Rightarrow$ $a(x)$ or $b(x)$ is a unit
Answer: Your proof doesn't show the claimed statement.
First of all your proof basically goes: We can write $p(x)=\lambda b(x)$ with $\lambda$ a unit in $K$, $b(x)=\newcommand{\inv}{^{-1}}\lambda\inv p(x)$. Then you write $cp(x)=(c\lambda) b(x)$ and claim that this implies that $cp(x)$ is irreducible. But this doesn't follow. It's essentially circular, you don't know that $b(x)$ or $(c\lambda) b(x)$ are irreducible without using this lemma in the first place.
Also as pointed out in the comments, depending on your definition of irreducible, this statement may be false.
Also the choice of $K$ to represent an integral domain is less than ideal. $K,L,M$ are usually reserved for fields. More common for integral domains are either $A,B,\ldots$ or $R,S,T,\ldots$.


Surface integral of sphere within a paraboloid in spherical coordinates

Question: Find the surface area of the portion of the sphere $x^2 + y^2 + z^2 =3c^2$ within the paraboloid $2cz =x^2+y^2$  using spherical coordinates. ($c$ is a positive constant)
I've found it in cartesian coordinates and then polar coordinates by taking limits $r$ from $0$ to $\sqrt 2 c$ and $\theta$ from $0$ to $2\pi$ and got the answer $4\sqrt 3\pi c^3$.
But for the spherical coordinates I am getting the limits $\phi$ from $\arccos(\sqrt 3)$ to $\pi/2$ and $\theta$ from $2\pi$ to $0$ and the answer is $6\pi/\sqrt3 c^2$ which is $2c$ times less than in cartesian coordinates. What am I doing wrong?
Answer: The limits for $\phi$ are wrong. Note that $\sqrt{3}>1$ and $\arccos(x)$ is defined in $[-1,1]$. Solving the equation $2cz+z^2=3c^2$ we get $z=c$ and $z=-3c$ (which is not acceptable because $x^2+y^2=2cz=-6c^2<0$). Hence $\phi$ goes from $0$ (north pole) to $\arccos(1/\sqrt{3})$. Therefore
$$S=3c^2\int_{\theta=0}^{2\pi}\int_{\phi=0}^{\arccos(1/\sqrt{3})}\sin(\phi) d\phi d\theta=6\pi c^2[-\cos(\phi)]_0^{\arccos(1/\sqrt{3})}=2\pi c^2(3-\sqrt{3}).$$
P.S. Your result $4\sqrt 3\pi c^3$ seems to be a volume not a surface:
$$S=\iint_{x^2+y^2\leq 2c^2}\frac{\sqrt{3}c}{\sqrt{3c^2-x^2-y^2}}dx dy=
2\pi\sqrt{3}c\int_{\rho=0}^{\sqrt{2}c}\frac{\rho}{\sqrt{3c^2-\rho^2}}d\rho=2\pi c^2(3-\sqrt{3})$$
Comment: I used that method to get my final answer.since surface is double integral of root(1+fx^2+fy^2) which becomes root(3c^2)/root(3c^2-r^2). c is a positive constant and r is from 0 to root2*c. So that's the answer I get. Git any ideas?(c is positive so it doesn't depend on angle anymore)
Comment: @UsamaNotkani See my P.S.
Comment: Ok I get what you're saying thanks. I think I made a mistake in one calculation which I am starting to see now that you've written it out


Prove $\min_{i}|\lambda_i| \leq |r_{jj}| \leq \max_{i}|\lambda_i|$

Question: Let A be a normal $n \times n$ matrix with the eigenvalues $\lambda_1,...,\lambda_n$ |A| = |QR|, $|Q^HQ| = I$, $|R| = [r_{ik}]$ upper triangular matrix. Prove: $$\min_{i}|\lambda_i| \leq |r_{jj}| \leq \max_{i}|\lambda_i|, \; j = 1,...,n$$
In this problem, I know that somehow we have to use Cholesky decomposition, which is $A = LL^H$, but I don't know how can I do it to prove.
Comment: I am guessing there is something missing here. If $Q,R$ is a QR decomposition, then so is $-Q,-R$, so perhaps you need absolute values here?
Comment: yes, you are right. I fixed it.
Comment: Oops, that's not quite what I was expecting, I was thinking $|r_{jj}|$...
Comment: I fixed it, but I think the other things are correct too
Comment: If you are using Cholesky, you probably need symmetric positive definite?
Comment: This matrix is symmetric in $\mathbb{C}^n$, and we can assume it is positive define
Comment: You maybe mean the Cholesky factorization of $A^HA$ instead of $A$. But it does not much matter since the (upper triangular) Cholesky factor of $A^HA$ is the same as the triangular factor of the QR factorization (up to some scaling with a unitary diagonal matrix).
Answer: If $A$ is normal, then the absolute values of its eigenvalues are equal to its singular values. In particular, if $\sigma_{\min}(A)$ and $\sigma_{\max}(A)$ are the minimal and maximal singular values of $A$, respectively, then
$$
\sigma_{\min}(A)=\min_{\|x\|=1}\|Ax\|_2=\min_{1\leq i\leq n}|\lambda_i|
\quad\text{and}\quad
\sigma_{\max}(A)=\max_{\|x\|=1}\|Ax\|_2=\max_{1\leq i\leq n}|\lambda_i|.
$$
The easiest way to see this is to consider the spectral decomposition $A=U\Lambda U^*$ and note that $\Lambda=|\Lambda|W$, where $W$ is a unitary diagonal matrix (if $\lambda=|\lambda|e^{\iota\phi}$ is an eigenvalue of $A$, the corresponding factor on the diagonal of $W$ is exactly the phase part of $\lambda$). Hence $A=U|\Lambda|(U\bar{W})^*$. But with $\Sigma:=|\Lambda|$ and $V:=U\bar{W}$, $A=U\Sigma V^*$ is the SVD of $A$.
It remains to show that the diagonal entries of the triangular factor $R$ satisfy
$$\tag{1}
\sigma_{\min}(A)\leq |r_{jj}| \leq \sigma_{\max}(A), \quad 1\leq j\leq n.
$$
Let $e_j$ be the $j$th column of the identity matrix. Then
$$\tag{2}
\sigma_{\max}(A)=\max_{\|x\|=1}\|Ax\|_2=\max_{\|x\|=1}\|Rx\|_2\geq\|Re_j\|_2=\sqrt{\sum_{i=1}^j|r_{ij}|^2}\geq|r_{jj}|,
$$
which proves the upper bound.
For the lower bound, if $A$ is singular, then $\sigma_{\min}(A)=0$, and the bound is trivial. If $A$ is invertible, then similarly as before, we have
$$\tag{3}
\frac{1}{\sigma_{\min}(A)}=\sigma_{\max}(A^{-1})=\max_{\|x\|=1}\|A^{-1}x\|_2=\max_{\|x\|=1}\|R^{-1}x\|_2\geq \frac{1}{|r_{jj}|},
$$
where the last equality is due to the fact that the diagonal of $R^{-1}$ is the inverse of the diagonal of $R$. Putting (2) and (3) together gives (1).
Comment: Nice Approach!! +1.
Comment: thank you, it's nice approach


How many power bi Embed tokens have been generated?

Question: I have Power BI embedded reports with dedicated capacity. We now want to see usage of these. I'd like to be able to see how many embed tokens are generated each day. I can't find any details on this in the documentation or APIs.
In the standard Report usage metrics, all the stats are against a single user - because it's the website connecting to the report. Does anyone know the best way to report on per-user usage of embedded reports?
Thanks
Michael
Answer: Not sure if you what you want is possible. Once you have purchased a dedicated capacity, there is no limit to how many embed tokens you can generate.
You could have a look at the AdditionalFeatureInfo
<code>GET https://api.powerbi.com/v1.0/myorg/availableFeatures(featureName='{featureName}')
</code>

Returns the token generation usage (in %) from the limitation on
shared capacity

There is also a number of endpoints for usage of reports you could have a look at: https://learn.microsoft.com/en-us/rest/api/power-bi/reports


Adding an inverse of $(2, 0)$ to $\Bbb{R\times R}$

Question: This is a problem from Artin:

Describe the ring obtained by adding an inverse of $(2, 0)$ to $\Bbb{R\times R}$.

I can see that this also adds inverses for all elements of the form $(a, 0)$, but how do I proceed from here?
I'd like a small hint.
Comment: What are the operations considered on $\mathbb R \times \mathbb R$?
Comment: Elementwise addition and multiplication.
Comment: Have you read about localization yet?
Comment: @VJP Yes, I have. I haven't used it much besides proving that localizations at prime ideals are local rings. It seems that this ring is the localization of $\Bbb{R\times R}$ at the multiplicative set
$$\{(1,1), (1,0), (2,0), (4,0), \ldots\}$$, but how do I describe that further?
Comment: i.e. as a quotient of some "well-known" ring, etc.
Comment: When you localize to the set, what do the elements of localization look like?
Comment: Quotients of the form $$\frac{(a,b)}{(2, 0)^n}?$$
That probably does not exclude $(1,0)$, since that can be remedied by adding a factor of $2$ to the numerator.
Comment: Yes. Now, what happens when you add an inverse to a zero divisor like $(2,0)$?
Comment: Um, I think then every element is zero. Is this justified?
$$a = a\times 1 = a\times(r\times (2,0)) = a\times(r\times (0,0)/r) = 0$$[Wikipedia seems to do something similar.](https://en.wikipedia.org/wiki/Zero_divisor#Properties)
Comment: @VJP Why don't you add an answer? The hint was very helpful.
Comment: For anyone stumbling upon these comments: $(0,0)$ is not the multiplicative identity! :P
Answer: Actually the questions says "by inverting the element $(2,0)$".
In terms of rings of fractions this means to look for $R[a^{-1}]$, where $R=\mathbb R\times\mathbb R$, and $a=(2,0)$. (The multiplicative set is $S=\{1,a,a^2,\dots\}$).

In general, if $R_1,R_2$ are two commutative rings and $S_1,S_2$ are multiplicative sets, $S_i\subset R_i$, $i=1,2$, then $(S_1\times S_2)^{-1}(R_1\times R_2)\simeq S_1^{-1}R_1\times S_2^{-1}R_2$. (The correspondence is easily seen: $\frac{(r_1,r_2)}{(s_1,s_2)}\mapsto(\frac{r_1}{s_1},\frac{r_2}{s_2})$.)

In your case set $S_1=\{1,2,2^2,\dots,\}$, and $S_2=\{0,1\}$. Then $R[a^{-1}]\simeq\mathbb R\times\{0\}\simeq\mathbb R$.
Edit. The objection that $S=\{(1,1), (2,0), (2^2,0),\dots\}\subsetneq S_1\times S_2$ is right, but only of pedantic nature. We obviously have $S^{-1}(\mathbb R\times\mathbb R)=(S_1\times S_2)^{-1}(\mathbb R\times\mathbb R)$.
Comment: Actually, isn't the set $\{(1,1),(2,0),(4,0),\dots\}$?
Comment: Yes since $\{(1,1),(2,0),(4,0),\dots\} \neq S_1 \times S_2$.
Comment: You could add that since every element that is not in $S$ but is in $S_1 \times S_2$ already has an inverse, the localization is the same.
Comment: @user268578, is this why the localization you give is the "correct one"?

Your method uses a set which has $(1,0)$ and $(2^k,1)$ as extra elements (which are not in the "real" multiplicative set). But the latter are all already invertible, so adding a new inverse makes no difference, and an inverse of $(1,0)$ is already going to be present, since if $r$ is the inverse of $(2,0)$, then $2r \times (1,0) = r \times (2,0) = 1$.
Comment: @SohamChowdhury Exactly.
Comment: @user26857 Good to know, thanks.
Answer: Let's look at the problem from a more general point of view. Let $R$ be a commutative ring and $f\in R$. If $f$ is a zero-divisor, you can't find an overring $S$ of $R$ such that $f$ is invertible in $S$, because $f$ would remain a zero-divisor also in $S$ and no zero-divisor is invertible, unless we're in the trivial ring.
So the best we can hope to find is another ring $S$ and a ring homomorphism $\lambda\colon R\to S$ such that $\lambda(f)$ is invertible. However we need to keep $\ker\lambda$ as small as possible, because choosing $S$ as the trivial ring would solve the problem, but it would be a very uninteresting solution.
Thus we try to add as little as possible. Suppose we found a solution, that is, a pair $(S,\lambda)$. We shall assume that $S$ is generated by the elements of the form $\lambda(a)$, for $a\in R$, and $\lambda(f)^{-1}$ (such elements are those "reached" by $\lambda$, together with the inverse of $\lambda(f)$). In $S$ we'll have elements of the form $\lambda(f)^{-m}\lambda(a)$, with $m\ge0$ and this is indeed a subring of $S$, because
\begin{align}
\lambda(f)^{-m}\lambda(a)+\lambda(f)^{-n}\lambda(b)
&=\lambda(f)^{-m}\lambda(f)^{-n}\lambda(f^na)+
\lambda(f)^{-m}\lambda(f)^{-n}\lambda(f^mb)\\
&=
\lambda(f)^{-(m+n)}\lambda(f^na+f^mb)\\[6px]
\bigl(\lambda(f)^{-m}\lambda(a)\bigr)\bigl(\lambda(f)^{-n}\lambda(b)\bigr)
&=\lambda(f)^{-(m+n)}\lambda(ab)
\end{align}
In order to save space, we set
$$
\lambda(f)^{-m}\lambda(a)=\frac{a}{f^m}
$$
that's only a formal notation. The above relations become
$$
\frac{a}{f^m}+\frac{b}{f^n}=\frac{f^na+f^mb}{f^{m+n}},
\qquad
\frac{a}{f^m}\frac{b}{f^n}=\frac{ab}{f^{m+n}}
\tag{*}
$$
Notice that $\frac{0}{f^m}=0$ (the zero of $S$), because $\lambda(0)=0$ by assumption. Note also that we must have
$$
\frac{a}{f^m}=\frac{f^na}{f^{m+n}}
$$
because $\frac{f}{1}=\lambda(f^{-0})\lambda(f)=\lambda(f)$ is invertible in $S$ by assumption.
We now ask when
$$
\frac{a}{1}=\frac{0}{f^n}
$$
should hold. If we multiply both sides by $f^n/1$, we get
$$
\frac{f^na}{1}=\lambda(f^n)\lambda(f^{-n})\lambda(0)=\lambda(0)
$$
Thus
$$
\ker\lambda\supseteq\{a\in R: f^na=0\text{ for some }n\ge0\}
$$
Note that the right-hand side set is an ideal of $R$, which is $\{0\}$ if and only if $f$ is not a zero divisor. (On the contrary, the set coincides with $R$ if and only if $f$ is nilpotent.)
In particular, by the homomorphism theorem, we get an embedding
$$
R/\ker\lambda\to S
$$
Now that we know a bit of what $S$ and $\lambda$ should look like, the trick is to define $S$ as the set of equivalence classes of elements of the form $(a,f^m)$ under the equivalence relation
$$
(a,f^m)\sim(b,f^n)
\quad\text{if and only if}\quad
f^p(f^na-f^mb)=0
$$
for some $p\ge0$. The equivalence class of $(a,f^m)$ is denoted by $\frac{a}{f^m}$ as before.
The verification that we get a ring by defining operations like in (*) is just tedious. The map $a\mapsto \frac{a}{1}$ is a ring homomorphism and
$$
\ker f=\{a\in R: f^na=0\text{ for some }n\ge0\}
$$
so the kernel is as small as possible.
In your specific case, the kernel is
$$
\{(a,b)\in\mathbb{R}\times\mathbb{R}:(2^n,0)(a,b)=0\text{ for some }n\ge0\}
=\{0\}\times\mathbb{R}
$$
so the ring we obtain is (isomorphic to) a subring of
$$
\mathbb{R}\times\mathbb{R}/\ker\lambda\cong\mathbb{R}
$$
and it's easy to see $\lambda$ is surjective, in this case.
Comment: In a tedious way you showed that the ring $S^{-1}R$, where $S=\{1,f,\dots,f^n,\dots\}$, is minimal with respect to property that $f$ becomes invertible and for the present question the canonical homomorphism $R\to S^{-1}R$ is surjective and this helps us to find an isomorphism.
Comment: @user26857 I did the assignment "describe the ring…"
Answer: The multiplicative set is $S = \{(1,1), (2,0), (4,0), \dots\}$.
Since $(2,0) \cdot (0,a) = 0$ for all $a \in \mathbb{R}$, when we add an inverse to $(2,0)$, we make $(0,a)/1 = 0$ for all $a \in \mathbb{R}$.
Let's now show that $S^{-1}(\mathbb{R} \times \mathbb{R}) \cong \mathbb{R}$. Define $f \colon \mathbb{R} \to S^{-1}(\mathbb{R} \times \mathbb{R})$ by $f(x) = (x,0)/1$. Since $1 = (1,1)/1 = (1,0)/1 + (0,1)/1 = (1,0)/1$ this is clearly a ring homomorphism. This is also injective, since if $(x,0)/1 = (y,0)/1$, then $2^nx = 2^ny$ for some $n$, but then $x = y$.
All that is left is to show that this mapping is surjective. Let's take $(a,b)/(2,0)^n \in S^{-1}(\mathbb{R} \times \mathbb{R})$. We already know that $(a,b)/(2,0)^n = (a,0)/(2,0)^n$. Now, let $x = 2^{-n}a$. Then we get $(2,0)^n \cdot (x,0) = (2^nx,0) = (a,0)$ so $(x,0)/1 = (a,0)/(2,0)^n$. Hence $f$ is surjective, and so $\mathbb{R} \cong S^{-1}(\mathbb{R} \times \mathbb{R})$.
Comment: I just wanted to give my view of the situation. What I see is that we are simply killing the second component of the product and after that we aren't adding anything new since $\mathbb{R}$ is already a field.


Which Smirnov is behind the Smirnov topology?

Question: Good old Steen and Seebach discuss the Smirnov deleted sequence topology in their Counterexamples in Topology (2nd ed. 1978).
This is also reported as the $K$-topology, in e.g. Wikipedia etc.
However, none of the sources that I've found tell us which particular Smirnov is behind it.
I am guessing it's Yurii Mikhailovich Smirnov as of all the Smirnovs I know of in mathematics, he is the one who has greatest involvement in topology.
(For example: Vladimir Ivanovich is known for a 5-volume textbook, and Nikolai Vasilyevich made a name for himself in statistics.)
Yurii Mikhailovich is of course the mathematician whose name is associated with the Nagata-Smirnov metrization theorem, so it's more than plausible it's the same one.
Can anyone point me towards a source that can confirm this?
Comment: It's in Mémoire sur des espaces topologiques compacts. By Alexandroff & Urysohn and they credit it to Smirnov IiRC that's a French paper do a lot easier.
Comment: It's probably not Yakov Smirnov but I suppose you can't be too sure
Comment: Considering the provenance of Tom Lehrer, I can't fault your logic. :-)
Comment: He must have been active around 1929, as he's credited with the example in a paper from around that time. The metrisation theorem is from the fifties.
Comment: @Henno Brandsma: Any source for that? The metrization paper includes this example of a topology, sure, but the 1951 paper does not actually make any reference to any 1929 paper. My Russian's a but rusty so it will take effort to make sense of the 1951 paper.
Comment: Got it, thanks, it's referenced in the bibliography of S&S.
Comment: @Henno Brandsma Yurii Mikhailovich Smirnov was born in 1921, so now I'm not sure this *is* the same Smirnov, if it dates from back then. Thanks for the pointer, further research to be done.
Comment: It's probably Yurii, in view of Brian's find. The paper by A&U contains many examples (the double circle and the lexicographically ordered square and some other examples in S&S come from that paper too), it need not be for the deleted sequence topology (which is not even (locally) compact, so fits better in the metrisation context (as an example why we need $T_3$ and not just $T_2$ etc.).
Comment: @HennoBrandsma Easy enough to read it in French if you can actually find a copy of the thing in the first place. So while some topological concepts indeed seem to be discussed in that Alexandroff and Urysohn paper, as there's no immediate evidence that it ever included the Smirnov topology, I'll disregard it until I get some better info. Thx.
Comment: Willard has it as Ex. 14.2 without reference. The paper (translated version) is in the bibliography though..
Answer: It is Yurii Mikhailovich Smirnov: the space is Example $1$ in his paper О МЕТРИЗАЦИИ ТОПОЛОГИЧЕСКИХ ПРОСТРАНСТВ (On metrization of topological spaces), Uspekhi Matem. Nauk, 1951, 6, 100-111. It's on p. 107 at the end of Section 2.
Comment: In light of this and Henno's research, I'll go with this reference. Until I manage to get hold of a copy of the 1929 document and confirm this topology is or is not in there, I'll assume that the 1951 ref is the first time it's detailed. Thx.
Comment: @PrimeMover: My pleasure.
Comment: @PrimeMover It's translated in Smirnov Yu. M. On metrization of topological spaces Amer. Math. Soc. Transl. 8 (Ser. 1) 63–77 (thx to Engelking). Engelking (General Topology 2nd ed.) treats the example in 1.5.6 but gives no reference in the historical notes, which is atypical.
Comment: Yes, that's the 1951 reference, I've got that, that's not a problem, it's the 1929 dissertation I haven't been able to lay my hands on. Besides, all I really need is just confirmation of which Smirnov this topology was named after, and I think it's fair to go with Yu.M.


Commerce Price Table: What would cause sporadic zeroing of prices when adding to cart?

Question: I'm having an issue where the prices in the price tables are sometimes being applied when adding items to the cart, and later, other items are set to zero when added to the cart. First off, I must mention that I am working with products that have 3 price tables, and each price table has 4 price breaks. I wasn't exactly clear on if/why support for multiple tables was or wasn't possible, but I am worried that this might be the culprit. If it's not safe to have multiple price tables for a product, please let me know right away!
Other details: Each of the 3 price tables for a product is for a different user role. I use field permissions on a multipage view to make this possible. What may make it complicated is that not every product has a price for each role. That is to say, not all products are available to all roles. To combat this, I added a filter to only show items where the price is not $0.
I'm very deeply entrenched in this module, as I have several commerce feeds going and thus have spent many hours formatting the incoming data in the CSV files, so Commerce Pricelist would not be a good alternative.
Answer: Obviously, something is wrong somewhere when the rules are firing to apply pricing. Read up on debugging rules and you'll likely find your problem.
One thing you may want to consider is just writing your own custom logic and then creating a new rule to call your custom logic, bypassing the logic of Commerce Price Table. You'll likely need to really spend your time adding your logic to commerce_price_table_get_amount_qty since that's where the actual field and price get determined.


Como interromper o algoritmo?

Question: Não estou conseguindo interromper a execução do programa, caso o aluno seja aprovado sem recuperação. Já tentei return e break, mas, não funcionou.
n1 = int(input('Insira a nota da prova 1: '))
n2 = int(input('Insira a nota da prova 2: '))

media = (n1 + n2) / 2

print ('A média é: ', media)

if media > 5:
    print ('Aprovado')
else:
    print ('Reprovado')

if media < 5:
    recuperação = int(input('Nota da recuperação: '))
    media_rec = (media + recuperação)/2
    print ('A média é: ', media_rec)
if media_rec > 5:
    print ('Aprovado')
else:
    print ('Reprovado')`

Answer: Caro,
A identação no Python é crucial.
Seu último if que testa media_rec será executado independente de o aluno ter passado ou não e esta variável só é inicializada se o aluno ficar em recuperação.
Duas soluções
1 - Fazer o media_rec ser igual a media. Esta é uma solução feia e vai ter um bug, pois se Aprovado a mensagem aparecerá duas vezes
n1 = int(input('Insira a nota da prova 1: '))
n2 = int(input('Insira a nota da prova 2: '))

media = (n1 + n2) / 2

media_rec = media

print ('A média é: ', media)

if media > 5:
    print ('Aprovado')
else:
    print ('Reprovado')

if media < 5:
    recuperação = int(input('Nota da recuperação: '))
    media_rec = (media + recuperação)/2
    print ('A média é: ', media_rec)
if media_rec > 5:
    print ('Aprovado')
else:
    print ('Reprovado')

2 - Identar de forma correta e melhorar os if
n1 = int(input('Insira a nota da prova 1: '))
n2 = int(input('Insira a nota da prova 2: '))

media = (n1 + n2) / 2

print ('A média é: ', media)

if media >= 5:
    print ('Aprovado')
elif media < 5:
    print ('Reprovado')
    recuperação = int(input('Nota da recuperação: '))
    media_rec = (media + recuperação)/2
    print ('A média é: ', media_rec)
    if media_rec > 5:
        print ('Aprovado')
    else:
        print ('Reprovado')

Epero que ajude.
Answer: Não consegui compreender a sua dúvida, pois, rodei seu código aqui e deu tudo certo! Se o problema for que quando o aluno é aprovado, o outro bloco if também passa no teste retornando "aprovado" duas vezes é bem simples de resolver, é só mover o bloco da nota de recuperação dentro do teu primeiro bloco else ficando dessa forma:
`n1 = int(input('Insira a nota da prova 1: '))
n2 = int(input('Insira a nota da prova 2: '))

media = (n1 + n2) / 2

media_rec = media

print ('A média é: ', media)

if media > 5:
    print ('Aprovado')
else:
    if media < 5:
        recuperação = int(input('Nota da recuperação: '))
        media_rec = (media + recuperação)/2
        print ('A média é: ', media_rec)
    if media_rec > 5:
        print ('Aprovado')
    else:
        print ('Reprovado')`

Como pode ver apenas idententei o 2° bloco if/else dentro do 1° else e removi uma das duas intruções "print('reprovado')
Quanto a razão de nem o return, nem o break e nem o return break funcionarem é que eles são "métodos" (por assim dizer) especificos de outras estruturas lógicas e funções. O "return" só funciona e é válido em uma função no teu caso se você tivesse pegado esse código e transformado ele numa função e pedisse para que a função retornasse um print do estado do aluno. Já o "break" é exclusivo do laço de repetição "while", que no teu caso serveria para aprovar/reprovar n alunos, ou seja, enquanto tiver n alunos repita as perguntas atribuições e etc. Quando não tiver mais n alunos (que pode ser um input do usuário) break que pararia a repetição.
Comment: Complementando: o `break` pode ser usado dentro de um `for` também.
Comment: Correto! Esqueci de faler esse caso, mas obrigado pelo complemento

Como interromper o algoritmo?


Prove if $\epsilon>0$ is sufficiently small then $f(\underline{p}+\epsilon\underline{n}\left(\underline{p}\right))>0$

Question: A region in $\mathbb{R}^n$ is a subset $\Omega$ of $\mathbb{R}^n$ for which $\exists$ a function $f:\mathbb{R}^n\ \rightarrow\ \mathbb{R}$ with following properties:
(i) all partial derivatives of f are continuous,
(ii) $\Omega = \left \{\underline{x} \in \mathbb{R}^n \mid \ f\left(\underline{x}\right)<0 \right \}$ and
(iii)$\nabla f\left(\underline{x}\right) \neq 0\, \forall \underline{x} \in  \partial{\Omega}$ where $\partial{\Omega} := \left \{\underline{x} \in \mathbb{R}^n \mid \ f\left(\underline{x}\right)=0 \right \}$ is the boundary of $\Omega$
$f$ is called a defining function of the set $\Omega$.
Condition (iii) in the definition of a region allows us to define the
outward unit normal $\underline{n}$ to $\Omega$ by $\underline{n}\left(\underline{p}\right) := \frac{\nabla f\left(\underline{p}\right)}{ \left\|{\nabla f\left(\underline{p}\right)}\right\|} \forall \underline{p} \in \partial{\Omega}$

Observe that, if $\epsilon>0$ is sufficiently small then $f(\underline{p}+\epsilon\underline{n}\left(\underline{p}\right))>0$. (How do I prove this?) and therefore $\underline{p}+\epsilon\underline{n}\left(\underline{p}\right) \notin \Omega$ (this makes sense)
Answer: You may consider
$$
\lim_{\epsilon\to 0}\frac{f(p+\epsilon n(p))-f(p)}{\epsilon}=\langle \nabla f(p),n(p)\rangle =\frac{\langle \nabla f(p),\nabla f(p) \rangle}{\|\nabla f(p) \|} = \|\nabla f(p) \| > 0.
$$
So for $\epsilon$ small, you have $$
f(p+\epsilon(p))>f(p)=0.
$$
Comment: @George 1. I just edited the answer to explain the equality 2. the limit is the definition of directional derivative.
Comment: How did you get the last equality (before >0)?
Comment: Also how did you get that limit?