Can getString() method of ResultSet can be used for getting the value of a TEXT type column from a MySQL table?

Question: I am trying to retrieve the value of a TEXT field from a table in a MySQL database.
MySQL version is 5.6.21
& I am using mysql-connector-java-5.1.18-bin.jar
My file is given below
import java.sql.*;

public class DatabaseConnection {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/book";

    // database credentials
    static final String USER = "username";
    static final String PASS = "password";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {

            Class.forName("com.mysql.jdbc.Driver");

            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String query;
            query = "Select b_name, description columns from brands";
            ResultSet rs = stmt.executeQuery(query);

            while(rs.next()) {

                String first_name = rs.getString("b_name");
                String description = rs.getString("description");

                System.out.println(first_name);
                System.out.println(description);
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch(SQLException se) {
            se.printStackTrace();
        } catch(ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        }
        finally{
            //finally block used to close resources
            try{
                if(stmt!=null)
                    stmt.close();
            } catch(SQLException se2){
            }// nothing we can do
            try{
                if(conn!=null)
                    conn.close();
            } catch(SQLException se){
                se.printStackTrace();
            }//end finally try
        }//end try
        System.out.println("Goodbye!");
    }
}

This says that my column does not exist although I have tried this on another table, it works on VARCHAR columns but not on TEXT columns
This error shows up:
But the table has a column named description:
Comment: Note that MySQL Connector/J 5.1.18 is pretty old (6 years), the latest is 5.1.42. You might want to consider upgrading, see https://dev.mysql.com/downloads/connector/j/
Answer: The problem is NOT about the column type being text.
You can get the value of a TEXT type using getString.
You can verify in the documentation.
The problem is in the query:

query = "Select b_name, description columns from brands";

"columns" there is a mistake.
Written this way, the description column is in fact renamed to columns in your result set.
If you did rs.getString("columns") you would get the value.
But that's not what you want to do. You want to fix the query by dropping that word:
query = "Select b_name, description from brands";


The $L^2$ norm of a function bounded by $L^2$ norm of its weak derivative in unit ball

Question: Fix $\alpha>0$ and let $U=B_1(0)$. Show that if $u\in H^1(U)$ and $|\{x\in U:u(x)=0\}|\ge \alpha$, then there exists a constant $C=C(n, \alpha)>0$, such that $$\int_U u^2dx \le C\int_U {|Du|}^2dx.$$

I tried to prove by contradiction. Suppose there exists a sequence $u_n \in H^1(U)$ with $|\{x \in U: u^n(x)=0\}|\ge \alpha$ such that $\int_U u_n^2dx \ge n\int_U {|Du_n|}^2dx$. However I was stuck here to obtain a contradiction.
Answer: Suppose there is a sequence $u_n$ such that $\int_U u_n^2dx \ge n\int_U {|Du_n|}^2dx$. Normalize it so that $\int_U u_n^2dx =1$. Then $\int_U {|Du_n|}^2dx \to 0$. Since the sequence $\{u_n\}$ is bounded in $H^1(U)$, it has a weakly convergent subsequence, which is again denoted $\{u_n\}$. Let $u$ be its limit. The Dirichlet functional $\int_U {|Du|}^2dx$ is convex and therefore lower semicontinuous under weak convergence. This implies
$$
\int_U {|Du|}^2dx  \le \liminf_{n\to\infty} \int_U {|Du_n|}^2dx = 0
\tag1$$
hence $u$ is constant.
Weak convergence in $H^1(U)$ implies strong convergence in $L^2(U)$, hence $u_n\to u$ in $L^2(U)$. But this is impossible. Indeed, if $u\equiv c$ with $c\ne 0$, then for every $n$ we have
$$
\int_U |u-u_n|^2 \ge c^2 |\{x\in U:u_n(x)=0\}| \ge c^2\alpha
$$
And if $c=0$, then
$$
\int_U |u-u_n|^2 = \int_U u_n^2 = 1
$$
by the normalization.
Answer: It is also possible to reduce the problem to the better-known version of Poincare's inequality
$$ \int_U |u - \bar{u}|^2 \le C(U)^2 \int_U |\nabla u|^2, $$
where $\bar{u}$ is the average of $u$ over $U$. This way we can obtain a constant that depends on $\alpha$ explicitly.
Let $Z = \{ u = 0 \}$ be the zero set. Using Holder's inequality on $U \setminus Z$, we get
\begin{align*}
\int_U \bar{u}^2
& = |U| \cdot \bar{u}^2 \\
& = \frac{1}{|U|} \left( \int_{U \setminus Z} u \right)^2 \\
& \le \frac{|U \setminus Z|}{|U|} \int_{U \setminus Z} u^2.
\end{align*}
It is important that the coefficient above is strictly smaller than $1$, since this enables us to estimate
$$ \| u \|_{L^2} \le \| u-\bar{u} \|_{L^2} + \| \bar{u} \|_{L^2} \le \| u-\bar{u} \|_{L^2} + \sqrt{1 - \frac{\alpha}{|U|}} \| u \|_{L^2}, $$
$$ \left( 1 - \sqrt{1 - \frac{\alpha}{|U|}} \right) \| u \|_{L^2} \le \| u-\bar{u} \|_{L^2} \le C(U) \| \nabla u \|_{L^2} $$


How to understand CPU allocation in Mesos?

Question: I am reading Building Applications on Mesos, and come across the following statements:

cpus
      This resource expresses how many CPU cores are available. Tasks may use fractional parts of a CPU—this is possible because Mesos slaves use CPU shares,
  rather than reserving specific CPUs. This means that, if you have 1.5  cpus
  reserved, your processes will be allowed to use a total of 1.5 seconds of CPU time each second. That could mean that, within a single executor, two processes each get 750 milliseconds of CPU time per second, or one process gets 1 second of
  CPU time and another gets 500 milliseconds of CPU time each in a given second.
  The benefit of using CPU shares is that if some task would be able to utilize more than its share, and no other task would use an otherwise idle CPU, the first task can potentially use more than its share. As a result, the  cpus reserved provides a guaranteed minimum of CPU time available to the task—if additional capacity is available, it will be allowed to use more.

I can't understand "if you have 1.5 cpus reserved, your processes will be allowed to use a total of 1.5 seconds of CPU time each second.". How can it use 1.5 seconds of CPU time each second?
Answer: cpu=1.5 should stand for one and half CPU core. You can see in Mesos Web UI how many cores each Mesos agent (slave) offers. That's pretty much what nproc shows unless mesos-slave is configured to offer less CPUs. Mesos counts resources with 3 decimal places precision.
There are several flags that influence the way how Mesos limits resources. For CPU is most important isolation (we're talking about mesos-slave/mesos-agent settings):

--isolation=posix/cpu,posix/mem None CPU limiting is applied mesos-executor is just a process that runs other process. You can use nice, e.g. nice -20 (for highest priority) or cpulimit commands to influence kernel planning, but Mesos's e.g. cpu=0.1 won't be taken into consideration.
--isolation=cgroups/cpu,cgroups/mem cgroups (part of Linux Kernel since 2.6.29) allows limiting resources used by each process or group of processes. Some distributions does not enable memory limiting by default and cgroup_enable=memory need to be passed to the kernel. But let's focus on CPU. By default cgroups takes conservative approach where cpu=1.0 means that at least one CPU core will be reserved for the task. But in case that there is no other task running on the host it can consume all of the CPUs. Assuming that we have a host with 12 CPUs and there are two tasks running with cpu=2.0. Then each task might get up to 6 CPUs cores! (assuming no other Mesos task is running on that host). This is very dangerous, when cluster is at low load all tasks will look fine, but once there are many tasks performance of some hosts will decrease.

--cgroups_enable_cfs CFS stands for Completely Fair Scheduler which takes more strict approach. By default it is turned off, also not all distributions support this (you can use e.g. Docker's check-script.sh to verify support on your system). CFS will guarantee that each process can use at most the portion specified (e.g. cpu=2.5). This comes at a cost that no other process can utilize reserved cores when some task is idle. So, make sure you'll define your requirement well.

Last mentioned issue could be solved by CPU oversubscription that is described in the Mesos documentation.
Answer: By utilizing more than one cpu/core :-).
Note that the actual behavior/enforcement of these limits will highly depend on the actual containerizer/isolator used.
Unfortunately I could not find any good/recent documentation (but I know that there are people working on improving this :-) ), but you could have a look at this blog post:
Blog Post about CPU resources
Update
There is als hard cap on the CPU utilization: See the
 --[no]-cgroups_enable_cfs configuration parameter
or this Jira.


how to hide android softkeys

Question: In my android app I hide soft keys bar using this:
View decorView = getWindow().getDecorView();

int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                  | View.SYSTEM_UI_FLAG_FULLSCREEN
                  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

decorView.setSystemUiVisibility(uiOptions);

But the problem is when some message box or toast display then softkeys display again.
I want to hide soft keys when any message box or toast displaying.
Is it possible.. how can i do this.
Comment: In which lifecycle method do you implement this ? onCreate() i assume
Comment: yes. onCreate()
Comment: You could wrap this up in a method and call the method every time you want to hide soft keys.
Comment: The way I code isn't match with display and hide. Is there any way to do this..
Answer: Messages like dialogs, intent chooser, soft keyboard and toasts use a different Window than your main application window.
These extra Windows can change your SystemUiVisibility and Window flags as they appear and disappear.
What I found to work in most cases is to setup your flags in onWindowFocusChanged in the Activity class:
public void onWindowFocusChanged(boolean hasFocus) {
    if(hasFocus) {
        View decorView = getWindow().getDecorView();

        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

        decorView.setSystemUiVisibility(uiOptions);
    }
}

You then no longer need this code in onCreate, as window focus is also gained at activity creation.
Comment: your solution is perfect. but the problem is  I used this on video recording then displaying and hiding soft keys effect to the recorded video.
Comment: Working with these flags is always be a bit tricky. If it doesn't work as expected its usually because of window changes (the MediaController for videoview is also in a separate window). I'm not sure about your current troubles, but I would make a `setFullscreen(boolean)` method that sets the correct flags, then try calling that in all thinkable, possibly correct, places.

how to hide android softkeys


error: expected identifier or '(' before ')' token after changing a macro

Question: In a C program (u-boot), to check if the program runs that macro, I changed a define state
from
#define debug_cond(cond, fmt, args...)                  \
({                                  \
    if (cond)                           \
        log(LOG_CATEGORY,                   \
            (enum log_level_t)(LOGL_FORCE_DEBUG | _LOG_DEBUG),  \
            fmt, ##args);                   \
})

to
#define debug_cond(cond, fmt, args...)                  \
({                                  \
extern uint64_t myptr;              \
    if (cond) {                         \
        *((uint64_t *)myptr) = 0x801; myptr+=8; \
        log(LOG_CATEGORY,                   \
            (enum log_level_t)(LOGL_FORCE_DEBUG | _LOG_DEBUG),  \
            fmt, ##args);                   \
    }
})                 <==== line 267

and the compiles gives me this error message.
In file included from include/linux/printk.h:4,
                 from include/common.h:20,
                 from lib/asm-offsets.c:14:
include/log.h:267:1: error: expected identifier or '(' before '}' token
  267 | })
      | ^
include/log.h:267:2: error: expected identifier or '(' before ')' token
  267 | })

