I can't find some types of Admin Audit Activity Events

Question: I checked this url below,
https://developers.google.com/admin-sdk/reports/v1/appendix/activity/admin-event-names
And created a script to check event for each activity type. After then, I found some activity types are Not listed on this table.

CUSTOM_USER_SCHEMA_SETTINGS
SAML2_SERVICE_PROVIDER_CONFIG_SETTINGS

Could you please tell me where I can get more information regarding them if you have.
Best regards,
Comment: Where did you get the names of these events if they are not listed? I am just curious if you have added "CUSTOM_USER_SCHEMA_SETTINGS" because you believe that that is what it should be listed as, or if you have found it somewhere else?
Comment: @iansedano, thank you for your comment. I' writing up a program to check admin activity so I read [this page](https://developers.google.com/admin-sdk/reports/v1/guides/manage-audit-admin) and have implemented.
By checking JSON response events-> name through this program, I could found activities that are defined such as `APPLICATION_SETTINGS`, `DELEGATED_ADMIN` or `ORG_SETTINGS` etc. That's why I found unknown event name `CUSTOM_USER_SCHEMA_SETTING`.
Answer: For what its worth, I can't find it either
It seems that these activity types are not supported by the API, at least I could not find any way to get those events.
In which cased I would encourage you to make a feature request using this template:

Admin SDK Feature Request

That way Google at least know that there are people who would like to see this. Make sure to justify the request with your practical use case so that they understand why you need it.
Comment: Thank you very much. I'll put the request on the site.


MySQL PDO connection php

Question: I am trying to do a simple pdo connection using the following:
test.php:
require 'config.php'

