Como Printar o passo a passo

Question: Tenho o seguinte programa que faz o seguinte, vc insere as regras(V,T,P,S), através de 1 arquivo e depois vc insere a palavra(GLUD) para ver se ela faz parte ou n da linguagem que está na regra, e ai o programa retorna um Sim ou um Não caso a palavra faça ou n parte, só que agora eu Gostaria de saber como fazer para printar o passo a passo do método CheckWord(); no arquivo verificador.java.
Para assim quando não for aceita a palavra, mostrar aonde que foi o erro.
PS: isso é um trabalho de linguagens formais e autômatos que lé linguagem GLUD
Programa em execução:

Main.java

package verificador;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        Verificador verificador = new Verificador();
        String word;
        String g = "";
        BufferedReader bufferedReader;
        if(args.length > 0){
            bufferedReader = new BufferedReader(new FileReader(args[0]));
        }else{
            System.out.print("Não ha parametros, digite o nome do arquivo: ");
            bufferedReader = new BufferedReader(new FileReader(in.nextLine()));
        }
        String line;
        while((line = bufferedReader.readLine()) != null){
            g += line;
        }
        verificador.readGrammar(g);
        System.out.println("Gramatica: " + g.replaceAll("\\s+"," "));
        while (true) {
            try {
                System.out.print("Digite a palavra: ");
                word = in.nextLine();
                if(word.length() == 0){
                    return;
                }
                word = word.replaceAll("\\s+|λ|#", "");
            } catch (NoSuchElementException e) {
                return;
            }
            if (verificador.checkWord(word)) {
                System.out.println("Sim");
                word.length();

            } else {
                System.out.println("Não");
            }
            //verificador.ShowRules(word);
        }
    }
}

Verificador.java

package verificador;

import java.util.ArrayList;
import java.util.Arrays;

public class Verificador {

    private final ArrayList<State> states;
    private final ArrayList<String> alphabet;
    private final ArrayList<Rule> rules;
    private State inicial;

    public Verificador() {
        states = new ArrayList<>();
        alphabet = new ArrayList<>();
        rules = new ArrayList<>();
    }

    public void setStates(String states) {
        states = states.replaceAll("\\{|\\}", ""); // Tira {}
        for (String e : states.split(",")) {
            this.states.add(new State(e));
        }
        this.states.add(new State("DEFAULT", true));
    }

    public State getStateByName(String name) {
        for (State e : states) {
            if (e.getName().equals(name)) {
                return e;
            }
        }
        return null;
    }

    public void setAlphabet(String alphabet) {
        alphabet = alphabet.replaceAll("\\{|\\}", ""); // Tira {}
        this.alphabet.addAll(Arrays.asList(alphabet.split(",")));
        this.alphabet.add("#");
        this.alphabet.add("λ");
    }

    public boolean checkLetter(String letter) {
        for (String l : alphabet) {
            if (l.equals(letter)) {
                return true;
            }
        }
        return false;
    }

    public void setRules(String regras) throws Exception {
        regras = regras.replaceAll("\\{|\\}", ""); // Tira {}
        for (String regra : regras.split(",")) {
            String[] r = regra.split("->");
            if (r.length != 2) {
                throw new Exception("Regra mal formatada");
            }
            State estadoAtual = getStateByName(r[0]);
            if (estadoAtual == null) {
                throw new Exception("Regra mal formatada - Estado invalido1:" + r[0]);
            }
            try {
                for (String transicao : r[1].split("\\|")) {
                    State estadoDestino;
                    String letter = transicao.substring(0,1);
                    if(!checkLetter(letter)){
                        throw new Exception("Regra mal formata - Caracter invalido: " + transicao.substring(0,1));
                    }
                    if (transicao.substring(1).equals("")) {
                        estadoDestino = getStateByName("DEFAULT");
                    } else {
                        estadoDestino = getStateByName(transicao.substring(1));
                        if (estadoDestino == null) {
                            throw new Exception("Regra mal formatada - Estado invalido:" + transicao.substring(1));
                        }
                    }
                    this.rules.add(new Rule(letter, estadoAtual, estadoDestino));
                }
            } catch (RuntimeException e) {
                throw new Exception("Regra mal formatada");
            }
        }
    }

    public ArrayList<Rule> getPossibleRules(State estado, String elemento) {
        ArrayList<Rule> regras = new ArrayList<>();
        for (Rule r : this.rules) {
            if (r.getState() == estado && r.getElement().equals(elemento)) {
                regras.add(r);
            }
        }
        return regras;
    }

    public void setInicial(String inicial) throws Exception {
        State estado = getStateByName(inicial);
        if (estado == null) {
            throw new Exception("Estado inicial invalido");
        }
        this.inicial = estado;
    }

    // ({A,B,C}; {a,b,c}; A -> aB | bA | cA | λ, B -> aB | bC | cA | λ, C -> aB | bA | λ; A)
    public void readGrammar(String gramatica) throws Exception {
        gramatica = gramatica.replaceAll("\\(|\\)|\\s+|\\n", ""); // Tira parentesis e espaços

        if(gramatica.contains("=")){ // Tira o nome da gramatica do inicio
            gramatica = gramatica.split("=")[1];
        }
        gramatica = gramatica.replaceAll("\\},", "\\};"); // Substitui a , por ;
        String[] g = gramatica.split(";"); // Quebra partes da gramatica
        if (g.length != 4) {
            throw new Exception("Gramatica mal formatada");
        }
        setStates(g[0]);
        setAlphabet(g[1]);
        setRules(g[2]);
        setInicial(g[3]);
    }

  public void printRules() {
        for (Rule r : rules) {
            System.out.println(r.toString());
        }
    }

    boolean checkWord(String palavra) {
        return checkWord(palavra, inicial);
    }

    boolean checkWord(String palavra, State estadoAtual) {
        if (palavra.isEmpty() && estadoAtual.getIsFinal()) { // terminou a palavra
            return true;
        } else if (palavra.isEmpty()) {
            return false;
        }
        ArrayList<Rule> possiveisRegras = getPossibleRules(estadoAtual, String.valueOf(palavra.charAt(0)));
        for (Rule r : possiveisRegras) {
            if (checkWord(palavra.substring(1), r.getDestiny())) {
                return true;
            }
        }
        return false;
    }

}

State.java

package verificador;

public class State {
    private String name;
    private boolean isFinal;

    public State(String name){
        this.name = name;
    }

    public State(String name, boolean isFinal){
        this.name = name;
        this.isFinal = isFinal;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean getIsFinal() {
        return isFinal;
    }

    public void setIsFinal(boolean isFinal) {
        this.isFinal = isFinal;
    }

    @Override
    public String toString(){
        if(name.equals("DEFAULT")){
            return "";
        }
        return name;
    }

}

Rule.java

package verificador;

public class Rule {
    private String element;
    private State state;
    private State destiny;

    public Rule(String element, State state, State destiny){
        this.element = element;
        this.state = state;
        this.destiny = destiny;
        if(element.equals("#") || element.equals("λ")){
            this.state.setIsFinal(true);
        }
    }

    public String getElement() {
        return element;
    }

    public void setElement(String element) {
        this.element = element;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public State getDestiny() {
        return destiny;
    }

    public void setDestiny(State destiny) {
        this.destiny = destiny;
    }

    @Override
    public String toString(){
        return state + " -> " + element + destiny;
    }
}

Answer: Tenta fazer dessa forma:
boolean checkWord(String palavra) {
    System.out.format("%-10s %-10s\n", "Palavra", "Estado");
    System.out.format("%-10s %-10s\n", palavra, inicial);
    return checkWord(palavra, inicial);
}

boolean checkWord(String palavra, State estadoAtual) {
    System.out.format("%-10s %-10s\n", palavra, estadoAtual);
    if (palavra.isEmpty() && estadoAtual.getIsFinal()) { // terminou a palavra
        return true;
    } else if (palavra.isEmpty()) {
        return false;
    }
    ArrayList<Rule> possiveisRegras = getPossibleRules(estadoAtual, String.valueOf(palavra.charAt(0)));
    for (Rule r : possiveisRegras) {
        if (checkWord(palavra.substring(1), r.getDestiny())) {
            return true;
        }
    }
    return false;
}

O resultado final será uma tabelinha com o seguinte formato:
Gramatica: Gram = ({S, A, B}, {a,b}, { S -> aA, A -> bB, A -> λ, B -> aA, },S)
Digite a palavra: aba
Palavra    Estado
aba        S
aba        S
ba         A
a          B
           A
Sim

O %-10s no system.out.format está dizendo que a string s deverá ocupar 10 espaços, com alinhamento à esquerda (-). Tirando o sinal de - o alinhamento seria à direita.
Comment: Seria interessante explicar essas formatações utilizadas no printf, as vezes o OP ou outro usuário pode não entender muito bem.
Comment: Obrigado pela dica, realmente não pensei nos iniciantes.

Como Printar o passo a passo


Maria DB - Before Insert Trigger assign value to NEW.field

Question: i am new for this, background is totally based on Oracle and related products. i have installed XAMPP 3.3.0,  i have created a trigger which works fine.
DELIMITER $$

CREATE OR REPLACE
    TRIGGER bi_cancel_booking BEFORE INSERT
    ON cancelled_booking
    FOR EACH ROW BEGIN
    --
    DECLARE next_receipt VARCHAR(20);
    DECLARE rct_no INT(5);
    --
    SELECT MAX(starting_number)+1, CONCAT(receipt_prefix,'-',MAX(starting_number)+1)
      INTO rct_no, next_receipt
      FROM com_receipt_types
     WHERE receipt_type = 'Cancel Booking';

    END$$

DELIMITER ;

but when using NEW.cancel_receipt_no (see below code) it is showing error : Error Code: 1327 Undeclared variable: NEW
DELIMITER $$

CREATE OR REPLACE
    TRIGGER bi_cancel_booking BEFORE INSERT
    ON cancelled_booking
    FOR EACH ROW BEGIN
    --
    DECLARE next_receipt VARCHAR(20);
    DECLARE rct_no INT(5);
    --
    SELECT MAX(starting_number)+1, CONCAT(receipt_prefix,'-',MAX(starting_number)+1)
      INTO rct_no, NEW.cancel_receipt_no
      FROM com_receipt_types
     WHERE receipt_type = 'Cancel Booking';

    END$$

DELIMITER ;

is there any restriction that i cannot assign the value to NEW.field as in my first code here when i am trying to assign the value as: NEW.cancel_receipt_no := next_receipt then it also showing error. please help, how i can do this here?
Answer: i used below code and error has gone (used SET):
SET NEW.cancel_receipt_no = next_receipt;
DELIMITER $$

CREATE OR REPLACE
TRIGGER bi_cancel_booking BEFORE INSERT
ON cancelled_booking
FOR EACH ROW BEGIN
--
DECLARE next_receipt VARCHAR(20);
DECLARE rct_no INT(5);
--
SELECT MAX(starting_number)+1, CONCAT(receipt_prefix,'-',MAX(starting_number)+1)
  INTO rct_no, next_receipt
  FROM com_receipt_types
 WHERE receipt_type = 'Cancel Booking';

    SET NEW.cancel_receipt_no := next_receipt;