I can't figure out what is wrong here. Can anyone tell me where I'm doing wrong?
Comment: Have you checked that you have the *line-continuation* escape on all lines in the macro?
Comment: ah yes, line 266 had no `line continuation` at then end. Write a simple answer so that I can select it.
Answer: You have a space after the ending \ in the 5-th macro line. Delete the trailing space:
#define debug_cond(cond, fmt, args...)                  \
({                                  \
extern uint64_t myptr;              \
    if (cond) {                         \
        *((uint64_t *)myptr) = 0x801; myptr+=8; \
        log(LOG_CATEGORY,                   \
            (enum log_level_t)(LOGL_FORCE_DEBUG | _LOG_DEBUG),  \
            fmt, ##args);                   \
    }
})

The space breaks the macro definition in half and the second half is being interpreted by the compiler leading to a syntax error.
Turning on the "Show whitespace characters" option of your editor might be quite helpful in the long run.


$K\subset L$ is finite implies $\mathcal O_K/ \mathfrak{m}_K \subset \mathcal O_L/\mathfrak{m}_L$ is finite

Question: Given complete discrete valuation fields $K$ and $L$, finite extension $K\subset L$, corresponding d.v.r. $\mathcal O_K$ and $\mathcal O_L$ with maximal ideals $\mathfrak{m}_K$ and $\mathfrak{m}_L$ is it true that $\mathcal O_K/ \mathfrak{m}_K \subset \mathcal O_L/\mathfrak{m}_L$ is a finite field extension. I can see that one is subset of another, but why should this extension be finite?
Thank you.
Answer: You can show the following statement from which the result follows

If $\alpha_1,\dots,\alpha_n\in\mathcal O_L^\times$ are elements such that $\bar\alpha_1,\dots,\bar\alpha_n\in\mathcal O_L/\mathfrak m_L$ are linearly independent over $\mathcal O_K/\mathfrak m_K$, then $\alpha_1,\dots,\alpha_n$ are linearly independent over $K$.

Do this as follows:

Suppose $\bar\alpha_1,\dots,\bar\alpha_n$ are linearly independent over $\mathcal O_K/\mathfrak m_K$, and suppose you have an equation $c_1\alpha_1+\cdots+c_n\alpha_n=0$ in $L$ with $c_i\in K$.

Scale by the $c_i$ with largest absolute value so that, without loss of generality, you can assume some $c_i$ has absolute value $1$ and the rest $\le1$.

Consider the equation modulo $\mathfrak m_L$ and derive a contradiction.
Comment: Thanks, that is very nice. Another question: if I know that $\mathcal O_L\cong\bigoplus\limits_{i=1}^{[L:K]} \mathcal O_K $ is there a more straightforward argument? Seems like finiteness of extension must follow immediately from this fact, however I am not sure.
Comment: Oh yeah if you take a uniformizer $\pi$ for $K$, the equality of $\mathcal O_K$-modules you've given implies the isomorphism $L=\mathcal O_L[1/\pi]\simeq\oplus_{i=1}^{[L:K]}\mathcal O_K[1/\pi]=\oplus_{i=1}^{[L:K]}K$ of $K$-modules


brokerURL syntax not clear to me

Question: Can some one help me to understand this syntax on this ActiveMQConnectionFactory bean ? What are the 3 options for? what is the logic?

DU_MESSAGING_SERVER_URL (system param on our system)
MESSAGING_SERVER_URL    (system param on our system)
tcp://localhost:61917

<property name="brokerURL" value="${DU_MESSAGING_SERVER_URL:${MESSAGING_SERVER_URL:tcp://localhost:61917}}"/>

Answer: This syntax using ${} is for loading system or environmental properties into a configuration file.
This is useful in situations where you might not want to modify the configuration file but rather just set a system property (e.g. moving between a test environment and prod). You just put the name of the system property in the configuration file and the value of that property will be substituted when the configuration is loaded. For example, you could use ${foo} in your config file and then define this system property -Dfoo=bar and then the value bar would be used in your config file.
The : character defines a default value if the system property is not set. For example, you could use ${foo:defaultFoo} in your config file and then if the foo system property was not defined then the value defaultFoo would be used in your config file.
In your situation these ideads are being nested together. So if you use ${DU_MESSAGING_SERVER_URL:${MESSAGING_SERVER_URL:tcp://localhost:61917}} then the value of the DU_MESSAGING_SERVER_URL system property will be used in the configuration. If DU_MESSAGING_SERVER_URL is not defined then ${MESSAGING_SERVER_URL:tcp://localhost:61917} will be evaluated which will use the value of the MESSAGING_SERVER_URL system property in the configuration. If MESSAGING_SERVER_URL is not defined then tcp://localhost:61917 will be used.

brokerURL syntax not clear to me


cookies not deleted in javascript

Question: I have three cookies compare1,compare2 and compare3. After the user clicks on the close button i want to delete the cookie and then get the cookies which are set either compare2 or compare3 or compare1. I am using javascript for the same, but my cookies are not deleted. Here is my code:
<code>  $('#srchresult #frmCompare a.close').click( function() {
   var parentName = $(this).parent().attr('id');
   var parentId=  parentName.replace('dvPkg','');
   document.cookie = 'compare'+parentId + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        alert(document.cookie);
        var username1=getCookie("compare1");
        var username2=getCookie("compare2");
        var username3=getCookie("compare3");

        if (username1!=null && username1!="")
  {
  alert(username1);
  }
   if (username2!=null && username2!="")
  {
  alert(username2);
  }
   if (username3!=null && username3!="")
  {
  alert(username3);
  }
});
</code>
Inspite of deleting the cookie, I am still getting the cookies in the alert. I want to delete the cookies without refreshing the page and get the remaining two cookies.
I am not setting the domain or path when creating the cookie. I want to delete the cookie without refreshing the page. I am creating the cookie using php
<code>  $cookie = array( 'name' => 'compare' . $noOfItem, 'value' => $noOfItem . '^' . $postId . '^' . $postType . '^' . $return_result['deal_title'] . '^' . $return_result['img_filename'] . '^' . $postcompareCountry, 'expire' => '0', );

$this->input->set_cookie($cookie);
</code>
Comment: How are the cookies created? Do they have a domain or path specified? If so you need to specify the same domain and path when deleting.
Comment: Creation of cookie depends upon your path and domain so as deletion .Thus kindly tell us how you are creating cookie..
Comment: I am not setting the domain or path when creating the cookie. I want to delete the cookie without refreshing the page. I am creating the cookie using php  $cookie = array(
                'name' => 'compare' . $noOfItem,
                'value' => $noOfItem . '^' . $postId . '^' . $postType . '^' . $return_result['deal_title'] . '^' . $return_result['img_filename'] . '^' . $postcompareCountry,
                'expire' => '0',
            );

            $this->input->set_cookie($cookie);
Comment: Please Edit your question and put above thing there ...if you are not setting the path then cookie created will be accessible only in the scope of that page only .
Comment: getCookie is not js function,
Comment: https://github.com/carhartl/jquery-cookie
Answer: You need to add a 'path' to your cookie. For example:
<code>document.cookie = 'cookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';
</code>
The path represents the relative path in your website which the cookie will be readable. path=/ means it'll be readable in your whole website. path=/common/ means it'll be readable only in /common/ folder (and its subfolders)
Here is nice tutorial on MDN about cookies:-
UPDATE :-
While Creating Cookie try to add path also :-
<code> $cookie = array( 'name' => 'compare' . $noOfItem, 'value' => $noOfItem . '^' . $postId . '^' . $postType . '^' . $return_result['deal_title'] . '^' . $return_result['img_filename'] . '^' . $postcompareCountry, 'expire' => '0','path' => '/' );
</code>
you can check out this also :-
Comment: I tried your reply but my cookie is deleted only on page refresh. I don't want to refresh the page.
Comment: Can you show me your set_cookie($cookie) function ...May be then i can help
Comment: I have already added it in my question above. I am setting the cookie via php

cookies not deleted in javascript


10 Values to run on same SQL query

Question: I got 10 values in my array and I am currently looping my query for each array. Is there a way to put it in one statement without looping?
SELECT
    a.OrderSuffix AS 'OrderSuffix',
    COUNT(1) AS 'CountNew'
FROM
    dbo.Orders AS a,
    dbo.OrderStatus AS b
WHERE
    b.Status = 'Finished' AND
    a.OrderSuffix = array

Comment: Yes, an IN clause or TVP for example, the best/easiest way depends on what you are calling the SQL from - which you need to add to your question.
Comment: You mean something like `a.OrderSuffix in ('A','B','C')`?
Comment: Thank you for your answers. I was able to get it.
Comment: Let's say I want to put in a date, too, per value of the array. I wanna count all new data based on a variable date. Should I put IN as well?
Comment: Without knowing the details it's basically a guess... but yes, you can put dates in `in` clause too, and they can also be variables, like `in (@date1, @date2, @date3)`
Answer: SELECT
    a.OrderSuffix AS 'OrderSuffix',
    COUNT(1) AS 'CountNew'
FROM
    dbo.Orders AS a,
    dbo.OrderStatus AS b
WHERE
    b.Status = 'Finished' AND
    a.OrderSuffix IN ('ABC', 'DEF', 'HIJ')
GROUP BY
    a.OrderSuffix

10 Values to run on same SQL query


$\mathbb{Q}_p$ contains a square root of $4p+1$, but not of $4p$.

Question: Let $p$ be a prime, let $\mathbb{Q}_p$ be the field of $p$-adic numbers. I want to show that it contains a square root of $4p+1$, but does not contain a square root of $4p$.
I could only manage the case for $4p+1$. First of all, assume that $p\neq 2$, we know that a necessary and sufficient condition for $4p+1$ to have a square root is the existence of $a\in \mathbb{Q}_p$, such that
$$
|4p+1-a^2|_p<1.
$$
Taking $a=1$, we get
$$
|4p|_p=\frac{1}{p}.
$$
Now, if $p=2$, we want $a$ to satisfy
$$
|4p+1-a^2|_p<\frac{1}{4},
$$
but here the same $a=1$ will do, since
$$
|8|_2=\frac{1}{8}<\frac{1}{4}.
$$
For $4p$, again assume $p
\neq 2$ first, we need to show that for any $a\in \mathbb{Q}_p$ we have
$$
|4p-a^2|_p\geq1.
$$
Using the reverse triangle inequality,
$$
|4p-a^2|_p\geq |4p|_p-|a^2|_p=\frac{1}{p}-|a^2|_p,
$$
and so, it follows that $|4p-a^2|_p\geq \frac{1}{p}$, so it does not help that much. How do I prove this?
Answer: Hint: Because $\Bbb{Q}_p$ always contains $\sqrt4$ you really only need to worry about the (non)-existence of $\sqrt p$. But if $a^2=p$, then $|a|_p^2=|p|_p=1/p$.

You're doing fine with $\sqrt{4p+1}$.


Safely get nested list index from json?

Question: I know how to safely get keys from json using .get()
data = {"person": {"name": "chris", "age": 11, "interests": []}}

data.get("person", {}).get("height") would just return None
But what if I wanted to do the same with a list?
data.get("person", {}).get("interests", []).get([3], {}).get("someotherdata")
How do I assume the list index exists and carry on safely if it doesn't?
Obviously I could just try getting the list and checking its length before trying to get the index, but is there not a cleaner way?
Chris
Comment: `.get()` only works with dictionaries. I don't think there's anything equivalent for lists.
Comment: You can easily write a `list_get()` function that does what you want.
Comment: I don't agree with the dupe because its not applicable to method chaining
Answer: You can use match-case:
data = {"person": {"name": "chris", "age": 11, "interests": []}}
match data:
   case {"person": {"interests": [_, _, _, val, *_]}}:
      print(val)
   case _: #default case, only executes no match is made
      pass

Here, the case block attempts to match a nested dictionary containing the keys "person" and "interests", and then provides a match if the "interests" key has a corresponding list with an index of three.
In the example above, nothing will be printed, since the list value for "interests" is empty. However, if "interests" has an index of 3, 4 will be printed:
data = {"person": {"name": "chris", "age": 11, "interests": [1, 2, 3, 4]}}
match data:
  case {"person": {"interests": [_, _, _, val, *_]}}:
     print(val)
  case _:
     pass

Output:
4

Edit: purely inline solution:
r = v[3] if len(v:=data.get('person', {}).get('interests', [])) > 3 else {}

Comment: excellent answer! maybe provide a default case for the match statement, to emulate `get`.
Comment: @timgeb Thank you, good suggestion, please see my recent edit.
Comment: That is a good answer but not what I was after. I was after something more "inline" and simpler than getting the list, checking if its valid, then getting the index.
Comment: @Chris Please see my recent edit, I added an inline solution which will produce either the third element of the list if available, and an empty dictionary if it is not.

Safely get nested list index from json?


Let $A\in M_n(\mathbb{Q})$ with $A^k=I_n$. If $j$ is a positive integer with $\gcd(j,k)=1$, show that $ \operatorname{tr}(A)= \operatorname{tr}(A^j)$.

Question:
Let $A\in M_n(\mathbb{Q})$ with $A^k=I_n$. If $j$ is a positive
     integer with $\gcd(j,k)=1$, show that $ \operatorname{tr}(A)=
   \operatorname{tr}(A^j)$.

I don't know how to start to prove that. I tried to find the matrix $B$ similar with $A$, but I am stuck...
Thank you.
Answer: Note that eigenvalues $\lambda_i, i=1,\ldots, n$ of $A$ are roots of the rational polynomial
$$
p(t) = \det(tI-A)=\prod_{i=1}^n (t-\lambda_i).
$$ Since $Ax=\lambda_i x$ implies $A^kx = x = \lambda_i^k x$, we have $\{\lambda_i\}\subset \mu_k =\{\zeta\in\mathbb{C}\;|\;\zeta^k=1\}$. Let $\omega$ be the $k$-th primitive root of unity. Since $(j,k)=1$, we can define $\sigma\in \text{Aut}(\mathbb{Q}(\mu_k)/\mathbb{Q})$ by letting
$$
\sigma(\omega)= \omega^j.
$$ Then, it holds
$$
p(t) = \sigma(p(t)) = \sigma\left[\prod_{i=1}^n (t-\lambda_i)\right]=\prod_{i=1}^n (t-\sigma(\lambda_i))=\prod_{i=1}^n (t-\lambda_i^j).
$$ Now, it follows
$$
\text{tr}(A) = \sum_{i=1}^n \lambda_i =  \sum_{i=1}^n \lambda_i^j = \text{tr}(A^j).
$$
Comment: This is a nice answer that also nicely shows why we do need to do this over $\mathbb{Q}$, since it will fail in suitable extensions.
Comment: I think this answer is wonderful..... I sincerely appreciate you!
Comment: why does an eigenvalue $\lambda_i$ occur with the same algebraic multiplicity as an eigenvalue $\lambda_i^j$ of $A^j$?
Comment: @M.Van Because $\{\lambda_i\} = \{\lambda_i^j\}$ ..? Equality not as a set, but counted with multiplicity.
Comment: Umm... Could you explain why $\lambda_i \in \mu_k$?.... why $\prod_{i=1}^n \lambda_i^k =1$ implies $\lambda_i  \in \mu_k$??
Comment: @w.sdka This is why: Let $x$ be an eigenvector corresponding to $\lambda_i$. Since $Ax = \lambda_i x$, we get $A^k x = \lambda_i^k x = x$. Since $x\neq 0$, it follows $\lambda_i^k = 1$. I hope this makes it clear.
Comment: Thank you! It's clear.
Comment: @Mr. Van i think multiplicity can be derived by digonalization over $\mathbb{C}$
Answer: We must use the fact that $A\in M_n(\mathbb{Q})$ because the  result is false over $M_n(\mathbb{C})$. Indeed, consider $A=diag(e^{2i\pi/3},i)$ where $k=12$; then $trace(A)\not= trace(A^5)$.
$\textbf{Proposition.}$ When $A\in M_n(\mathbb{Q})$ and $(j,k)=1$, $spectrum(A)=spectrum(A^j)$.
$\textbf{Proof}.$
We may assume that $order(A)=k$ ($k=\min\{l;A^l=I_2\}$) and that $j<k$. Clearly, $order(A^j)=l$. $A$ is diagonalizable over $\mathbb{C}$ and its minimal polynomial divides $x^k-1$.
Therefore, $\chi_A$, the characteristic polynomial of $A$, is a product of (irreducible) cyclotomic polynomials $\phi_a(x)=\Pi_{(u,a)=1}(x-e^{2i\pi u/a})\in\mathbb{Q}[x]$ where $a|k$. Since $(j,a)=1$, it is easy to see that $\phi_a(x)=\Pi_{(u,a)=1}(x-(e^{2i\pi u/a})^j)$ and we are done.  $\square$


2 gang 2 way switch button on and off are reverse

Question: I have a 2 gang 2 way switch for 2 lights (corridor light and bathroom light).
COM1, LA1 and LA2 is for switch 1 (Bulb 1).
COM2, LB1 and LB2 is for switch 2 (Bulb 2).
Remark: Those yellow cable are yellow, so we don't know which is live wire.

When the switches are on. The bulb 2 is on but the bulb 1 is off.

When the switches are off. The bulb 2 is off but the bulb 1 is on.

The button switch 1 (bulb 1) is reverse. How to make it right?
Answer: You have 2-way switches (US: 3-way) but you're only using them as 1-way.   Which is fine.
But for some reason you wired the always-live wires to to Com1 on one side but LB1 on the other.  Weird.  Limits your choice somewhat.
Move LA2 to LA1.   Now, the switches will act together.
If that's upside down of what you want, then rotate the entire switch assembly 180 degrees.


Showing complex numbers being equal without using argument properties

Question: If we are given two lines given by : $z \bar{a}_{1}+\bar{z} a_{1}+b_{1}=0$
$z \bar{a}_{2}+\bar{z} a_{2}+b_{2}=0$ for them to be parallel/perpendicular they must have their real slopes equal or product = -1 . As we know it implies $\frac{-Re(a_1)}{Im(a_1)} = \frac{-Re(a_2)}{Im(a_2)}$ for parallel how does this imply that $\frac{a_1}{-\bar{a}_1}$ = $\frac{a_2}{-\bar{a}_2}$ ? Without going into taking argument of the complex numbers ? By argument i can think of taking two points each on both lines and showing that the real slopes condition being that imples the required condition .
Answer: So, $x+iy$ and $u+iv$ are two complex numbers.  Prove
$$
\frac{-x}{y}=\frac{-u}{v}\quad\Longrightarrow\quad
\frac{x+iy}{-x+iy}= \frac{u+iv}{-u+iv}
$$
This is easy: Assume
$$
\frac{-x}{y}=\frac{-u}{v}\quad\text{so that}\quad\frac{x}{y}=\frac{u}{v}
$$
In particular, $y \ne 0$ and $v \ne 0$.
Then
$$
\frac{x+iy}{-x+iy} = \frac{x/y+i}{-x/y+i} = \frac{u/v+i}{-u/v+i}
=\frac{u+iv}{-u+iv}
$$


Is my plan for running cable 250ft to a subpanel OK?

Question: Im running 2224 aluminum 250ft to a subpanel. I need two 15amp outlets. I plan on using 2224 and a subpanel. Is there a better option. Thank you !
Comment: The only real issue is voltage drop. Which is determined by total simultaneous load. According to [the Southwire Voltage Drop calculator](https://www.southwire.com/calculator-vdrop) you are good on 120V up to 24A before you hit a 3% issue. (Note: 3% is not an absolute rule, just a guide). 24A would actually be enough for **4** fully loaded (80% continuous) 15A receptacles (2 on each leg). TL;DR No problem. But explain the *full* plans - unusual to actually plan on such heavy wire to run a pair of 15A receptacles. As in: Is this likely to expand to additional uses?
Comment: 2224 is the smallest SER I can find locally. It's also pretty reasonable per foot, cheaper than four strands of #6 THWN2, while also being more capable. I can get 4444 but nobody local stocks it, and it's barely cheaper. OP is that your reasoning or is it something else?
Comment: CONDUIT! Make sure you run this in conduit. It'll cost more up front, but it will be far cheaper in the future should you ever need to repair or replace it. Also, conduit is less tasty to burrowing critters than plain cable insulation, so you're less likely to have to replace it due to hungry gophers or other.
Answer: 250 feet is too far to be entirely within a structure or otherwise above ground. SER can't go underground.  If you're undergrounding any of this, you'll need a buryable wire type such as MH feeder (however that has limits on use indoors, which can be cured by putting it inside conduit).
I think going with #2 aluminum is a great plan.
Since you only want 120V out there right now, it would be possible to pinch pennies by only using 3-wire cable.  However if you ever did anything more serious later, you'd regret the short-sightedness.
Since you only need two outlets (and I'm not sure if that means two circuits or not), one option is to skip the subpanel and its grounding rod requirement, and make it a "MWBC" or Multi-Wire Branch Circuit. The problem with this approach is you need to find a way to splice #2 aluminum to #12 copper, since a 20A breaker won't take #2 aluminum, and neither will common receptacles.  The cost of those six splices may be considerably more than the cost of the subpanel and ground rods.
Comment: My local electrical distributor stocks 2246 aluminum mobile home feeder cable, which can be direct buried or run in conduit. It might be a great choice here.
Comment: 2-2-4-6 might not might not be ideal for future-proofing since the undersized neutral may limit loads compared to 2-2-2-4. Although it's still plenty of headroom compared to the initial planned 15A loads.
Answer: Because of the typical pricing of 2-2-2-4 being low, due to volume, and the length of run, and the non-competetitive price of other wire/cable options with adequate capacity for such a long run, that's probably the best choice, yes. Shop around and see what your local prices say, but it's commonly the best price for a long run, even where it's somewhat overkill.
Your sub-panel can be any ampacity equal to or larger than your feed breaker. Your feed breaker could be anything from a two-pole 15A (your stated need at the far end) on up to a two pole 90A (the limit of the wire) and choosing something like 30-50A would allow for possible additional load at little to no extra initial cost over a 15A two pole.
You'll need a set of grounding rods at the sub-panel location. Those connect to the ground of the case of the panel and the incoming ground from the house. The neutral at the sub-panel remains isolated from (not bonded to) ground there. It connects to the neutral from the house.


Filtering and searching with UISearchBar on the iPhone?

Question: For iPhone development, is there any UI/UX pattern I should be following with the UISearchBar to permit both filtering and searching?
My use case is one screen were we display nearby in a UITableView nearby restaurants pulled from Yelp. Above the restaurants we have a search bar. When the user initially displays this screen, we display the nearest 30 or so restaurants from Yelp. Now above the UITableView we have a UISearchBar; entering text into the search bar will filter the 30 or so restaurants displayed (like filtering your Contacts), but if you're in a city with a high density of restaurants, you may be looking for a restaurant that is not on that list. Now I want the search bar to not filter, but actually search, whereby I can use their input as a query parameter in a HTTP request to Yelp in an attempt to retrieve the restaurant that they actually want.
Any patterns or inspiration on the best way to do this? The iPhone HIG says that I can enable a "results list" icon for the search bar that "indicates the presence of search results. When users tap the results list icon, your app can display the results of their most recent search." Does this mean that the Search button the keyboard will really filter, and pressing the results list icon will actually perform a search? Any examples of its usage anywhere?
Right now I'm leaning toward displaying a "Search for a restaurant..." row above the 30 or so restaurants initially displayed. When the user presses that, they go to another screen with a search bar fixed at the top. Whenever they activate the search bar and press the Search button on the keyboard, it issues a new query to Yelp. Note that this basically does away with filtering on both screens (although the latter is implicitly filtered by your query), but at least it's understandable.
Answer: Great question. I do not fully understand the "result list icon" thing. But imo, pressing a button to perform the actual search (call by HTTP) is more natural than changing the contents of the list without user actions. Clearness and control over least-number-of-taps.
Here is some inspiration. I call this pattern Filtering as Typing, Searching by Button, Awesome.
We made an app with a search box and a result list that is well received by all users. I paint three screen dumps in ASCII for you here:
App starts                 User types '2'               User presses (search) btn

[search box empty  ]       [2         (x)] (search)     [2          (x)] (cancel)
- "Recent" header -        - "Recent" header -          - "Search result" header -
Recent post 1              Recent post *2*              *Searching* spinner
Recent post 2
Recent post 3

Consider our Recent header as your Nearby header.
If your user renders the list empty by filtering, she will have easier to understand that she needs to press the Search button if you make that really obvious in that scenario. We did this by placing a big "Continue Search on Server" button when the list is filtered empty. Fool safe, and familiar from searching for emails in the Mail app of the iPhone.
(I am currently trying to find out how to combine suggestions with filtering in the searchbox)
If you still want it to start searching automatically, then a good start could be doing that once the list is rendered empty, instead of showing the Continue Search on Server button. To take it further, there are many examples of apps doing a really good job in displaying relevant search results as the user is typing. But combining that with your Nearby-list, I would not want to start on that end. I rather ship. :)
Hope this helps!


Is there a maximum for Mixer ingredients in Wonderful 101?

Question: In the mixer service you can use in the Wonderful 101, there are three ingredients (so far, just completed mission 001C). If there a maximum of these ingredients? The maximum that can be used in a mix are 30, and I haven't collected as much yet. But if I cannot exceed the 30 limit, I will use some of them right now instead of letting them going to waste.
Comment: Incidentally, if you press the Home button and navigate to an image-upload form, you can upload a screenshot directly from the Wii U itself without having to deal with this take-a-picture-of-the-TV nonsense.
Answer: You can hold a max of 99 of each of the three ingredients. So once you're approaching 90, you should mix something.


int32 and decimal convert

Question: I have a problem. In my class I defined product_ID as a int32 and product__price as a decimal. When I have to save data in database using textbox, i cant do it, it cannot convert it or something. please help me if you can. thank you.
public Int32 Product_ID { get; set; }
public String Product_name { get; set; }
public String Product_category { get; set; }
public Decimal Product_price { get; set; }
public string image_location { get; set; }

Product product = new Product();

product.Product_ID = int.Parse(textBox1.Text);
product.Product_name = textBox2.Text;
product.Product_category = textBox3.Text;

product.Product_price = int.Parse(textBox4.Text);
product.image_location = textBox5.Text;

Product.Save(product);

Comment: Have you tried `Decimal.Parse`?
Comment: `it cannot convert it or something`? What error are you getting?
Comment: How do you know there is a problem?  Perhaps there is an error message you could share with us?
Comment: What is the error message?
Comment: hmm.. input string was not in correct format
Answer: Correct this line:
product.Product_price = int.Parse(textBox4.Text);

to
product.Product_price = decimal.Parse(textBox4.Text);

Optimally you should check the content of the textbox first (if you don't already) so you are having correct comma, numbers only, try-catch and so forth.
Comment: Better yet, use a `NumericUpDown`.
Answer: You must convert it to a decimal instead of a int sinse product.Product_price is of type decimal.. The types must always match.
product.Product_price = Convert.ToDecimal(textBox4.Text);

or
product.Product_price = decimal.Parse(textBox4.Text);

Update
It's just a wild guess, but try this:
if(IsPostback)
{

    Product product = new Product();

    product.Product_ID = int.Parse(textBox1.Text);
    product.Product_name = textBox2.Text;
    product.Product_category = textBox3.Text;

    product.Product_price = Convert.ToDecimal(textBox4.Text);
    product.image_location = textBox5.Text;

    Product.Save(product);

}

Comment: I corrected it but it doesnt even come to that line. Error is on first line. message: input string is not in a correct format :S
Comment: Maybe textBox3.Text is not the price? or maybe its empty (not filled out yet)
Comment: Try to debug (press f5) and when it stops at that line, place your cursor on textBox4.Text to see what is in it.

int32 and decimal convert


Is top navigation an accepted pattern for mobile devices?

Question: I have always found the bottom nav bar to be one of the worst UI conventions in common practice, as it is a violation of information hierarchy. Of course, the hamburger menu is also universally hated, so I'm not wanting to do that.
How well tested and established is the top nav bar on mobile devices? Obviously it is the gold standard for desktop experience, but I'm specifically designing for phone at the moment.
Comment: For clarity, can you provide a screenshot/wireframe of a bottom nav bar so everyone is clear what you're referring to?
Answer: The good and bad of bottom nav
Bottom nav was a great idea when Apple first came out with it. Steve was laser-focused on one-handed usability. The bottom nav was designed to accommodate fast and convenient view switching where the mobile use case seemed to demand it.

Unfortunately, bottom nav is a hierarchy nightmare when used for an app's main info architecture. Product designers primarily familiar with iOS began to take the lower position as a given and put everything down there. As web apps became a viable mobile solution and the top navigation was carried over as part of simple responsive layouts, a new pattern started to take shape.
Enter Google's gradual shift to an experience-centered org ...
Top nav makes sense
Look at the Material Design guidelines for a well-developed perspective on top nav. They've recently added bottom nav for frequent switching scenarios, but it has a little different angle in MD.

Part of the logic behind MD's top nav solution, in addition to the obvious info hierarchy win, is the fact that action should guide you through an app's views. We don't have to force users to tap tabs and manually move through their workflow.

Taking that even further, Google has advocated an activity-centric feature model: regardless of the view or even the app, an "intent" will take the user where the app component they need.
The recent addition of bottom tabs in MD is not just in response to the iOS-minded product designers of the world. The use of bottom tabs can be used where manual rapid view switching is needed. Thise seems particularly good in a gesture-based view where you want to provide guideposts for left/right swiping behavior (though top nav can do the same).

Ironic sidebar
The bottom nav perspective on physical usability has an issue: user's have made up their mind that it's not a big deal. How many 4" phones are making hot tech lists these days. The remaining small-format phones are mostly budget devices. So how many users are one-handed phoners now?
For one-handed iPhone 6+ users, should we develop a bottom-left nav?

This is probably more realistic ...
Comment: +1 Great answer. And I love the "This is probably more realistic" picture. As a user of the original Samsung Galaxy Note - my first (and only) smart phone - I never understood single handed use...
Comment: To defend single-handed use, don't forget that sometimes you're doing multiple things at once. No matter how many finger-wagging nannies out there will hem and haw, people use their phones while driving. That said, the app I'm working on has an extremely low probability of use during driving.
Comment: @JClaussFTW Within the next 24 months it won't matter anyway because we'll be accustomed to yelling instructions at our phone as it drives us down the road.
Comment: +1 Great answer! But I think the more "technical stuff" about Intents (and the image) is out of place and doesn't add anything to the answer other than complexity.
Comment: @Rolfツ Interesting perspective. I think the Android team's codification of app-agnostic activity flow is critical to how we think about navigation. OTOH, I'm a nerd.
Comment: @plainclothes that's true. But I think it's good to remember that material design (which you heavily reverence too) has been created without a specific platform in mind.
Comment: @Rolfツ Untrue -- Material has synthesized the software industry's findings on multiple platforms. Each is addressed for it's own strengths.
Answer: I think you should reconsider the bottom navigation:

Bottom navigation is very well established in mobile apps, far more so than top navigation, and there is good reason for this.
In most cases i disagree with your point about incorrect information hierarchy - the content takes prime visual position in the interface, and the navigation is simply a tool for users to find the content they want. Where it is positioned should be governed by the usability constraints of the device in question. On handheld touch screen devices one of the primary usability issues is covering/obscuring the screen with the hand whilst touching and interacting. The bottom navigation avoids this issue, offering full view of the screen whilst interacting, to see any immediate feedback that is given. It is also easier for the thumb of the hand that is holding the phone to access a bottom menu than a top one, simply because of the distance.
The top bar has an established, conventional use, and this is for 'Back' actions, some core application functions (e.g. to create a new Tweet, in Twitter), accessing search functionality or for things like close actions on modal windows.
Lots of people hate the hamburger icon, but not because in general this way of displaying navigation is not effective on mobile. I know some people will argue that navigation should not be hidden, but this depends on the use case, and the size of the navigation. You can have a hidden navigation menu in an off-canvas side panel, and instead of having a hamburger icon, have a menu button with the word 'menu', or similar in it. It also depends on your market - there are certainly markets that are very familiar with the hamburger icon, for whom its use is not a usability issue.
Other options all come with their own, more significant issues, e.g. using a less well established off-canvas menu interaction like swiping comes with issues around signifying its presence (its discoverability).
Answer: One line answer to this is the Usability of choosing that position.
When you hold your mobile in hand, your thumb immediately gets into action and the bottom position is easily accessible to it than the top. In the era of large screen devices it's difficult to hold the phone in hand and access the navigation placed on top. Which is why Apple has changed the positions of Volume buttons for the iPhone 6+ devices to make them accessible by one hand.
There could be many more reasons to it, but I think this is the primary. The bottom navigation is more Useful than the top.


Can you sister floor joists with smaller boards?

Question: Does adding a sister that is smaller than the original joist actually increase strength at all? If so, does it need to be sistered at the bottom (so both beams touch the sill) or does it still add strength if sistered to be flush on the top?
To extend the question, does a sistered joist that doesn't go the full span add strength?
Answer:
Does adding a sister that is smaller than the original joist actually increase strength at all?

Yes.  They will both bear the load.

If so, does it need to be sistered at the bottom (so both beams touch the sill) or does it still add strength if sistered to be flush on the top?

As long as the joists are attached together with sufficient strength, the force will be carried by both joists through the entire length of the span, but the larger joist will transfer all of the load to the sill.  That will work.
Now if the joists are the same size, the attachment from joist to joist is not so critical - they can share the load from the floor without transferring part of that load from one to the other.

To extend the question, does a sistered joist that doesn't go the full span add strength?

Yes, it will add some strength, although calculating just how much strength it will add may be difficult.
Comment: This is true, but only to a point. If you were to add 2x4s to 20 foot 2x12s, for example, you'd be adding weight without any significant increase in rigidity. You'd have a net loss in terms of the robustness of the floor.
Comment: @isherwood If the 2x4's were added like an "I-beam" they would significantly increase its strength...
Comment: @isherwood - I think a 2x4 would significantly stiffen a 2x12.  Picture them sitting side by side spanning sill to sill.  Let's say a load of 500 pounds on the center of the 2x12 will cause 1/4" deflection.  The 2x4 isn't carrying anything.  Now remove the load, sister the 2x4 to the 2x12, replace the load.  It will deflect less than the original 1/4" because the weight has to bend both the 2x12 and the 2x4.
Comment: Have you ever fiddled with a 20' 2x4? It's a noodle. It offers virtually no rigidity within the range of motion we're discussing (which I hope is much less than 1/4"). It's just not tall enough. Now reconfigure to a 1x8 and we have something useful.
Comment: To put it simply, you could deflect it an inch with one finger. It makes no difference if you attach it to something else.
Answer: Joists and beams are sized based on 3 conditions: 1) bending, 2) shear, and 3) deflection. However, only one of these elements will "govern". That is to say, one will fail before the others.
Long spans usually fail in bending or deflection, while short spans with heavy loads fail in shear.
Adding smaller boards to existing joists is called a "composite" joist. Each member has certain characteristics and determining how (and where) to fasten them together is critical.
If additional boards are not added uniformly then the joist can be eccentrically loaded, which will cause it to twist and possibly fail.
Because of the complexity of calculating these loads (and connections), generally we design joists so loading is evenly distributed to the top of joists (and sistered joists) so the load is applied uniformly to all members. Therefore, we like all members to align on top. If one member is smaller (or has many knots and is not as good of grade) it doesn't matter, as the load will transfer to adjacent members.
Also, your question about sistered joists not "going the full length" is important, because when joists bend they have tension on the bottom edge and compression on the top edge. So, if the sistered joist is not continuous on the bottom, then it can't carry the tension throughout the joist. But if it's discontinuous on top, the ends of each piece just presses against one another and is effective...if ends are pressed against each other tightly.


No Scoreboard (how do I fix?)

Question: I'm making a Kit PvP and I decide to add a scoreboard. A few minutes later, an admin joins and removes the scoreboard. I then kick the admin that removed the scoreboard and added the scoreboard back. The game said it added the scoreboard but nothing is on the right side of the screen.
How do I fix this?
Answer: There are two things that can be causing this:

You didn't run the command to make it show on the side:
<code>/scoreboard objectives setdisplay sidebar <objectiveName>
</code>

There are no values on the scoreboard, making it hidden, even if the setdisplay command was ran:
<code>/scoreboard players set @p <objectiveName> 1
</code>
to set your score to 1 and make it show.
Comment: @Daemoncito09 I understand you might notve been able to because of the cooldown, but if this worked for you please accept it now by clicking the grey checkmark! This shows other uses that this solution worked and gives Bruno Rodrigues reputation.
Comment: The first one worked but the second didn't. But either way Thank you!
Comment: What do you mean, the first one didn't solve the problem?
Comment: no he means the second one didnt but the first one did

No Scoreboard (how do I fix?)


how to simulate any command to see what would happen before actually executing it?

Question: I would like to know how to simulate a command before running it, to see what the output would look like.
Comment: This is logically absurd. Read the `man` page for the command.
Comment: `mv` can be simulated with `ls`. That's about the only one I can think of.
Comment: `rsync`, `rename`, and some `apt-get` commands also allow for simulation.
Answer: What you are referring to is a "dry run", but there is no way to run all commands like this. You would have to check the manual pages on a command-by-command basis.
If you want to run potentially harmful commands just to see the outcome, I would recommending looking into virtualizing your OS and load files on it. This would be beneficial to you because it would allow you to take checkpoints/snapshots (terminology is different per virtualization program) which you can revert to at any time. This would allow you to run whatever commands you want on whatever files you want, see what happens, and if you don't like it, revert to your checkpoint. Virtualization is popular for software development environments because they offer reproducible and disposable machines.
Comment: Correct. This is because some commands permanently modify files or make calls to external systems you wouldn't have control over reverting the changes on (Ex: you can't dry-run sending an e-mail because you can't unsend it). This is called "not being [idempotent](http://docs.ansible.com/ansible/latest/glossary.html)". If you plan to do this often, I would recommend scripting it. Consider looking into Ansible/Vagrant or something of the sort.
Comment: so this "dry run" wont work for everything, I guess i'll be running some virtualbox then.


Android ArrayAdapter crashing when inserting

Question: The application crashes when inserting data from the database in an autoCompleteTextView.
I have 2 classes
First, Test class
public class Test extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    final DataBaseHelper myDb = new DataBaseHelper(this);
    final String [] myData = myDb.SelectAllData();
    final AutoCompleteTextView autoCom = findViewById(R.id.stations);
    ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, myData);
    autoCom.setAdapter(arrayAdapter);
}}