try {
    $dox_db = new PDO('mysql:host=localhost;dbname=test', $config['DB_USER'], $config['DB_PW']);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

and config.php:
$config = array(
    'DB_USER' => 'root',
    'DB_PW' => 'password'
);

Due to the fact that when I put in wrong information, the page does not display an exception, I'm lead to believe that the database must not be connecting. I have verified that the db service & server is up. Does anyone have any suggestions?
Comment: At top of your script add error_reporting(E_ALL); what you see?
Comment: I added error_reporting(E_ALL); at the top of the script. The php doc is still blank, even though the name of the database is incorrect and exception message appear
Comment: If you don't have exception, how do you know that the DB is not connected? How do you try to access your data?
Comment: in my connection string i reference (new PDO('mysql:host=localhost;dbname=test') and i do not have a database named 'test' in my sql server
Comment: Try adding double quotes for those $config
Comment: The error is not in connection. It's too simple to make a mistake here.
Comment: hello, I just noticed that this only happens when I'm running on .NET environment (using Microsoft WebMatrix). I see that in the web.config file the connection is already referenced. Does anyone know how to query when the connection string is in the web.config?
Answer: If test database doesn't exist, must appear something like that on page;

ERROR: SQLSTATE[42000] [1049] Unknown database 'test'

And I didn't understand how it's work
require 'config.php'

Can you try this
require 'config.php';

try {
    $dox_db = new PDO('mysql:host=localhost;dbname=test', $config['DB_USER'], $config['DB_PW']);
    var_dump($dox_db);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Answer: Add
<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
?>

on top of test.php and check what errors it showing?

MySQL PDO connection php


Add Taxonomy Tags to uploaded images

Question: Is there any way to add the taxonomy term reference (tags) for each image uploaded? It just has 'alt tags' and title as default...
So far I can just add tags for a set of images (albums) but I want to be able to tag each of the images separately - one by one.
Answer: You can achieve your requirement by installing and configuring Taxonomy Image module.

The taxonomy_image module allows site administrators to associate
  images with taxonomy terms. With the association created, an admin can
  then make a call to 'taxonomy_image_display()' from their theme or
  other PHP code to display the appropriate image.

Please follow this link as well.
Comment: I will try that later - I have D7 does it work with the D7 DEV version?
Comment: Yes. It should work.

Add Taxonomy Tags to uploaded images


Iterating thru an array using javascript for

Question: How do I iterate thru an array like this using 'for' in jquery. This one has me totally lost. I cant figure how to get those values out from an array like this and I cant change the way the array is done.
//Php
$errors['success']   = false;
$errors['#errOne']   = "Enter a valid username";
$errors['#errTwo']   = "Enter a valid email";
$errors['#errThree'] = "Enter a valid password";
echo json_encode($errors);//

dataType:"json",
cache:false,
success: function(data){
for (i=1; i<?; i++){//Start at 1
//I'm totally lost here.
//Output: "#errOne" "Enter a valid username" ->Loop thru remaining messages
}
},

Comment: Careful `i` is global, use `var`.
Answer: since your passing data as parameter, you can access the data
try something like this :
var $errors = {};
$errors['success']   = false;
$errors['#errOne']   = "Enter a valid username";
$errors['#errTwo']   = "Enter a valid email";
$errors['#errThree'] = "Enter a valid password";
    data : $errors;
    success: function(data){
    for (var i in data ){
       console.log(i + ':' + data[i]);
    }

Comment: @some i am creating object in the first line itself. and wher do you think i am abusing arrays in javascript?
Comment: This is 99% what I needed. Only thing is: any idea how to start this at [1] and not [0]?
Answer: May be you need this:
success: function(data){
    $.each(data, function(key, value) {
        alert(key + ': ' + value);
    });
}

Comment: In different browsers sorting of Data will be different. In FF it will be as is, but Chrome will sort Data by keys automatically. So in different browsers first element will be different
Comment: I started off which $.each. Would be really nice if we could tell $.each where to start- at [0] or [1]. Eg: for (i=1;...
Answer: for (var key in data){
   alert(key); // gives keys  success, #errOne, #errTwo, #errThree
   alert(data[key]); // gives values  false, Enter a valid username, Enter a valid email, Enter a valid password
}

Comment: when using for (var key in data) can we tell it to start at [1] and not [0]? Eg: for (i=1;...
Answer: If your PHP code is like this:
// Use $errors = array(...) if your PHP version is < 5.4
$errors = [
    'success' => false, // Why is 'success' part of the $errors array?
    'error_1' => 'Enter a valid username.',
    'error_2' => 'Enter a valid email.',
    'error_3' => 'Enter a valid password.'
];

print json_encode($errors);

, then in your JavaScript, you can do the following:
$.ajax({
    'url': 'your.url.com/data.json',
    'dataType': 'json',
    'cache': false, // Why are you doing this?
    'success': function (json_data) {
        var i = json_data.length;
        while (i--) {
            alert(json_data[i]); // Or whatever you want to do with the data.
        }
    }
});

I'm pretty sure this is one of the best ways to do this. Someone please correct me if I'm wrong.


Bounded convergence theorem - 2M

Question:
Can someone please help me with where the 2M is coming from?
Answer: By the triangle inequality,
$$\int_{B_n} |f_n-f| \mathop{d\mu} \le \int_{B_n} (|f_n|+|f|) \mathop{d\mu} \le 2M \int_{B_n} \mathop{d\mu}$$
where the last inequality is due to $|f_n| \le M$ and $|f| \le M$.
Comment: But is it not only f_n which is smaller than M?
Comment: @PeterMortensen See [this](https://math.stackexchange.com/questions/980096/a-bounded-function-is-converge-in-measure-then-its-limit-is-also-converge)

Bounded convergence theorem - 2M


File to import not found or unreadable [omega 4] Windows OS

Question: I have installed omega 4 theme successfully with the help of this link on Windows 7 machine. Working with the theme is awesome, however when I enabled the sub theme ohm, there I am getting issues. I have made a change to the following line in ohm/sass/layouts/hero/hero.layout.scss
<code>.l-constrained {
  width: 95%;
</code>
to
<code>.l-constrained {
  width: $desk;
</code>
<code>$desk is a variable declared in sass/variables/_grid.scss file.</code>
Afterwards I am getting following error.

sass/layouts/hero/hero.layout.scss (Line 1 of sass/variables/**/*:
  File to import not found or unreadable: ../../variables/_colors.scss

I can see there is slolution mentioned here, buit don't know how to implement it in omega 4 config.rb file.
Edit:
This is the problem of gem sass-globbing on Windows. If you are using it on Windows version having this issue, than try following solution sass-globbing does not support Windows 7. If it does not work, try the following alternative (not the best solution but it works). Add following line in ohm/sass/layouts/hero/hero.layout.scss
<code>// Globbing from within sub-folders only works with relative paths.
@import "../../variables/colors";
@import "../../variables/grid";
@import "../../variables/legacy";
@import "../../variables/typography";
</code>
Comment: I was baffled by the same issue with my own Omega 4 custom layout and your method worked. Thank you!
Answer: You can fix this by editing your Gemfile and changing:
gem 'sass-globbing'
to
gem 'sass-globbing', '1.1.0'
Then go back to terminal and type:
bundle
All should be fixed


Moment generating function (MGF) of the sum of $n$ uniform random variables divided by $\sqrt{n}$

Question:
Find the moment generating function (MGF) of $$\frac{U_1 + U_2 + \dots + U_n}{\sqrt{n}}$$ where $U_i \sim \mbox{Unif}(-1,1)$.

I know that the MGF of a sum of independent random variables is equal to the product of the MGF of each random variable, so that in this case $$M(U_1+U_2+\dots+U_n)= \left(E\left(e^{tU_i}\right)\right)^n = \frac{e^t - e^{-t}}{2t}$$
but what do you do about the $\sqrt{n}$ in the denominator? Are you allowed to say that $$M\left(\frac{U_1 +\dots+U_n}{\sqrt{n}}\right)=\frac{\left(E\left(e^{tU_i}\right)\right)^n}{\sqrt{n}}\text?$$
Comment: [https://en.wikipedia.org/wiki/Moment-generating_function#Linear_combination_of_independent_random_variables](https://en.wikipedia.org/wiki/Moment-generating_function#Linear_combination_of_independent_random_variables)
Comment: Your first ${}^n$ calculation doesn't seem to maintain a ${}^n$ exponent.
Answer: Let $S_n = \sum_{k=1}^n U_k$ where $U_k \sim \mathcal{U}(-1,1)$.
It's not clear from your question if you mean discrete uniform or continuous uniform distribution? You seems to be using the MGF from the continuous one, not sure if it is intended, assuming so.
The MGF indeed is $$M_U(t) = \frac{e^t-e^{-t}}{2t}$$ and for the combined one it is
$$
M_S(t) = \prod_{k=1}^n M_U(t) = M_U(t)^n= \left( \frac{e^t-e^{-t}}{2t} \right)^n.
$$
Finally, there is a question of scaling. For $a\in \mathbb{R}^+$, let $X = S/a$, then
$$
M_X(t)
 = \mathbb{E}\left[e^{tX}\right]
 = \mathbb{E}\left[e^{St/a}\right]
 = M_S(t/a).
$$
Can you now plug that back into $M_S(t)$ we used above, letting $a = \sqrt{n}$ and examine what happens when $n \to \infty$?


Add minutes to an Oracle date

Question: I am trying to add minutes to my sql but no error and no data.
This is my sql
select distinct mo.reference_no payment_id, mo.dcn message_id,
mo.amount, mo.ccy, decode (mo.msg_status, 'R', 'Repair', 'P',
'Processed','N','Ungenerated','G','Generated',mo.msg_status)
message_status, to_char
(MO.INSERT_TIME,'DD-MM-YYYY HH24:MI:SS')
paym_date, mo.branch_date, mo.maker_id
from table1 mo
left join table2 mi
on mo.reference_no = mi.generated_ref_no
where mo.swift_msg_type = 103
and mo.ccy = 'XXX' and mo.branch_date = trunc(sysdate)
and mo.msg_status in('R','N','G','P')
order by PAYM_DATE desc;

And I want to add 5 minutes to (MO.INSERT_TIME,'DD-MM-YYYY HH24:MI:SS')
So I want my sql show me after 5 minutes for this column (MO.INSERT_TIME,'DD-MM-YYYY HH24:MI:SS')
I wrote sql like that
select distinct mo.reference_no payment_id, mo.dcn message_id,
mo.amount, mo.ccy, decode (mo.msg_status, 'R', 'Repair', 'P',
'Processed','N','Ungenerated','G','Generated',mo.msg_status)
message_status, to_char
(MO.INSERT_TIME,'DD-MM-YYYY HH24:MI:SS')
paym_date, mo.branch_date, mo.maker_id
from table1 mo
left join table2 mi
on mo.reference_no = mi.generated_ref_no
where mo.swift_msg_type = 103
and mo.ccy = 'XXX' and mo.branch_date = trunc(sysdate)
and MO.INSERT_TIME = to_date (sysdate,'DD-MM-YYYY HH24:MI:SS') + INTERVAL '5' MINUTE
and mo.msg_status in('R','N','G','P')
order by PAYM_DATE desc;

And after 5 minutes I am selecting this sql and their is no data. Can you explain why?
Answer: This is what you used:
and MO.INSERT_TIME = to_date (sysdate,'DD-MM-YYYY HH24:MI:SS') + INTERVAL '5' MINUTE

It is wrong because you're applying TO_DATE function to SYSDATE which already returns DATE datatype, so there's no point in doing it.

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate,
  2         sysdate + interval '5' minute
  3  from dual;

SYSDATE             SYSDATE+INTERVAL'5'
------------------- -------------------
10.01.2023 09:49:05 10.01.2023 09:54:05

SQL>

It is probably not very likely that MO.INSERT_TIME will exactly  be the same as SYSDATE (which is right now) + 5 minutes, which is in the future.
Perhaps you'd rather set that condition to e.g. rows inserted during last 5 minutes (which makes more sense to me):
and MO.INSERT_TIME >= sysdate - INTERVAL '5' MINUTE

Comment: Hello! Thank you very much for your solution tip. It really helped me to figure out my SQL.
If I use ''and MO.INSERT_TIME >= sysdate - INTERVAL '5' MINUTE'' - it will show me sysdate too. But I don't want to see last 3 minutes. So I used 'between'. And it works exactly how I want

''and MO.INSERT_TIME between sysdate - INTERVAL '15' MINUTE and sysdate - INTERVAL '3' MINUTE''
Comment: You're welcome; I'm glad you made it work.
Answer: DATE + NUMBER where number can be fractional and is interpreted as days, and a minute is 1/(24*60) of a day...

Add minutes to an Oracle date


Porque meu esse ResultSet está retornando nulo?

Question: Se eu executo uma query no banco de dados retorna resultado, porém,
quando executo o código em java, atribuindo o resultado para um ResultSet,
o mesmo aparenta estar vazio. Podem me ajudar?
PreparedStatement ps = conectar.con.prepareStatement("select colaborador.codigo as 'colabcod', nome,"
                    + " emprestimo.codigo as 'emprescod', idcolaborador, dataempres from emprestimo, colaborador where "
                    + "idcolaborador = colaborador.codigo and dataEmpres between ? and ?");
            ps.setString(1, "'" + datainicial + "'");
            ps.setString(2, "'" + datafinal + "'");
            ResultSet rs = ps.executeQuery();

            if (!rs.next()) {
                JOptionPane.showMessageDialog(null, "Não há resultados para essa pesquisa");
            }else{
                while (rs.next()) {

                model.addRow(new String[]{rs.getString("emprescod"), rs.getString("nome"),
                rs.getString("dataempres"), "<Não Definido>"});

                }
            }

Answer: O método setString() já escapa e adicina aspas nos valores, logo não é necessário adicionar aspas, são elas o problema.
Seu código deve ficar assim:
ps.setString(1, datainicial);
ps.setString(2, datafinal);

Comment: @MarcoAurélioSouza Se esta resposta solucionou o seu problema, clique na marquinha verde para marcar a pergunta como resolvida e para marcar que esta resposta serviu para resolvê-la.
Comment: Está correto, agora retirei os apóstrofes tanto do setString() quanto do comando SQL e funcionou perfeitamente. Obrigado!
Comment: Pronto, Obrigado!
Answer: Usar um between entre Strings pode causar muitos bugs, existem maneiras melhores de implementar (usando um like usando wildcards por exemplo).
Vendo o nome do campo dataEmpres me parece errado mesmo, o atributo (no SQL) é tipo data então:
Primeiro efetue um parse (usando SimpleDateFormat) da string para um objeto Date:
Note que usei o pattern "dd/MM/yyyy" você deve aplicar o seu conforme o padrão que é obtido das variaveis datainicial e datafinal.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date datai = formatter.parse(datainicial);
java.util.Date dataf = formatter.parse(datafinal);

Mantenha seu PreparedStatement:
PreparedStatement ps = conectar.con.prepareStatement("select colaborador.codigo as 'colabcod', nome,"
                    + " emprestimo.codigo as 'emprescod', idcolaborador, dataempres from emprestimo, colaborador where "
                    + "idcolaborador = colaborador.codigo and dataEmpres between ? and ?");

Defina as datas usando o metodo setDate enviando um tipo java.sql.Date
ps.setDate(1, new java.sql.Date(datai.getTime()))
ps.setDate(2, new java.sql.Date(dataf.getTime()))


iniciar com o 9 na frente com jquery

Question: Tenho esse código que me da a mascara do telefone, porém não consigo fazer com que o input já inicie com o 9 na frente, impedindo que o usuário consiga apagá-lo, tornando-o obrigatório. Alguém tem ideia que como fazer?

    Numero

    <input readonly maxlength="10" required class="inp_editar" type="text" name="fone_tel" id="fone"/>

Answer: Pode fazer algo parecido com isso
$("input").keydown(function(e) {
    var oldvalue=$(this).val();
    var field=this;
    setTimeout(function () {
        if(field.value.indexOf('9') !== 0) {
            $(field).val(oldvalue);
        }
    }, 1);
});

Aqui um exemplo funcionando
Utilizei o jquery que pode ser baixado aqui
subistitua input por #seuId ou .suaClas
Comment: No meu caso não funcionou, pois interfere com a primeira função, obrigado!

iniciar com o 9 na frente com jquery


How to fit an Image to column width in Flutter?

Question: I want to fit a child image to the width of the column father.
Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
    Image.network("Some image url"),
    Text("Fitted image"),
  ],
),

Answer: I suggest the following chenges
Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Image.network("Your image url",
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),
        Text("Fitted image"),
      ],
    )

Comment: Perfect, this answer is even better!
Answer: Well, I resolved my problem using MediaQuery.
Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
    Container(
        child: Image.network("Some image url", fit: BoxFit.fill,),
        width: MediaQuery.of(context).size.width,
    ),
    Text("Fitted image"),
  ],
),

Answer: Maybe wrapping your Image with an Expanded Widget and give it BoxFit.fitWidth would also be useful. Or in case the times when you can't use MediaQuery.
     Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 5,
            child: Image.network(
              "Some Image Url",
              fit: BoxFit.fitWidth,
            ),
          ),
          Text("Fitted image"),
        ],
      ),

If you need to control the size of elements in the column try to wrap all your widgets inside column with expanded widget and adjust elements sizes with flex value.
Comment: Your solution is not bad, but Expand expands through the main axis, so it will grow vertically (column), it works because the image keeps his aspect ratio and grows his width also ;-)


String equation for simple to complex equations

Question: I'm trying to write a program that solves any equation (from simple to complex) in the form of a string by using an Arraylist to break down the equation into seperate parts. It checks for parentheses first, then goes into the deepest set of parentheses it can find, and solves the set of operations inside, starting with the stronger operators, then moves on. It continues checking until there are no more parentheses, then it does what's left, starting with the stronger operators. The number left over in the arraylist is the answer. But I'm having trouble. Here's my code:
import java.util.ArrayList;

public class StringEquation
{
    public static void main(String[] args)
    {
        String s = "80+5+3*(11%(3*2)-(5+1)+6)-(10+10)+(2*2)*5";

        ArrayList<String> equation = new ArrayList<>();

        String ns = "";

        String b;

        int nsi;

        int si;

        int res = 0;

        boolean hasParen = false;

        for(int c=0; c<s.length(); c++)
        {
             b = s.substring(c,c+1);
             if("0".equals(b)||"1".equals(b)||"2".equals(b)||"3".equals(b)||"4".equals(b)||"5".equals(b)||"6".equals(b)||"7".equals(b)||"8".equals(b)||"9".equals(b))
             {
                 ns += b;
                 if(c==s.length()-1)
                 {
                     nsi = Integer.parseInt(ns);
                     equation.add(Integer.toString(nsi));
                 }
             }
             else if(("+".equals(b)||"-".equals(b)||"*".equals(b)||"/".equals(b)||"%".equals(b))&&!"".equals(ns))
             {
                nsi = Integer.parseInt(ns);
                equation.add(Integer.toString(nsi));
                equation.add(b);
                ns = "";
             }
             else if("(".equals(b))
             {
                 equation.add(b);
             }
             else if (")".equals(b))
             {
                nsi = Integer.parseInt(ns);
                equation.add(Integer.toString(nsi));
                equation.add(b);
                ns = "";
             }
             else if("+".equals(b)||"-".equals(b)||"*".equals(b)||"/".equals(b)||"%".equals(b))
             {
                 equation.add(b);
             }
        }

        while(true) //checks for parentheses
        {
            for(int d=0; d<equation.size(); d++)
            {
                if("(".equals(equation.get(d)))
                {
                    hasParen = true;
                }

                if(hasParen==true)
                {
                    while(!")".equals(equation.get(d)))
                    {
                        d++;
                    }
                    while(!"(".equals(equation.get(d)))
                    {
                        d--;
                    }
                    d++;

                    while(!")".equals(equation.get(d+1)))
                    {
                        if("-".equals(equation.get(d))) //checks to see if the String number on the Arraylist is negative
                        {
                            equation.remove(d);
                            si = Integer.parseInt(equation.get(d));
                            si *= -1;
                        }
                        else
                        {
                            si = Integer.parseInt(equation.get(d));
                        }

                        switch(equation.get(d+1))
                        {
                            case "*": si *= Integer.parseInt(equation.get(d+2));
                            equation.set(d, Integer.toString(si));
                            equation.remove(d+1);
                            equation.remove(d+2);
                                break;
                            case "/": si /= Integer.parseInt(equation.get(d+2));
                            equation.set(d, Integer.toString(si));
                            equation.remove(d+1);
                            equation.remove(d+2);
                                break;
                            case "%": si %= Integer.parseInt(equation.get(d+2));
                            equation.set(d, Integer.toString(si));
                            equation.remove(d+1);
                            equation.remove(d+2);
                                break;
                            default: d+=2;
                        }
                    }

                    while(!"(".equals(equation.get(d)))
                    {
                        d--;
                    }
                    d++;

                    while(!")".equals(equation.get(d+1)))
                    {
                        if("-".equals(equation.get(d))) //checks to see if the String number on the Arraylist is negative
                        {
                            equation.remove(d);
                            si = Integer.parseInt(equation.get(d));
                            si *= -1;
                        }
                        else
                        {
                            si = Integer.parseInt(equation.get(d));
                        }

                        switch(equation.get(d+1))
                        {
                            case "+": si += Integer.parseInt(equation.get(d+2));
                            equation.set(d, Integer.toString(si));
                            equation.remove(d+1);
                            equation.remove(d+2);
                                break;
                            case "-": si -= Integer.parseInt(equation.get(d+2));
                            equation.set(d, Integer.toString(si));
                            equation.remove(d+1);
                            equation.remove(d+2);
                                break;
                        }
                    }

                    if("(".equals(equation.get(d-1))&&")".equals(equation.get(d+1)))
                    {
                        equation.remove(d-1);
                        equation.remove(d+1);
                    }

                    hasParen = false;

                    d = 0;
                }
            }
            break;
        }

        for(int e=0; e<equation.size(); e+=2) //does all multiplication, division and modulus first
        {
            if("-".equals(equation.get(e))) //checks to see if the String number on the Arraylist is negative
            {
                equation.remove(e);
                si = Integer.parseInt(equation.get(e));
                si *= -1;
            }
            else
            {
                si = Integer.parseInt(equation.get(e));
            }

            switch(equation.get(e+1))
            {
                case "*": si *= Integer.parseInt(equation.get(e+2));
                equation.set(e, Integer.toString(si));
                equation.remove(e+1);
                equation.remove(e+2);
                    break;
                case "/": si /= Integer.parseInt(equation.get(e+2));
                equation.set(e, Integer.toString(si));
                equation.remove(e+1);
                equation.remove(e+2);
                    break;
                case "%": si %= Integer.parseInt(equation.get(e+2));
                equation.set(e, Integer.toString(si));
                equation.remove(e+1);
                equation.remove(e+2);
                    break;
                default: e+=2;
            }
        }

        for(int f=0; f<equation.size(); f+=2) //does the rest (addition and subtraction)
        {
            if("-".equals(equation.get(f))) //checks to see if the String number on the Arraylist is negative
            {
                equation.remove(f);
                si = Integer.parseInt(equation.get(f));
                si *= -1;
            }
            else
            {
                si = Integer.parseInt(equation.get(f));
            }

            switch(equation.get(f+1))
            {
                case "+": si += Integer.parseInt(equation.get(f+2));
                equation.set(f, Integer.toString(si));
                equation.remove(f+1);
                equation.remove(f+2);
                    break;
                case "-": si -= Integer.parseInt(equation.get(f+2));
                equation.set(f, Integer.toString(si));
                equation.remove(f+1);
                equation.remove(f+2);
                    break;
            }
        }

        System.out.print(equation.get(0)); //Arraylist should only have the answer of the string equation by this point.

        //The part below was to see if lines 25-59 had obtained the whole equation in seperate parts within the arraylist.

//        for(int i=0; i<equation.size(); i++)
//        {
//            System.out.print(equation.get(i));
//        }
//        System.out.println("\n");
    }
}

When I run this, it gives me this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "("
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:527)
    at stringequationfull.StringEquationFull.main(StringEquationFull.java:87)