    END$$

DELIMITER ;

it was because of my lack of knowledge, gradually i will learn the things with help of all seniors here.


Is there attribute like android:onClick for spinner?

Question: I want to find any way to run a method when i select any item in spinner like Button attribute android:onClick or something else.
Comment: well yes there is! its onItemSelected! please search google for it here is the referral link for the docs https://developer.android.com/reference/android/widget/Spinner.html
Comment: `spinner like Button` elaborate, please. use `onItemSelected`
Comment: @IntelliJAmiya, you mean i can use android:onItemSelected in spinner tag ?
Answer: You can use DataBinding and follow this post Custom XML attribute on android databinding.
Or the easiest way is to implement OnItemSelectedListener on your Activity.
Set listener to your spinner:
spinner.setOnItemSelectedListener(this);

Override onItemSelected() method:
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(),
        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
}

Refer: How can I use onItemSelected in Android?
Comment: when i put android:onItemSelectedListener it say "Unknown attribute android:onItemSelectedListener", what can i do ?
Comment: Instead of `android:onItemSelectedListener`, you can implement `OnItemSelectedListener` on your `Activity`, which is by far the easiest and cleanest approach.
Answer: You need to implement OnItemSelectedListener
YourClass implements AdapterView.OnItemSelectedListener

Then in onCreate
spinner.setOnItemSelectedListener(this)

and overrided method
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {}

where position is the position of the item that you selected from spinner. Hope it helps.


Does $f\cdot \chi_{A_n}\to f\cdot \chi_A$?

Question: Let $(\Omega,S,\mu)$ be a measure space. Suppose $f$, a non-negative function is integrable on $A_1\supset A_2 \supset A_3\dots$, a decreasing sequence of measurable sets $\{A_n\}_n\subset S$ and denote $$A:=\bigcap_nA_n.$$, Does $$f\cdot \chi_{A_n}\to f\cdot \chi_A$$(where the convergence is pointwise)?
On the one hand $$f\chi_{A}=\lim_{n\to\infty}f\cdot\chi_{A}\le\lim_{n\to\infty}f\chi_{A_{n}}$$ but I can't find out why the limit is upper bounded by $f\chi_A$. How can I complete the second direction of the squeezing theorem here?
Comment: Notice that $\chi_{A_n} \to \chi_A$ pointwise as $n\to\infty$.
Comment: But why precisely?
Answer: At each point $ x $, the sequence $\chi_{A_n}(x) $ is eventually constant. In particular, if $ x $ is in the intersection, then the sequence is identically 1. Otherwise $ x $ is not in the intersection, meaning it is not in some $ A_N $. In this case it is not in $ A_n $ for any $ n \geq N $ either, so the sequence is zero from then on.
Now an eventually constant sequence is convergent.
Answer: Maybe this will help:
$$0 \leq \limsup_{n \to \infty} |f \chi_{A_n} - f \chi_A| \leq |f| |\chi_{A_n} - f \chi_A|.$$
Now eventually for a fixed $x$, the expression $\chi_{A_n} - \chi_A$ will be zero.


Is it possible with Drupal Views to have AND and OR in a filter set?

Question: I am attempting to build a view with four filters (A, B, C, D). With Views 3 it is possible to select whether you want these filters to be chained with AND statements or OR statements. Is there a way to configure views so as to chain some of them with AND and others with OR?
For example, ending up with a query that is similar to:
SELECT *
FROM {table}
WHERE A = 0
  AND B = 0
  AND (C = 1 OR D = 1)`

Answer: Looks like this is entirely possible with the Views 3.x branch. You can create custom Filter groups directly in the Views UI itself, and set the AND/OR for each group separately.
Comment: This is possible in Views 2.x with the [Views OR](http://drupal.org/project/views_or) module, but it is much more confusing than the interface in Views 3.x.
Comment: To answer, my question, you can do that, but you have to duplicate things, e.g. ((x OR y) AND (i AND j)) OR ((a AND b) AND (i AND j)). The other problem is, if some of these conditions are exposed, then you can't do it. Discussed here: https://drupal.org/node/1244772#comment-7430080
Comment: The easiest way to do this in Views 2.x is probably with: http://api.lullabot.com/hook_views_query_alter
Comment: Can Views 3.x nest? e.g. ((x OR y) OR (a AND b)) AND (i AND j)
Answer: If you still wish to use views2 you can write your own filter as I did.
Though, in my case the only requirement was to place OR field IS NULL in the query..
so it worked for me..
i hope it could be extended further..
If someone likes the idea..
I could upload the code.. here..!!


Getting a JDBC connection by JNDI in Spring JDBC

Question: This page on Spring JDBC says

The DataSourceUtils class … provides static methods to obtain connections from JNDI

However the API doc for DataSourceUtils does not include the said static methods, as far as I can see.
What am I missing?
Answer: As I understand, what would be really useful to you is JndiObjectFactoryBean. This Spring factory bean returns object published in JNDI.
You would configure it like this, and then you would get the Connection using DataSourceUtils on the injected DataSource:
<bean name="myDataSourceInJndi" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:comp/env/jdbc/MyDataSource</value>
    </property>
</bean>

<bean name="myBean" class="MyClass">
...
    <property name="dataSource" ref="myDataSourceInJndi">
...
</bean>

Comment: hi, I am new to spring, and I would like to know if I am using the method you mentioned above, where do I store the `username` and `password` for my connection?
Answer: Hmm... Somehow, the Javadoc of DataSourceUtils is more "accurate" (I mean, the doc is not wrong but technically, you obtain a connection from a DataSource - that can be obtained via JNDI):

Helper class that provides static methods for obtaining JDBC Connections from a DataSource.

And the following methods should be what you're looking for:

DataSourceUtils.getConnection(DataSource)
DataSourceUtils.getGetConnection(DataSource)

Basic example (from the MySQL documentation):
// Create a new application context. this processes the Spring config
ApplicationContext ctx = new ClassPathXmlApplicationContext("ex1appContext.xml");
// Retrieve the data source from the application context
DataSource ds = (DataSource) ctx.getBean("dataSource");
// Open a database connection using Spring's DataSourceUtils
Connection c = DataSourceUtils.getConnection(ds);
try {
    // retrieve a list of three random cities
    PreparedStatement ps = c.prepareStatement(
        "select City.Name as 'City', Country.Name as 'Country' " +
        "from City inner join Country on City.CountryCode = Country.Code " +
        "order by rand() limit 3");
    ResultSet rs = ps.executeQuery();
    while(rs.next()) {
        String city = rs.getString("City");
        String country = rs.getString("Country");
        System.out.printf("The city %s is in %s%n", city, country);
    }
} catch (SQLException ex) {
    // something has failed and we print a stack trace to analyse the error
    ex.printStackTrace();
    // ignore failure closing connection
    try { c.close(); } catch (SQLException e) { }
} finally {
    // properly release our connection
    DataSourceUtils.releaseConnection(c, ds);
}

Answer: For further future references: the jndi is managed on the application server i.e. : standalone.xml (Wildfly) with Postgresql driver:
 <datasource jta="true" jndi-name="java:comp/env/jdbc/MyDataSource" pool-name="myDS" enabled="true">
                <connection-url>jdbc:postgresql:[<//host>[:<5432>/]]<database></connection-url>
                <driver>postgresql</driver>
                <security>
                    <user-name>$USER</user-name>
                    <password>$PWD</password>
                </security>
            </datasource>


Pass Variable to Custom Block template file

Question: I want to create my custom block with custom content in Drupal 8,in start I create  Block with just simple text on it, and work correctly, my Problem is how can I pass my custom variable to it?
I saw some tutorial about it , my Module name is tcdev and this is content of .module file.
function tcdev_theme($existing, $type, $theme, $path) {
    return array('tcdev' =>
        array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
            'template' => 'block--sliderblock'
        )
    );
}

and my SliderBlock.php
    namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;

/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build(){
        return array(
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
}
}

and finally my template file block--sliderblock.html.twig

My Custom Block{{ title }}-{{ description }}

But Result is only "My Custom Block-" .
The problem is variables not getting passed to template file,where is my fault?
appreciate any help
Answer: Your return array doesn't contain a #theme key. So at the moment you aren't using a template file at all.
And you  probably have a mix up between the outer block and theming the content inside of the block. Your template inside has the name tcdev, because that is the name you defined at the top of the array in *_theme(), and tcdev.html.twig is where your variables will end up.
Your code would look like the following one.
function tcdev_theme($existing, $type, $theme, $path) {
  return array('tcdev' =>                  // this is the name of the template
           array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
        )
    );
}

SliderBlock.php
namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;

/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#theme' => 'tcdev',
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
   }
}

tcdev.html.twig

My Custom Block{{ title }}-{{ description }}

You wrote that you saw some tutorials about it. Probably this was about two different topics, and you are trying to apply them at the same time.

Create custom twig templates from custom module
Override Twig Templates

The custom template in the first link is tcdev.html.twig. What you are trying to do with the method in the second link is for block--sliderblock.html.twig.
Comment: But  `block--sliderblock.html.twig` rendered, the problem is  how pass my variable to it !!!?
what is you suggest to me according to my code. ?
tnx for your attention
Comment: You want the content of the variables inside a block? Then this is not connected to a block template, because this is for the outside of the block. (`block--sliderblock.html.twig` rendered, because you used the name of a theme suggestion, this would render even if the block would be totally empty, you can try this)
Comment: I tried to change your code to make things clearer, hope this works, didn't debug it.
Comment: I apply your code, rebuild the cache, but still read from `block--sliderblock.html.twig` and nothing passed to it .
I enable  debug info and debug info is `

Block-`
Comment: Your variables are not read by `block--sliderblock.html.twig`. This templates works with its own set of variables. (If you want to use this twig you would have to copy it from core or base theme and then you see what variables are inside). Your variables set in the render array of the build function will end up in `tcdev.html.twig`. Did you create this twig file?
Comment: I did, I create `tcdev.html.twig` but it ,clear cache but hit not rendered !!!
Comment: If you still have the wrong `block--sliderblock.html.twig`, your block will never work. You have to remove this twig or put the correct content in it: http://cgit.drupalcode.org/drupal/tree/core/themes/stable/templates/block/block.html.twig
Comment: I found this to work. I had to study the number of bracket enclosures for the array in the tcdev_theme (hook_theme) function above and corrected mine as I had one too many arrays within arrays. Also, I'm curious to see that there is apparently more than one way to pass variables to twig, see also here https://drupal.stackexchange.com/questions/260469/pass-variable-from-custom-module-file-to-twig-template-in-d8
Answer: So that I found, you want to overwrite a default block template with a custom block (module) template, and then pass your variables to it, first of all you must make sure overwrite your template correctly because seems your current block template outputed from your Theme directory (not module):

To do this first you should create a directory called templates/ in your modules root and then place your template there.
Now let Drupal know you store the template in your module. in your_module.module add this function:
function YOUR_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'block__my_module' => array(
      'render element' => 'elements',
      'template' => 'block--my-module',
      'base hook' => 'block'
    )
  );
}

Finally be careful about where you place your twig file and what you name it. Create a templates directory in your module directory, and replace the _ in the theme function name with -: mymodule-block.html.twig
Don´t forget to clear the cache.

With the help of the answer written by Nicensin in this post: Drupal 8 custom block (module) create twig template file
Comment: What about the variables OP asked for?
Answer: I got to this point too. The variables don't seem to be pass to to the block template. I have almost the same code as you, in my case I enabled twig debug and disable cache in services.yml. Even clearing cache I was having this issue but got solved once I activated this config in my dev environment.
twig.config:
# Not recommended in production environments
# @default false
debug: true
# Not recommended in production environments
# @default null
auto_reload: true


A simple configuration: LAN + direct connect simultaneously

Question: This should be an easy configuration, but I'm struggling to Google for it; the vocabulary eludes me.
I've got a desktop with onboard gigabit which finds its way to the internet via the router. Naturally.
I've got a server with onboard gigabit which finds its way to the internet in much the same way. No surprises.
The router provides DHCP to the clients.
I grabbed a couple of old Intel 10GbE cards from eBay and am keen to create a 10Gbit direct connection between my desktop and the server. I've got the cards in and the cables run. I assigned IPs to all four ports (two on each card) statically and connected one port on each. When I enable the interfaces, I get a reported 10Gb connection, but cannot figure a means by which to establish communication between the two.
Here's a map, for completeness' sake.

I've touched nothing with regards to routing tables. ip route shows whatever it defaulted to on both machines. On the desktop, for example:
[patrick@manifold-arch ~]$ ip route
default via 192.168.4.1 dev enp4s0 proto dhcp metric 100
192.168.4.0/22 dev enp4s0 proto kernel scope link src 192.168.4.73 metric 100
192.168.5.0/24 dev enp9s0f1 proto kernel scope link src 192.168.5.203 metric 101

And all I've tried to do is ping back and forth as well as SSHing from server to desktop (I've got sshd enabled on my desktop). Ping says the destination is unreachable and SSH says no route to host. I know the topology is nonstandard, but beyond ensuring the physical connection, I'm not sure how to troubleshoot this. Any pointers or direction would be most welcome!
EDIT
I've changed the IP addresses to 172.16.0.x, but the behaviors described above persist.
[patrick@manifold-arch ~]$ ip route
default via 192.168.4.1 dev enp4s0 proto dhcp metric 100
172.16.0.0/24 dev enp9s0f1 proto kernel scope link src 172.16.0.4 metric 101
192.168.4.0/22 dev enp4s0 proto kernel scope link src 192.168.4.73 metric 100

Answer: The /22 subnet on the 1Gb interfaces is swallowing up (overlapping) the /24 addresses of the 10Gb interfaces (i.e. packets are sent out the wrong interface). Adjust the addresses on the 10Gb interfaces and you'll be fine.  I'd suggest something in the 10.x.x.x range to make it obvious they're "different".
Comment: Doesn't routing select the most specific prefix by default? I thought `192.168.5.0/24` would be preferred for that range because `/24` is more specific than `/22`.
Comment: It *should* work that way.  Not sure if the metric is interfering with it or what.  Regardless, in this simple use case I'm not sure why the OP wouldn't want to avoid the overlapping subnets.  He may or may not have a good reason that's not apparent.
Comment: Right on. I've made that change, and learned a new command along the way. `ip route 172.16.0.x` shows that the requests are hitting the right interfaces, but I'm still seeing no conversation between the two interfaces.
Comment: Sorry, I meant `ip route get 172.16.0.x` shows it hitting the right interfaces.


Why μ of partial recursive functions requires values of least zero's predecessors be defined

Question: The definition of partial recursive function says that given a partial recursive function $G(x,y)$, a new partial recursive function can be generated as$$F(x)\simeq\mu y[G(x,y)=0]$$
$F(x)$ is equal to the least $y$ such that $G(x,y)=0$ and for all $y'$ less than $y$, $G(x,y')$ is defined and is not zero, otherwise $F(x)$ is undefined. I don't think the $\forall y'<yG(x,y')\neq\bot$ requirement is needed. Suppose $G$ is implemented by a register machine program $P$. In searching for the least zero, one can use dovetailing technique by executing the first instruction of $P(x,0)$, then the first two instructions of $P(x,0)$ and $P(x,1)$ and so on, until $0$ is reached. Am I right?
Answer: The problem is that when you find the first $y$ such that $P(x, y) = 0$ using  dovetailing technique, it doesn't mean that there is no $z < y$ with $P(x, z) = 0$. There are two cases:

such $z < y$ exists, but the computation for $P(x, z)$ just takes more time than for $P(x, y)$ (and the only way to "check" this is to wait for the convergence of  $P(x, t)$ for all $t < y$);
there is no such $z$, and $y$ is indeed the least such number.

There is the halting problem inside. Let's show that there is a partial recursive $G(x, y)$ such that $F(x) = \min(y)[G(x, y) = 0]$ defined as "the least $y$ such that $G(x, y) = 0$" is not recursive.
Consider the following function
$$
G(x, y) = \begin{cases}
0,& \text{if } y = 1 \text{ or } (y = 0 \text{ and } \varphi_x(x)\!\downarrow),\\
\uparrow,& \text{otherwise.}
\end{cases}
$$
Clearly,
$$F(x) = \begin{cases}
0,& \text{if } \varphi_x(x)\!\downarrow,\\
1,& \text{otherwise},
\end{cases}$$
which is the characteristic function of the halting set $K = \{x \mid \varphi_x(x)\!\downarrow\}$. Given that $K$ is not recursive, we have that $F(x)$ is not recursive too.


How to find $\sup \Pi_{i=0}^{n} (\sin(i)^2 - \frac{25}{16})$?

Question: Let $\sup,\inf,{\rm dif}$ denote resp supremum , infimum and $\rm dif$ = supremum - infimum.
Does any of the 3 below have a closed form ?
$\sup \Pi_{i=0}^{n} (\sin(i)^2 - \frac{25}{16})$
$\inf \Pi_{i=0}^{n} (\sin(i)^2 - \frac{25}{16})$
${\rm dif} \Pi_{i=0}^{n} (\sin(i)^2 - \frac{25}{16})$
Comment: By $\sup / \inf$, do you mean $\sup\limits_{n\in\mathbb{N}}$ / $\inf\limits_{n\in\mathbb{N}}$ or some thing like that?
Comment: Is your dummy variable $i$ used at all?
Comment: Oh sorry. edited. Thanks Jeff.
Comment: no included efforts to solve this, therefore downvote.
Comment: @achille yes exactly. Although if we used a continu product that would give the same result. ( this might confuse Some , srr ). Maybe you or myself should edit.
Comment: Dif = 0 by symmetry !! Sup = 1,66785193... Apparantly.
Comment: Symmetry from $( sin(i) - 5/4 )(sin(i) + 5/4 ) = sin^2(i) - 25/16 )$.
Answer: Here is a partial answer. Let:
$$A_n := \prod_{k=0}^{n-1} \left( \sin^2 (k)-\frac{25}{16} \right),$$
and:
$$F(x) := \ln \left( \frac{5}{4}-\sin(x) \right).$$
Then:
$$\ln (A_n) = (-1)^n \sum_{k=0}^{n-1} \left(F(k)+F(-k)\right).$$
Now, $F$ has integral $0$ (this comes from the choice of the constant $5/4$), and is analytic. In addition, $1/\pi$ has a finite irrationality measure. Hence, $F$ is a coboundary for the translation by $1$ on $\mathbb{R}_{/2\pi\mathbb{Z}}$. More precisely, we can solve the equation:
$$F(x) = g(x+1)-g(x),$$
with $g(0)=0$. Taking the Fourier coefficients, we get, for $\xi \neq 0$:
$$\hat{g} (\xi) = \frac{\hat{F} (\xi)}{e^{i\xi}-1},$$
whence:
$$g(x) = \sum_{\substack{\xi \in \mathbb{Z} \\ \xi \neq 0}} \hat{F} (\xi) \frac{e^{i\xi x}-1}{e^{i\xi}-1}.$$
Going back to our initial problem, we get:
$$\ln (A_n) = (-1)^n (g(n)+g(-n)).$$
The translation by $1$ is uniquely ergodic on $\mathbb{R}_{/2\pi\mathbb{Z}}$. Better, the translation by $(1,1)$ is uniquely ergodic on $\mathbb{R}_{/2\pi\mathbb{Z}} \times \mathbb{Z}_{/2\mathbb{Z}}$, so that we don't have to worry about the sign. Hence,
$$-\ln(\inf_n A_n) = \ln(\sup_n A_n) = \max_{x \in \mathbb{R}_{/2\pi\mathbb{Z}}} |g(x)+g(-x)| = 2 \max_{x \in \mathbb{R}_{/2\pi\mathbb{Z}}} \left| \sum_{\substack{\xi \in \mathbb{Z} \\ \xi \neq 0}} \hat{F} (\xi) \frac{1-\cos(\xi x)}{1-e^{i\xi}}\right|.$$
Disclaimer : sign errors may be hidden somewhere.
Comment: I think this can be improved. I had similar ideas. Neef to consider it again. +1 anyways.


Como posso concluir essa função no Javascript?

Question: Não consigo chegar na
solução da questão! Não estou conseguindo apresentar na tela a solução completa! (https://i.stack.imgur.com/0uE45.jpg)
Answer: Diego, se compreendi bem, uma das formas de implementar essa função é a seguinte:

function retornaEnderecoUsuario(endereco) {
  return 'O usuário mora em ' + endereco.cidade + ' / ' + endereco.uf + ', no bairro ' + endereco.bairro + ', na rua "' + endereco.rua + '" com nº ' + endereco.numero + ".";
}

var endereco = {
  rua: "Rua dos pinheiros",
  numero: 1293,
  bairro: "Centro",
  cidade: "São Paulo",
  uf: "SP"
}

var informacoesEndereco = retornaEnderecoUsuario(endereco);

console.log(informacoesEndereco);

A concatenação de string também pode ser feita da seguinte forma:
function retornaEnderecoUsuario(endereco) {
  return `O usuário mora em ${endereco.cidade} / ${endereco.uf}, no bairro ${endereco.bairro}, na rua "${endereco.rua}" com nº ${endereco.numero}.`;
}

Comment: Muito obrigado! Deu certo!


Angular4: Como recuperar valores no Response Headers

Question: Tenho um WebService que retorna um arquivo PDF (byte[]). Estou retornando o nome do arquivo no Header da resposta.
No Chrome eu consigo ver os valores de 'Response Headers' e vejo que todos os headers estão lá, inclusive o nome do arquivo. Porém, quando tento recuperar esses valores no Angular, eu não consigo, pois no headers vem apenas o "Content-Type:application/pdf".
getPdf(url: string){

    this.http.get(url, {responseType: 'arraybuffer', observe:'response'})
        .subscribe(data => {
            console.log(data.headers.get('filename')); // Imprime: null
            console.log(data.headers.keys()); // Imprime: ["Content-Type"]
            this.downloadFile(data.body);
    });
  }

Response Headers exibido no navegador:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Request-Width, Content-Type, Accept, authCode
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Disposition:attachment; filename=arquivo.pdf
Content-Type:application/pdf
Date:Mon, 26 Nov 2018 14:23:37 GMT
filename:arquivo.pdf
Server:JBoss-EAP/7
Transfer-Encoding:chunked
X-Powered-By:Undertow/1

Alguém sabe o que está errado? Como faço para recuperar esse valor?
Comment: Tenta assim: `data.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1]` se funcionar te explico. Não tenho como testar!
Comment: Não funciona assim pois ele só está recebendo o 'Content-Type' nos headers.
Answer: Descobri o problema. No retorno do meu serviço, preciso definir os Headers que eu quero expostos com o valor 'Access-Control-Expose-Headers'. Se não definir isso o Angular ignora os valores passados.
Por exemplo, meu webservice em java ficou:
protected Response buildFile(Status status, byte[] file, String nomeArquivo) {
        return Response.status(status)
                .entity(file)
                .header("Access-Control-Allow-Credentials", "true")
                .header("Access-Control-Expose-Headers", "Content-Disposition, filename")
                .header("Content-Type", "application/pdf")
                .header("Content-Disposition", "attachment; filename="+ nomeArquivo)
                .header("filename", nomeArquivo)
                .build();
    }

Mais informações sobre:
https://stackoverflow.com/questions/50044299/how-to-get-the-name-of-a-file-downloaded-with-angular5
Comment: Depois dessa sua alteração o código que mostrei não funcionou?
Comment: Não. Respondi seu comentário lá.


Alterar o valor de um número em uma matriz sem saber a posição (índice) no Python

Question: Olá,
como faço para alterar o valor de um número em uma matriz quando não sei qual o seu índice e pode acontecer de existir mais de um valor a ser alterado?
Por exemplo, se eu tiver a matriz:
[[4,5,3,15,4],
 [20,17,3,4,56],
 [5,6,2,90,32],
 [18,7,1,8,13],
 [0,20,30,4,7]]

E eu quero que todos os valor que sejam menores ou iguais 4 sejam alterados pra 10, como faço? Especificamente uma estrutura de repetição, pois a matriz pode ter diferente tamanho dependendo do caso.
Eu tentei fazer da seguinte forma:
lista  = [[4,5,3,15,4],
          [20,17,3,4,56],
          [5,6,2,90,32],
          [18,7,1,8,13],
          [0,20,30,4,7]]
numero <= 4
if numero in lista:
    lista[lista.index(4)] = 10
print (lista)

Porém, a estrutura de repetição não funciona... A saída deveria ser:
 [[10,5,10,15,10],
  [20,17,10,10,56],
  [5,6,10,90,32],
  [18,7,10,8,13],
  [10,20,30,10,7]]

Answer: O lista.index() retornará apenas o menor índice em que este número ocorre, use um laço for para alterar os valores.
lista  = [[4,5,3,15,4],
          [20,17,3,4,56],
          [5,6,2,90,32],
          [18,7,1,8,13],
          [0,20,30,4,7]]

for i in range(0,len(lista)):
    for j in range(0,len(lista[i])):
        if lista[i][j] <= 4:
            lista[i][j] = 10

print(lista)

Answer:
A linha numero <= 4 não faz muito sentido, não está a fazer absolutamente nada.
Lembra-te que tens uma lista de listas, logo a lógica dentro do for não está correta, tu deves aceder a dois indices, ao da sublista e ao do número dentro dessa sulista para que consigas comparar/alterar o seu valor.
lista.index(...) apenas te retorna o indíce da primeira ocorrência de um determinado elemento (4, neste caso) dentro de uma lista

Usando ciclo for, enumerate e fazendo da maneira pythonica:
lista = [[4,5,3,15,4],
         [20,17,3,4,56],
         [5,6,2,90,32],
         [18,7,1,8,13],
         [0,20,30,4,7]]

for idx1, i in enumerate(lista): # percorrer elementos (sublistas), e respetivos indices, contidos na lista principal
  for idx2, j in enumerate(lista[idx1]): # percorrer elementos e respetivos indices contidos na sublista, aqui enumerate(i) tambem daria
    if(j <= 4):
      lista[idx1][idx2] = 10 # alterar valor

print(lista) # [[10, 5, 10, 15, 10], [20, 17, 10, 10, 56], [5, 6, 10, 90, 32], [18, 7, 10, 8, 13], [10, 20, 30, 10, 7]]

DEMONSTRAÇÃO
Que usando list compreension pode ser reduzido para uma linha:
lista = [[4,5,3,15,4],
         [20,17,3,4,56],
         [5,6,2,90,32],
         [18,7,1,8,13],
         [0,20,30,4,7]]

lista = [[10 if j <= 4 else j for j in i] for i in lista]
# [[10, 5, 10, 15, 10], [20, 17, 10, 10, 56], [5, 6, 10, 90, 32], [18, 7, 10, 8, 13], [10, 20, 30, 10, 7]]

DEMONSTRAÇÃO
Com numpy e place:
import numpy as np

lista = [[4,5,3,15,4],
         [20,17,3,4,56],
         [5,6,2,90,32],
         [18,7,1,8,13],
         [0,20,30,4,7]]

arr = np.asarray(lista)
np.place(arr, arr<=4, [10])

print(arr) # [[10 5 10 15 10] [20 17 10 10 56] [ 5 6 10 90 32] [18 7 10 8 13] [10 20 30 10 7]]

DEMONSTRAÇÃO


Silent redirect based on domain

Question: I've set up my own server.
Let's say my main server folder is /home/www and I've set the nameservers so that all domains point to this location.
Now, here's what I want to do :

Have each domain's files in a separate subfolder
Based on the domain requested, silently redirect to the appropriate subfolder

E.g.

if we need somedomain.com or www.somedomain.com or www.somedomain.com/anything/ (or any such variation for that matter) redirect the request from /home/www/ to /home/www/somedomain.com/

How can this be done?

And here's what I've tried (but given that .htaccess is definitely ... not my thing, it'll most likely be close to non-sensical...) :
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www.)?somedomain.com$ [NC]
RewriteRule ^(/)?$ somedomain.com [L]

Answer: There are two possible choices. you can create Virtual Host for each domain and set virtual document root.
Or
You can use rewrite rule.
From apache Virtual host documentation:
# Listen for virtual host requests on all IP addresses
NameVirtualHost *:80

<VirtualHost *:80>
DocumentRoot /www/www.example1.com
ServerName www.example1.com

# Other directives here

</VirtualHost>

<VirtualHost *:80>
DocumentRoot /www/www.example2.org
ServerName www.example2.org

# Other directives here

</VirtualHost>

You can find out more in http://httpd.apache.org/docs/2.2/vhosts/examples.html
Comment: Yes. you need to put virtual hosts in apache configuration file.
Comment: Could you please give me an example? As for Virtual Hosts are we talking about tweaking the `apache2.conf` file?
Comment: Great answer! That (or something along these lines) did the trick. Thanks a lot, buddy! ;-)

Silent redirect based on domain


Function that mimics remove from standard template library doesn't work correctly

Question: In the CS class in college we have been given the assignment to write several function templates that mimic the functionality of those in the standard library. I've tested all of them and they all work, except for the last one the "remove" function.
template <typename T>
T* remove(T *left, T *right, T &item)
{
  T *element = left; // Need a pointer to the element we are manipulating
  int GoAhead;   // How much in advance is the next element to check
  T *finalElement = right; // The new final pointer of the array.

  while(element < right)
  {
    if(*element == item)
    {
      GoAhead = 0;
      while(element + GoAhead < finalElement)
      {
        T *tempElement = element + GoAhead;
        *tempElement = *(tempElement + 1);
        ++GoAhead;
      }
      --finalElement;
    }
    ++element;
  }
  return finalElement;
}

It works well when the arrays are small, but when the array has many elements (In the test we are given arrays of 100000 elements) for some reason it misses some of the elements it should erase. I don't really understand why this happens.
Can someone point me what I'm doing wrong please?
Comment: Another problem is that you should test the new current item for equality rather than incrementing to the next in case you have two or more matching items one right after the other.
Comment: should the `while(element < right)` be instead `while(element < finalElement)` so that if elements are removed, the end will adjusted?
Comment: I tried both ways and they give the same result. And I think while(element < finalElement) is a little bit faster as it only copies everything until the new ending.
Comment: So, Should I test it and copy the elements again before continuing?
Comment: probably easiest would be to make the increment of `element` to be in an `else` so that it is incremented only when `*element != item` and make the change to `while(element < finalElement)` to end the loop when everything has been moved up.  I think that would do it.  It still seems pretty inefficient to me with too much moving.  See the answer below for another insight.
Comment: It works now, but it still fails with one of the tests, so Im going to try with the answer below.
Comment: Well I don't really know if it's failing or going too slow and I don't have the patience to wait for it.
Answer: Your function didn't work for [2, 2, 1, 1, 2, 1, 0, 0, 1, 2], not to mention an array of 100000 elements. If you are really mimic those in the standard library, it would be much simpler by replacing the elements that compare equal to val by the next element that does not, and signaling the new size of the shortened range by returning an pointer to the element that should be considered its new past-the-end element:
template <typename T>
T* remove(T *left, T *right, const T &item) // you didn't modify the item, so add a const before it
{
    T* result = left;
    while (left!=right) {
        if (!(*left == item)) {
            *result = *left;
            ++result;
        }
        ++left;
    }
    return result;
}

it returns an pointer to the new end of that range.


Differentiation with respect to vector

Question: I have a function,
$$ K\left(\nabla u \right) = \left(K_0 + K_1 \textrm{norm} \left(\nabla u \right)^2 \right) \nabla u $$
and I want to differentiate $K$ with respect to $ \nabla u $.
I will try to rephrase this question,
let$$\nabla u = e$$
$$e = e\left(e_1, e_1 \right)$$
This is more like $$ K\left(\nabla u \right) = K\left(e \right) $$
If I have $$ K\left(e_1, e_1 \right) $$
e is a vector $$e \in R^2$$ and k is a function that takes a vector as an input and gives a vector as an output. $$K \in R^2$$
I want derivative/gradient of $$K$$.
Can someone help me with this?
Comment: You differentiate with regards to a variable, which is not the case for $\nabla u$. Can you clarify your question ? Or does it mean that $\nabla u$ is the name of a variable like $v$ or whatever else ? Also, you need to tell us what your norm is.
Comment: This is more a math question. I've voted to migrate this to the math exchange.
Comment: So do you have a function of two variables and you want the total derivative? Is this your function: $K(x,y)=(K_0+K_1(x^2+y^2))\cdot (x,y)$, with $K_0,K_1$ being constants? But then it takes value in $\mathbb R^2$ and not $\mathbb R$, right? In general, it is not at all clear (at least to me) what any of your symbols mean.
Answer: Consider the vector
$$
\mathbf{k}
= (k_0+k_1 \| \mathbf{x} \|^2) \mathbf{x}
$$
with $\mathbf{x} \in \mathbb{R}^N$.
From what I understand, you are asking for the Jacobian.
Using differentials (and product rule), we have
$$
\mathrm{d}\mathbf{k}
=
(k_0+k_1 \| \mathbf{x} \|^2) \mathrm{d}\mathbf{x}
+
k_1 \mathbf{x}\mathbf{x}^T \mathrm{d}\mathbf{x}
$$
from which you deduce that
$$
\frac{\partial \mathbf{k}}{\partial \mathbf{x}}
=
(k_0+k_1 \| \mathbf{x} \|^2) \mathbf{I}_N
+
k_1 \mathbf{x}\mathbf{x}^T
$$
where $\mathbf{I}_N$ is the identity matrix.

Differentiation with respect to vector


How do I use cookies to store complex information and subsequently dynamically trigger an action based on the data?

Question: I have a simple (yet somehow convoluted) issue.  Basically I'm adding items to make my web app more "desktop-like".  For instance, right now I'm trying to get a page to dynamically load info into a DIV based on previously selected items.  I'm currently using a cookie to handle saving the data, but I can't for the life of me get my brain to work this problem out.
I have a scenario with the following relationships:
SITE has_many BUILDINGS
BUILDING has_many METERS
METER
All entities can have associated charts.  So, in an effort to make it generic, I set up a "has_many" relationship for each to CHARTS and abstracted it like so.
SITE has_many CHARTS, as chartable
BUILDING has_many CHARTS, as chartable
METER has_many CHARTS, as chartable
Once the user selects an item from the menu on the left, I then use a method to determine what item needs charts found and I display the particular item's charts.  That all works fine.
My issue now is working with cookies in order to either save data to independent keys (or perhaps Marshal objects) in order to dynamically reload the previously selected item's data whenever the page reloads.  The ajax call requires several values in order for the "update" action to find the correct item and display it.  I'm having trouble with whether to use Javascript directly, try to trigger an action, or use some kind of combination.
As I said, I'm sure the issue is rather simple or straightforward, but I'm just not seeing it.  If this description is a bit vague, I do apologize.  Feel free to ask for more info.
Best
Answer: When the user selects an item from the menu, save all the necessary information to re-select that item to a cookie. Bind a Javascript method to the page load and check the value of that cookie. If the information is there indicating that an item should be preselected, just call the same Javascript method that is called when the user selects a new item from the menu. If you're using JQuery, for example, you might do something like this to bind to the page load:
$(document).ready(function() { /* check cookie and do stuff */ }

Another thing you could do is pre-render that stuff in your RoR code if that cookie exists so you don't immediately execute an AJAX call on page load (since that is sometimes considered bad form due to the page load performance hit).
Comment: Well, currently the "update_div" action that's part of my controller (I know, bad) handles everything and updates the div.  I simply have a "link_to" that calls it.  Perhaps I should check the cookie inside the action?  I've boiled the method down a bit.  Now the only data I POST to the action is as follows:  chartable_type, chartable_id, title.  With that data it acquires the chartable item and renders the new html based on it.

As a bit of a side question, how would I trigger the RoR action on page load?
Answer: This is too big for storing in cookies, you should either:

Store an id cookie client-side and store the data on the server-side which can be accessed with a corresponding id cookie and valid authentication credentials.
Use HTML5 client-side storage such as localStorage or a local database.


How to get to the returned object in jquery?

Question: I'm having some problems with getting to the object which is returned by one method. To make it simple, for example:
var param = { }; // global variable
var url = 'some url which executes query';

function openURL(url) {

    var http_request = new XMLHttpRequest();
    http_request.onreadystatechange = handle_json;
     // Gets data in JSON format
    http_request.open("GET", url);
    http_request.send(null);

 function handle_json() {
        if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                        var json_data = http_request.responseText; // gets text response
                        var obj = jQuery.parseJSON(json_data);
                                                param = { lastID: obj.data };
                        if(obj.returnCodeDescription == null) {
                            //alert("Data updated!");
                        } else {
                            //alert("Error!");
                        }
                } else {
                        alert('There was some problems! Sorry!');
                }
                http_request = null;
        }
 }

 return param;

}

Now in some other method, let's say QueryResult() I would like to get to the variables which object param contains.
function QueryResult {

var query = 'some query here';
var result = openURL(url+query);

alert( ??? ); **// here I would like to display the value of param.lastID**

}

I really do not have any ideas how to make this work. Could anyone give me a hint which will help me to get the returned object from openURL method in QueryResult?
Comment: if you have param as a global you shouldnt have to return it to get access to the new values.  Also, are you sure that the code that assigns a value is getting run?
Answer: You're trying to use an asynchronous function as if it was synchronous.
openURL() returns its value before handle_json() is called.
You can fix this by making openURL() an asynchronous function. So the function where you use openURL would be like this:
function QueryResult() {
  var query = 'some query here';
  var result = openURL(url+query, function(param) {
    alert( ??? ); **// here I would like to display the value of param.lastID**
  });
}

...and openURL() would be like this:
function openURL(url, callback) {

    var http_request = new XMLHttpRequest();
    http_request.onreadystatechange = handle_json;
     // Gets data in JSON format
    http_request.open("GET", url);
    http_request.send(null);

 function handle_json() {
        if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                        var json_data = http_request.responseText; // gets text response
                        var obj = jQuery.parseJSON(json_data);

                        // *instead of returning, call callback*
                        callback({ lastID: obj.data });

                        if(obj.returnCodeDescription == null) {
                            //alert("Data updated!");
                        } else {
                            //alert("Error!");
                        }
                } else {
                        alert('There was some problems! Sorry!');
                }
                http_request = null;
        }
 }
}

Answer: Asynchronous function is called when event accour - so it's after outer function is called. Try that:
http://jsfiddle.net/Jacek_FH/AAQqt/
function openURL(url, callback) {
    ...

    function handle_json() {
        ...

        callback(param);
    }
}

openURL(url, function(param){
    alert(param.lastID);
});


Bash: For loop concatenates results instead of assigning individual lines;

Question: This code parses a folder and if the folder contains multiple subfolders/files they are concatenated on ONE line with a space in between (subfolder1 subfolder2 subfolder3 /yo) instead of (subfolder1 /yo) newline (subfolder2 /yo) etc. I need one subfolder per line (it works as expected if there is only ONE subfolder in the directory).
Any suggestions?
FolderName=/yo
SUBDOMAINS=/data

for sourceX in "$SUBDOMAINS/*"
do
echo $sourceX $FolderName

done

Answer: Glob char in "$SUBDOMAINS/*" must not be quoted:
"$SUBDOMAINS"/*

Better quote your arguments properly as well:
echo "$sourceX" "$FolderName"

Comment: That's it thanks, that was driving me nuts for a minute.
Answer: Drop the quotes around the globbing *. You want the quotes around the variable but not around the glob. You are telling the shell to make the glob expanded list of files into one string and then looping over that one string and printing it out.
You also probably want quotes around the variables in the echo line (though that's not related to this issue).


Constructing an isomorphism from group of Cosets to Z

Question: I am trying to show the below:
Let H ≤ Z × Z be the cyclic subgroup generated by the element (m, n) with m and n relatively prime. Show that the quotient (Z × Z)/H is isomorphic to Z.
The way I want to do this is define a homomorphism from the group generator for the cosets to 1 in Z, so surjectivity will come for free, and all I will have to do is show injectivity.
Is this a good way to go about doing it? How do I find the generator for the elements of the form (a+km, b+kn)?
Comment: Can you find a homomorphism $h: \Bbb Z \times \Bbb Z \to G$ then $\Bbb Z \times \Bbb Z /kern(h)$ is the quotient group and is isomorphic to $Z$ if $Z$ is the image of $h$.($G$ is some group containing $Z$) By first isomorphism theorem.
Comment: Sure, a homomorphism (and a surjective one) would be mapping (1,1) to (m,n), but I am confused about the second half of your response, is this by the isomorphism theorem, because if so, I do not have that yet
Answer: Hint. I do not quite understand what you mean with "group generator for the cosets" (as the coset to $(a,b) \not\in H$, namely $(a,b) + H$, does not form a group). The most basic way to do something like that is to make you of the homomorphism theorem, by giving an epimorphism $\phi \colon \def\Z{\mathbf Z}\Z\times \Z \to \Z$ that has kernel $H$. Such a $\phi$ gives us an isomorphism
$$ \Z = \phi(\Z^2) \cong \Z^2/\ker \phi = \Z^2/H. $$
To find $\phi$, just try to map $(m,n)$ to zero in the almost simplest way you can think of, which is not by means of the zero map.
Comment: In this case they do form a group as H is a normal subgroup (ZxZ is abelian). I need to show that the group defined by (ZxZ/H) is isomorphic to Z. I also cannot use isomorphism theorem, as we have not proved this yet.
Comment: Think you will have to make use of the order of the groups then.
Comment: The order of the two is clearly countably infinite, but I still need to construct an explicit isomorphism correct?
Comment: Well using the isomorphism theorem as axiom, you simply require a homomorphism so one such would be $m+n$. This is a homomorphism you can verify from $\Bbb Z \times \Bbb Z \to \Bbb Z$. The kernal is all pairs $(m,n)$ such that $m=-n$. The isomorphism theorems state that this subgroup is isomorphic to $\Bbb Z$. Though you can show that by simply mapping $(x,-x)$ to $\Bbb Z$ by taking only the $m$. Show that it is in fact a group, group homomorphism and that it is one to one and onto.
Comment: Sorry I forget the quotient group part.
Comment: so is the previous comment not valid? I think I tried that mapping and found it was not well defined.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31180/discussion-between-marshal-craft-and-qbert).


Atualizar um elemento de uma lista genérica por um item específico

Question: Como faço para atualizar um elemento específico de uma lista genérica localizando pelo ID e passar um objeto atualizado em seu lugar, atualizando o nome e o e-mail?
class Program
{
    static void Main(string[] args)
    {
        List<Aluno> aluno = new List<Aluno>{
            new Aluno() { AlunoId = 1, Nome = "Cláudia",Email="email@example.com" },
            new Aluno() { AlunoId = 2, Nome = "Pedro",Email="firstname.lastname@example.com" },
            new Aluno() { AlunoId = 3, Nome = "Eduardo",Email="firstname.lastname@example.com" }
        };

        Console.WriteLine("==================================");

        foreach (var item in aluno)
        {
            Console.WriteLine("ID: {0}\nNome: {1}\nEmail: {2}", item.AlunoId, item.Nome,item.Email);
            Console.WriteLine("==================================");
        }

        Console.WriteLine("\nLista Atualizada\n");

        int iElemento = 1;

        var elem = aluno.Where<Aluno>(a => a.AlunoId == iElemento).FirstOrDefault();
        int index = aluno.IndexOf(elem);

        aluno[index].Nome = "Cláudia Limeira";
        aluno[index].Email = "firstname.lastname@example.com";

        foreach (var item in aluno)
        {
            Console.WriteLine("ID: {0}\nNome: {1}\nEmail: {2}", item.AlunoId, item.Nome, item.Email);
            Console.WriteLine("==================================");
        }

        Console.Read();
    }
}

class Aluno
{
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}

Answer: Refiz o código dando uma solução mais geral, acredito que você possa tirar o que não precisa:
using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main(string[] args) {
        var alunos = new List<Aluno> {
            new Aluno() { AlunoId = 1, Nome = "Cláudia", Email = "firstname.lastname@example.com" },
            new Aluno() { AlunoId = 2, Nome = "Pedro",   Email = "email@example.com" },
            new Aluno() { AlunoId = 3, Nome = "Eduardo", Email = "email@example.com" }
        };
        ImprimeAlunos(alunos);
        while (true) {
            var id = 0;
            Write("Qual ID de aluno deseja modificar? (-1 para encerrar)");
            if (int.TryParse(ReadLine(), out id)) {
                if (id == -1) break;
                var alunoAchado = alunos.FirstOrDefault(x => x.AlunoId == id);
                if (alunoAchado != null) {
                    Write("Qual o novo nome? ");
                    alunoAchado.Nome = ReadLine();
                    Write("Qual o novo e-mail? ");
                    alunoAchado.Email = ReadLine();
                } else WriteLine("Id inválido tente outro");
            } else WriteLine("Id inválido tente outro");
        }
         WriteLine("Nova Lista");
        ImprimeAlunos(alunos);
    }

    static void ImprimeAlunos(List<Aluno> alunos) {
        WriteLine("==================================");
        foreach (var item in alunos) {
            WriteLine($"ID: {item.AlunoId}\nNome: {item.Nome}\nEmail: {item.Email}");
            WriteLine("==================================");
        }
    }
}

class Aluno {
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Note que no caso de estar fazendo uma busca usando LINQ o retorno é o próprio item, então não precisa usar índice para acessá-lo. O que for mudado no item encontrado se refletirá na lista de alunos.
No seu código o código usa o Where e o FisrtOrDefault. Isto é redundante já que o o segundo já faz o que o primeiro faz de forma mais adequada ao contexto (o primeiro tende ser mais lento). Aí o código recebe o item. O ideal é alterá-lo e você preferiu achar o índice dele para alterar pelo índice conforme foi informado na pergunta anterior. Só que neste caso não precisa, é trabalho desnecessário. A não ser que o problema exija que faça isto, o que eu duvido, mas aí seria melhor resolver de outra forma (retornando o índice e não o item).
Note também que usei um estilo mais moderno de codificação. Se tiver alguma dúvida específica peça esclarecimento ou abra uma pergunta se achar que o tema merece.
Dá para melhorar ainda mais, dá para validar mais coisas, mas isto é o básico.
Fiz uma outra versão sem usar LINQ. Ou seja, eu fiz o que o LINQ faria.
Comment: Quase nada de fato. Mas eu gosto de fazer o mais curto possível que mantenha a legibilidade. E gosto de usar as coisas mais modernas. Alguns não estão disponíveis em compiladores antigos, o que pode precisar de adaptação. Uma das coisas que certamente eu faria de qualquer forma no momento que houve duas impressões da lista, é transformar isto em método para atender o [DRY](http://pt.stackoverflow.com/q/23052/101). Ou até mesmo para atender o princípio da [responsabilidade única](http://pt.stackoverflow.com/q/81314/101).
Comment: Tem sempre várias formas de fazer. Se seu exercício exigisse fazer pelo índice, eu faria assim, mas não parece ser o caso. Se exigisse criar uma nova instância do `Aluno` e substituir a antiga pela nova, eu teria feito assim. Mas não está especificado isso na pergunta, acho que é livre para fazer como quiser, por isto optei pela mais simples e lógica.
Comment: Eu não falei besteira quando falei em **tipo por referência** na minha resposta, né?
Comment: Não, está certinho.
Comment: Bigown, ficou ótimo, vou mercar como resposta!!! Você acha que a forma como fiz acabei usando muito código desnecessário? A minha ideia como eu passei na mensagem era de criar uma instância da classe aluno, passar os valores para as propriedades e em seguida localizar o elemento na lista e colocar esse objeto na posição do elemento desatualizado, fazendo isso de forma automática, mas acabei estendendo o código.
Comment: @KellySoares eu vi que você trocou a aceitação da resposta, você sabe que só pode aceitar uma resposta? Votar pode em todas, mas aceitar só uma, quando você aceita a segunda, você troca o voto. Se ainda não tinha entendido isto dê uma revisada em todas suas perguntas e veja e não trocou a aceitação por acidente. Você pode aceitar qualquer achar melhor, isto é uma decisão só sua, mas tenha certeza que esta aceitando de fato o que escolheu.
Comment: Comentei sobre passar um objeto atualizado porque eu achei estranho a parte onde tive que passar valores propriedades por propriedades, este exemplo que fiz na verdade vou adaptar a um código que já recebe a classe aluno com as suas propriedades atualizada, o que preciso é lançar essa propriedade na lista para simplificar mais. As dúvidas que eu tinha era em localizar um item por ID e atualizar a lista com o objeto que já recebe as informações atualizada. Mas posso criar uma nova pergunta para finalizar essa última questão de passar o objeto direto para o elemento localizado.
Comment: Você fala em clicar no triângulo onde aceita a pergunta como útil ou no triângulo que aponta para cima e tem a opção abaixo marcar como resposta?
Comment: @KellySoares falo na marca de *check* verde, só pode uma por pergunta sua. Veja o [tour]. O triângulo pra cima e p/ baixo, é voto, esse você pode votar em tudo no site todo, não são nas suas perguntas, e se quer aprender sugiro ler outras perguntas, votar nelas, votar nas respostas que acha úteis. Tem muito material bom aqui pra aprender. Exemplo pra começar: http://pt.stackoverflow.com/questions/tagged/c%23?sort=votes&pageSize=50
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29204/discussion-between-kelly-soares-and-bigown).
Answer: Para localizar o item, você precisa fazer:
var item = aluno.First(x => x.Id == 1); //Localizando o aluno com id 1

Para atualizá-lo:
item.Nome = "Novo nome";
item.Email = "firstname.lastname@example.com";

Como Aluno é um tipo por referência, ao alterar o objeto item, o objeto dentro da Lista também será atualizado.
Comment: Obrigada Jéferson mais uma vez!
Comment: Obrigado pela edição @bigown, eu estava mesmo procurando por essa questão.
Comment: Eu sei :) .....
Answer: Você pode criar um crud pra cuidar da lista :) o/
tipo isso ó
    private List<Obj> listaDeObjetos = new List<Obj>();

    public void Add(Obj obj)
    {
        listaDeObjetos.Add(obj);
    }

    public Obj Get(int id)
    {
        return listaDeObjetos.Find(c => c.Id == id);
    }

    public void Remove(Obj obj)
    {
        listaDeObjetos.Remove(obj);
    }

    public void Update(Cart objQueVaiSerAtualizado)
    {
        var objQueVaiSerRemovido= Get(objQueVaiSerAtualizado.Id);
        Remove(objQueVaiSerRemovido);
        Add(objQueVaiSerAtualizado);
    }

como pra remover um objeto de uma lista é necessario passar o objeto, logo o update se torna o mais "complexo" dos metodos.
no metodo update: vc chama ele passando o objeto que vai ser atualizado, digamos que vc alterou o nome, que é uma propriedade do objeto e tal, ai vc passa o obj com o novo nome, dentro do metodo vc procura na lista utilizando o metodo Get passando o id do objeto que vai ser atualizado, o metodo get retorna o objeto que está na lista e não foi alterado o nome, com esse objeto vc passa para o metodo remove, que vai remover esse objeto desatualizado em sequida chama o add pra adicionar o objeto atualizado.
Comment: Obrigada Evilasio e desculpe pelo retorno. Só agora consegui acessar. Gostei da sua explicação!


How to get the parent comments (in a custom module)?

Question: I'm writing a module that uses flag to handle notifications, and one of the options is to be notified of replies to a given comment.
I can implement without problem hook_comment_publish($comment), but I want to get all of its parent comments so that I can pick up the users that flagged them.
So, how can I retrieve all the parent comments of a given comment (if any)? I noticed that in taxonomy there is a taxonomy_get_parents($tid) but I can't find anything similar for threatened comments.
Answer: This code does the trick:
  $threads = explode('.', $comment->thread);
  $thread = "";
  $pnids = array();
  for($i=0;$i<(count($threads)-1);$i++){
        $thread .= $threads[$i];
        $local_thread = $thread."/";
        $result = db_query('SELECT c.cid FROM {comment} c WHERE c.nid = :nid AND c.thread = :thread AND c.status = :status',
        array(':nid' => $comment->nid, ':thread' => $local_thread, ':status'=>'1'));
        foreach ($result as $record) {
            $pnids[] = $record->cid;
        }
        $thread .= ".";
  }

However this code produces 1 DB query for each parent. I don't know if it is feasible/better to include all the :thread in a single query with OR.


Why does `git describe` show "warning: tag 'xxx' is externally known as 'refs/tags/xxx'"?

Question: I am trying to use git describe to retrieve the latest tag name for the current branch, but I'm facing unexpected warnings in the output.
-> git describe
warning: tag 'v0.0.6' is externally known as 'refs/tags/v0.0.6'
refs/tags/v0.0.6-0-g5392899

-> git describe --tags
warning: tag 'v0.0.6' is externally known as 'refs/tags/v0.0.6'
refs/tags/v0.0.6-0-g5392899

-> git describe --tags --abbrev=0
warning: tag 'v0.0.6' is externally known as 'refs/tags/v0.0.6'
refs/tags/v0.0.6-0-g5392899c48d700b48e0dda16129dac6a60bb3b1e

As indicated, the tags locally do not have the refs/tags prefix:
-> git tag -l
v0.0.1
v0.0.2
v0.0.3
v0.0.4
v0.0.5
v0.0.6

However, I'm not sure why the warning is being received or what I can do about it.
The tags were not deleted and recreated, nor have they been renamed.
The tags are created from our build environment (Jenkins).
Is there something I can do to correct or work around the warning?
-> git show
commit 5392899c48d700b48e0dda16129dac6a60bb3b1e (HEAD -> master, tag: v0.0.6, origin/master, origin/HEAD)
...

-> git --version
git version 2.30.1 (Apple Git-130)

Edit:
Our Jenkins build which creates the tags uses jgit. The configuration for checking out the branch/code is as follows:

The tag creation is done using Git Publisher:
Answer: I was able to reproduce the same error using git version 2.25.1. The only difference is that the error message returned is:

warning: tag 'refs/tags/1.0' is really '1.0' here

This warning comes from the append_name function and I guess the problem is that name_checked field is false. I tried to find some logic behind that field but I did not make it, besides I am not that good with C and I would have lost a day at least.
The warning you are seeing might be caused by something else, but it came out after I (manually) generated a discrepancy between .git/packed-refs, .git/refs/tags/1.0 and the tag object. Specifically, I created a tag named refs/tags/1.0, but I modified the .git/packed-refs like this:
975b54bb9b78e245f5abd1b10d6f090c4e0bbf58 refs/tags/1.0 # instead of refs/tags/refs/tags/1.0
^f84bc266f21fa641076a9bef0de4bf2ce1fa5090

However, unlike you, I am not seeing only the correct tag with git tag -l, but also the forged one.
Two advices for you: firstly I would check that those 3 files (.git/packed-refs, .git/refs/tags/your_tag and the tag object file in .git/objects) do not contain any contradictory reference. In either case, please edit your question with how the Git plugin for Jenkins clones the remote repository. If I am not mistaken, it tries hard to optimize performances by reducing at the minimum the references it checks out (and maybe there is just a bug in the plugin).
Comment: I have added detail regarding how Jenkins performs checkout and tagging. I am wondering if the issue is in Git Publisher. We are using `refs/tags/TAG_NAME` in Jenkins Git Publisher config as a workaround for [other issues faced](https://issues.jenkins.io/browse/JENKINS-37120) when using jgit. Thank you!
Comment: Regarding the local tag files, I cloned a fresh copy of the repo and do not see any tags in `.git/refs/tags` (even after `git fetch --tags`). It seems tags are only in `.git/packed-refs`. I see only two files in `.git/objects/pack` but am not sure how they are used (filename has different has than commit).
Comment: The workaround you have used might be the problem. How are tags named in `.git/packed-refs`? I do not think packed objects could cause it, but I would not bet.
Comment: Here's a screenshot of the `.git/packed-refs` file: [https://i.stack.imgur.com/jJsGL.png](https://i.stack.imgur.com/jJsGL.png).
Comment: Thanks, at this point I guess the tag object created is named `refs/tags/v0.0.x`. In that case try to reproduce the issue in a new clean repository with that git version, the tag object named `refs/tags/v0.0.1` (and not just `v0.0.1`) and the same name in the `packed-refs` file (as it is now). If it is not the case, then we are missing something.


Display hash anchor tags into drupal 7 menu items without modifying hooks or adding modules?

Question: currently when path url in menu items are set to: node/1#anchor the anchor is removed.
How would you solve this?
Comment: Why _"without modifying hooks or adding modules"_? That's how Drupal works :)
Comment: At the least, you'll need to add a function to template.php
Comment: but i would imagine it should just work.. its just a # hash tag in a url. i dont see why i gotta go through all that just to get it working.
Answer: Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.


PHP methods return array and still be chainable

Question: I'm quite sure this isn't possible but I'm really hoping its gonna be possible.
i want to call my models in this way for instance
$getAll = models\company::getInstance()->getAll("ID < 4")

which is basicaly just
class company extends _ {
private static $instance;
function __construct() {
    parent::__construct();
}
public static function getInstance(){
    if ( is_null( self::$instance ) ) {
        self::$instance = new self();
    }
    return self::$instance;
}
function getAll($where = "") {
    // yada yada
    $this->return = $return;
    return $this;
}

at the moment i have to add a variable $this->return = $return; inside there and then later on call $getAll = models\company::getInstance()->getAll("ID < 4")->show();
function show(){
    return $this->return;
}

the idea is so that i can for instance do a $getAll = models\company::getInstance()->getAll("ID < 4")->format()->show();
so the question. is there a way to do it without show() on the end?
Ideally i want $getAll = models\company::getInstance()->getAll("ID < 4") to output the array and if i do $getAll = models\company::getInstance()->getAll("ID < 4")->format() for it to take the array from getAll() and do stuff and output the result. just seems cleaner than having to put show() on everything
please don't crucify me for bad practices. thanks in advance
Comment: This barely makes sense. By this you're lying to the one who's using your code as it is expected to get same object in return (chaining), but in fact it does manipulation with collection structure. Use explicit collection methods instead. This will be strict, type-hint-able, flexible and, in the very end, just more readable.
Comment: I really would want to crucify you for bad practices! ;)
Comment: @AlmaDo mind explaining that a bit more? not sure im following? basicaly i wanted to have a system where i can chain if theres more to do like call ->get("1")->remove() but if i just call get("1") it returns the data for it
Answer: Somehow you must "flag" the last call, a quick and dirty solution
class confusing {
private static $instance;

function __construct() {
    $this->return = 'nothing';
}

public static function getInstance() {
    if (is_null(self::$instance)) {
        self::$instance = new self();
    }
    return self::$instance;
}

function getAll($where = "") {
    $this->return = 'getAll'.$where;
    return $this;
}

function format() {
    $this->return = strtoupper($this->return);
    return $this;
}

function __call($name,$args) {
    $rthis = true;
    if ( 'last_'==substr($name,0,5) ) {
        $toCall = substr($name,5);
        $rthis = false;
    }
    else {
        $toCall = $name;
    }
    call_user_func_array([$this,$toCall],$args);
    return $rthis?$this:$this->return;
}
}

$x = confusing::getInstance()->getAll('x')->last_format();
$y = confusing::getInstance()->last_getAll('y');
$z = confusing::getInstance()->getAll('z');

var_export($x);
var_export($y);
var_export($z);

Or create a wrapper which outboxes
function toResult($x) {
  return is_object($x)?$x->show():$x;
}

$getAll = toResult(models\company::getInstance()->getAll("ID <4")->format());

Anyhow the called method never will know about the chain countinues or not.
Comment: " the called method never will know about the chain countinues or not." was hoping i was wrong with this... i thought something like this :/

marking yours as the answer. that __call thing seems like the best idea. but i think im just going to get used to using ->show() to output anything.
Comment: This is not the only way. Implementing ArrayAccess and Countable will get you what you want. See my answer below.
Answer: bottom line. its not possible.
in my case im going to keep all my methods chainable except for a ->show() which would then return the "result"
so even if i do something like users->get("1")->remove() it wont return any message but it will perform the action. users->get("1")->remove()->show() will output "User successfully removed"
previously i never bothered with chaining things but it gets frustrating fast. chaining definately does seem to help. starting a new big project and trying to do it "better" from the start
Comment: It is possible to achieve what you asked for in your question. See my answer above. Chaining methods is by the way no holy grale. Over use can lead to breaking of the law of demeter.
Answer: This is absolutely possible! What you need to do is to create a class representing a ResultSet, that can both be used as an ordinary array (by implementing the interfaces ArrayAccess, Iterator and Countable) and as an object.
Example
class ResultSet implements ArrayAccess, Countable, Iterator {

    private $data = array();
    private $position = 0;

    public function __construct(array $data=array())
    {
        $this->data = $data;
    }

    /* * Implement methods of the Countable interface * */

    public function count()
    {
        return count($this->data);
    }

    /* * Implement methods of the ArrayAccess interface * */

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->data[$offset];
    }

    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        if( $this->offsetExists($offset) )
            unset($this->data[$offset]);
    }

    /* * Implement methods of the Iterator interface * */

    function rewind()
    {
        $this->position = 0;
    }

    function current()
    {
        return $this->data[$this->position];
    }

    function key()
    {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next()
    {
        ++$this->position;
    }

    function valid()
    {
        return isset($this->data[$this->position]);
    }

    /* * Implementation of ResultSet specific methods  * */

    public function show()
    {
        //....
    }

    /**
     * @param $in
     * @return ResultSet
     */
    public function format($in)
    {
        // do the stuff
        return $this;
    }

}

This implementation would allow a call like ->getAll('...')->format()->show(); and at the same time allow the programmer to treat the output of getAll() as an array.
Comment: seems incomplete, please show concrate usage. for array access `[]` is required, but with `Iterable` ... maybe
Comment: Ah yes, that is true. It should also implement Iterable ... (fixed)
Comment: Still no sample how you use it :(, countable is irrelevant
Comment: If your API states that a certain method returns an array one would expect that you could count the number of elements in that array. For what reason do you find Countable irrelevant?
Comment: thanks for the answer.. will check it out on tuesday. :D (been a looooong week, NEED the weekend off lols)


Get term plain text aliased url from tid

Question: I realise that this is similar to other questions posted, but they all seem to involve using print l() to output a fully formed anchor.
What I need is just the uri, output in plain text to use directly in the node template. I nearly got there with the following, but end up with the unaliased version:
<?php
  if (isset($node->field_source_of_tid['und'][0]['tid']) && $node->field_source_of_tid['und'][0]['tid']) :
    $term=taxonomy_term_load($node->field_source_of_tid['und'][0]['tid']);
    $term_uri = taxonomy_term_uri($term);
    $output = $term_uri['path'];
endif; ?>

And I use the output as so:
<a href="<?php print render($output); ?>">A BUTTON

Any ideas?
Thanks!
Answer: You're probably looking for url()

Generates an internal or external URL.

e.g.
$output = url($term_uri['path']);


What is a LEFT JOIN in PostgreSQL

Question: I've seen a query using a LEFT JOIN as opposed to an INNER or LEFT OUTER.
What is a LEFT JOIN exactly?
Comment: A more graphic explanation: [Visual-Representation-of-SQL-Joins](http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins)
Comment: All JOIN types of PostgreSQL are explained [in the manual](http://www.postgresql.org/docs/current/interactive/queries-table-expressions.html#QUERIES-JOIN) including examples. So basically the `OUTER` keyword is optional for `LEFT`, `RIGHT` and `FULL` joins.
Answer: Where an inner join returns only entries that match in both tables, a left join takes all the entries from first table and any that match in the second table. A right join is the reverse of a left join (ie: all from the second table)
So if TableA is
A B
1 a
2 b
3 c

and TableB is
A B
1 d
2 e

Then Select * from TableA inner join TableB on TableA.A = TableB.A returns
1 a 1 d
2 b 2 e

And Select * from TableA left join TableB on TableA.A = TableB.A returns
1 a 1 d
2 b 2 e
3 c null null

Comment: I think the results aren't right. First query should give 1 a 1 d / 2b 2 e Second query should give: 1 a 1 d / 2b 2 e / 3 c NULL NULL.
Answer: It is the same as LEFT OUTER (The OUTER is implied because an INNER JOIN requires bilateral matching so a LEFT INNER JOIN would make no sense). The same applies for RIGHT JOIN and FULL JOIN these are equivalent to RIGHT OUTER JOIN and FULL OUTER JOIN respectively

What is a LEFT JOIN in PostgreSQL


If $a, b, c, d>0$ such that $a+b+c=1$, prove that $a^3+b^3+c^3+abcd\ge \min(\frac{1}{4}, \frac{1}{9}+\frac{d}{27})$

Question: If $a, b, c, d>0$, such that $a+b+c=1$, prove that: $$a^3+b^3+c^3+abcd\ge \min\left(\frac{1}{4}, \frac{1}{9}+\frac{d}{27}\right).$$
I tried solving it as follows:
$$a^3+b^3+c^3=3abc+1-3(ab+bc+ac).$$
From Schur we have that:
$$a^3+b^3+c^3+3abc\ge ab(a+b)+bc(b+c)+ac(a+c).$$
Hence $1+9abc\ge 4(ab+bc+ac)$.
This is as far as I got. I do not know how to introduce the $\min(\frac{1}{4}, \frac{1}{9}+\frac{d}{27})$ to my inequalities. Could you please explain to me how to solve it?
Comment: https://artofproblemsolving.com/community/c6h89449p521967
Answer: This is an easy application of Lagrange as the first equality of $$3a^2+bcd=3b^2+acd=3c^2+abd=\lambda$$ gives $3(a+b)(a-b)=(a-b)cd$ so either $a=b$ or $3(a+b)=cd$. Thus there are two possibilities:

$a=b=c$ so that $f(a,b,c)=1/9+d/27$;

$a=b$ and $3(b+c)=ad$ so that $d=3/a-3$ since $c=1-2a$ giving $$f(a,b,c)=2a^3+(1-2a)^3+a^2(1-2a)\left(\frac3a-3\right)=3a^2-3a+1\ge\frac14.$$
Answer: WLOG, assume $c = \min(a, b, c)$.
Let $P(x) = a^3 + b^3 + c^3 + abc x$ and $Q(x) = 2(\frac{a+b}{2})^3 + c^3 + (\frac{a+b}{2})^2 c x$ where $x \ge 0$.
We have
\begin{align}
P(x) - Q(x) &= a^3 + b^3 - 2(\tfrac{a+b}{2})^3
- ((\tfrac{a+b}{2})^2 - ab)c x \\
&= \frac{3}{4}(a+b)(a-b)^2 - \frac{1}{4}(a-b)^2 cx\\
&= \frac{1}{4}(a-b)^2(3a + 3b - cx)\\
&\ge \frac{1}{4}(a-b)^2(3a + 3b - \tfrac{a+b}{2} x)\\
&= \frac{1}{8}(a-b)^2(a+b)(6 - x). \tag{1}
\end{align}
Also, since $a + b + c = 1$, we have $Q(x) = \frac{1}{4}(x+3)c^3 + \frac{1}{4}(-2x+3)c^2 + \frac{1}{4}(x-3)c + \frac{1}{4}$.
Now, we split into two cases:
If $d > \frac{15}{4}$, by (1), we have
\begin{align}
a^3 + b^3 + c^3 + abcd &\ge a^3 + b^3 + c^3 + \frac{15}{4} abc\\
&= P(\tfrac{15}{4}) \\
&\ge Q(\tfrac{15}{4}) \\
&= \frac{1}{4}(\tfrac{15}{4} +3)c^3 + \frac{1}{4}(-2\cdot \tfrac{15}{4} + 3)c^2 + \frac{1}{4}(\tfrac{15}{4}-3)c + \frac{1}{4}\\
&= \frac{3}{16}c(3c-1)^2 + \frac{1}{4}\\
&\ge \frac{1}{4}\\
&= \min\left(\frac{1}{4}, \frac{1}{9}+\frac{d}{27}\right).
\end{align}
If $d\le \frac{15}{4}$, by (1), we have
\begin{align}
a^3 + b^3 + c^3 + abcd &= P(d) \\
&\ge Q(d)\\
&= \frac{1}{4}(d+3)c^3 + \frac{1}{4}(-2d+3)c^2 + \frac{1}{4}(d-3)c + \frac{1}{4}\\
&= \frac{1}{9} + \frac{1}{27}d + \frac{1}{108}(3c-1)^2(3cd + 9c - 4d + 15)\\
&\ge \frac{1}{9} + \frac{1}{27}d\\
&= \min\left(\frac{1}{4}, \frac{1}{9}+\frac{d}{27}\right).
\end{align}
We are done.
Answer: My second solution:
By using Schur's inequality and the identity
$$a^3 + b^3 + c^3 + \frac{15}{4} abc =
\frac{3}{4}[a(a-b)(a-c) + b(b-c)(b-a) + c(c-a)(c-b)] + \frac{1}{4}(a+b+c)^3,$$
we have
$$a^3 + b^3 + c^3 + \frac{15}{4} abc \ge \frac{1}{4}.$$
If $d \ge \frac{15}{4}$, we have
$$a^3 + b^3 + c^3 + abcd \ge a^3 + b^3 + c^3 + \frac{15}{4} abc \ge \frac{1}{4}.$$
If $d < \frac{15}{4}$, we have
\begin{align}
a^3 + b^3 + c^3 + abcd &= a^3 + b^3 + c^3 + \tfrac{15}{4} abc - (\tfrac{15}{4} - d)abc \\
&\ge \frac{1}{4} - (\tfrac{15}{4} - d)(\tfrac{a+b+c}{3})^3\\
&= \frac{1}{4} - (\tfrac{15}{4} - d)(\tfrac{1}{3})^3\\
&= \frac{1}{9} + \frac{d}{27}.
\end{align}
We are done.


Cannot recover Linux VM disk in Azure

Question: The thing is that I have managed to recover one of Ubuntu server disks which caused "Error 'grub_calloc not found' and VM in rescue mode". Also I have swapped this disk with the original VM, but I get notification when I am trying to connect via Serial Console in Azure. When I press enter in Serial Console, nothing happens.
This is the notification I am getting. I have tried to Google, but I, personally, cannot find any related stuff to Linux VMs in Azure.
Ubuntu Server VM - Serial Console - Azure
This is the picture from boot diagnostics.
Boot diagnostics
Would really appreciate any answer as Microsoft is sort of failing to help.
Comment: This may sound stupid, but connecting to the serial console may take some time. Have you waited long enough?
Comment: I also suggest to enable `Boot diagnostics`, have a look here: https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/boot-diagnostics#enable-boot-diagnostics-on-existing-virtual-machine
Comment: Not stupid at all @Matze :) I have tried to wait, yes. Boot diagnostics seems enabled for the customer. I have attached picture from boot diagnostics. Well, it should not be a problem as we could run this disk on another VM. Seems that this could be related to disk misconfiguration?
Comment: Okay, maybe this will help: https://askubuntu.com/questions/1263125/how-to-fix-a-grub-boot-error-symbol-grub-calloc-not-found. This might help as well: https://docs.microsoft.com/en-us/answers/questions/72418/problem-with-starting-on-of-my-azure-ubuntu-1804-s.html
Comment: @Matze Thank you for this. I will try the solution.
Answer: It should be sufficient to reinstall grub2. Try to follow this steps, that I have borrowed from here.

Create a rescue VM using the Azure repair VM feature

Login to the rescue VM and mount the root disk. Then chroot(1) to it and reinstall grub.
$ sudo su –
$ mkdir /rescue
$ mount /dev/sdc1 /rescue
$ for fs in {proc,sys,tmp,dev}; do mount -o bind /$fs /rescue/$fs; done
$ cd /rescue
$ chroot /rescue
$ lsblk <-- this will identify the attached disk, usually /dev/sdc
$ grub-install /dev/sdc
$ exit
$ cd /
$ for fs in {proc,sys,tmp,dev}; do umount /rescue/$fs; done
$ umount /rescue

Restore the VM by using az vm repair restore -g MyResourceGroup -n MyVM --verbose

Further information:
Chroot environment in a Linux Rescue VM
Enable boot diagnostics on existing virtual machine
Comment: Thanks @Matze. I got an answer from Microsoft and someone from Linux team is going to contact me soon. I will keep this post updated anyways.
Comment: The thing is that I have managed to recover one of Ubuntu server disks which caused "Error 'grub_calloc not found' and VM in rescue mode". Also I have swapped this disk with the original VM. The thing is that I am trying to run recovered disk on the original VM. I have already swapped the recovered disk. Microsoft already tried to help me, no luck. They told three days ago that someone from their Linux team will contact me, but no answer. :( I am just curious why I cannot run the recovered VM.

Cannot recover Linux VM disk in Azure


Standard Matrix of a linear transformation

Question: Let $T : R^3 → R^4$ be the linear transformation defined by:
$$T(x_1, x_2, x_3) = (3x_1 − 4x_2 − x_3, x_1 + 2x_2 + 3x_3, 6x_1 − x_2 + 5x_3, 10x_2 + 10x_3)$$
Determine the standard matrix representation of T.
Can someone please help me with this? I am not sure how to go about this
Answer: By matrix multiplication rules, we have
$$T(x_1,x_2,x_3)=\begin{bmatrix}t_1\\t_2\\t_3\\t4\end{bmatrix}=\begin{bmatrix}3&-4&-1\\1&2&3\\6&-1&5\\0&10&10\end{bmatrix}\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}$$
which is the standard matrix according to the standard basis.


Real Analysis, Folland Proposition 2.11

Question: This proposition was left for the reader to prove:
The following implications are valid if and only if the measure $\mu$ is complete:
a.) If $f$ is measurable and $f = g$ $\mu$-a.e., then $g$ is measurable.
b.) If $f_n$ is measurable for $n\in \mathbb{N}$ and $f_n\rightarrow f$ $\mu$-a.e., then $f$ is measurable.
I am not looking for an answer, just need some guidance or hint, I also fail to grasp the concept of the $\mu$ almost everywhere part. Any suggestions is greatly appreciated.
attempted proof of b.) $\Rightarrow$ We are given $f_n$ to be measurable for $n\in\mathbb{N}$, and $f_n\rightarrow f$ a.e. From proposition 2.7 we can let $$\hat{f} = \lim_{n\rightarrow \infty}\sup f_n$$ since $f_n$ is stated to be measurable, then $\hat{f}$ is also measurable. Also, since $f_n\rightarrow f$ a.e, we then have $\hat{f} = f$ a.e, so by part (a) $f$ is measurable.
$\Leftarrow$ suppose $\mu$ is not complete. Then there exists a measurable set $E$ such that $\mu(E) = 0$ and a set $F\subset E$ such that $F$ is not measurable. Then for (a), note that $1_F$ is not measurable and $1_F = 0$. Similarly, for (b) define $f_n = 0$ for all $n$ and $f = 1_F$
Answer: Note that one  must be careful about what ae. means. When we say that $f=g$ ae., it means that there is a measurable set $E$ of measure zero such that
$f(x)=g(x)$ for $x \notin E$.
Suppose $\mu$ is complete. Let $E$ be the exceptional set where $f(x) \ne g(x)$.
Suppose $A$ is measurable. Then $g^{-1}(A) = ( g^{-1}(A) \cap E) \cup ( g^{-1}(A) \cap E^c)$. The set  $g^{-1}(A) \cap E$ is measurable since
it is contained in $E$ which has measure zero.
We have $g^{-1}(A) \cap E^c= f^{-1}(A) \cap E^c$, hence it is measurable
and so $g^{-1}(A)$ is measurable, and so $g$ is measurable and so Part (a)
holds.
Now suppose Part (a) holds. Let $N \subset E$, where $E$ has measure zero. Let
$f=1_{E}$ and $g = 1_{N}$. Then $f=g$ ae. and so $g$ is measurable. Hence
$g^{-1}(\{1\}) = N$ is measurable. Hence $\mu$ is complete.
Part (b) is similar. Note that if $h_n \to h$ with the $h_n$ measurable, then
$h$ is measurable. So, this really can be reduced to Part (a) fairly easily.
Comment: @Wolfy I think the following is also correct for converse of part (b): Set $f_j= 1_N$ for all $j$. Take any $E\subset N$ and note that since $1_N=1_E$ a.e., we have $f_j\to 1_E$ a.e. whence $1_E$ is measurable and therefore $E=(1_E)^{-1}(\{1\})$ is in the sigma algebra.
Comment: I never heard of the term "exceptional set", what does that mean?
Comment: Just a descriptive term, it contains the elements that are exceptions to the rule $f(x)=g(x)$.
Comment: I am trying to understand why $g^{-1}(A)\cap E^c = f^{-1}(A) \cap E^c$ could you explain that part?
Comment: If $x \in g^{-1}(A) \cap E^c$ then $g(x) \in A$ and $x \in E^c$, so $f(x) = g(x) $ and we have $x \in f^{-1}(A) \cap E^c$. Similarly for the other direction.
Comment: I tried to prove part b for the if part, am I on the right track?
Comment: I can't tell unless I have some idea of what you are doing!
Comment: Wait what do you mean, the attempted proof is posted where I wrote the question? or does it just not make sense at all
Comment: You do understand that I don't spend my time checking questions to see if they have changed????
Comment: Yes, I understand that I just wanted to see if I was on the right track with the proof of part b. Sorry if I am wasting your time
Comment: I looked at your edit, but have no idea what you are doing. You can't conclude that $h=h_n$ ae.
Comment: I changed it, I think this is correct now
Comment: I'm sorry, I really don't follow what you are doing and I don't have time to work through it line by line now. You need to start with $f_n \to f$ ae. with $f_n$ measurable and then **show** that $f$ is measurable if $\mu$ is complete. If $E$ is the exceptional set, let $h_n = f_n 1_{E^c}$ which is measurable and converges **everywhere** hence it converges to some measurable $h$, and you have $h=f$ ae. Now use part (a) to conclude that $f$ is measurable.
Answer: The $\mu$-a.e. condition says that $f=g$ everywhere except on some (possibly empty) set $S$, and $S$ is of measure zero according to measure $\mu$.
Couple this to the definition of measurable, and part A becomes easy.
Part B requires a bit more thought.
Comment: Been thinking about part a.) for almost an hour now still have no idea where to start, any other hints you can give me?

Real Analysis, Folland Proposition 2.11


Como obter o resultado da soma de dois valores do tipo float ao clicar num input?

Question:

<fieldset>
    <legend>Cálculo do salário</legend>
    Valor 1:
    <input id="s1" type="text"/>
    Valor 2:
    <input id="s2" type="text"/>

    Resultado:
    <input id="resultado" onclick="somarValores()" type="text">

</fieldset>

Comment: você já fez praticamente todo o trabalho, só falta mostrar o resultado, colocar num campo, um alert, console.log? a *function* está retornando pra ninguém, no lugar de *return* tente mostrar o resultado. agora você colocou na pergunta *"tipo float"*, mas está usando `parseInt`, por que não `parseFloat`?
Answer: Creio que assim resolva o seu problema, o seu código só faltou basicamente mandar escrever o valor do resultado no input referente ao resultado:

function somarValores(){
        var s1 = document.getElementById("s1").value;
        var s2 = document.getElementById("s2").value;
        var s3 = parseInt(s1) + parseInt(s2);
        document.getElementById("resultado").value = s3;
    }
<fieldset>
    <legend>Cálculo do salário</legend>
    Valor 1:
    <input id="s1" type="text"/>

    Valor 2:
    <input id="s2" type="text"/>

    Resultado
    <input id="resultado" onclick="somarValores()" type="text">

</fieldset>