Second, DataBaseHelper class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "stations";
private static final String TABLE_STATIONS = "stations";

public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

public String[] SelectAllData() {
    try {
        String arrData[] = null;
        SQLiteDatabase db;
        db = this.getReadableDatabase();
        String strSQL = "SELECT name FROM " + TABLE_STATIONS;
        Cursor cursor = db.rawQuery(strSQL, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                arrData = new String[cursor.getCount()];
                int i = 0;
                do {
                    arrData[i] = cursor.getString(0);
                    i++;
                } while (cursor.moveToNext());
            }
        }
        cursor.close();
        return arrData;
    } catch (Exception e) {
        return null;
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}}

Comment: Please post the stacktrace if you can, it helps a lot.
Answer: The Issue
I believe that your issue is that you will encounter a table not found error as the database contains no tables. However, your are trapping the exception and taking no action as such the App will appear to not work.
If you were to add
e.printStackTrace();
before return null then the log would include something similar :-
2020-01-10 11:32:17.856 E/SQLiteLog: (1) no such table: stations
2020-01-10 11:32:17.856 W/System.err: android.database.sqlite.SQLiteException: no such table: stations (code 1 SQLITE_ERROR): , while compiling: SELECT name FROM stations
2020-01-10 11:32:17.859 W/System.err:     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
2020-01-10 11:32:17.859 W/System.err:     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
2020-01-10 11:32:17.859 W/System.err:     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
2020-01-10 11:32:17.859 W/System.err:     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
2020-01-10 11:32:17.860 W/System.err:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
2020-01-10 11:32:17.860 W/System.err:     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
2020-01-10 11:32:17.860 W/System.err:     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
2020-01-10 11:32:17.860 W/System.err:     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
2020-01-10 11:32:17.860 W/System.err:     at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)
2020-01-10 11:32:17.860 W/System.err:     at a.so59673151notable.DataBaseHelper.SelectAllData(DataBaseHelper.java:27)
2020-01-10 11:32:17.860 W/System.err:     at a.so59673151notable.MainActivity.onCreate(MainActivity.java:14)