Java Result: 1

Any help?
Answer: See the documentation of Integer#parseInt:

Throws: NumberFormatException - if the string does not contain a
  parsable integer.

The error message you're getting is very informative.
You're trying to parse "(", which is not a parsable integer.
Using a debugger will solve this for you in less than a minute.
Answer: You should really use a parsing/lexing framework for this, and then implement the equation solver on top of the parse tree.
Here's a starting point: How to write LALR parser for some grammar in Java?
Answer: As mentioned you are trying to parse "(" as an Integer.
But this is not your main problem.
The main issue is that you have a huge gigantic hunk of code which is unnecessarily hard to reason about.
You need to convert the string into a tree like structure instead of an array list which would allow you to do the calculations in a much easier and bug free way.
Since your problem is simple I would not recommend using a parser generator for this task. ( takes too long imho ). However you will still need to design the data structure to suit your requirements.
There are a bunch of parsers for mathematical equations that you can examine to get an inspiration from.
In general you will have something like:
Class Statement{}

class AddStatement extends Statement{
    Statement lhs;
    Statement rhs;
}

Class constant extends Statement{
    int value;
}

you will need to make classes for all the operations you support and then  recursively parse the input into this structure. If done properly, evaluation becomes simple.
I am not going into detail because there are enough resources available online to use for guidance.
If you wish you can continue with your code above but I would recommend you somehow figure out how to split it into smaller chunks which are easier to debug and good luck
Comment: P.S this is so much easier in functional languages like haskell


How would I disallow special characters in usernames?