It is not a good idea to trap SQLite Exceptions as they will, in general, be serious errors and as can be seen from your own experience, confusing as you believe that the issue lie with the Array not being built.

The Fix
Part 1
You should use the onCreate method, of the DataBaseHelper class to create the stations table.
e.g.
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_STATIONS + "(name TEXT);");
}

of course that may well not be the schema that you require, it is purely an example. You may wish to refer to CREATE TABLE

Part 2
As the database has been created, the DataBaseHelper's onCreate method will not run, as it only runs one when the database is created. As such you need to delete the database. When developing the easiest ways to do this is to either :-

Delete/Clear the App's data
Uninstall the App

After which you can then rerun the App.
More
To get data from the database you need to add the data to the database, as such you'd want to add a method to the DataBaseHelper class along the lines of (again the assumption is of the basic table created above) :-
public long insertStation(String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("name",name);
    return db.insert(TABLE_STATIONS,null,cv);
}

You may wish to have a read of insert
You could then have something like the following in the Test class :-
final DataBaseHelper myDb = new DataBaseHelper(this); //<<<<< EXISTING LINE
myDb.insertStation("MyFirstStation");
myDb.insertStation("MySecondStation");
final String [] myData = myDb.SelectAllData(); //<<<<< EXISTING LINE

Note this is just for testing, it will add the same data each time the App is run, so for each run there will be 2 extra rows.

Testing
The above changes have been tested by using :-
    final DataBaseHelper myDb = new DataBaseHelper(this);
    myDb.insertStation("MyFirstStation");
    myDb.insertStation("MySecondStation");
    final String [] myData = myDb.SelectAllData();
    for (String s: myData) {
        Log.d("STATIONINFO","Station Name is " + s);
    }

This results in (for the first run after installing the App) :-

2020-01-10 11:49:42.321 D/STATIONINFO: Station Name is MyFirstStation
2020-01-10 11:49:42.321 D/STATIONINFO: Station Name is MySecondStation


Capturing a click event on all md-buttons with directive with Angular Material

Question: I'm using Angular Material as a UI framework in my AngularJS web application.
I am trying to perform a specific action on each md-button click. I assumed that it would just be as simple as adding a directive, although unfortunately nothing happens.
app.directive('md-button', function(){
    return {
        restrict: 'AEC',
        link: function(scope, element){
            $(element).on('click', function (e) {
                console.log("button clicked");
            });
        }
    };
});

How can I perform an action on every md-button click on my site?
EXAMPLE
Answer: You have to declare your directive name using camelcase like this:
.directive('mdButton', function(){
  return {
    restrict: 'AEC',
    link: function(scope, element){
        angular.element(element).on('click', function (e) {
            console.log("button clicked");
        });
    }
  };
});