Question: By default, Drupal 9 allows usernames to have spaces, periods(.), hyphens(-), apostrophes('), underscores(_) and @ symbols.
How would I disallow spaces, periods, apostrophes and @ symbols?
Comment: Maybe [User Name Validation module](https://www.drupal.org/project/username_validation) or [User Restrictions module](https://www.drupal.org/project/user_restrictions) can help.
Comment: Thanks Patrick. Looks like the User Name Validation module does exactly what I need.
Comment: Great.  If it works for you, feel free to answer your own question with the details of how you configured the module.
Answer: I used the Username Validation module suggested by Patrick Kenny in his comment. The Blacklist characters field shown by the module on /admin/config/people/user-name-validation did the trick.
Comment: There are also a LOT of other questions on here that ask the same or similar question. See the "Related" block to the right ->
Comment: All of those questions are outdated or have nothing to do with the question of disallowing characters. I did search the website first before posting. Now admittedly, I didn't search "validation" when googling, which is probably why I didn't find the module that solved my problem.


Empty array returned by mapPartitions in PySpark

Question: hello could someone explain to me why mapPartitions reacts differently to those two functions? (I have looked at this this thread and I don't think my problem comes from the fact that my iterable is TraversableOnce as I create it.
L=range(10)
J=range(5,15)
K=range(8,18)

data=J+K+L

def function_1(iter_listoflist):
    final_iterator=[]
    for sublist in iter_listoflist:
        final_iterator.append([x for x in sublist if x%9!=0])
    return iter(final_iterator)

def function_2(iter_listoflist):
    final_iterator=[]
    listoflist=list(iter_listoflist)
    for i in range(len(listoflist)):
        for j in range(i+1,len(listoflist)):
            sublist=listoflist[i]+listoflist[j]
            final_iterator.append([x for x in sublist if x%9!=0])
            pass
        pass
    return iter(final_iterator)

sc.parallelize(data,3).glom().mapPartitions(function_1).collect()

returns what it should while
sc.parallelize(data,3).glom().mapPartitions(function_2).collect()

returns an empty array, I have the checked the code by returning a list at the end and it does what I want it to.
thanks for your help
Philippe C
Answer: It is actually quite simple. listoflist has always length equal to 1. To understand why that is the case you have to think about what is going on when call glom. To quote the docs it returns:

an RDD created by coalescing all elements within each partition
  into a list.

It means that when you call:
listoflist=list(iter_listoflist)

You get a list with a single element list containing all elements from that partition. Ignoring all the details:
(sc.parallelize(data, 3)
    .glom()
    .mapPartitionsWithIndex(lambda i, iter: [(i, list(iter))])
    .collect())

## [(0, [[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]]),
##     (1, [[8, 9, 10, 11, 12, 13, 14, 15, 16, 17]]),
##     (2, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])]

It means that

range(len(listoflist)) contains a single element equal 0.
range(i+1,len(listoflist)) by substitution is an empty range(1, 1)

Hence there is nothing to do and you get an empty iterator.
On a side note all these pass statements as well as iter calls are completely obsolete.
Comment: thank you for your answer and side note I'll take it into account. Is it of length 1 because it is called by mapPartition? When I did my tests it was of length the size of my list or iterator.
Comment: No, it because you're using `glom`
Comment: Ok thank you very much, my work arround was to do the two for loops somewhere else and then call parallelize and it worked. If I don't use glom() I have an error message as I try to iterate on ints. is there a way to have the loop inside the function? I am basically trying to compute the lists in parallel but need that they don't mix. thanks again
Comment: Could you ask this a separate question and try to explain exactly what is the logic here? I have this strange feeling that code you've provided doesn't really reflect the expected output.
Comment: sure here it is http://stackoverflow.com/questions/33562318/how-to-specify-the-partition-for-mappartition-in-spark


Inconsistency parsing numeric literals according to C++ Standard's grammar

Question: Reading through the C++17 standard, it seems to me that there is an inconsistency between pp-number as handled by the preprocessor and numeric literals, e.g. user-defined-integer-literal, as they are defined to be handled by the "upper" language.
For example, the following is correctly parsed as a pp-number according to the preprocessor grammar:
123_e+1

But placed in the context of a C++11-compliant code fragment,
int  operator"" _e(unsigned long long)
    { return 0; }

int test()
    {
    return 123_e+1;
    }

the current Clang or GCC compilers (I haven't tested others) will return an error similar to this:
unable to find numeric literal operator 'operator""_e+1'

where operator"" _e(...) is not found and trying to define operator"" _e+1(...) would be invalid.
It seems that this comes about because the compiler lexes the token as a pp-number first, but then fails to roll-back and apply the grammar rules for a user-defined-integer-literal when parsing the final expression.
In comparison, the following code compiles fine:
int  operator"" _d(unsigned long long)
    { return 0; }

int test()
    {
    return 0x123_d+1;  // doesn't lex as a 'pp-number' because 'sign' can only follow [eEpP]
    }

Is this a correct reading of the standard?  And if so, is it reasonable that the compiler should handle this, arguably rare, corner case?
Comment: For the note, MSVC compiles both cases fine.
Comment: There's no underscore allowed in [lex.ppnumber](http://eel.is/c++draft/lex.ppnumber)! So parsing `123_e+1` as `pp-number` is wrong...
Comment: @Aconcagua - actually _`pp-number`_ lexes _`identifier-nondigit`_ and _`nondigit`_ includes underscore.
Comment: This isn't an answer because I'm not 100% sure that it's true for C++17, but similar corner cases exist in C and the interpretation is that the standard actually _requires_ it to be an error:  each pp-token is to be converted to one and only one phase-7 token, the compiler is not allowed to "roll back" as you put it.
Comment: @AndyG Oh, you seem to be right, sorry - but `+` is not covered? Interesting: p/P are included, but the 0x prefix isn't either...
Comment: My first instinct is that this is a [maximal munch case like >=](https://stackoverflow.com/a/28354898/1708801) and [a+++++b](https://stackoverflow.com/a/24947922/1708801) CC @zwol
Comment: @DeiDei MSVC is not correct on this one.
Comment: @Aconcagua `+` is covered by the `pp-number e sign` production, which is hard to spot at first and `0x` is covered by `pp-number identifier-nondigit`.
Comment: @ShafikYaghmour Hm, that would require to parse 1.e+E+p+P+e as `pp-number` as well... I'd say these construction rules are too generic then, next standard might (hopefully) get more precise (having two paths: allowing `e sign` only if not yet an identifier occured and vice versa)...
Comment: @Aconcagua it will be ill-formed at later stages, the grammar does not need to catch it here.
Comment: @ShafikYaghmour If it would, we wouldn't need spaces, thus the `e` and `d` examples would not need to be treated differently. Interesting example, though, on how good formatting can prevent errors...
Comment: Interesting to note that a similar `123_p+1` has inconsistent treatment from clang and gcc [see it live](https://godbolt.org/z/3MsH9R) and using that example as opposed to the `_d` one and asking why clang and gcc has inconsistent results seems like a reasonable way to differentiate this and the duplicate.
Answer: You have fallen victim to the maximal munch rule which has the lexical analyzer take as many characters as possible to form a valid token.
This is covered in section [lex.pptoken]p3 which says (emphasis mine):

Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name ([lex.header]) is only formed within a #include directive.

and includes several examples:

[ Example:
#define R "x"
const char* s = R"y";           // ill-formed raw string, not "x" "y"

— end example ]
4 [ Example: The program fragment 0xe+foo is parsed
  as a preprocessing number token (one that is not a valid floating or
  integer literal token), even though a parse as three preprocessing
  tokens 0xe, +, and foo might produce a valid expression (for example,
  if foo were a macro defined as 1). Similarly, the program fragment 1E1
  is parsed as a preprocessing number (one that is a valid floating
  literal token), whether or not E is a macro name. — end example ]
5[ Example: The program fragment x+++++y is parsed as x ++ ++ + y,
  which, if x and y have integral types, violates a constraint on
  increment operators, even though the parse x ++ + ++ y might yield a
  correct expression. — end example  ]

This rule effects in several other well known cases such as a+++++b and tokens  >= which required a fix to allow.
For reference the pp-token grammar is as follows:

pp-number:
  digit
  . digit
  pp-number digit
  pp-number identifier-nondigit
  pp-number ' digit
  pp-number ' nondigit
  pp-number e sign
  pp-number E sign
  pp-number p sign
  pp-number P sign
  pp-number .

Note the e sign production, which is what is snagging this case. If on the other hand you use d like your second example you would not hit this (see it live on godbolt).
Also adding spacing would also fix your issue since you would no longer be subject to maximal munch (see it live on godbolt):
123_e + 1

Comment: Since you pinged me, again, I haven't close-read the C++ standard in many years and in particular I don't know if there are special rules for user-defined literals. This interpretation is correct for C provided you also take into account the usual interpretation of 220.127.116.11p1#7 "Each preprocessing token is converted into a token" meaning _one and only one_ token -- the compiler isn't supposed to split up a single pp-token into two phase 7 tokens, either, even when that would lead to a valid parse.
Comment: @Aconcagua I mean that's the whole question. `0xe+foo` is one _preprocessing_ token. The standard _could_ have been written to specify that lexical analysis is repeated after preprocessing, in which case the pp-token `0xe+foo` would become three phase 7 tokens, the integer-literal `0x3`, the operator `+`, and the identifier `foo`. The C standard wasn't written that way; instead it requires `0xe+foo` be converted to a _single_ phase 7 token, and there is no lexical production that matches, so it's a syntax error. I believe, but am not 100% sure, that the C++ standard is the same way.
Comment: (Maximal munch _on phase 7 tokens_ would produce `0xe + foo` from example 4, because `0xe` is an integer-literal token and the production for integer-literals does not allow `+` at that point.)
Comment: Thanks for the answer and for the example from the standard.
Comment: @zwol Just following the parser rules, I think `0xe+foo` would need to be accepted as one token - as far as I understand (and learned...), interpreting the token as integer or FP literal is done at a later stage?
Comment: Now out of curiosity: How is the `x` in `0x` covered? Would it be treated as identifier-nondigit while parsing?
Comment: @zwol: C++ is the same.
Comment: @rici Good to know, thanks.


Custom navigation menu bar

Question: I use the main menu as navigation bar, and I would like to obtain the following result: When the mouse is hovered on one navigation item, the sub menu should be shown as
 under this item. I would like to be able to style the sub menu
s as well.
Shall I actually use the navigation menu or just the main menu?
I am using Drupal 7.
Comment: details r not enough
Answer: It sounds to me like you are looking for something like Superfish or Nice Menus.
My personal preference is Superfish, as it has become pretty damn useful in recent updates. It's also responsive if that's a requirement, and support touchscreens quite nicely.
EDIT
Something I missed (possibly another personal preference) is that I find the CSS for Nice Menus an absolute NIGHTMARE in comparison with Superfish.
Comment: Didn't know Superfish was responsive now, awesome :)
Comment: Yup - surprised me too when I was doing a responsive site and it just worked ;-)
Comment: I've used Nice Menu like forever. I agree that initially figuring out the CSS is confusing. Use an override file to change just the things you need. I also agree that the latest (dev version important!) of Superfish is very convenient; yeah, it just works! Many options for screen or user agent.
Answer: I depends on your theme. It is often useful to turn off the main menu in the theme appearance settings, and then using the block system to place the menu.
NiceMenus or Superfish give you the ability to modify the drop-downs. With NiceMenus you'll have to set the @media breakpoints yourself for different screen sizes. Superfish has these features built-in, which can save you a lot of responsive design-time.
Also, see the Menu Block module which has lots of menu placement options.

Custom navigation menu bar


How to add alt tag to image from views

Question: I have created views with image gallery. Now I want to add alt tag to image how can I do it. I have not enabled alt field in content type configuration.
I want add alt tag to already existing images. Kindly provide the solution to achieve this.
Comment: is the alt tag unique for each image? or all of them will have the same alt tag?
Comment: I need unique alt@NoSssweat
Comment: just wondering why not do it through the content type config?
Comment: We can do it. But I already created content without adding alt tag.@NoSssweat
Comment: then all you would have to do is edit the content and add the tag text...
Comment: I have more than 150 content. So i am asking for alternative @NoSssweat
Answer: There is no way to add unique alt text using views, unless... you use:
Editable Fields

This module allows CCK fields to be edited on a node's display (e.g.
at node/123), not just on the node edit pages (e.g. node/123/edit). It
also works within views etc. Anywhere a 'formatter' can be selected,
you can select editable (or click to edit).

Video tutorial/demo
You would have to enable the alt in your content type, then you should be able to edit it in your view.

I have more than 150 content. So i am asking for alternative

I take it you're looking for an easy & quick way so you don't have to edit 150 nodes one by one.
Another method
would be to find the alt field in your database and export the table as .csv file.
Then edit it using excel, and add your alt text here, save.
Import back in and clear the Drupal cache.

How to add alt tag to image from views


Is there a binary spigot algorithm for log(23) or log(89)?

Question: The Bailey-Borwein-Plouffe formula yields a binary spigot algorithm for π, and related formulas give the bits of log(2) and those of the logarithms of some other integers.  I got stuck (over a year ago, so none of this is fresh in my head) trying to find a spigot algorithm for the bits of log(23), and I guess that the difficulty is because $23 \times 89 = 2^{11}-1$ is a Mersenne number.
Is any binary spigot algorithm known for log(23) or log(89) which is just as fast as those for π and log(2)?  If not, is there any reason to think that one doesn't exist?
Comment: @kuch, because 2047 = 23 * 89...  I noticed it and thought of this old question. :)
Comment: Have a look at Page 7 of this [link](http://crd.lbl.gov/~dhbailey/dhbpapers/bbp-formulas.pdf) It contains a list of primes whose logarithms have a binary BBP formula. Neither 23 nor 89 are
on the list.
Comment: "it is unknown whether or not all primes have this property".  If it is an open problem I will accept an answer to that effect.
Comment: I'm wondering why I got notified without `@`. Anyhow, regarding the above comment, what has your reputation got to do with it?
Comment: Can a fast series for log(23) be obtained by accelerating a slow one?
http://math.stackexchange.com/questions/1605204/a-binary-bbp-type-formula-for-log23
Comment: For reference, the list of primes $p<100$ where $\log(p)$ has no known spigot algorithm is $p=23, 47, 53, 59, 67, 71, 79, 83, 89, 97$. However, I think $97 = 2^5\times3+1$ might have one.
Answer: Dang-Khoa Do, Spigot algorithm and reliable computation of natural logarithm, Reliable Computing 10 (2004) 489-500, gives spigot algorithms for computing various logarithms. I didn't look at it closely enough to tell whether $\log23$ is amenable to Do's methods.
EDIT: Incidentally, OP is quite correct to relate the difficulty to the Mersenne connection. See the top of page 11 of http://crd-legacy.lbl.gov/~dhbailey/dhbpapers/digits.pdf, Bailey, Borwein, and Plouffe, On the rapid computation of various polylogarithmic constants.
Comment: @Dan, authors love to know that someone is actually reading the papers they are writing and is interested, even if only out of idle curiosity, in the same things that interest them. There is absolutely no reason to feel uncomfortable about asking an author for access to a paper. Alternatively, perhaps you have access to a library that will do interlibrary loan for you?
Comment: +1 for Gerry's suggestion. All mathematicians I know are more than happy to send you electronic copies of their papers. Just make sure not to send your request by post using barely legible handwriting with the demand that a physical copy be FedEx'ed to your location. =) (Unless, of course, you include a pre-paid return mailer.)
Comment: @Dan, perhaps you can find contact information for the author and ask for the paper (or just ask the author about the answer to your question).
Comment: Gerry, I wouldn't feel comfortable doing that just to satisfy my idle curiosity.  I don't have anything to offer in return except upvotes and I guess these guys have students who pay tuition.
Comment: I don't have free access, and I can't find a free copy on Google, so I can't tell either.  I did find http://docserver.carma.newcastle.edu.au/47/1/machin.pdf which says "There is no non-Aurifeuillian binary Machin-type BBP logarithms formula for ln(23) or for ln(89)" but I don't know what this means and I don't think it addresses my question about the existence of an algorithm as fast as that for log(2) or π.


Android AnimationDrawable start

Question: I'm using AnimationDrawable to show missing network connection.
Show/hide logic is linked to network status change receiver. It works fine.
But when start activity knowing status and try to start animation - animated drawable shows and freezes on first frame. I've read in documentation - 'do not start animation in OnCreate'.
So I wrote code in onResume, but animation still not playing - only shows first frame.
Starting from button or event works fine.
Tried to start with separate thread and wait some time - but this doent sounds good.
Any idea?
This code works when called from net status change handler
<code>private void _NetStatus(boolean start)
{
    if (start)
    {
        m_NetStatus.setVisibility(View.VISIBLE);
        m_NetStatusFrameAnimation.start();
    }
    else
    {
        m_NetStatusFrameAnimation.stop();
        m_NetStatus.setVisibility(View.INVISIBLE);
    }
}
</code>
Answer: Hmm. After trying some samples advising me to use new Runnable at end of onCreate - I tried to start animation when activity shows on screen:
<code>@Override
public void onWindowFocusChanged(boolean hasFocus)
</code>
Works fine for now.

Android AnimationDrawable start


GeoKettle Pan/ Kitchen Hangs at New Database Defined

Question: Pan/ Kitchen of
Spatially enabled version of
Pentaho Data Integration (Kettle) version 3.2 hangs at 'New Database Defined'. I am trying to extract some data from a MS Sql Server 2005 table through a ODBC connection and populate a postgis table. Every time when the transformation reaches "a new database connection defined" it hangs.
Transformation runs flawless in spoon though.
I tried running seperate steps, everything works fine, till the last step is added, when writing to postgis output is inserted this starts happening. Yet if an output to a postgis table done seperately the task runs fine.
Please help!
Thanks in advance.
Answer: For questions about GeoKettle, please join the user mailing list at: https://lists.sourceforge.net/lists/listinfo/geokettle-users. Do not hesitate to post your transformation file on the list. It will help in identifying the problem and in solving it.
Cheers,
Comment: Hi Dr Thierry Badard, It is so nice to here from you about an answer for my question. I will definitely post a thread at the mailing list you gave me. We recently integrated geo kettle to populate our postgres based datawarehouse and looking forward to doing more with the same. Great to here that your are there for assistance. Thanks!!!


Order of operation: division and multiplication

Question: I always thought division and multiplication have the same order of operation, so it does not matter which of these you do first. But in helping a young student with her math I realized that it does matter.
<code>Example 1: 8 x 5 / 10.
Multiplication first: = 40 / 10 = 4
Division first: = 8 x 1/2 = 4

Example 2: 6 / 2 * 4
Multiplication first: = 6 / 8 = 3/4
Division first: = 3 * 4 = 12
</code>
Trying to find an answer to this I found 2 mnemonics:
BODMAS (which seems to say division first)

and PEMDAS (which seems to say multiplication first)

I would appreciate some clarification here.
Comment: They say the same thing. They say that you should do the divisions and the multiplications in that step, in whatever order they occur as you go  left to right.
Comment: These are the same  conventions, with different words. They are commonly taught in school. M and D should go left to right. In real mathematics, people *should) use parentheses when there is any doubt.,
Comment: I would strongly advise avoiding ambiguous notation.  It is easy enough to write, e.g., $6/(2\times 4)$ or $(6/2)\times4$ and thereby remove the ambiguity.  As to conventions, note that both Excel and Wolfram Alpha parse $6/2\times 4$ as $12$.
Comment: OK, so to confirm: 6 / 2 x 4 = 12?
Comment: Of course it makes a difference. $2-3-2$ if done left to right is $-3$: $2$ minus $3$ is $-1$, and $-1$ minus $2$ is $-3$. But if you do $3-2$ first, then you get $1$. Neither subtraction nor division are associative. And of course $a-(b+c)= (a-b)-c\neq (a-b)+c$. Exactly the same problem as with mutliplication and division.
Comment: $6-2+4$ is $(6-2)+4=8$  but you could read it as $6-(2+4)=0$.  Exactly the same ambiguity that you eluded to in your post (though we are more used to interpreting this as $6+(-2)+4$ so it tends not to generate controversy).
Comment: But if you do that with addition and subtraction, then you should do the same thing with multiplication and division, and interpret $6/2\times 4$ as $6\times (2^{-1})\times 4$, and then there is no ambiguity regardless of whether you do the first product first or second. If there is no subtraction, just addition of additive inverses, then there is no division, just multiplication of multiplicative inverses. Geese and gander and all that.
Comment: And it's not a matter of "correct" and "incorrect". It's a matter of **convention**. We agree on how to interpret potentially ambiguous formulas ahead of time, to eliminate ambiguity. We can agree on whatever resolution we want, even choosing between contradictory ones, as long as we are both clear on which convention we are using and we use the same convention.
Comment: Always go left to right.  So $6-2+4=(6-2)+4=8$ which, as I said, is what you'd get if you interpreted the expression as $6+(-2)+4$.
Comment: Thanks for the responses. As for the ambiguous notation: fully agree (being a programmer myself). These are primary school questions intended to be ambiguous so as to specifically focus on the rules for order of operation.
Comment: Note that the mnemonics don't separate M from D, or A from S. There's a reason for that.  They say: first explicit groupings; then exponentiations; then product-and-divisions-at-the-same-time; then sums-and-differences-at-the-same-time. Otherwise, PEDMAS would have separate lines for P, E, D, M, A, and S.
Comment: @ArturoMagidin Sure, and this is how I always understood it to be. It is the (left to right) part that I apparently never learnt. Thing is, (left to right) is also shown next to  Addition and Subtraction whereas there it makes absolutely no difference. If I am wrong here then please tell me.
Comment: @lulu exactly: I interpreted 2 - 3 - 2 as 2 + (-3) + (-2), in which case order obviously does not matter as it is all addition. You say 'we are more used to interpreting this as'. But one of these interpretations must be correct and one must be incorrect, right?
Comment: I guess sometimes one uses rules that you are not actually aware of (such as left to right) and operates under assumptions (like the order of division and multiplication does not matter) that work in most cases (university math, 25 years programmer). And then you help a 12 year old and suddenly realize there is a puzzle piece missing. ;-)
Answer: It definitely matters and the reason is associativity. For both addition and multiplication we have that $(a+b)+c=a+(b+c)$ and $(ab)c=a(bc)$ however for subtraction and division we don't because in general $(a-b)-c \neq a-(b-c)$ and likewise with $(a/b)/c \neq a/(b/c)$.
To get rid of this problem in higher mathematics we get rid of subtraction and division entirely and instead add negatives and multiply reciprocals. So if I write $a-b$ what I really mean is $a + -b$ and if I write $a/b$ I really mean $ab^{-1}$. This allows us to use associativity with abandon and avoids any ambiguity about which order we should do things.


Fade out preloader

Question: How can I make my preloader to fade out when finished loading? I tried adding transition: 1s ease; but I guess I'm forgetting something.
HTML:

function onReady(callback) {

var intervalID = window.setInterval(checkReady, 1000);

}

function checkReady() {

if (document.getElementsByTagName('body')[0] !== undefined) {

window.clearInterval(intervalID);

}

//loading%

CSS:
.preloader{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    display: table;
    background: #000;
    z-index: 9999;
}

.preloder-wrap{
    display: table-cell;
    vertical-align: middle;
}

.preloder-inner {
    width: 200px;
    height: 100px;
    margin: 0 auto;
}

Thanks.
Answer: in your javascript, when it has finished loading you can use use jquery's fadeOut function:
$("preloader").fadeOut();

Comment: Thanks, I had this function set `$(".preloader").delay(1600).fadeOut("fast").remove;` and had to take off the `.remove` part. Thanks!

Fade out preloader


Prevent Apache 2 to search for /index

Question: I have a problem with my apache 2 configuration. If I run
http://myhost.com/user/search

Everything works fine. My website loads perfectly. But if I run
http://myhost.com/index

I get a 404 error. Is it possible to prevent this?
I thank you for your help!
Comment: http://stackoverflow.com/questions/5190206/apache-htaccess-how-do-i-redirect-for-files-that-arent-found-without-sending
Answer: include the following, and replace index.htmlwith any page you want the visiter to land on:
ErrorDocument 404 /index.html

Prevent Apache 2 to search for /index


Solving the recurrence $g(n)=g(n-1)\left(1+\frac{1}{n}\right)+\left(1+\frac{1}{n}\right)$ with $g(0)=0$

Question: I ran across the following math puzzle: a mouse is on a circle with circumference of 100 units and every turn he walks on the circle a unit of 1 after every turn the circle is increased by 100 units (evenly distributed) will the mouse ever reach the end.
To solve this, I came up with the following distance equation for the mouse:

$$g(n)=g(n-1)\left(1+\frac{1}{n}\right)+\left(1+\frac{1}{n}\right)$$
$$g(0)=0$$
How does one go about solving this equation?
Comment: Shouldn't your initial condition be $g(1)=0$ ?
Comment: @Dr.WolfgangHintze the function describes the mouse distance in units at each turn, my definition of turn 0 is before any turns were made, hence the mouse moved 0 units at turn 0,
Comment: @  Mike How do you then calculate $g(1)$ from the recursion? My solution is $g(n) = n H_{n-1}$ ($H_n$ the harmonic number). The values of $g(n)$ for $n=0 ..5$ are $\left\{-1,0,2,\frac{9}{2},\frac{22}{3},\frac{125}{12}\right\}$. Here $g(0)$ has to be understood as a limiting value.
Comment: @Dr.WolfgangHintze its a matter of definition, I defined the function $g(n) = (n+1)H_n$ which shifts the above values left one, retaining the $g(0)=0$
Comment: @ Mike That is just what I was saying. You should do the shift in the first place. Otherwise (I repeat) your recurrence leads to infinity for g(1).
Comment: @Dr.WolfgangHintze sorry, i missed that, you are absolutely correct. in my notes the function was denoted $g(n) = g(n-1) (1+1/n)+(1+1/n)$ where $g(0)=0$ which works as expected. i must of mixed up the index when typing the question, will edit question, thank you.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95097/discussion-between-mike-and-dr-wolfgang-hintze).
Answer: Hint.
$$
ng_{n+1}=(n+1)g_n+n+1\Rightarrow \frac{g_{n+1}}{n+1} = \frac{g_n}{n}+\frac 1n
$$
now calling $f_n = \frac{g_n}{n}$ we have
$$
f_{n+1} = f_n +\frac 1n
$$
for $n > 0$
Answer: Starting from @Cesareo's answer
$$f_{n+1} = f_n +\frac 1n \implies f_n=\psi (n)+\gamma+c$$ where appears the digamma function. So
$$g_n=n\left(\psi (n)+\gamma+c \right)$$ but the condition should be something else than $g_0=0$.
If it is $g(1)=0$, then $c=0$.
Comment: Lebovici: It would be nice to mention that $f(n)$ is in fact in the form of a first-order harmonic number (up to the additive constant $C$). In fact, $\psi (n)+\gamma =H_{n-1}$ with $H_m:=\sum_{i=1}^{m}1/i$.
Comment: @MarianG. You are totally correct. I shall not edit my naswer on purpose just to show how stupid I can be. Cheers :-(
Comment: Sorry for your name distortion.


Get Tag ID rally query

Question: I am using this function to get Project ID in Rally.
def getProjectID(projectName)
results = @rally.find(RallyAPI::RallyQuery.new({:type => :project, :query_string => "(Name = \"" + projectName + "\")"}))
project = results.first.read
@projectID = project.ObjectID
end

Can anyone suggest me anything on these lines to get the Tag ID, given the Tag Name. Thanks!
Answer: This code prints tag's ObjectID after it queried tags by Name:
require 'rally_api'

#Setup custom app information
headers = RallyAPI::CustomHttpHeader.new()
headers.name = "Find Tag's ObjectID given the Name"
headers.vendor = "Nick M RallyLab"
headers.version = "1.0"

# Connection to Rally
config = {:base_url => "https://rally1.rallydev.com/slm"}
config[:username] = "firstname.lastname@example.com"
config[:password] = "secret"
config[:workspace] = "W"
config[:project] = "P"
config[:version] = "v2.0"
config[:headers] = headers #from RallyAPI::CustomHttpHeader.new()

rally = RallyAPI::RallyRestJson.new(config)

tagQuery = RallyAPI::RallyQuery.new()
tagQuery.type = :tag   #userstory or hierarchical_requirement or hierarchicalrequirement will also work
tagQuery.fetch = "ObjectID"
tagQuery.project = {"_ref" => "https://rally1.rallydev.com/slm/webservice/v2.0/project/2222.js" }
tagQuery.order = "Name Asc"
tagQuery.query_string = "(Name = \"tag1\")"
tagResults = rally.find(tagQuery)
myTag = tagResults.first
puts "ObjectID: #{myTag.ObjectID}"

Get Tag ID rally query


loading extjs bar chart sample into a div tag

Question: Just a newbie here trying to understand and work on extjs 4.2.1. I really like the charts and grids and wanted to incorporate them into my current application. I got the sample grid to work in my application but the chart turns out to be a little harder. I used the sample code at
sample code
which renders the chart in another window and was wondering if someone can help me put this into a div tag on one of my panels.
Here is the container I have for the chart:

and the chart script: charts.js
Ext.require('Ext.chart.*');

Ext.require(['Ext.Window', 'Ext.fx.target.Sprite', 'Ext.layout.container.Fit']);
Ext.onReady(function () {
    var textArea;
var store = new Ext.data.JsonStore({
    fields: ['name', 'visits', 'views'],
    data: [
        { name: 'Jul 07', visits: 245000, views: 3000000 },
        { name: 'Aug 07', visits: 240000, views: 3500000 },
        { name: 'Sep 07', visits: 355000, views: 4000000 },
        { name: 'Oct 07', visits: 375000, views: 4200000 },
        { name: 'Nov 07', visits: 490000, views: 4500000 },
        { name: 'Dec 07', visits: 495000, views: 5800000 },
        { name: 'Jan 08', visits: 520000, views: 6000000 },
        { name: 'Feb 08', visits: 620000, views: 7500000 }
    ]
});

Ext.define('Ext.chart.theme.CustomBlue', {
        extend: 'Ext.chart.theme.Base',
    constructor: function (config) {
        var titleLabel = {
            font: 'bold 18px Arial'
        }, axisLabel = {
            fill: 'rgb(8,69,148)',
            font: '12px Arial',
            spacing: 2,
            padding: 5
        };

        this.callParent([Ext.apply({
            axis: {
                stroke: '#084594'
            },
            axisLabelLeft: axisLabel,
            axisLabelBottom: axisLabel,
            axisTitleLeft: titleLabel,
            axisTitleBottom: titleLabel
        }, config)]);
    }
});

var chart = Ext.create('Ext.chart.Chart', {
    animate: true,
    shadow: true,
    store: store,
    axes: [{
        type: 'Numeric',
        position: 'bottom',
        fields: ['data1'],
        label: {
            renderer: Ext.util.Format.numberRenderer('0,0')
        },
        title: 'Number of Hits',
        grid: true,
        minimum: 0
    }, {
        type: 'Category',
        position: 'left',
        fields: ['name'],
        title: 'Month of the Year'
    }],
    theme: 'CustomBlue',
    background: {
        gradient: {
            id: 'backgroundGradient',
            angle: 45,
            stops: {
                0: {
                    color: '#ffffff'
                },
                100: {
                    color: '#eaf1f8'
                }
            }
        }
    },
    series: [{
        type: 'bar',
        axis: 'bottom',
        highlight: true,
        tips: {
            trackMouse: true,
            width: 140,
            height: 28,
            renderer: function (storeItem, item) {
                this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
            }
        },
        label: {
            display: 'insideEnd',
            field: 'data1',
            renderer: Ext.util.Format.numberRenderer('0'),
            orientation: 'horizontal',
            color: '#333',
            'text-anchor': 'middle'
        },
        xField: 'name',
        yField: ['data1']
    }]
      renderTo: "container"
});

});
Answer: You didn't explain what the problem was, however it's pretty clear from looking at the code.
The issue is that you need to give the chart a width/height, because it needs those to size appropriately. In the original example in the docs, the dimensions are provided explicitly by the fit layout used on the window.
Comment: Thanks so much. Yes I did not clarify, that I was not seeing the chart. Once I added the  height: 350,
        width: 800, I can see the chart just not the bars and data; so I will work on that a bit before accepting your answer. Really appreciate your response.
Comment: The fields in your chart definition `data1` don't match what's in the store.
Comment: Yep, got it to work, thanks. By the way do you perhaps know of a link that illustrates getting data from a remote source and passing it to these kinds of widgets, charts/grids in extjs. I will leave you alone now and thanks again.
Comment: Yes, there are plenty of examples. `grep` the examples directory for calls to `.load()` on a store.


How to negate the satement "If $3y$ is a perfect cube then there exists an even number $n$ so that $y = 3n^3$"

Question:
Let $x \in \mathbb{Z}$. If $3y$ is a perfect cube then there exists an even number $n$ so that $y = 3n^3$.

Question: I am a little bit confused here. I know this statement is false and I would like to find 2 things.
(1) What is the negation of this statement? Important: If I want to disprove a statement, do I need to take the negation of the WHOLE implication like $\neg (a \implies b)$? Or just take the negation by parts like $a \implies b \equiv \neg a \implies \neg b$?
I need to find a counter example, but according to a professor I need to find it using the negation.
(2) In what cases would you use $\neg(a \implies b)$ versus $\neg a \implies \neg b$?
Comment: Where is $x$ in this problem? Perhaps thats a $y$?
Comment: The *negation* of $a \to b$ is $a \land \lnot b$.
Comment: Thus, the negation of the iniatial statement must be : "$3y$ is a perfect cube **and** does not exist an even number $n$ such that ..."
Answer:
(1) What is the negation of this statement? Important: If I want to disprove a statement, do I need to take the negation of the WHOLE implication like $\neg (a \implies b)$? Or just take the negation by parts like $a \implies b \equiv \neg a \implies \neg b$?

This is important, yes! You ALWAYS take the negation of the whole statement, not the parts. The negation of an implication is NOT the negation of its parts. What we do is
$$
\lnot (a \implies b) = a \land (\lnot b).
$$
In the end you should get the statement: "$3y$ is a perfect cube and for all even numbers $n$, $y \ne 3n^3$."

(2) In what cases would you use $\neg(a \implies b)$ versus $\neg a \implies \neg b$?

Always the first one. Never the second, when negating a statement.
$\lnot a \implies \lnot b$ may come up if you are doing a proof and you want to prove the converse of a statement $a \implies b$. But don't worry about that.
Comment: THANKS! So how do I prove the negation is true? It isnt an implication so I am not sure what to do now?  Shouldn't the negation be "$3y$ is a perfect cube and for all **odd numbers** $n$, $y \ne 3n^3$?
Comment: @dbz1 no it should be for even numbers, not for odd numbers. To prove it, pick a y.
Comment: I meant the negation? Does it change? I have the statement "all even numbers $n$..." isnt the negation for "all odd numbers $n$..."
Comment: @dbz1 Nope! You are wrong. Think carefully. The opposite of "there is an even number n such that blah blah blah" is "for all even numbers n, not blah blah blah". You don't switch from even to odd or vice versa.


Proving uniform convergence of a Fourier series

Question: Let $f(x):\mathbb{R}\to\mathbb{R}$, $f'(x) > 0$ for $x\in\mathbb{R}$ and $g(x):\mathbb{R}\to\mathbb{R}$ a periodic function with a $2\pi$ period such that $g(x)=f(x)$ if $-\pi < x < \pi$.
I need to prove, or disprove, that the Fourier series of $g(x)$ converge uniformly in $(0, \pi)$.
First, $g$'s Fourier series is
$$g(x)\sim \frac{1}{2}a_0+\sum_{n=1}^{\infty}(a_n\cos nx+b_n\sin nx)$$
I know that for every $x_0\in(0, \pi)$, $g(x_0)=f(x_0)$ is continuous in $x_0$ and both the left and right derivative exists thus for every such $x_0$ the Fourier series of $g(x)$ converge to $f(x_0)$, i.e.
$$\frac{1}{2}a_0+\sum_{n=1}^{\infty}(a_n\cos nx_0+b_n\sin nx_0) = f(x_0)$$
Now all that left is to show that $$\sum_{n=1}^{\infty}(a_n\cos nx+b_n\sin nx)$$ converges to $f(x)$ uniformly for $x\in(0,\pi)$.
Comment: that is not true even for the simplest such functions like $f(x)=x$ where the convergence is uniform on any compact subinterval of $[0, \pi)$ but not near $\pi$ (see Gibbs phenomenon for example https://en.wikipedia.org/wiki/Gibbs_phenomenon)
Comment: @Conrad but here I was asked about the interval $(0, \pi)$ the sum of the series for any $x$ in that interval is continuous so I don't see why it can't converge uniformly
Comment: @Conrad In other words if it doesn't converge uniformly how can I prove it, for example, with $f(x)=x$
Comment: because $g$ (the periodic extension of $f$) has a jump at $\pi$ so its Fourier series converges to the average value of the left and right limits (which is zero for $f(x)=x$ since the right limit of $g$ at $\pi$ is $-\pi$ by periodicity) but uniform continuity of the Fourier series on $(0, \pi)$ trivially implies convergence to the left limit at $\pi$ by general topology (if $g_n$ are continuous on $(a,b]$ and converge uniformly on $(a,b)$ to some $g$ then that $g$ (which is continuous on $(a,b)$) has a continuous extension to $(a,b]$ and $g_n(b) \to g(b)$)
Answer: $\def\R{\mathbb{R}}\def\N{\mathbb{N}}\def\paren#1{\left(#1\right)}$The counter-example provided by @Conrad is enough to disprove the proposition. A stronger proposition, however, can be proved:

If $f: [-π, π] → \R$ is strictly monotonic and has only a finite number of points of discontinuity, and $g$ is a $2π$-periodic function with $f = g$ on $(-π, π)$, then the Fouries series of $g$ does not converge uniformly on $(0, π)$.

Proof: Denote the partial sums of the Fourier series by $S_N(x) = a_0 + \sum\limits_{n = 1}^N (a_n \cos nx + b_n \sin nx)$ for $N \in \N$. Note that the Dirichlet condition implies that$$
\lim_{N → ∞} S_N(x) = \frac{1}{2} (g(x + 0) + g(x - 0)).\quad \forall x \in \R
$$
Suppose $\{S_N\}$ converges uniformly on $(0, π)$, then\begin{gather*}
\frac{1}{2} (g(π + 0) + g(π - 0)) = \lim_{N → ∞} S_N(π) = \lim_{N → ∞} \lim_{x → π-} S_N(x)\\
\stackrel{(1)}{=} \lim_{x → π-} \lim_{N → ∞} S_N(x) = \lim_{x → π-} \frac{1}{2} (g(x + 0) + g(x - 0)) \stackrel{(2)}{=} g(π - 0),
\end{gather*}
where (1) uses uniform convergence and (2) uses monotonicity of $g$ on $(-π, π)$. But$$
g(π - 0) = f(π - 0) \geqslant f\paren{ \frac{π}{3} } > f\paren{ -\frac{π}{3} } \geqslant f(-π + 0) = g(-π + 0) = g(π + 0),$$
a contradiction.


Interpretation of sums using $\cdots$

Question: Consider the sum
$$\sum_{1\le k_1 < k_2 < \cdots < k_r \le n}k_1k_2\ldots k_r$$
Does this simply mean
$$\sum_{\substack{|K|=r}\\\inf(K)\ge 1\\\sup(K)\le n}\prod_{k\in K} k$$
I am specifically worried about the situation when $n=r=0$. In the second notation, this is clearly 1, but I'm not sure if it is 0 or 1 in the first notation.
Comment: It would need clarification for the specific situation, but an empty product usually $=1$. In passing, I would say you are overloading the second expression; set $K$ could be defined separately.
Comment: @Joffan I don't understand your second sentence at all. The only overloading I know of is using the same symbol to mean multiple things, but I don't think I have done that here. What do you mean by defining K separately?
Comment: \begin{eqnarray*}
\sum_{1 \leq k_1 \leq k_2 \cdots \leq k_{r-1} \leq k_r \leq n} k_1 k_2 \cdots k_{r-1} k_r = \sum_{ k_1=1}^{n} \sum_{ k_2=k_1}^{n} \cdots \sum_{ k_{r-1}=k_{r-2}}^{n} \sum_{ k_r=k_{r-1}}^{n} k_1 k_2 \cdots k_{r-1} k_r
\end{eqnarray*}
This sum will become more and more difficult as you do each one & will relate to the Bernoulli numbers. I am not sure if there is a neat closed form for it.
Comment: @DonaldSplutterwit That is not the sum I am looking at, but it illustrates the same question. I am looking for advice on how to interpret it, not solve it. What happens when $n$ and $r$ are 0? (If you are curious, your sum does have a neat closed form)
Comment: Sorry just spotted the $<$'s not $\leq$'s (I will buy some glasses) ... what is the closed form for my misunderstanding ?
Comment: @DonaldSplutterwit I don't know yet. Finding one is an exercise in a book I am working through. An answer is provided, but I don't want to look at it before attempting the problem. I will probably put it here in a couple of days.
Comment: @eigensheep I misunderstood slightly, my apologies, but I still think there could be a simpler way to express it - perhaps $$\sum_{r\text{-combinations}\\\text{ from }[1,n]=:K}\prod^r k_i$$but it will end up being a matter of taste no doubt. :-)
Comment: Your second expression is fine ... you want the sum to go over elements of the power set $2^{[n]}$ that are of cardinality $r$ and then take the product of the elements in each set. I get the feeling both problems will have closed forms.
Comment: @DonaldSplutterwit They do. But "I am specifically worried about the situation when n=r=0. In the second notation, this is clearly 1, but I'm not sure if it is 0 or 1 in the first notation."
Comment: @eigensheep It is $1$ in the first notation as well. In both cases, it is an empty product and those are always $1$. (Although I admit that it feels more unintuitive when written with dots.)
Comment: @EikeSchulte Of course an empty product would be 1. I'm worried the sum may be empty.
Comment: @eigensheep Oh, I see. Let me try to add an answer then.
Comment: Empty products are 1, empty sums are 0, hence, when n=r=0, one gets an empty sum of empty products, that is, the value 0.
Answer: I set out to write an answer that said that clearly the first notation gives $1$ as well but now I am not so sure anymore.
You are essentially defining the set $I = \{\,(k_1, \dots, k_r)\,\vert\,1 \leq k_1 < \dots < k_r \leq n\,\}$. I see three sensible ways to translate the condition $1 \leq k_1 < \dots < k_r \leq n$.

You can first split it into conditions for each $k_i$, i.e. $1 \leq k_1 < k_2$, $k_1 < k_2 < k_3$, $\cdots$, $k_{r-1} < k_r \leq n$ (and then split each of those into two inequalities). If you proceed like this, you don't get any conditions in case $r = 0$, thus leaving you with the one-element set $\{()\}$ and a value of $1$.
Alternatively, you translate the condition directly as $1 \leq k_1$, $k_1 < k_2$, $\cdots$, $k_r \leq n$ which would give you $1 \leq n$ in case that $r = 0$ and thus $I$ would be empty if $n = 0$ as well.
You might also translate the condition as $1 \leq k_i$, $k_i \leq n$ for each $i$ and $k_1 < k_2$, $\cdots$, $k_{r-1} < k_r$. Treating the to relations on the outside differently doesn't seem completely ridiculous, after all, it is a different relation. This would also give the value $1$.

It seems to me that the third interpretation is the correct one, but I really can't give a better reason than that it agrees with your second notation which seems reasonable. If you want to use the first notation and the case $r = n = 0$ is important, you should probably mention which value you intend the sum to denote.
Answer: Usually the empty sum is defined to be $0$ and the empty product is defined to be $1$.

We find in Concrete Mathematics by R.L. Graham, D.E. Knuth and O. Patashnik in section 2.1:
We write
  \begin{align*}
\sum_{P(k)}a_k\tag{1}
\end{align*}
  as an abbreviation for the sum of all terms $a_k$ such that $k$ is an integer satifying a given property $P(k)$. A property $P(k)$ is any statement about $k$ that can be either true of false. If $P(k)$ is false for all integers $k$, we have an empty sum; the value of an empty sum is defined to be zero.
Considering OPs sum
  \begin{align*}
\sum_{1\le k_1 < k_2 < \cdots < k_r \le n}k_1k_2\ldots k_r\tag{2}
\end{align*}
  we observe according to (1) that if $n=0$, the sum is zero, independent of the setting of $r$. We do not need to care about the specific structure of the summands, when the sum is already an empty sum.

The summands of $(2)$ are finite products
\begin{align*}
\prod_{j=1}^r k_j\tag{3}
\end{align*}
We find in section 4.2 that the value of an empty product is by definition given as $1$. So, if $r=0$ the product in (3) is equal to $1$.
Answer: The sum $\sum_{1\leq i < j \leq n}$ is merely a shorthand for $\sum_{1 \leq i \leq n}\sum_{i<j\leq n}$. Hence
$$\sum_{1 \leq k_1 <k_2 < \dots < k_r \leq n} k_1k_2\dots k_r = \sum_{1\leq k_1 \leq n}\sum_{k_1 < k_2 \leq n}\dots \sum_{k_{r-1} < k_r \leq n}k_1k_2\dots k_r$$
Written like this the interpretation when $r=0$ is obvious: There is no sum operator, so $n=0$ cannot produce an empty sum. It is then clear that the two expressions in the question are equivalent.

Interpretation of sums using $\cdots$


How does a semantic reasoner for protegé is made?

Question: I'm new in "ontology world". I've been practicing Protegé and ontologies for 2 months and now I would like to understand (and if it is possible to create) a reasoner. But I don't know what is its structure, the language used by it and so on.
Can you please me provide me a piece of information and something to read? Thank you.
Answer: The task of a reasoner is to produce inferences. Standard reasoning tasks are consistency check, realization, instance check and satisfiability. You can find all these defined in a number of books and articles about description logic.
Protege uses the OWL API to interface to reasoners so they are implementations of OWLReasoner. Not all of them are written in Java (e.g., FaCT++ is written in C++).
They are quite complex systems, so describing how to implement one takes chapters - too big for an answer here.
I'd recommend exploring the source code of a few of them. Open Source ones, off the top of my head: HermiT, FaCT++, Pellet, JFact, ELK.


Printing Specific Elements from a Nested List

Question: I have a nested list that looks like this:
 [['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
 ['Thorny', '100', '90', '80'],
 ['Mac', '88', '99', '111'],
 ['Farva', '45', '56', '67'],
 ['Rabbit', '59', '61', '67'],
 ['Ursula', '73', '79', '83'],
 ['Foster', '89', '97', '101']]

I was able to pull out student names using the following:

`def get_students(grades):
    student_names = []
        for i in range(1,len(grades)):
    student_names.append(grades[i][0])
    return student_names  `

The output was ['Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster']
Now I need to pull out the "Exam" headers. I used similar code but it is getting very different results.

`def get_assignments(grades):
    exam_list = []
        for i in range(6, len(grades)):
    exam_list.append(grades[0][1 : ])
    return exam_list`

This returns the output:
`[['Exam 1', 'Exam 2', 'Exam 3']]`

I have been looking here and at GeeksForGeeks to try and figure out what I am doing wrong. It seemed like it should be a simple tweaking of the first code to access a different part of the nested list but I can't seem to get it. Any tips would be appreciated.
EDIT: Apologies, my problem may not have been clear. The desired output is

['Exam 1', 'Exam 2', 'Exam 3']

Thank you!
Comment: `for i in range(1, len(grades)): exam_list.append(grades[i][1:])`
Answer: this is a short solution with list Comprehension
lst=[['Student', 'Exam 1', 'Exam 2', 'Exam 3'], ['Thorny', '100', '90', '80'], ['Mac', '88', '99', '111'], ['Farva', '45', '56', '67'], ['Rabbit', '59', '61', '67'], ['Ursula', '73', '79', '83'], ['Foster', '89', '97', '101']]
lstStudents=[nlst[0] for nlst in lst]
lstExams=[nlst[1:] for nlst in lst[1:]]

print(lstStudents)
print(lstExams)

the out put will be:
['Student', 'Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster']
[['100', '90', '80'], ['88', '99', '111'], ['45', '56', '67'], ['59', '61', '67'], ['73', '79', '83'], ['89', '97', '101']]

Answer: Maybe consider turning your data in to a list of dictionaries, then we can make use of Python's list comprehensions to retrieve whatever you need.
grades = [['Student', 'Exam 1', 'Exam 2', 'Exam 3'], ['Thorny', '100', '90', '80'], ['Mac', '88', '99', '111'], ['Farva', '45', '56', '67'], ['Rabbit', '59', '61', '67'], ['Ursula', '73', '79', '83'], ['Foster', '89', '97', '101']]
headers = grades[0]
grades_list = [dict(zip(headers, student)) for student in grades[1:]]

print(*(grade for grade in grades_list if grade['Student']=='Rabbit'))
# Output {'Student': 'Rabbit', 'Exam 1': '59', 'Exam 2': '61', 'Exam 3': '67'}


All finite groups that have exactly 3 conjugacy classes .

Question: This question was asked in my abstract algebra quiz .

Determine all finite groups which have exactly 3 conjugacy classes .

I solved that $\mathbb{Z}/3$ is only group with conjugacy class 3.
While checking my argument by google search here :https://www.cefns.nau.edu/~falk/old_classes/511/extras/threeclass.html
I found that $S_{3}$ also has 3 conjugacy classes . But I have a question in the argument of the link .

Question :How does in the explanation given in the link author wrote :"m divides 1 + n and n divides 1 + m" in the 3rd line of the argument . I know the result"since the size of a conjugacy class equals the index of the centralizer of one of its elements)" which is given before the deduction but I dont know how to use it to deduce the result.

Can anyone please tell how   to deduce the result ?
Comment: For the quiz question, see the solution [here](https://math.stackexchange.com/questions/52350/finite-groups-with-exactly-n-conjugacy-classes-n-2-3).
Answer: $|G|-m=1+n$. Since $m$ divides the order of the group and itself, it has to divide $1+n$. The same works for $n$.
Answer: according to class equation
$|G| = |C(x_1)| + |C(x_2)| + |C(x_3)|$
according to counting formula
$|G| = |Z(x_1)||C(x_1)| = |Z(x_2)||C(x_2)| = |Z(x_3)||C(x_3)|$
we have $1 = \frac{1}{|Z(x_1)|} + \frac{1}{|Z(x_2)|} + \frac{1}{|Z(x_3)|}$
case 1
let $|Z(x_1)| = 2, |Z(x_2)| = 3, |Z(x_3)| = 6$
accordingly, $|C(x_1)| = 3, |C(x_2)| = 2, |C(x_3)| = 1$
$G \cong S_3$
case 2
$|Z(x_1)| = |Z(x_2)| = |Z(x_3)| = 3$
accordingly, $|C(x_1)| = |C(x_2)| = |C(x_3)| = 1$
$G \cong C_3$
case 3
let $|Z(x_1)| = 2, |Z(x_2)| = |Z(x_3)| = 4$
accordingly, $|C(x_1)| = 2, |C(x_2)| = |C(x_3)| = 1$
$G \cong C_2 × C_2 \cong V$ (Klein four-group)
if the number of conjugacy classes is smaller than 3, it can be analyzed the same way


Joomla 3.x - how do I have students (we register them) access one area, and public (self registration) another area?

Question: Apologies for what is I suspect an easy question for many - I am very new to Joomla.  I am building a website for my wife on Joomla 3.x (Noteworthymusictuition.co.uk).  I already have an area for her music students, in which they log in and can access teaching material not available to the public.  We register them.
I want to create an area of 'free downloads' for members of the public to self-register and automatically go to an area for them to download material.  They need to be able to log in again after registration.  To build up a newsletter group, I want to capture the registrations and store them for subsequent emails.
I do struggle to understand the ACL in Joomla, but if I try and set up a registration form for the public to use, I have to enable self registration in the admin and that affects the existing student login.
I hope that's enough detail!  I was wondering whether I need an extension to enable multiple levels, such as Access Manager Pro?  But on the other hand, what I'm asking for doesn't really sound like rocket science!
Many thanks!
By the way, I have never done any programming in Joomla - apart from occasional HTML editing.
Anthony
Comment: you can make a special category group for students and for those specific page when any body enter there you can check the special group.
Answer: If you choose the 'self' registration option that doesn't stop you creating users as you do now. As long as you set the user up correctly they should be able to log in without issue.
New users would have the option to create an account and would be activated via a confirmation email.
You need to create at least one new user group though. For example, a 'download' group which has access to the additional material. Then, if you use a decent component (http://www.joomlatools.com/extensions/docman/ - see access control new tab) you will be able to control access to documents and downloads by specifying which groups are able to see download links etc.
Hope that helps a bit!


ledger-cli journal automated resetting virtual account

Question: i'm using ledger-cli (http://www.ledger-cli.org).
i wanna reset my virtual account balance automated like what mention in documentation section 5.10.3 Resetting a balance.
i tried like :
= /Income:Salary/
   (Asset:Budget:Utility)    = $ 1000

But get an error
Error: Unexpected char '=' (Note: inline math requires parentheses)

Can somebody explain how should i get this done automaticly...
Answer: The error is due to the first "=", not the second.
You should have the following:
Income:Salary
   (Asset:Budget:Utility)    = $ 1000


How to minimalize multiple Audio Codes

Question: I am trying to minimalize my code for more than one audio. This looks just awful. How can I minimalize those many codes into one good legible code.
public class Sound {
    public static int playerSound (char[][] gameBoard) {
        try (AudioInputStream inStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream("Spieler x.wav")) ){
            Clip clip = AudioSystem.getClip();
            clip.open(inStream);
            clip.start();
        } catch (LineUnavailableException lue) {
            System.out.println("Spieler x.wav" + lue.getMessage());
            lue.printStackTrace();
        } catch (UnsupportedAudioFileException uafe) {
            System.out.println("Spieler x.wav" + uafe.getMessage());
            uafe.printStackTrace();
        } catch (IOException ioe) {
            System.out.println("Spieler x.wav" + ioe.getMessage());
            ioe.printStackTrace();
        }
        return 0;
    }
    public static int computerSound (char[][] gameBoard) {
        try (AudioInputStream inStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream("Bot.wav")) ){
            Clip clip = AudioSystem.getClip();
            clip.open(inStream);
            clip.start();
        } catch (LineUnavailableException lue) {
            System.out.println("Bot.wav" + lue.getMessage());
            lue.printStackTrace();
        } catch (UnsupportedAudioFileException uafe) {
            System.out.println("Bot.wav" + uafe.getMessage());
            uafe.printStackTrace();
        } catch (IOException ioe) {
            System.out.println("Bot.wav" + ioe.getMessage());
            ioe.printStackTrace();
        }
        return 0;
    }

Answer: First, combine your exceptions:
try (AudioInputStream inStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream("Spieler x.wav")) ){
    Clip clip = AudioSystem.getClip();
    clip.open(inStream);
    clip.start();
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
    System.out.println("Spieler x.wav " + e);
    e.printStackTrace();
}

Second, move the code which is identical in both methods into a separate private method:
private static void play(String resourcePath) {
    try (AudioInputStream inStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(resourcePath)) ){
        Clip clip = AudioSystem.getClip();
        clip.open(inStream);
        clip.start();
    } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
        System.out.println(resourcePath + ": " + e);
        e.printStackTrace();
    }
}

public static int playerSound(char[][] gameBoard) {
    play("Spieler x.wav");
    return 0;
}

public static int computerSound(char[][] gameBoard) {
    play("Bot.wav");
    return 0;
}

Third, since you always return the same value (zero), there is no point in having a return value at all:
public static void playerSound(char[][] gameBoard) {
    play("Spieler x.wav");
}

public static void computerSound(char[][] gameBoard) {
    play("Bot.wav");
}

You never make use of gameBoard, so that argument can be removed from the methods:
public static void playerSound() {
    play("Spieler x.wav");
}

public static void computerSound() {
    play("Bot.wav");
}

As a side note, you probably should not autoclose the AudioInputStream before the Clip has finished playing, since the Clip may still be reading from it:
private static void play(String resourcePath) {
    try {
        AudioInputStream inStream = AudioSystem.getAudioInputStream(
            Sound.class.getResourceAsStream(resourcePath));

        Clip clip = AudioSystem.getClip();
        clip.addLineListener(e -> {
            if (e.getType().equals(LineEvent.Type.STOP)) {
                clip.close();
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        clip.open(inStream);
        clip.start();
    } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
        System.out.println(resourcePath + ": " + e);
        e.printStackTrace();
    }
}

Comment: Mostly a very helpful answer, but if a given `Clip` is being played more than once, repeatedly loading the data from the file for each playback is very wasteful. A `Clip` will not even begin to play until the redundant open operation has completed, potentially adding latency. You should either make your `Clips`  instance variables and only open them once, or use `SourceDataLine` for playback instead of `Clip` (for longer audio files).

How to minimalize multiple Audio Codes


Emacs org-mode: how to determine, that the current node was clocked in

Question: Suppose, we have an org file like this:
* TODO Write function x

I want to clock the time working on it. There are 2 functions in org mode:

org-clock-in
org-clock-out

I decided to combine them in this manner:
(defun org-set-clock ()
  "Clock current node in/out"
  (if (<current node is not clocked in>))
    (org-clock-in)
    (org-clock-out)
  )

And attach this function to a simple shortcut:
(add-hook 'dired-mode-hook
          (lambda ()
            (define-key dired-mode-map (kbd "M-q") 'org-set-clock)))

How to write this code: <current node is not clocked in>?
Answer: Below you can find an updated solution.
(defun org-set-clock ()
  "One-off function for `org-mode' task clocking.

Behaviour:
* When there is no running clock, start
  the clock for the item at point.
* When there is already a running clock and
  `point' is at the item which is being clocked
  stop the corresponding clock.
* When there is already a running clock but `point'
  is not at the item which is being clocked,
  stop the clock and restart it for item at `point'."
  (interactive)
  (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
               (org-clocking-p))))
    (if interrupting
    (if (save-excursion
          (org-back-to-heading t)
          (and (equal (marker-buffer org-clock-hd-marker)
              (current-buffer))
           (= (marker-position org-clock-hd-marker)
              (point))
           (equal org-clock-current-task (nth 4 (org-heading-components)))))
        (org-clock-out)
      (org-clock-in))
      (org-clock-in))))

Edit: If you are unable to update org-mode to a sufficiently recent version, you can use
(defun org-set-clock ()
  "One-off function for `org-mode' task clocking.

    Behaviour:
    * When there is no running clock, start
      the clock for the item at point.
    * When there is already a running clock and
      `point' is at the item which is being clocked
      stop the corresponding clock.
    * When there is already a running clock but `point'
      is not at the item which is being clocked,
      stop the clock and restart it for item at `point'."
  (interactive)
  (if (org-clocking-p)
      (if (save-excursion
        (org-back-to-heading t)
        (and (equal (marker-buffer org-clock-hd-marker)
            (current-buffer))
         (= (marker-position org-clock-hd-marker)
            (point))
         (equal org-clock-current-task (nth 4 (org-heading-components)))))
      (org-clock-out)
    (org-clock-in))
    (org-clock-in)))

however, I'd recommend using the org-mode elpa which'll keep you always up to date.
Comment: @user4035 I'm using the most recent `org-mode` with version `8.2.8`. Okay, so assume you are already clocking some task. Now you go to some `org-mode` buffer and move the curser (`point`) on some other task and execute the function. It will not check, whether the cursor is over the task which is currently being clocked. It will stop **any** running task. If there is no running task, it will start clocking the one, the cursor is over.
Comment: Seems, that `org-clock-resolving-clocks-due-to-idleness` is undefined in my org-mode. I'll try to update it. I didn't understand your question. Can you explain it in more details?
Comment: It would be better, if it checked, whether the current task is clocked.
Comment: So what should it do if a task is being clocked but the cursor is on a different task?
Comment: It should do clock-in for the new task
Comment: @user4035 Updated the code, could you check that it behaves as desired?
Comment: Thanks, I tried it on Windows machine with org-mode 7.9.3f. But `org-clock-resolving-clocks-due-to-idleness` is undefined. Is it possible to do without it or I'll need to upgrade?


Append in Python Game

Question: number_of_enemies = 5
enemies = []
for i in range(number_of_enemies):
    enemies.append(turtle.Turtle())
for enemy in enemies:
    enemy.shape(enemys)
    enemy.penup()
    enemy.speed(0)
    enemy.setposition(random.randint(-245, 245), random.randint(-245, 245))

I want to call on each enemy separately, but I don't know how to call them
Answer: What exactly do you mean with "to call"?
enemies[0] To get the first enemy

Append in Python Game


Is there a way in Powershell to append or prepend the value of a variable to the output of a piplined command

Question: I have the one-liner:
Get-ADPrincipalGroupMembership $username | select name | where {$_.name -like 'HI_*'}

and I would like to add the value of $username to every row of the output, and get the output in CSV format using ConvertTo-CSV (or similar).
e.g., output would look like this:
HI_Users,JBloggs
HI_Supervisors,JBloggs
HI_Admins,JBloggs
This is needed for downstream processing on another system.
Comment: So why don't you extend your command with ```| foreach-object { … } | export-csv ...``` I'd also change the sequence of select and where...
Answer: Use a calculated property where you would include your variable.
Get-ADPrincipalGroupMembership $username |
    where-object{$_.name -like 'HI_*'} |
    select @{label="username";Expression={$username}},name

No need to do anything fancy with that either for CSV output. Just pipe to Export-CSV