Using Protractor, failing test cases using maven and then maven build should fail or not?

Question: Some of test cases are failed so due to that maven build is also failed .Just because of maven failure , Jenkins build is also failed.
So is it right or something is wrong in it?
Answer: In your Jenkins job you could run Maven with either of the following parameters:

-DskipTests=true to skip test execution entirely
-Dmaven.test.failure.ignore=true to ignore test failures

But if the tests are important (and they certainly should be :) then perhaps ignoring them (or not running them) is the wrong approach, perhaps you should instead fix the failed tests.
Comment: Yeah those Test Case have major priority so Its good not to fix it through maven build success
Thank you for giving clarification on it
Comment: So u want to say that if test case are failing then Maven build has to be failed.
and that is a right approach.Is it so?


How do I show current age using liquid?

Question: I have a Jekyll website about my pets. I want it to automatically update my pet's age based on their birthday. I cannot, for the life of me, figure out the liquid formula to show their age based on today's date and their birthday.
What is the right liquid formula to show this?
Answer: You can either use JS with libraries like moment to compute the birthday client-side, like this:

const pet_birthday_element = document.querySelector("#pet_birthday");
const pet_age_element = document.querySelector("#pet_age");
const pet_age = moment().diff(pet_birthday_element.innerText, 'years');

pet_age_element.innerText = `Your pet is ${pet_age} years old!`;

Your per birthday is: 2020-07-10 15:00:00.000

Or, if you prefer a strict liquid approach, David Jacquel had a nice solution in a different thread. He turns both the birthday and the current date into timestamps (number of seconds), then substracts one from the other, and displays the difference, something like this:
{% assign dateStart = "2020-04-09" | date: '%s' %}
{% assign nowTimestamp = 'now' | date: '%s' %}

{% assign diffSeconds = nowTimestamp | minus: dateStart %}
{% assign diffDays = diffSeconds | divided_by: 3600 | divided_by: 24 | divided_by: 365 %}

Your pet is {{ diffDays | round: 0 }} years old!

You can test it here.
Comment: amazing, thank you. I couldn't figure out what I needed in a single liquid formula, and didn't know how it worked, nor did anywhere really explain it in this kind of context. this solves my problem. Thank you!

How do I show current age using liquid?


How can I capture the error output from the ipython shell?

Question: I'm writing an ipython macro that processes the output of a program. The thing is, the program can sometimes write to stderr , so if I do something like this :

out = !my_program

the out variable will not contain the output. I think it will contain the exit code ( correct me if I'm wrong ).
How can I capture both stdout and stderr streams?
Answer: foo 2>&1 means redirect all of the output, including handle 2 (that is, STDERR), from the foo command to handle 1 (that is, STDOUT)
so here out = !foo 2>&1 maybe good enough. below is the demo:
egg.py:
#!/usr/bin/env python
# -*- coding: utf8 -*-
def main():
    print 'hello'
    print 3/0
if __name__ == "__main__":
    main()

IPython 0.10
In [5]: out = !egg.py
Traceback (most recent call last):
  File "D:\python\note\egg.py", line 7, in <module>
    main()
  File "D:\python\note\egg.py", line 5, in main
    print 3/0
ZeroDivisionError: integer division or modulo by zero

In [6]: out
Out[6]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello

In [7]: out = !egg.py 2>&1

In [8]: out
Out[8]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: hello
1: Traceback (most recent call last):
2:   File "D:\python\note\egg.py", line 7, in <module>
3:     main()
4:   File "D:\python\note\egg.py", line 5, in main
5:     print 3/0
6: ZeroDivisionError: integer division or modulo by zero

Hope this helps
Comment: sunqiang:  UNIX had this sort of redirection (**`2>&1`** to duplicate stderr to stdout, for example) long before MS added support for it in their systems.  Under UNIX it's generalized (you can redirect, duplicate and close other file descriptors if you know their numbers).
Comment: @Jim Dennis, thanks for the info. I am just a Linux newbie. don't know this before. I have edited the answer correspondingly.
Comment: would you happen to know if one can capture the output of a macro?
Comment: @Geo, sorry I don't know macro.


Devise redirect after sign up fails

Question: Is there any easy way to disable devise sign_up page? I have forms for registration and authorization on one page so i don't need any other pages. I want to disable routes responsible for these pages, so that if a user enters users/sign_up he should't get to the sign up page but should be redirected to some other page.
Comment: Did you find a solution to this? Did you change the `respond_with`?
Comment: @Ashitaka
Finally i skipped all devise default routes and specified a list of `post` and `get` routes mapped to devise controllers. Then i overrided
devise controllers to use `respond_with({}, :location => after_sign_up_fails_path_for(resource))` when authentication or registration or password restore fails. Note that you have to create a method `after_sign_up_fails_path_for(resource)`. Inside it just put where you want to go(for_example `home_path`). That worked for me.
Answer: You can overwrite the registrations controller and make the new action redirect somewhere.  Here are some responses to a similar question that was posted on StackOverflow which explain the necessary steps.
Comment: #Batkins,
`clean_up_passwords resource;
 respond_with resource`
This code is executed when there are errors during registration(ex. a user exists, empty email). If i write `redirect_to some_path` after this code i get double render exception. If i write `redirect_to some_path` instead of `respond_with resource` i am redirected but `devise_error_messages` are empty so i can't use them in the view i'm redirected to. Is there any way to make error messages available in the view i'm redirected to?
Comment: You need to use `redirect_to some_path and return`.  That will make it stop executing code within that method after the redirect code occurs which will prevent other render/redirect statements that might occur afterwards.  [Read this documentation on the RoR official site](http://guides.rubyonrails.org/layouts_and_rendering.html#avoiding-double-render-errors) for a more detailed explanation.

Devise redirect after sign up fails


Expected value of the random variable $Xe^X$ where $X\sim N(0,1)$

Question: It is known that
$$
E(X) = \int_{-\infty}^{\infty}e^x\frac{1}{2\pi}e^{-0.5x^2}\; dx= e^{0.5}
$$
while
$$
E(Xe^X) = \int_{-\infty}^{\infty}xe^x\frac{1}{2\pi}e^{-0.5x^2}\; dx
$$
By integration by parts, I get $\displaystyle\left.xe^{0.5}\right|_{-\infty}^{\infty} - xe^{0.5}$, but I am stuck here. I suppose I cannot say the first part is $0$ as it is divergent?
Comment: I do not think that you may use the first result for the  integration by parts of the second integral.
Comment: Since the mgf of $X$ is $M(t)=E(e^{tX})=e^{t^2/2}$, we have $M'(t)|_{t=1}=E(Xe^X)=\sqrt e$.
Comment: Your formulas are missing some square root signs.
Answer: Applying $\partial_t$ to $\Bbb Ee^{tX}=e^{t^2/2}$, $\Bbb EXe^{tX}=te^{t^2/2}$, so $\Bbb EXe^X=e^{1/2}$.
Answer: Denote the density of $X\sim N(0,1)$ by $\phi$, i.e., $$\phi(t)=\frac{1}{\sqrt{2\pi}}e^{-t^2/2}\,\qquad ,\, t\in\mathbb R$$
Then your first line should have read $$E\left[e^X\right]=\int_{-\infty}^\infty e^x \phi(x)\,dx=\sqrt e$$
To evaluate $E\left[Xe^X\right]$, keep in mind that $$\phi'(t)=-t\phi(t)$$
and integrate by parts taking $u=e^t$ as first function and $dv=t\phi(t)$, i.e. $v=-\phi(t)$.
We arrive at
\begin{align}
E\left[Xe^X\right]&=\int_{-\infty}^\infty te^t\phi(t)\,dt
\\\\&=\int_{-\infty}^\infty u\,dv
\\\\&=uv \Big|_{-\infty}^\infty -\int_{-\infty}^\infty v\,du
\\\\&=-\underbrace{\lim_{\substack{a\to-\infty \\ b\to +\infty}} e^t \phi(t)\Big|_{a}^{b}}_{0}+\underbrace{\int_{-\infty}^\infty e^t\phi(t)\,dt}_{E(e^X)}
\\\\&=\sqrt e
\end{align}
Comment: Thank you for your answer! But could you kindly explain how do you arrive at the 4th line? (E($Xe^X$))
Comment: @waipun Which part is unclear?
Comment: @StubbornAtom you take the function $e^{t}$ out of the integral in line two at the beginning. How does this work?
Comment: @Karl As far as I remember, this is integration by parts, taking $e^t$ as the first function and $t\phi(t)$ as the second function.
Comment: @StubbornAtom but here $e^t$ is not defined then! It has a meaning inside the integral, but outside? What is $t$ here?
Comment: @Karl I do not follow. Tell me what I should have written.
Comment: @StubbornAtom you have to know what you want to write, but $e^t$ at the beginning of the second line is just meaningless!
Answer: Ok, nobody, I will try with $\phi(x)=\frac{1}{2\pi}e^{-0.5x^2}$:
$\int_{-\infty}^{\infty}e^x((-x)\frac{1}{2\pi}e^{-0.5x^2})dx  = [e^x \phi(x)]_{-\infty}^{\infty}-\int_{-\infty}^{\infty} e^x \phi(x) dx = 0
-\int_{-\infty}^{\infty} e^x \phi(x) dx = -e^{1/2}$
Similar to @StubbornAtoms solution, but the terms have all a meaning.


How to customise maximum login attempt attribut in asp.net

Question: I'm implementing a security mecanism in a asp.net application , eventually I'm thinking about using this property
PasswordAttemptWindow
<code>  <membership defaultProvider="SqlProvider"
  userIsOnlineTimeWindow="20">
  <providers>
    <add name="SqlProvider"
      type="System.Web.Security.SqlMembershipProvider"
      connectionStringName="SqlServices"
      requiresQuestionAndAnswer="true"
      maxInvalidPasswordAttempts="5"
      passwordAttemptWindow="30"
      applicationName="MyApplication" />
  </providers>
</membership>
</code>
But if I would like to make something  that will increment the waiting delay from the previous attempts ,is there any way to do it ?
Example :  if a user try 5 wrong password for the first time , the account should be locked to 1 min , but after that min if he still enter 5 other wrong passwords the delay should increase to 5 min and so on
Thank you
Comment: I don't think so, not out of the box anyway. Although I'd question if it matters? This is all to prevent brute force, so does a rolling window really matter? My logic is that even if you find something that works, will it be stable or will it cause more headaches  than it saves in the future.
Comment: @Joe_DM You guessed it right , yes it's eventually to reduce brute force effectiveness ( we all know that brute force cannot be stopped 100%) The reason is I'm building an application for a school project , eventually the professor will come at some point and run script as to guess the passwords , and it explains why I'm looking around to maximize login security
Comment: @napi15: a more correct way of preventing bruteforce attacks is to activate a captcha after, say, 3 failed login attempts. Assuming you have a strong captcha, auto probing is no longer possible.
Answer: First
Configure in you database some columns where you want to stores value
Second
<code>  maxInvalidPasswordAttempts=YourDBValue

  passwordAttemptWindow=YourDBValue
</code>
of course you should implement elswhere a mecanism where you have to let the admin be able to save the data inside those columns


QMessageBox - Style sheet for it

Question: I am using QMessageBox and trying to use setSyleSheet to change the background colours.
In the picture you see, the top half has white background and the bottom half has a grey background.
I wish to change these colours. I have been unsuccessful and have not found any useful pointers on the web. What is the correct CSS to do this?
Answer: Try this:
#include <QApplication>
#include <QMessageBox>

int  main(int argc, char *argv[])
{
    QApplication  a(argc, argv);
    // Create a QMessageBox
    QMessageBox  msgBox;

    // Set the text and title
    msgBox.setText("This is a QMessageBox");
    msgBox.setWindowTitle("Customized QMessageBox");

    // Set the background color of the QMessageBox
    msgBox.setStyleSheet("background-color: lightblue;");

    // Customize the text color
    QColor  textColor(255, 0, 0);     // Red text color

    msgBox.setStyleSheet(QString("background-color: lightblue; color: %1;").arg(textColor.name()));

    // Get the palette of the QMessageBox to modify child widget colors
    QPalette  palette = msgBox.palette();

    // Set the background color of child widgets (QLabel)
    palette.setColor(QPalette::Window, QColor(255, 255, 0));      // Yellow background color
    msgBox.setPalette(palette);

    // Show the QMessageBox
    msgBox.exec();

    return a.exec();
}

Comment: Thanks. But I do not want the whole background the same colour. In the example in the question the box is divided. Top bit is white with the label. Bottom bit is grey with the button. How can I change those two bits.
Comment: @EdHeal when you set a nameless style, it us set to particular element. In vase things like QMessageBix implementation may vary and may contain other widgets. You have to set style for whole QWidget class (see QSS and CSS selectors)
Comment: @Swift-FridayPie How does one find out the widgets in the box?
Comment: @EdHeal: `children()` but you don't need to. As I said, read about QSS. You're explicitly giving style that doesn't affect widget's children.
Comment: @EdHeal if you want to set stylesheet for just one specific object you need to add "#objectname".for example `QPushButton#pushButtonName
{
 background-color: rgb(51, 209, 122);
}`

QMessageBox - Style sheet for it


16.04 switches from default audio device when not available, but doesn't switch back when the default becomes available

Question: I have a laptop hooked up to a TV via HDMI. When the TV powers off, the audio output switches from HDMI to the built-in laptop speakers. This behaviour is new, as previous Ubuntu versions would always stay on the last device I chose (HDMI.) How can I control this feature so as to always have HDMI selected even when the TV is off?
Failing that, how can I disable the built-in laptop speakers so they are never available, hopefully forcing the audio output to HDMI?
Answer: So it turns out everything you think you're editing in /etc/pulse/default.pa file isn't doing squat until you copy it to your current user profile (~/.config/pulse/) Shout out to Nebuzaradan for discovering the solution: https://unix.stackexchange.com/questions/293399/how-to-set-hdmi-sound-output-as-default-on-ubuntu-16-04
Answer: You can use pavucontrol  (Pulseaudio volume control, install if necessary):
Launch it from multimedia menu, go to the "output devices" tab, and click the green "define as alternative" button that is near HDMI soundcard.
Look also "configuration" tab: you will find various profile such as HDMI .
Comment: Hi laugeo, the option you're referring to was "define as fallback device" and was already selected for my HDMI and built-in speakers. I de-selected the option for the built-in speakers, but it made no difference after power cycling my TV. Thanks for the idea though.


What is the purpose of region-locking video game systems?

Question: What is/are the purpose(s) of region-locking video game systems? Is it a decision made by the console's developer (i.e. Nintendo) or this is enforced by governments?
As far as I remembered, it began with the Super Nintendo and the Super Famicom as a Japanese equivalent. Then Sony also region locked some of their first PlayStation models. Some manufacturers like Nintendo are still region-locking their system.
Do they ever exeplained why (in official sources)?
Answer: I'll quote an answer on another forum from 2015 :

It's because of price discrimination. Steam, for example, used to have
  all its prices in USD, and no games were region locked. Then they
  switched to regional currencies for price discrimination reasons. A
  $60 game is way too high a price for a consumer in the Philippines, so
  the same game that costs $60 USD will usually be around $40 when
  converting from the Philippine price, and so it has a higher chance to
  get sold.    Then people started figuring out that you could have
  people buy games from the "cheap" regions, then gift them to you via
  Steam's in-client trading feature. This started a whole fiasco of
  furious trading and basically everyone was buying the cheapest copy
  around, resulting in a net loss of money for Valve and the developers.
  So they banned cross-region trading, and made it so that most games
  could only be played if bought in your region--yep, region-locking.
  People started getting scammed too, which is the on-paper reason that
  region-locking was enforced, but the above is what the community
  generally agrees upon.

https://www.quora.com/Video-Games-Why-is-region-locking-still-a-thing
Comment: The price differences are much higher actually... it can get close to 80% discount if you pick the right countries.
Comment: Following-up Nelson's comment, you can see the price differences on SteamDB (example for [CS:GO](https://steamdb.info/app/730/))
Comment: Steam made a policy change so that in order to change your location in your account, you must make a purchase using a credit-card that is located in that country (the card's address matches where you say you've moved to). The worst part is that VPNs still tout this sort of regional bypass as a feature of using a VPN, knowing full-well that a lot of sites already take measures like Steam's to prevent it, and worse, attempting to bypass it will get your account suspended (the same with bypassing geo-fencing of content like with Netflix or Hulu).
Answer: EDIT:
Ok, after some more research, I found an official statement from the President of Nintendo:
"From some people's perspective, it might seem like a kind of restriction. However, we hope people can appreciate the fact that we're selling our products worldwide. There are many different regions around the world, and each region has its own cultural acceptance and legal restrictions, as well as different age ratings. There are always things that we're required to do in each different region, which may go counter to the idea that players around the world want the freedom to play whatever they want."
So, it really isn't about language, but the fact different regions have different criteria for rating games and determining if the content is OK.
Comment: You might need to include the source of the quote (official statement from the President of Nintendo)


C++ error: fields must have a constant size

Question: can someone please give me a hint how to solve the following problem:
clang++-7 -pthread -std=c++17 -o main createLibrary/configuration.cpp createLibrary/growbox.cpp createLibrary/helper.cpp createLibrary/httprequests.cpp main.cpp
In file included from createLibrary/configuration.cpp:2:
In file included from createLibrary/configuration.h:1:
In file included from createLibrary/growbox.h:12:
createLibrary/httprequests.h:13:10: error: fields must have a constant size:
      'variable length array in structure' extension will never be supported
    char device[configuration::maxNameSize];
         ^
1 error generated.

I'm including the .h files in the order configuration.h, httprequests.h. I want all necessary config-parameters to be configured in the configuration.cpp file, but I got the displayed error. What am I doing wrong here?
configuration.h
extern int const maxNameSize;

configuration.cpp
int const configuration::maxNameSize = 30;

httprequests.h
char device[configuration::maxNameSize];

httprequests.cpp
char HTTPREQUESTS::device[configuration::maxNameSize];

Comment: Array size must not only be constants, they must be *compile time constants*. A value declared in another compilation unit is not a compile time constant, because obviously the compiler doesn't know what it's value is when compiling httprequests.h
Answer: An extern const int is not a constant expression.

a variable is usable in constant expressions at a point P if

the variable is

a constexpr variable, or
it is a constant-initialized variable
of reference type or
of const-qualified integral or enumeration type

and the definition of the variable is reachable from P
and

P is in the same translation unit as the definition of the variable

(emphasis added)

I want all necessary config-parameters to be configured in the
  configuration.cpp file

You are out of luck. The value of maxNameSize must be visible to it's compile-time users.
Answer: Declare maxNameSize like this
// configuration.h
class configuration
{
public:
    static const int maxNameSize = 30;
    ...
};

And no need to define it in configuration.cpp.
Your way doesn't make maxNamesize a compile time constant.
EDIT, I am assuming that configuration is a class. If it's a namespace then do the following instead
// configuration.h
namespace configuration
{
    const int maxNamesize = 30;
    ...
}

Constants are an exception to the one definition rule, so it's OK to define them in a header file.
Comment: Both of your suggestions violate ODR when included into multiple translation units.
Answer:
What am I doing wrong here?

You have defined an array variable with size that is not compile time constant.
Solution: You can either

Define the variable in the same translation unit where you use it as the size of an array so that it may be compile time constant. Given that the array is in a header, which presumably is included into multiple translation units, the size cannot be defined externally. It has to be either static or inline.
Or use a dynamic array instead. Simplest way to create dynamic array is to use std::vector.


Android IR Remote Override Power Key

Question: How to Override the power key of an IR remote for a rooted Android device? I have tried the following
<code>         case KeyEvent.KEYCODE_STB_POWER:
            Toast.makeText(this, "KEYCODE_STB_POWER key pressed",
                    Toast.LENGTH_SHORT).show();
            return true;

        case KeyEvent.KEYCODE_AVR_POWER:
            Toast.makeText(this, "KEYCODE_AVR_POWER key pressed",
                    Toast.LENGTH_SHORT).show();
            return true;

        case KeyEvent.KEYCODE_TV_POWER:
            Toast.makeText(this, "KEYCODE_AVR_POWER key pressed",
                    Toast.LENGTH_SHORT).show();
            return true;

        case KeyEvent.KEYCODE_POWER:
            Toast.makeText(this, "KEYCODE_POWER key pressed",
                    Toast.LENGTH_SHORT).show();
            return true;
</code>
But none of the above worked. Am I missing anything?
Answer: Try logging the key so you get the actual KeyEvent to be treated.
for example:
<code>@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    Log.d("keycode", "" + keyCode);
(...)
}
</code>

Android IR Remote Override Power Key


What is the asymptotic behavior of the function counting the number of (not necessarily distinct) prime divisors?

Question: From http://en.wikipedia.org/wiki/Arithmetic_function#.CE.A9.28n.29.2C_.CF.89.28n.29.2C_.CE.BDp.28n.29_.E2.80.93_prime_power_decomposition
Ω(n), ω(n), νp(n) – prime power decomposition
The fundamental theorem of arithmetic states that any positive $n = p_1^{a_1}\cdots p_k^{a_k}$   where $p_1 < p_2 < ... < p_k$ are primes and the $a_j$ are positive integers. (1 is given by the empty product.)
It is often convenient to write this as an infinite product over all the primes, where all but a finite number have a zero exponent. Define $νp(n)$ as the exponent of the highest power of the prime $p$ that divides $n$. I.e. if $p$ is one of the $p_i$ then $νp(n) = a_i$, otherwise it is zero. Then
$$
n=\prod_p p^{\nu_p(n)}.
$$
In terms of the above the functions ω and Ω are defined by
<code>ω(n) = k,
Ω(n) = a_1 + a_2 + ... + a_k.
</code>
To avoid repetition, whenever possible formulas for the functions listed in this article are given in terms of n and the corresponding pi, ai, ω, and Ω.

It seems that a few things are clearly known about $\omega(n)$. For instance, it has normal order $log \ log \ (n)$.
How can we bound $\Omega (n)$ in the asymptotic limit?
Answer: $\Omega[N]$ asymptotically approaches $\ln \ ln \ N$.
See this reference: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.118.4755&rep=rep1&type=pdf
In chapter 7, they talk about related results. In particular see Exercise 7.1:
(i) Show that, for any ξ(N) → ∞,
ν N {n : |Ω(n) − log log N| > ξ(N) log log N}
ξ(N) −2 ,
and deduce that Ω(n) has normal order log log n.


How to use zope.interface.directlyProvides with instances of build in types (dict, string, ...)

Question: I have a bunch of dictionaries, which I would like to annotate with type information, to be able to later get adapters for them. In the following example, the failing case is what I would like to do and the other case shows a working version. Is it somehow possible to get the first version working without introducing the extra object? The code which creates the dicts would not be easy to change, so I'm looking for the most simple and non intrusive way to add some type infos.
from zope.interface import Interface, implements, directlyProvides
from zope.interface.registry import Components

registry = Components()

class IA(Interface):
    pass

#   this one fails

data = {}
directlyProvides(data, IA)

#   this way it works

class X(dict):
    pass

data = X()
directlyProvides(data, IA)

Answer: zope.interface relies on the ability to set some magic attributes on various objects and classes.  This is what happens
>>> class Dict(dict):
...     pass
...
>>> getattr(Dict, '__provides__', None)

Nothing.  Now try to do what you did.
>>> from zope.interface import Interface, implements, directlyProvides
>>> class IA(Interface):
...     pass
...
>>> data = Dict()
>>> directlyProvides(data, IA)

Try to grab that __provides__ again
>>> getattr(Dict, '__provides__', None)
<zope.interface.declarations.ClassProvides object at 0x7f133cab48d0>

Reason this fails on the builtin types is because you can't actually set attributes on any of them (through standard means).
>>> setattr(dict, '__provides__', None)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'dict'

Hence if you want to assign some marker interface on some instances of standard types, it will fail.  Just subclass them as is, or create real objects which is more what the Zope Component Architecture was more designed to be used for.
Answer: You cannot annotate Python built-in types with interface information; you simply cannot add the required attributes.
You can register adapters for the type (so no interfaces implemented):
>>> from zope.interface.registry import Components
>>> from zope.interface import Interface
>>> registry = Components()
>>> class IA(Interface):
...     pass
...
>>> data = {}
>>> registry.registerAdapter(lambda o: 'adapter from dict to IA', [dict], IA)
>>> registry.queryAdapter(data, IA)
'adapter from dict to IA'

You cannot do this for instances, unfortunately:
>>> registry.registerAdapter(lambda o: 'adapter from data to IA', [data], IA)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/zope/interface/registry.py", line 186, in registerAdapter
    required = _getAdapterRequired(factory, required)
  File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/zope/interface/registry.py", line 432, in _getAdapterRequired
    raise TypeError("Required specification must be a "
TypeError: Required specification must be a specification or class.

This means that if you really must adapt specific dictionaries, then your options are limited. Using a subclass of dict is one work-around.
However, you must really ask if adapting dictionaries is the best approach for your problem here.


What determines the element 'mouseover' captures?

Question: Does this determine the element mouseover will capture with event.target?:
The element with the highest z-index. If a tie:
The most nested element. If a tie:
The element lowest down in source-order (the element that overlaps).

P.s. How would I have found this out from MDN (or another site that isn't the 'specs')?
Comment: Can you provide an example? Your question isn't clear to me.
Comment: @Phix The section 'mouseout when leaving for a child' should make it clear (https://javascript.info/mousemove-mouseover-mouseout-mouseenter-mouseleave)
Comment: If I understand correctly, you are looking for an explanation about how the foreground element is choosen ?
Comment: @Seblor yes I am
Answer: There is no way two elements on the same z-index level share an x-y coordinate, so you can stop at first point, except that you also need to account for their pointer-events computed rule.
Comment: The `z-index` CSS property is just a way to force some ordering, but it's not the only thing that determines the z-index. By default children will have higher z-index than their parents.
Comment: Yes, if its `pointer-events` computed rule allows it to be the target of pointer-events. -> What's written in my answer.
Comment: I'm talking about if the cursor hovers over a space on the website where a parent and child are
Comment: That doesn't change anything, either the parent has an higher z-index, either the child has, they can't have the same. Just take some sheets of paper and try to represent a web page with it, if the sheets share an x-y coordinate, they have to overlap and their z-index have to be different
Comment: Okay, I thought `z-index`'s initial value was `auto` which effectively means zero so both would be zero. Are you saying for elements with `z-index: auto` the parent is considered to have a 'higher z-index'?
Comment: Okay thank-you. 1. Would you be able to pass on something (not 'spec') that talks about 'z-index' in the way you're talking about it here (not directly related to the `z-index` property)? 2. Taking this knowledge to my question, where does 'the element lowest down in source-order' fit in? Is that part of 'z-index'?
Comment: 1. I'm really a "specs-guy" myself and don't trust random blog posts on the web, but for this case, real life and a bit of common sense (if it didn't work that way, browsers would have to draw all the elements with same CSS z-index of in a single call, mixing them in undetermined ways, imagine background images with texts and no way to tell which is in front of which). 2. There is no direct relation, it all depends on the document's stylesheet, but usually children are in front of their parents by default.
Comment: Alright did you get what my question was asking? So basically the element that's captured with `event.target` with `'mouseover'` when the cursor is above multiple elements is the element with the highest z-index?


C - struct returned from function not assigned to variable

Question: I am getting a segfault when trying to print a string.
here is some context for the problem, I think that it is due to me somehow passing a struct incorrectly.
Load file reads *file_path and it returns it as a document struct, but in int main() sudo never has any data in it. I run the program in gdb and doc inside of load_file() has valid data inside of it, but sudo (also a document struct in int main() never gets the data. Is there a reason why?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
const char *sudoers_path = "thing";
char *read_string = "sandos";
int read_string_len = 6;
struct document{
    char *string;
    int length;
};
struct document sudoers;
struct document loadfile(char *file_path){
    char char_temp[2] = "1";
    struct document doc;
    int temp=0;
    FILE *file = fopen(file_path,"r");
    doc.string = (char *)malloc(10*sizeof(*doc.string));
    doc.length=10;
    int len_doc_read = 0;
    while(temp != EOF){
        temp = fgetc(file);
    if(temp == EOF){
         break;
    }
    char_temp[0] = (char) temp;
    if(doc.length - len_doc_read==0){
        doc.string = (char *)realloc(doc.string, (doc.length+10)*sizeof(*doc.string));
        for(int i = doc.length; i< len_doc_read-2; i++)
            doc.string[i]=' ';
        doc.string[doc.length-1] = '\0';
    }
    len_doc_read++;
    strcat(doc.string, char_temp);
    strcat(doc.string, "\0");
    doc.length++;
}
//I am the cracker of C, destroyer of programming! --me
if(doc.string = NULL)
    printf("memory failed");
return doc;
}

int main(){
    struct document sudo = loadfile(sudoers_path);
    struct document sand_find;
    sand_find.string = "sandos";
    sand_find.length = 7;
    puts(sudo.string);
    return 0;
}

Incase it matters I am compiling and running the program on a modern version of Arch Linux and the comand that I am using to compile it is
$ gcc main.c -o out

Comment: Step 1: check the return value after `FILE *file = fopen(file_path,"r");`
Comment: the statement is assigning NULL to doc.string - if(doc.string = NULL). Change it to if(doc.string == NULL).
Comment: I recommend you read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to use a *debugger* to step through your code line by line. Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and edit your question to show us the contents of the file you read, and the expected and actual output of your program.
Comment: One thing I notice, is that after `for(int i = doc.length; i< len_doc_read-2; i++) doc.string[i]=' ';` you truncate it with `doc.string[doc.length-1] = '\0';` so removing any space padding just done. And what will happen when `doc.length == 0`?
Comment: Add -Wall to your build command line.  Clean up all warnings.
Comment: . . . if you intended to terminate the string after the space padding `i` loop there are two problems. First you would not want `doc.string[i-1] = '\0';` but `doc.string[i] = '\0';` However, `i` has gone out of scope.
Answer: In your program, by mistake instead of checking for NULL, you are assigning NULL to doc.string -
if(doc.string = NULL)

Change it to -
if(doc.string == NULL)


Dr. Kawashimas not compatible with "NINTENDO Switch Lite", because of missing IR Motion Camera Functionality?

Question: Popluar shops (at least in German speaking countries) sell a bundle NINTENDO Switch Lite and Dr. Kawashimas.

According to my research the Lite does not have an IR Motion Camera, which means is not compatible with Dr. Kawashimas. It seems you can buy wireless Joy-Con and pair it with Lite, but at additional costs.
It seems also you can't play Dr. Kawashimas at Big Screen (TV), only in handheld mode.
Do I miss something? Why MediaMarkt is selling this bundle?
Answer: According to this support page (it's in Japanese):

Nintendo Switch Lite でも遊べます。
ただし、Joy-Conの機能を使った一部のトレーニング(「後出勝負テスト」「指計算」「指体操」「野鳥数え」「旗上げ」「箱数え」)は遊べません。

Which (roughly) translates to:

It can also be played on Nintendo Switch Lite.
However, some training exercises that use the Joy-Con functionality (「後出勝負テスト」「指計算」「指体操」「野鳥数え」「旗上げ」「箱数え」) cannot be played.

(I didn't translate training's name since I don't know how it's called in English version)
However, as you already said in the OP, you can buy Joy-con and accessories that is able to charge Joy-con (since Nintendo Switch Lite can't charge Joy-con unlike normal Nintendo Switch) such as Joy-con Charging Grip and Joy-con AA Battery Pack.
As for the TV mode, some of the trainings can be played on TV mode, however almost all of trainings requires touch function and/or touch pens to write something in the training, so it's not a good idea to play this game in TV mode (to begin with, though, TV mode is not available on the Nintendo Switch Lite).
I'd recommend buying normal Nintendo Switch if you're planning to play any other game in TV mode. NS Lite doesn't have TV mode function as I said above. Just in case, source.
Comment: For the trainings names, google translator interprets them as "Late Bird Test", "Finger Calculation", "Finger Gymnastics", "Wild Bird Counting", "Raising the Flag", "Box Counting"
Comment: @Wondercricket While other translations may be correct, but unless there is a meaning I am unaware of, it's probably incorrect with regard to the "Late Bird Test", as the training is aimed at winning/losing the game of rock-paper-scissors by playing a move after the opponent. If "Late Bird Test" means that... English is a hard language for me, I guess.