text:
Q: How to get Sql data into string variable or into label How can I get the data from the a table and convert it into string. I'm trying to make [User Level] into a string variable or get it to a label.
My current code is
private void btnLogin_Click(object sender, EventArgs e)
{
    if (attempt == 0)
    {
        lblMsg.Text = ("ALL 3 ATTEMPTS HAVE FAILED - CONTACT ADMIN");
        return;
    }

    scn.ConnectionString = @"Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True";
    SqlCommand scmd = new SqlCommand("select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd", scn);
    scmd.Parameters.Clear();
    scmd.Parameters.AddWithValue("@usr", txtUser.Text);
    scmd.Parameters.AddWithValue("@pwd", txtPass.Text);
    scn.Open();

    if (scmd.ExecuteScalar().ToString() == "1")
    {

        MessageBox.Show("You are granted with access.");
        this.Hide();
        frmMain frmmain = new frmMain();
        frmmain.Closed += (s, args) => this.Close();
        frmmain.Show();

    }
    else
    {
        MessageBox.Show("Invalid Username or Password.");
        lblMsg.Text = ("You have only " + Convert.ToString(attempt) + " attempt left to try.");
        --attempt;
        txtUser.Clear();
        txtPass.Clear();
    }
}

A: If you want to read both the count and the user level you can use the SqlDataReader and ExecuteReader instead of ExecuteScalar(). I made a slight change to your SQL query string. Run this and review your variables to see what you're returning.
SqlCommand scmd = new SqlCommand("select count ([User Level]) as UserCount, [User Level] from tblUsers where [User Name]=@usr and Password=@pwd", scn);
scmd.Parameters.Clear();
scmd.Parameters.AddWithValue("@usr", txtUser.Text);
scmd.Parameters.AddWithValue("@pwd", txtPass.Text);
scn.Open();

string userLabel = "";
int userCount = 0;
try
{
      SqlDataReader reader = cmd.ExecuteReader();
      if (reader.Read())
      {
        userLabel = (string)reader["User Level"];
        userCount = (int)reader["UserCount"];
      }
 }
 catch (Exception ex)
 {
      //do something here if it fails.
 }

if (userCount == 1)
{
     MessageBox.Show("You are granted with access.");
     //rest of your code....
}

Maybe your query is just not returning 1 user as you're expecting. Try running the query in your db to see what it's returning. If this is the case then adjust the code as needed.

A: If want to read all data from table then please use this code.
    SqlCommand scmd = new SqlCommand("select * from tblUsers where [User Name]=@usr and Password=@pwd", scn);
    DataTable result = new DataTable();
    using (SqlDataReader reader = scmd.ExecuteReader())
    {
     result.Load(reader);
    }

then you can read data from table column.use this code
    result.Load(reader);
    var userLevel=result[0]["User Level"]

A: Your problem resides in your SQL query.
select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd

You are selecting a COUNT() and not the actual [User Level]. The COUNT() will always return a number, in this case 1 if an user with the supplied username and password exists (if it has a PRIMARY KEY) or 0 if it doesn't. You should try changing the query to:
select [User Level] from tblUsers where [User Name]=@usr and Password=@pwd

Then you can check it's user level with
string userLevel = scmd.ExecuteScalar();

If userLevel == null then the username does not exists (or doesn't have the supplied password). Keep in mind that if the value of [User Level] is NULL in your database, the ExecuteScalar() will return a DBNull which can't be cast into a String and will fail.

A: I changed my code and send a String to the mainform in a label form. I used sqladapter instead of sqlcommand.
if (dt.Rows.Count == 1)
            {
                if (dt.Rows[0][0].ToString() == "Admin")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
                else if (dt.Rows[0][0].ToString() == "User")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
            }


text:
Q: Why can't I sign up to Intel XDK? I can't seem to sign up to Intel XDK, I get the following error:

sendCommand : Error Parsing JSON Response

Intel XDK Version: xdk_web_win_master_0769

A: You need to provide more information regarding what you are doing and what is occurring, but it might be worth noting that Intel XDK is no longer around therefore the services themselves might have been retired (or they might no longer allow new registrations).

NOTE: As of August 16, 2017, Intel® App Preview has been retired and is no longer available in the respective mobile app stores; if you already have a copy of Intel App Preview on your test device it will continue to work, but you can no longer download it from a mobile store for new installations.

What I can suggest is what the XDK team were suggesting was to check out Cordova or what I would suggest is use something like Ionic
For more information, please read this article.

redpajama_set_name: RedPajamaStackExchange


text:
Q: sha256 based on different outcomes Is it posible to know the $server_seed value based on the different outcomes of this code?
$server_seed = "**4799e37e2f397e6196813367a11042335521f8d2**"; (unknown value)

$round_id = 73904; (known value);

$round_date = "2016-01-23-11-59-37"; (known value)

$hash = hash("sha256", $server_seed . "-" . $round_id . "-" . $round_date);

$roll = bcmod(hexdec(substr($hash, 0, 8)), 15);

echo $roll;

The code gives a value betwen 0 and 14 every time that $round_id increases by 1 and $round_date is increased by 45 seconds. I have access to tons of different outcomes and I know their $round_id and $round_date, but $server_seed is unknown (is always the same lenght).
My question is if there is a way to know the $server_seed value using different outcomes, like making a code that checks the different $server_seeds values and tells you what values would give you the outcomes you inserted.
Is there anyway to get the $server_seed value in a easy and simple way?

A: There is no simple way. Sha256 is a cryptographic hash function and completely satisfies the definition of such function:

A cryptographic hash function is a hash function which is considered
  practically impossible to invert.

Presently no successful attacks have been reported on SHA-2
As the other answer notes, only brute-force attack is possible that is unfeasible to perform at the current state of the existing computing technologies and hardware.

A: No simple way. Dictionary or brute force.


text:
Q: Replace string with file content $ cat input.txt
abc
$ sed -e '/PLACE_HOLDER/ {
    s/PLACE_HOLDER//g
    r input.txt
}' <<< '
PLACE_HOLDER
'

abc

I try to replace PLACE_HOLDER with the content of a file. But it pastes the file content after the matching line. How to just replace the match?
This is not a duplicate of
Use the contents of a file to replace a string using SED

*

*none of the answers there answer my question specifically. For the 2nd one, which use a bash variable. It is not appropriate when the file is very large. For the first one does not have the problem in my example. In fact, my code is exactly the same as the first answer.

A: This might work for you (GNU sed):
sed -i 's/PLACE_HOLDER/$(cat input.txt)/g;s/.*/echo "&"/e' file

Substitute the evaluated expression cat input.txt for each match of PLACE_HOLDER globally throughout file.

A: Like you discovered, the r command inserts new lines after the current line.
That's not suitable if you want to embed the contents of another file in the middle of other text on the same line which should not be replaced.
A crude fix is to build a sed script from your input file. Notice then that any & characters in the input file have to be escaped, as well as any literal newlines.
Because we will be escaping ampersands, I decided to use that as the separator for the s command, too.
sed 's/\&/\\&/g
     1s/^/s\&PLACE_HOLDER\&/
     $!s/$/\\/
     $s/$/\&/' input.txt |
sed -f - targetfile

Unfortunately, because standard input is tied to -f - your script can't process standard input for replacements. A simple workaround for that is to save the generated sed script to a temporary file and pass that as the value for the -f option; this will also be necessary if your sed is one which does not accept the script on standard input.
I believe this should be reasonably portable, apart from the notes about -f - above.
Demo: https://ideone.com/oVgIni

A: Using any awk:
$ awk '
    BEGIN { old="PLACE_HOLDER" }
    NR==FNR { new=(NR>1 ? new ORS : "") $0; next }
    s=index($0,old) { $0=substr($0,1,s-1) new substr($0,s+length(old)) }
    { print }
' input.txt - <<< '
PLACE_HOLDER
'

abc

The above will work no matter which characters are present in the string you want to match or the file you want to replace it with.


text:
Q: objective-c memory friendly way for background image i have an ipad app (>30 views / pages) each view has a unique background.
the problem:
whats the best way to set the background (memory friendly)
is there a better way than adding: uiimageview "backgroundView" as a subview?
version1:
[[UIImage alloc] initWithData:imageData];

which seems to be problematic with the retina switch
version2:
self.layer.contents = (id)image.CGImage;

version 3:
UIImage* image = [UIImage imageWithContentsOfFile:fileLocation];

version 2 seems to work fine. maybe someone tell me whats the best approach, and why ;)
thank you
Alex

A: CGImage is problematic with retina ... version3. is best for memory friendly !

A: In version 2, you generate a new image object which you have to release manually if you don't use ARC. Version 3 uses an autoreleased object.
Both versions are equal in memory-friendlyness.
I'd prefer version 3 because you don't have to do anything yourself to free the memory.
You could also use [UIImage imageNamed:@"image-name.png"], which also generates an autoreleased object.
If you want it as memory-friendly as possible, you should consider using PVR images, as those are natively supported by the graphics hardware.
Best,
Flo


text:
Q: Does the air pressure inside a box remain the same after it is sealed? Let's assume that the pressure is 1 atm outside the sealed box. I think that the pressure inside the box will be the same at 1 atm. But why?
Isn't the giant column of air above causing pressure stopped when I seal the box?

A: Short answer: Assuming you simply sealed the box while the air inside is at atmospheric pressure, then yes, it will stay that way.
Why: Without getting too into the weeds: microscopically, pressure is the result of the little air molecules bouncing against a surface. In this case, the surface is the side of a box. Each molecule bouncing imparts a small amount of force. If roughly equal particles bounce against both sides of that box side in a given time, the side doesn't move in either direction.
If we simply enclose a parcel of air inside of a boundary without squeezing it or doing anything to it, the same number of particles are in that volume as before and on average will continue hitting the inside and outside of any given side at the same rate as before (or passing a boundary if there's no physical barrier to stop them). Individual particles will not be able to enter or leave the parcel, but since the average number of particles bouncing against either side stay the same, we get the same pressure.

How many particles bounce against the side is governed by how many particles there are in the volume. So more particles -> more bounces -> more pressure. So if we have the same pressure on the inside and outside, we have roughly the same number of bounces on both sides, so the sides don't bulge inward or outward. See further down for a little math that backs this up.
Since the box sides themselves just respond to the bounces on both sides, the air column is still weighing down on the box, but keep in mind that the box is trying to "weigh down" the air inside of it as well, and that air inside is pushing back, which holds up the box, which holds up the air (this is newton's third law "every action has an equal and opposite reaction").
Yes, the atmosphere is pressing against the box from at least the top (and probably the sides as well, assuming they're exposed to the atmosphere). But don't forget that the air inside the box is also pressing back out against the sides of the box, balancing the inward force from the air outside.
Think of any given parcel of air as being "boxed in" on all sides". The air column pushes down on top, but the parcel can't go anywhere, because there's already air in those places blocking it from going into those spaces. The other air parcels are also likewise boxed in, so they can't really go anywhere either. Of course, individual particles can communicate between these parcels, since there's not a real boundary. For every particle that goes one way, another particle slides into the vacated spot, possibly from another parcel. If a real boundary did suddenly happen (for instance, we put a cap on a flat tire), the particles simply wouldn't be able to move between parcels, but the overall number of particles in a parcel would remain the same.

Fact: $$\text{Area of the side of the inside of the box} = \text{Area of the side on the outside of the box}$$ $$\text{Force}=\text{Pressure}*\text{Area}$$
Since $P_\text{inside} = P_\text{outside}$ and $A_\text{inside} = A_\text{outside}$, then $$F_\text{inside} = F_\text{outside}$$ for each side. Which means that the box isn't going to collapse because the forces from the air inside and outside balance out.
If you're wondering about what's supporting the column of air outside of the box, if you seal 1 Atm of air inside it, then that air inside is what's supporting it (it's basically like a solid block as far as the air column cares). The box itself only contains the volume, and doesn't provide any support here, per se.
If the box were sealed with a vacuum inside (0 Atm), and the box were strong enough not to collapse, then that means the physical material of the box itself is supporting the air column. That situation is a little different. You'd have to have a pretty strong box, otherwise you get things like this: https://www.youtube.com/watch?v=Zz95_VvTxZM

A: Before you sealed the box, the air inside and outside could communicate (exchange pressure waves), and so the pressure everywhere was 1 atm.  If there were any minute differences, they would have exchanged pressure waves and the gas would have moved until it equalized.
Once you seal the box, however, they both begin at 1 atm, but nothing is actively keeping them the same (if the walls are rigid), since pressure waves can no longer travel across the boundary.  If a change occurred, such as the box heating or cooling, or else ambient atmosphere dropping from 1 atm to .999 atm due to weather, the two pressures would be different.
This is the case for any air tank, scuba tank, or even your house to a extent.  Ventilation systems must be designed to allow the inside and outside to exchange air appropriately with temperature and weather swings, or else pressure imbalances would develop that could break walls or other structure.


text:
Q: Euler's constant greater than 0 for all values of n? If Euler's constant is described as the limit as n approaches infinity of the following:
$$t_n = 1 + \frac 12 + \frac 13 \cdots + \frac1n -\ln(n)$$
How can one prove that $t_n$ is greater than $0$ for all values of $n$?
Thanks!

A: First we have
$$\log (k+1)-\log k=\int_k^{k+1}\frac{1}{u}\,du\le \frac{1}{k} \tag 1$$
Next, we can sum both sides of $(1)$ to reveal that
$$\sum_{k=1}^n \left(\log (k+1)-\log k\right)=\log (n+1)\le \sum_{k=1}^n \frac{1}{k}\tag 2$$
Thus, we see that $(2)$ implies that
$$\sum_{k=1}^n \frac{1}{k}-\log (n+1)\ge 0$$
and therefore
$$\sum_{k=1}^n \frac{1}{k}-\log n > 0$$

A: First, put $s_n = 1+\dfrac{1}{2}+\cdots + \dfrac{1}{n}$, then
$1+\dfrac{1}{2}+\cdots + \dfrac{1}{n} - \ln n > 0$ because:
$1 = \displaystyle \int_{1}^2 1dx \geq \displaystyle \int_{1}^2 \dfrac{1}{x}dx$,
$\dfrac{1}{2} = \displaystyle \int_{2}^3 \dfrac{1}{2}dx \geq \displaystyle \int_{2}^3 \dfrac{1}{x}dx$, and
$.....$
$\dfrac{1}{n-1} = \displaystyle \int_{n-1}^n \dfrac{1}{n-1}dx\geq \displaystyle \int_{n-1}^n \dfrac{1}{x}dx$, and add these integrals we have:
$s_n = s_{n-1} + \dfrac{1}{n} \geq \displaystyle \int_{1}^n \dfrac{1}{x}dx + \dfrac{1}{n}=\ln n + \dfrac{1}{n} > \ln n\Rightarrow t_n = s_n - \ln n > 0$

A: By Abel's summation $$\sum_{k\leq n}\frac{1}{k}=1+\int_{1}^{n}\frac{\left\lfloor t\right\rfloor }{t^{2}}dt\geq1+\int_{1}^{n}\frac{t-1}{t^{2}}dt=\log\left(n\right)+\frac{1}{n}>\log\left(n\right)
 $$ where $\left\lfloor t\right\rfloor
 $ is the floor function.

A: Since the function $x \mapsto 1/x: ]0, \infty[ \to \mathbb{R}$ is strictly decreasing, we have $\sum_{k=1}^{n}\frac{1}{k} > \int_{x=1}^{n+1}\frac{1}{x} = \log (n+1)$ for all $n \geq 1$. But, since $\log (n+1) > \log n$ for all $n \geq 1$, we have $\sum_{k=1}^{n}\frac{1}{k} - \log n > 0$ for all $n \geq 1$.

A: Since $1+x\le e^x$ for $x\in\mathbb{R}$, we have that $\log(1+x)\le x$ for $x\gt-1$. Thus, for $x=-\frac1n$,
$$
\begin{align}
\frac1n-\log\left(\frac{n}{n-1}\right)
&=\log\left(1-\frac1n\right)-\left(-\frac1n\right)\\
&\le0\tag{1}
\end{align}
$$
Inequality $(1)$ means that
$$
\sum_{k=1}^n\frac1k-\log(n)\tag{2}
$$
is a decreasing sequence.
However, using the standard comparison of sum and integral of a decreasing function,
$$
\begin{align}
\sum_{k=1}^n\frac1k
&\ge\int_1^{n+1}\frac1x\,\mathrm{d}x\\
&=\log(n+1)\\[8pt]
&\ge\log(n)\tag{3}
\end{align}
$$

Inequality $(3)$ answers the question. In addition, it shows that $(2)$ is not only a decreasing sequence, but also bounded below by $0$. This means that $(2)$ decreases to a non-negative limit.

This limit is known as $\gamma$, the Euler-Mascheroni Constant, and a fairly simple and efficient method for computing $\gamma$ is derived in this answer.


text:
Q: How to pass Object to FragmentActivity I have an android application that have an activity with FragmentTabHost.
So this is the xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4d4d4d"
    android:baselineAligned="false"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:layout_weight="4"
            android:orientation="vertical">

            <EditText
                android:id="@+id/editDescrizione"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:hint="@string/inserisciragioneSociale"
                android:inputType="text"
                android:singleLine="true" />
        </LinearLayout>

        <ImageButton
            android:id="@+id/ImageButton02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="@null"
            android:onClick="checkCliente"
            android:src="@drawable/search_" />
    </LinearLayout>

    <android.support.v4.app.FragmentTabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

</LinearLayout>

This is the java class:
protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_clienti);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

        mTabHost.addTab(
                mTabHost.newTabSpec("tab1").setIndicator("Tab 1", null),
                infoCliente.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec("tab2").setIndicator("Tab 2", null),
                infoCliente.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec("tab3").setIndicator("Tab 3", null),
                infoCliente.class, null);

        apriConnessioneDB();
    }

public void ricercaCliente(String ragioneSociale){
        List<Cliente> listaClienti = db.fetchClienti(ragioneSociale);
        Cliente cliente = null;
        if(listaClienti==null || listaClienti.size()==0){
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle(R.string.AlertErrore_Titolo);
            // Setting Dialog Message
            alert.setMessage(R.string.AlertErroreClienteInesistente_Descrizione);
            alert.show();
        }else if(listaClienti.size()==1){
            //nel database � presente un solo articolo
            //in base ai criteri di ricerca
            cliente = listaClienti.get(0);
            TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

//          creaAlertQuantita(articolo);
        }else{

            //se ci sono pi� articoli in base al criterio di ricerca,
            //devo mostrare l'alert con una lista
            List<String> lista = new ArrayList<String>();
            for(Iterator<Cliente> it = listaClienti.iterator(); it.hasNext();){
                Cliente cliente2 = it.next();
                lista.add(cliente2.getDescrizione());
            }
            final CharSequence[] items = lista.toArray(new String[lista.size()]);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Più clienti trovati");
            builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String descrizione= (String) items[which];
                    List<Articoli> listaArticoli = db.fetchArticoli("",descrizione);
                    if(listaArticoli!=null && listaArticoli.size()==1){
                        Articoli articolo = listaArticoli.get(0);
                        //creaAlertQuantita(articolo);
                        //alertArticoli.dismiss();
                    }else{

                    }
                }
            });
            alertArticoli = builder.create();
            alertArticoli.show();
        }
    }

Now I want this, when the user check a shipper by EditTextView, I have from database an Object. I want insert the information of this object in the Fragment.
Now in the onCreate method I have insert in all tab, the same class, but I will to create three different class for the three tabs.

A: It seems you can add arguments to the tab via the Bundle paramaneter that you have now set null.
mTabHost.addTab( mTabHost.newTabSpec("tab1").setIndicator("Tab 1", null), infoCliente.class, null);

So instead of setting Bundle to null, you can do something like this:
  mTabHost.fragment = Fragment.instantiate(mContext, mTabHost.clss.getName(), mTabHost.args);

Check out this link for more info:
Android : passing parameters to a tab

A: You can create Bundle and use putExtra() method to put your Object. Then you must retrieve it in your Fragment in onCreate().
If you cant putObject`, try to use GSON library.


text:
Q: Issue Installing Knot Theory I have been trying to install the Knot Theory package from the knot atlas, but have been unsuccessful. Firstly I tried the command
<< KnotTheory`

but received a failure message. I then proceeded to modify the directory using the the AppendTo[$Path, "DIRECTORY"] command, and still receive the same failure message.
What is going wrong?

A: Here is my workaround for this problem. (The package is assumed to be unzipped in "C:/Parent" directory.)
(1) Find the "init.m" file in the directory "C:/Parent/KnotTheory".
(2) Open the file with a text editor, and replace the lines 51-53
    KnotTheoryDirectory[] = (File /.Flatten[FileInformation[ToFileName[#,"KnotTheory"]] & /@ ($Path /. "." ->Directory[])])

by
KnotTheoryDirectory[] = "C:/Parent"

(3) Save the "init.m" file.
(4) Add the installation directory to the search path:
AppendTo[$Path,"C:/Parent"]

(5) You can use the package by
Needs["KnotTheory`"]

A: i downloaded and unzipped the package in
C:\Parent

Appended the path as it is explained:
AppendTo[$Path, "C:\\Parent"]

There were some errors during the import
<<KnotTheory`
ParentDirectory::nums: Argument File should be a positive machine-size integer, a nonempty string, or a File specification.
ParentDirectory::nums: Argument File should be a positive machine-size integer, a nonempty string, or a File specification.
ToFileName::strse: String or list of strings expected at position 1 in ToFileName[{File,WikiLink,mathematica}].
ToFileName::strse: String or list of strings expected at position 1 in ToFileName[{File,QuantumGroups}].
Loading KnotTheory` version of September 6, 2014, 13:37:37.2841.
Read more at http://katlas.org/wiki/KnotTheory.

but some of the functions work:
In[8]:= KnotTheoryVersion[]
Out[8]= {2014,9,6,13,37,37.2841}

Mathematica version: 12


text:
Q: Adding a common, background box with different colors by column, to bootstrap row I am learning bootstrap now, and am trying to make a simple website. I created a row with 3 columns (sizes: 3,6,3), each with it's own text elements. I wanted the first and last column to be colored in red and the middle in grey. I used a background-color in css to do this, but I see that the color envelopes just around the text elements. Is there any way to quickly add a bar of different colors but same height? The image here may help better understand the problem. I could create a new bootstrap row with a bar and add it behind them, but wanted to know if there's a simpler solution. The html and css are as follows.

 231

Enthusiasts

 Kanye West

 Kanye Omari West is an American hip hop recording artist, record producer, rapper, fashion designer, and entrepreneur.West is one of the best-selling artists of all time, having sold more than 32 million albums and 100 million digital downloads worldwide.

 Follow

 Events

 Blog

CSS:
    .leftbar .col-xs-3 {
    background-color:red;
    color:white;
}

.middlebar .col-xs-6 {
    background-color:grey;
    color:white;
}

.rightbar .col-xs-3 {
    background-color:red;
    color:white;
}

Thanks in advance!

A: Set the same height to columns is a quite common problem.
I use a jquery plugin that force the same height to all columns of the row.
http://brm.io/jquery-match-height/


text:
Q: forall - Prolog Can someone explain how should the predefine predicate forall to find the minimum values within a list?

A: or you can use the predicate findall/3
findall(Value, minimumValues(Value), minimumValuesList)

it returns a list (minimumValuesList) with elements (all the minimum values, right).

A: Why do you want to use forall/2 to find the minimum?!
For the standard (linear) solution for picking the minimum/maximum/... element from a list look at SWI-Prolog's min_list/2:
?- listing(min_list).
lists:min_list([], A, A).
lists:min_list([A|C], B, E) :-
        D is min(A, B),
        min_list(C, D, E).

lists:min_list([B|A], C) :-
        min_list(A, B, C).

A: For a list L, you can use:
member(Min,L), forall(member(N,L), N>=Min).

However, while this is a nice demonstration of forall, it is not efficient (square complexity instead of linear).

A: Just use this:
minlist([X], X).
minlist([H|T], Min) :-
    minlist(T, Tmin),
    Min is min(H, Tmin), !.


text:
Q: Port forwarding doesn't work? I set up a linux box a few days ago to host a web server (nginx). The site is ilan.duckdns.org, and I can connect to it fine using my local IP as well as the external IP. However, when I use canyouseeme.org to check whether the ports are forwarded, it says that the connection timed out. I asked my friends from abroad to test, and they can't connect to it either. I can use my phone's mobile network to connect to it fine, so I assume that anyone in my country (Israel) can see it just fine. Is this my ISP's fault or is it mine? It doesn't work for MC servers, or tf2 servers, or just about anything. Will replacing the modem work?
I have a Hotbox modem/router (2-in-1), I don't know if the problem is with it or something else. The box is connected to it via LAN cable on the 1st port. Here is a picture of my site working for me. Here is an photo of the (shoddy) port config of my router. My linux box's IP is 192.168.1.30.

A:
Is this my ISP's fault or is it mine?

I had a look at your hotbox configuration.  I see that you have forwarded WAN requests on port 80 to port 8080 on your Nginx server, but I believe nginx listens on port 80 by default.  Unless I'm wrong or you've set that up yourself I would forward to port 80 on your nginx box instead.  Also, I'm assuming that the "0.0.0.0" addresses in the "external" column act as wildcards or something, which seems to be the case.  Also, your ability to establish a connection using your external (WAN) address means that your port forwarding is working properly on the boxes in which you tried that.  If we've addressed those items we can eliminate the hotbox as the culprit, because it doesn't know or care which country a request comes in from, it just waits for them and serves them to wherever it's supreme ruler (you) tell it.

Will replacing the modem work?

Nope.  If you've got a 2-in-1 box then the modem is inside there too, and we already see that requests are making it through intact.
The question I would be asking at this point is why are requests from other countries not making it through.  I suspect the answer is that your ISP is interfering for some reason.  I would call them, politely ask to speak with a technical person and walk through the situation we've outlined with them.  If they are doing some kind of filtering intentionally, he will likely know exactly you're talking about, and whether or not he can do anything about it.
Best of luck,
Ryan

A: It looks to me like your ISP is blocking the traffic.  Here are the last few lines from a traceroute I did:
9    37 ms    34 ms    36 ms  he-0-10-0-1-pe03.1950stemmons.tx.ibone.comcast.net [68.86.86.114]
10    34 ms    39 ms    35 ms  173.167.57.146
11   188 ms   187 ms   188 ms  et-11-3-0.catania7.cat.seabone.net [93.186.129.223]
12   217 ms   225 ms   221 ms  hot.catania7.cat.seabone.net [93.186.129.237]
13   215 ms   218 ms   215 ms  mx-pt-ae7-vl18.hotnet.net.il [213.57.0.217]
14   211 ms   211 ms   212 ms  core-213-57-0-142.ptr.hotnet.net.il [213.57.0.142]
15     *        *        *     Request timed out.

As you can see the traffic gets to the "core" router on the hotnet network, and then stops there.  So, there is not much you can do.  Your best bet would probably be to find some cheap hosting somewhere and host your services there instead.


text:
Q: How to make this MYSQL outer join work I have 4 tables:
comment (CommentID, StoryID, UserID, CommentContent),
vote (VoteID, UserID, AnswerID),
answer (AnswerID, StoryID, AnswerContent),
user (UserID, Username)

So I want to get all the comments of story 8 along with the info of the users who make those comments (including their voting information). Not all users who make comments would vote. So this is my query but it didn't work
SELECT * FROM comment a
  LEFT JOIN vote b ON a.UserID = b.UserID
  JOIN answer c ON b.AnswerID = c.AnswerID
  JOIN user d ON a.UserId = d.UserID
GROUP BY a.CommentID HAVING a.StoryID = 8

I don't know why this query shows the vote result of commenters who don't vote. Would you please help me to fix it? Thank you so much.

A: Your GROUP BY and HAVING clauses are incorrect.
SELECT * FROM comment a
  LEFT JOIN vote b ON a.UserID = b.UserID
  JOIN answer c ON b.AnswerID = c.AnswerID
  WHERE a.StoryID = 8


text:
Q: Update SQL Server Pivot with new month's data I have a pivot table in SQL server which I created with a query. The columns are months, and the rows are by Customer IDs, with the values in the pivot being sums of their subscription amounts for each month. I'd like to be able to update this every month with the new data for that month, but I'm not sure how to do this short of completely re-creating the table.
Is there a way to create a new column (for the new month) and use UPDATE to populate it with the summed subscription amounts by customer?
This is my query that created the table:
SELECT * INTO [Service Contract Data].[dbo].[Pivot_Results] FROM [Service Contract Data].[dbo].[filtered_data]
PIVOT (SUM([Service Contract Data].[dbo].[filtered_data].[Subscription Amount])
FOR filtered_data.[Month]
IN([2013-01-01 00:00:00.00],[2013-02-01 00:00:00.00],[2013-03-01 00:00:00.00],[2013-04-01 00:00:00.00],[2013-05-01 00:00:00.00],[2013-06-01 00:00:00.00],[2013-07-01 00:00:00.00],[2013-08-01 00:00:00.00],[2013-09-01 00:00:00.00],[2013-10-01 00:00:00.00],[2013-11-01 00:00:00.00],[2013-12-01 00:00:00.00],[2014-01-01 00:00:00.00],[2014-02-01 00:00:00.00],[2014-03-01 00:00:00.00],[2014-04-01 00:00:00.00],[2014-05-01 00:00:00.00],[2014-06-01 00:00:00.00],[2014-07-01 00:00:00.00],[2014-08-01 00:00:00.00],[2014-09-01 00:00:00.00],[2014-10-01 00:00:00.00],[2014-11-01 00:00:00.00],[2014-12-01 00:00:00.00],[2015-01-01 00:00:00.00],[2015-02-01 00:00:00.00],[2015-03-01 00:00:00.00],[2015-04-01 00:00:00.00],[2015-05-01 00:00:00.00],[2015-06-01 00:00:00.00],[2015-07-01 00:00:00.00],[2015-08-01 00:00:00.00],[2015-09-01 00:00:00.00],[2015-10-01 00:00:00.00],[2015-11-01 00:00:00.00],[2015-12-01 00:00:00.00],[2016-01-01 00:00:00.00]))
AS PVT;


text:
Q: Android Button and Variable I have a few buttons and I want to log the ID of the pressed button and undo it's action?
This is one of my buttons:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
   switch (v.getId()) {
   case R.id.btn1:
      // More code here...
      btn1.setVisibility(View.INVISIBLE);
break;
   case R.id.btn2:
   // More buttons...

I'm trying to get the last pressed button's ID and make it visible again when pressing an "UNDO" button.
How can I accomplish this? Thanks!

A: If you just want to toggle the visibility of the clicked view, there is no need for all that code.
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
   boolean vis = v.getVisibility();
   v.setVisibility(!vis);
}

Ok... To answer your updated question.
1) Create a class level variable.
private int mLastClickedId = -1;

2) In your undo-able buttons onClick store the Id of the clicked view into your variable.
Override
public void onClick(View v) {
    // Store the clicked view's Id
    mLastClickedId = v.getId();
}

3) In your undo button's onClick.
Override
public void onClick(View v) {
    // Fisrt make sure one of the undo-able buttons has been clicked.
    if (mLastClickedId != -1) {

        // Get the last clicked view
        View targetView = (View)findViewById(mLastClickedId);

        // Set its visibility
        targetView.setVisibility(View.VISIBLE);
    }
}

This provides a simple single undo. It could easily be modified using an array to store a history of clicked Ids.


text:
Q: nsoperationqueue with priority \ heap I'm building an ios app in which I need to control the download of multiple files (images but not just). I will need to prioritize the download of the files, which may change as the user interacts with the application.
I there any method to set the order in which operations are stored in nsoperationqueue. What I'm looking for is a heap data structure with the built in functionality of nsoperationqueue.
What would be the best way to achieve this?

A: There is a setQueueProperty method in NSOperation that can help you.
From Apple Docs:

Sets the priority of the operation when used in an operation queue.
  You should use priority values only as needed to classify the relative
  priority of non-dependent operations. Priority values should not be
  used to implement dependency management among different operation
  objects. If you need to establish dependencies between operations, use
  the addDependency: method instead.
If you attempt to specify a priority value that does not match one of
  the defined constants, this method automatically adjusts the value you
  specify towards the NSOperationQueuePriorityNormal priority, stopping
  at the first valid constant value. For example, if you specified the
  value -10, this method would adjust that value to match the
  NSOperationQueuePriorityVeryLow constant. Similarly, if you specified
  +10, this method would adjust the value to match the NSOperationQueuePriorityVeryHigh constant.

Read more


text:
Q: Will throwing an exception in a catch block lead to two exceptions being in flight? Consider the following C++ code:
class MyException {};

void someFunction()
{
    try
    {
        /// ... code that may throw
    }
    catch(std::exception& e )
    {
        throw MyException();
    }
}

Question
Is the exception e absorbed at the beginnging of the catch block or at the end of the catch block?
In the second case throwing the new exception would result in having two exceptions in flight, what is not what I want. I want to absorb the std::exception and start one of my own type.

A: No. That's how one should do it. The throw myException() can only occur if the first exception has been caught and hence is no longer 'in flight'.
This design pattern is quite common to 'translate' error messages coming from another library that your code is using to an error that the user of your code can better relate to.
Alternatively, if you want to do more than merely throw (say you want to do some clearing up of resources -- though that should really be done via RAII, i.e. from destructors), then you can simply rethrow the original exception via
try
{
    // ... code that may throw
}
catch(...) // catches anything
{
    // ... code that runs before rethrowing
    throw;    // rethrows the original catch
}

A: just throw; statement is enough in catch block to rethrow same exception in higher context.
It throws SAME exception again. No new exception is generated. So no fight :)
In case you want to catch exception of type A and then throw exception of type B, then the way you did it is absolute correct.
In this case, old exception (type A) is caught(absorbed) and only new exception(type B) is thrown to higher context. So, again no fight :)


text:
Q: Set ant bootclasspath: JDK 1.7 has a new javac warning for setting an older source without bootclasspath How do I set the ant bootclasspath in conjunction with -source 1.5 -target 1.5?
How can this not be a hardcoded path to the 1.5 JDK? Can I set an environment variable to bootclasspath similar to how JAVA_HOME can be used from ant?
Ideally I would like to do something like set an environment variable or pass an argument to ant.

A: It's worth noticing that variable JAVA5_BOOTCLASSES should contain all needed libraries not just rt.jar. In my case it was also jce.jar So it's good to set this variable using this simple snippet when in *nix environment:
export JAVA5_BOOTCLASSES=""
for i in /usr/lib/jvm/java/jre/lib/*.jar; do
    export JAVA5_BOOTCLASSES=$JAVA5_BOOTCLASSES:$i
done

A: Here's an illustration of how you might fetch the Java 5 boot classes location from an environment variable, then use it.
First, set the environment variable - say JAVA5_BOOTCLASSES.
The property task gives you access to the environment, then the bootclasspath argument of the javac task passes the setting to the compiler.
<property environment="env" />
<property name="java5.boot.classpath" value="${env.JAVA5_BOOTCLASSES}" />

<javac source="1.5" target="1.5"
       bootclasspath="${java5.boot.classpath}"
       ...
/>

Note that if the environment variable is not set, Ant will ignore it and proceed without - so the compiler will fall back to the default boot classpath.
Another option, if appropriate, is to switch off the warnings, and not bother with the bootclasspath.  Something like
<javac srcdir= ... >
    <compilerarg arg="-Xlint:-options" />
</javac>

But that's likely to expose you to some subtle bugs.


text:
Q: Media Queries - Target iPhone 6/ 6 Plus without older iPhones I am able to target the iPhone 6/ 6 Plus with Media Queries.
/* iPhone 6 */
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) {}

/* iPhone 6 Plus */
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (-webkit-min-device-pixel-ratio: 3) {}

Problem:
It targets all other iPhones (iPhone 6 style - the landscape orientation for older iPhones exceeds 375px).
Is there any way around this or will I have to use JavaScript?
I would also like to target other phones like a Samsung Galaxy S4 (360px).
Cheers.

A: I guess there is not a CSS3 solution to this question?
Most Media Queries will conflict.
I have decided to answer my own question with a JavaScript approach. I hope it helps.
This will cover most scenarios. You can then add different styles for each added class.
The width checks for portrait and the height checks for landscape basically. Pretty simple.
var $banner = $('#banner'),
    h = window.innerHeight,
    w = window.innerWidth;

if (w === 320 || h === 320) {
    //iPhone 5 or below
    $banner.addClass('iPhone');
} else if (w === 375 || h === 375) {
    //iPhone 6
    $banner.addClass('iPhone6');
} else if (w === 414 || h === 414) {
    //iPhone 6 Plus
    $banner.addClass('iPhone6Plus');
} else if (w === 346 || h === 346) {
    //Smart phone e.g. Q10
    $banner.addClass('smartPhoneSmall');
} else if (w === 360 || h === 360) {
    //Smart phone e.g. Samsung Galaxy S3/ S4
    $banner.addClass('smartPhoneMed');
} else if (w === 384 || h === 384) {
    //Smart phone e.g. LG Nexus 4
    $banner.addClass('smartPhoneBig');
} else if (w === 400 || h === 400) {
    //Smart phone e.g. Samsung Galaxy Note
    $banner.addClass('smartPhoneLarge');
}

Phone CSS width reference: http://mydevice.io/devices/
EDIT: I forgot about nesting so you can do it with CSS3
/* Portrait Styles */
@media only screen and (orientation : portrait) {
    @media only screen and (min-device-width: 346px) and (max-device-width: 359px) {
        /* Small Smartphones e.g. Q10 */
        .banner {
            height: 129px;
            width: 346px;
        }
    }
    @media only screen and (min-device-width: 360px) and (max-device-width: 374px) {
        /* Medium Smartphones e.g. Samsung Galaxy S3/ S4 */
        .banner {
            height: 135px;
            width: 360px;
        }
    }
    @media only screen and (min-device-width: 375px) and (max-device-width: 383px) {
        /* iPhone 6 */
        .banner {
            height: 140px;
            width: 375px;
        }
    }
    @media only screen and (min-device-width: 384px) and (max-device-width: 399px) {
        /* Big Smartphones e.g. LG Nexus 4 */
        .banner {
            height: 144px;
            width: 384px;
        }
    }
    @media only screen and (min-device-width: 400px) and (max-device-width: 413px) {
        /* Large Smartphones e.g. Samsung Galaxy Note */
        .banner {
            height: 150px;
            width: 400px;
        }
    }
    @media only screen and (min-device-width: 414px) {
        /* iPhone 6 Plus */
        .banner {
            height: 155px;
            width: 414px;
        }
    }
}

/* Landscape Styles */
@media only screen and (orientation: landscape) {
    @media only screen and (min-device-height: 346px) and (max-device-height: 359px) {
        /* Small Smartphones e.g. Q10 */
        .banner {
            height: 129px;
            width: 346px;
        }
    }
    @media only screen and (min-device-height: 360px) and (max-device-height: 374px) {
        /* Medium Smartphones e.g. Samsung Galaxy S3/ S4 */
        .banner {
            height: 135px;
            width: 360px;
        }
    }
    @media only screen and (min-device-height: 375px) and (max-device-height: 383px) {
        /* iPhone 6 */
        .banner {
            height: 140px;
            width: 375px;
        }
    }
    @media only screen and (min-device-height: 384px) and (max-device-height: 399px) {
        /* Big Smartphones e.g. LG Nexus 4 */
        .banner {
            height: 144px;
            width: 384px;
        }
    }
    @media only screen and (min-device-height: 400px) and (max-device-height: 413px) {
        /* Large Smartphones e.g. Samsung Galaxy Note */
        .banner {
            height: 150px;
            width: 400px;
        }
    }
    @media only screen and (min-device-height: 414px) {
        /* iPhone 6 Plus */
        .banner {
            height: 155px;
            width: 414px;
        }
    }
}


text:
Q: Why does Arrays.sort take Object[] rather than Comparable[]? I was wondering why the sort method of the Arrays class is asking for a parameter of type Object[].  Why the parameter is not of type Comparable[]. If you don't pass a Comparable[] it's generating a ClassCastException.
Why ... public static void sort(Object[] a) and not public static void sort(Comparable[] a) ?
Thanks

A: Because the second form would require a reallocation of the array. Even if you know that your array contains only comparables, you cannot just cast it to Comparable[] if the original type was Object[], since the array type does not match.
You can do:
Object[] arr = new String[0];
String[] sarr = (String[]) arr;

But you can't do:
Object[] arr = new Object[0];
String[] sarr = (String[]) arr;

So it's premature optimization :)

A: Otherwise you can't pass Object[] in.


text: Q: Run scala tests on Android (Sequel to this.)  There's a Java library to which I have added patches for Android support.  I would like to automate testing of the code, but in order to check if it runs properly on Android, I need to test it on Android.  (Current progress here.)  I've moved the main code into a "java" module, and created an "android" module to run the Android instrumented tests (tests that run on a device or emulator).  Now, I'd really prefer to run all the normal tests again but on Android (so nobody has to rewrite all the tests and keep them up-to-date), by e.g. adding a line to the gradle file or creating a symbolic link, but so far I haven't found a gradle command to do it, and a symbolic link did nothing that I could see.  Part of the problem, I think, is that the tests are in Scala.  Is there a way to run Scala tests as instrumented tests on Android?  (Or another way of equivalently solving the problem without a ton of recurring work?)  The easiest probably-doable way that's occurred to me is to add a test in Android that manually calls the other tests (e.g. com.whatever.Tests.testThatThing();), but that requires maintenance as tests are created/removed, and I'm not sure there won't be problems with like, tests not being exported for external use or something.


text:
Q: Scipy fsolve wont accept imginary values I am currently trying to numerically solve a system of non-linear differential equations for Heisenberg Equations of Motion for spin systems. I am currently using scipy's fsolve to do this, however it keeps on complaining that my equations are using complex numbers. Is it possible to use this function with complex numbers? Below is my code
import numpy as np
from scipy.optimize import fsolve

DELTA=1
OMEGA=10
GAMMA=1
J=6

def myFunction(z):
   SZ1 = z[0]
   SZ2 = z[1]
   SZ3 = z[2]
   SP1 = z[3]
   SP2 = z[4]
   SP3 = z[5]
   SM1 = z[6]
   SM2 = z[7]
   SM3 = z[8]

   F = np.empty((9))
   F[0] = -2*1j*OMEGA*(SP1-SM1)-2*1j*J*(SP1*SM2-SM1*SP2)-GAMMA*(SZ1+1)
   F[1] = -2*1j*OMEGA*(SP2-SM2)-2*1j*J*(SM1*SP2-SP1*SM2+SP2*SM3-SM2*SP3)-GAMMA*(SZ2+1)
   F[2] = -2*1j*OMEGA*(SP3-SM3)-2*1j*J*(SM2*SP3-SP2*SM3)-GAMMA*(SZ3+1)
   F[3] = -1j*OMEGA*(SZ1)+1j*DELTA*(SP1)-1j*J*(SZ1*SP2)-0.5*GAMMA*SP1
   F[4] = -1j*OMEGA*(SZ2)+1j*DELTA*(SP2)-2*1j*J*(SP1*SZ2-SZ2*SP3)-0.5*GAMMA*SP2
   F[5] = -1j*OMEGA*(SZ3)+1j*DELTA*(SP3)-1j*J*(SP2*SZ3)-0.5*GAMMA*SP3
   F[6] = 1j*OMEGA*SZ1-1j*DELTA*SM1+1j*J*(SZ1*SM2)-GAMMA*(SM1)
   F[7] = 1j*OMEGA*SZ2-1j*DELTA*SM2+2*1j*(SM1*SZ2-SZ2*SM3)-0.5*GAMMA*SM2
   F[8] = 1j*OMEGA*SZ3-1j*DELTA*SM3+1j*J*(SM2*SZ3)-0.5*GAMMA*(SM3)
   return F

zGuess = np.array([0,0,0,0,0,0,0,0,0])
z = fsolve(myFunction,zGuess)
print(z)

I am predicting the steady state properties, so the equations are equal to 0. SZ, SM and SP are the expectation values.

A: Indeed, fsolve only works with real-valued functions. You likely want to separate real and imaginary parts and solve the system of twice the size.


text:
Q: I want to convert a Widget into a StatelessWidget I have a Widget to build Cards using the data stored in the Firestore i want to convert this Widget into a StatelessWidget to use the buttons of the Card.
This is the Widget
Widget buildProducts(Products products) => Card(
  clipBehavior: Clip.antiAlias,
  child: SizedBox(
    width: 300,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Image(image: NetworkImage(products.imageUrl)),
        ListTile(
          title: Text(products.name),
          subtitle: Text('Precio: ${products.price} \$'),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(0, 0, 8, 8),
              child: ElevatedButton(
                style: ButtonStyle(
                  foregroundColor: MaterialStateProperty.all<Color>(
                    const Color(0xFFFFFFFF),
                  ),
                  backgroundColor: MaterialStateProperty.all<Color>(
                    const Color(0xFF6750A4),
                  ),
                ),
                onPressed: () => showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) => AlertDialog(
                    title: const Text('Subir Producto'),
                    content: const Text(
                        'El producto ha añadido a la base de datos correctamente'),
                    actions: <Widget>[
                      TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: const Text('OK'))
                    ],
                  ),
                ),
                child: const Text(
                  'Añadir al Carro',
                ),
              ),
            ),
          ],
        ),
      ],
    ),
  ),
);

A: Create a  StatelessWidget and pass the Products through constructor and paste the card on return section.

class ProductWidet extends StatelessWidget {
  final Products products;
  const ProductWidet({required this.products,Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      clipBehavior: Clip.antiAlias,
      child: SizedBox(
        width: 300,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Image(image: NetworkImage(products.imageUrl)),
            ListTile(
              title: Text(products.name),
              subtitle: Text('Precio: ${products.price} \$'),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 8, 8),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      foregroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFFFFFFFF),
                      ),
                      backgroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFF6750A4),
                      ),
                    ),
                    onPressed: () => showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) => AlertDialog(
                        title: const Text('Subir Producto'),
                        content: const Text(
                            'El producto ha añadido a la base de datos correctamente'),
                        actions: <Widget>[
                          TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: const Text('OK'))
                        ],
                      ),
                    ),
                    child: const Text(
                      'Añadir al Carro',
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: Detect click on Actionbar's Overflow menu button Can I detect click/tap on the menu button of action bar, i.e. used to show overflow menu items?
By default it opens up the list with one item "Settings". Here is the screenshot:

Until now it is detecting click on "2" but I want to detect click on "1".

A: To detect the click on the overflow menu have such code:
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    if(featureId == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null){
        //overflow menu clicked, put code here...
    }
    return super.onMenuOpened(featureId, menu);
}

@Override
public void onPanelClosed(int featureId, Menu menu) {
    ...
}

To detect click on menu items, in case you have a menu like that :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu2" android:alphabeticShortcut="b"
        android:title="Menu No. 2" android:orderInCategory="2">
        <menu >
        <group android:id="@+id/group2" android:checkableBehavior="single">
            <item android:id="@+id/submenu1" android:title="SubMenu No. 1" />
            <item android:id="@+id/submenu2" android:title="SubMenu No. 2" />
        </group>
        </menu>
    </item>
</menu>

You should be able to detect the click in

onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Log.w("ANDROID MENU TUTORIAL:", "onOptionsItemSelected(MenuItem item)");

    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu2:
        Toast.makeText(this, "Clicked: Menu No. 2", Toast.LENGTH_SHORT).show();
        return true;
        ...
}

A: Finally i found the solution. Override FragmentActivity.onKeyDown
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    switch (keyCode) {

    case KeyEvent.KEYCODE_MENU:
        // Do Sometihng
        break;

    default:
        break;
    }
    return super.onKeyDown(keyCode, event);
}

A: By default clicking on the overflow button shows the options menu, so i believe you should manage to intercept the event, then do what you want by overriding Activity.onPrepareOptionsMenu
This was a little tricky since i couldn't find an id for overflow button, so i used this hack.
In your Activity :
private boolean actionBarClicked = false;

@Override
public boolean onOptionsItemSelected (MenuItem item) {
    if (item.getId() == )
        actionBarClicked = true;
    return false; // Let default processing occur
}

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    if (actionBarClicked) {
        // Overflow button of ActionBar was clicked, do what you want here.
        actionBarClicked = false;
    }
    ...
}

A: If you have setup Toolbar and inflated menu correctly, just use these two function in MainActivity
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    //Perform some action on menu open
    return super.onMenuOpened(featureId, menu);
}

@Override
public void onPanelClosed(int featureId, Menu menu) {
    //Perform some action on menu closed
}

Setup toolbar in onCreate function of MainActivity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

And inflate your menu which is defined in xml file
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.my_menu, menu);
    return true;
}

my_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_something"
        android:title="@string/something_text" />
    <!--Other menu items-->
</menu>


text:
Q: Using table caption on R markdown file using knitr to use in pandoc to convert to pdf I am wondering if it is possible to use the table captions like figure captions using knitr in .Rmd file ?
I saw options for figure caption but I couldn't see the option for the table caption. I also want to remove the message such as "% latex table generated in R 2.15.2 by xtable 1.7-0 package % Wed Mar 06 15:02:11 2013" .
I used X table to create the table: The sample code I used is as follows:
```{r table2, results='asis', message=FALSE}
library(xtable)
print(xtable(head(iris)))
```

The table I got after processing through pandoc is as follows:

I tried to use message=FALSE in Rmd file to get rid of the message shown above. I also want to know if it is possible to automatically add the caption for table in Rmd ?
By caption I mean something like below (this is for the figure) and the figure number is automatically updated.
This output is a snapshot from the pdf generated by pdf using the markdown file created by knitr.

Thank you.

A: You can accomplish this with xtable. Add caption to xtable and comment=FALSE to the print function.
print(
  xtable(
    head(iris),
    caption = 'Iris data'
  ),
  comment = FALSE,
  type = 'latex'
)

See the xtable and print.xtable documentation.

A: If you do not insist on using a LaTeX/HTML-only solution with the otherwise awesome xtable package, you might achieve the same with Pandoc's markdown. One option is to add the caption manually below the table, or use my R Pandoc writer package:
> library(pander)                         # load pkg
> panderOptions('table.split.table', Inf) # not to split table
> set.caption('Hello Fisher!')            # add caption
> pander(head(iris))                      # show (almost) any R object in markdown
-------------------------------------------------------------------
 Sepal.Length   Sepal.Width   Petal.Length   Petal.Width   Species
-------------- ------------- -------------- ------------- ---------
     5.1            3.5           1.4            0.2       setosa

     4.9            3.0           1.4            0.2       setosa

     4.7            3.2           1.3            0.2       setosa

     4.6            3.1           1.5            0.2       setosa

     5.0            3.6           1.4            0.2       setosa

     5.4            3.9           1.7            0.4       setosa
-------------------------------------------------------------------

Table: Hello Fisher!

Then use Pandoc to convert this markdown file to HTML, LaTeX, docx, odt or any other popular document formats.

A: You can insert tables with automatically numbered captions in markdown for processing with pandoc using straight knitr code. Insert this code snippet at the top of your .rmd file:
```{r setup, echo=FALSE}
tn = local({
  i = 0
  function(x) {
    i <<- i + 1
    paste('\n\n:Table ', i, ': ', x, sep = '')
    # The : before Table tells pandoc to wrap your caption in <caption></caption>
  }
})
knit_hooks$set(tab.cap = function(before, options, envir) {
  if(!before)
    tn(options$tab.cap)
})
default_output_hook = knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  if (is.null(options$tab.cap) == F)
    x
  else
    default_output_hook(x,options)
})
```

To insert a numbered table caption:
```{r myirischunk, tab.cap="This is the head of the Iris table"}
kable(head(iris))
```

By overriding the output hook and using tab.cap you don't need to clutter your chunk options with results='asis'.
Thanks Knitr!
PS: If you want to convert to latex/pdf you would probably want latex to number the tables for you. In that case you could change tn(options$tab.cap) to paste('\n\n:', options$tab.cap, sep='') - but I haven't tested this.

A: I know this is since many years ago, but if there is someone like me who arrived here looking for an answer I'll tell you the answer that I found to the same problem.
It was really simply, we just need to put:
```{r mostrarSerie,results='asis',echo=FALSE}
library(xtable)
options(xtable.floating = TRUE)
print(xtable(AP, digits = 0,caption = "Serie de tiempo"),comment = FALSE)
```

The important step is to put into the options xtable.floating = TRUE because so LaTeX will recognize the table.


text:
Q: Sending terminal commands from ssh-remote server back to local through ssh? I'm trying to send terminal commands into my local Mac from my remote linux server. This is currently to generate
local notifications
(using terminal command:
"""osascript -e 'display notification "Message" with title "Title" subtitle "Subtitle" sound name "chimp"')"""

for changes determined by my app running on the server, but I think, if I have this sorted,
I might use this for other uses/sending/exchanging other commands too later.
Currently, I ssh in the server in the first place. I dont fully understand this process as it was preconfigured on my
system. Can someone explain how this can be achieved?
PS: it will be helpful to be able to keep my/local/receiver IP as a variable and use that variable, as I might have to do this with multiple systems or change my own ip sometime. Also, implementing a password protection so only my app/admin can change/use this channel will help.

A: You could make a script on your remote host that:

*

*SSH into your local machine

*executes the osascript command

But you need to configure it so that you don't have to enter a password when the script is SSH to your local machine. To make that work, you can copy the public SSH key of the user on the remote-host (maybe root) into the ~/.ssh/authorized_keys file of the user on your local machine.
On the remote host:
# copy the public key for the user on the remote host to the local host
cat ~/.ssh/id_rsa.pub | ssh <user>@<your-local-machine> 'cat >> ~/.ssh/authorized_keys'

Then write a script and save it on the remote host
#!/bin/bash

ssh <user>@<your-local-machine> osascript -e 'display notification "Message" with title "Title" subtitle "Subtitle" sound name "chimp"'

The program on your remote host can execute that script when it's appropriate.
If you need to SSH into a new machine, you'll have to copy the SSH keys again and change the <your-local-machine> address in the script.


text:
Q: Collapsible Menu Not Staying Open Hello ive  followed the instructions from this webspage Add a Blogger-like collapsible archive block to your Drupal 7 site and suprised myself that everything seems to be 'sort of' working. As you can see from my 'collapsible block' on the right of THIS PAGE that the block doesnt seem to want to stay open when viewing other months. I dont think this was the intended behaviour.
jQuery(document).ready(function($) {
    // init: collapse all groups except for the first one
    $(".view-collapsible-archive ul").each(function(i) {
        if (i==0) {
            $(this).siblings("h3").children(".collapse-icon").text("▼");
        } else {
            $(this).hide();
        }
    });

    // click event: toggle visibility of group clicked (and update icon)
    $(".view-collapsible-archive h3").click(function() {

        var icon = $(this).children(".collapse-icon");

        $(this).siblings("ul").slideToggle(function() {
            (icon.text()=="▼") ? icon.text("►") : icon.text("▼");
        });
    });
});

Could anyone suggest anything to me to make the menu block open on a month when clicked and to close the other 'months'?
thanks

A: It's because of this line:
$(this).siblings("ul").slideToggle

It says: "toggle the state of all the ul elements using a slide animation"
You will want to change this to slideDown when it's hidden in order to show it and slideUp when it's visible in order to hide it.
I would provide a code sample but I'm typing with one thumb on an iPhone at the moment.

A: The problem is that the code you have is already added inside the file http://netmagpie.com/sites/all/themes/feverultra/js/feverultra.js and by adding your file after that, you're binding twice to the event and the function toggles twice, so the elements open and close
If you want to only have one month open then you need to close any open months before opening the one that was clicked, something like:
jQuery(document).ready(function($) {
    // init: collapse all groups except for the first one
    $(".view-collapsible-archive ul").each(function(i) {
        if (i==0) {
            $(this).siblings("h3").find(".collapse-icon").text("▼");
        } else {
            $(this).hide();
        }
    });

    // click event: toggle visibility of group clicked (and update icon)
    $(".view-collapsible-archive h3").click(function() {

       $('.view-collapsible-archive ul:visible').not($(this).next('ul')).slideUp();

        var icon = $(this).find(".collapse-icon");
        $(this).siblings("ul").slideToggle(function() {
            (icon.text()=="▼") ? icon.text("►") : icon.text("▼");
        });
    });
});


text:
Q: Excel VB-Macro values from one column to only alphanumeric values on the next column This is for an EXCEL Visual Basic Macro.
I need to change all column B data to only have alphanumeric characters on column C.
My code works only for one cell. I want to loop this code for every active cell. Can anybody help me on this?
Sub macroalphanum()
    Dim a$, b$, c$, i As Integer
    a$ = Range("C1").Value
    For i = 1 To Len(a$)
       b$ = Mid(a$, i, 1)
    If b$ Like "[A-Z,a-z,0-9, ]" Then
        c$ = c$ & b$
    End If
    Next i
    Range("D1").Value = c$
End Sub

A: You just need to nest your For Loop in another For Loop that goes through each cell
Quick Example:
Sub macroalphanum()
    Dim a$, b$, c$, i As Integer, r as Integer
    For r=1 to 100 step 1  ' This will do it for all rows from 1 to 100. Change it to suit your needs
       a$ = Cells(r,3).Value
       c$ = "" ' (Re)Initialize c
       For i = 1 To Len(a$)
          b$ = Mid(a$, i, 1)
          If b$ Like "[A-Z,a-z,0-9, ]" Then
              c$ = c$ & b$
          End If
       Next i
    Cells(r,4).Value = c$
    Next r
End Sub


text:
Q: snakeyaml dump empty field instead of null I have a LinkedHashMap where some values might be null and I want them to be dumped as empty fields instead of null. Is it even possible or am I wrecking my nerves in vain? Also how can I get rid of the single quotes in case there is an integer printed?
My code:
Map<String, Object> map = org.createOrgYamlMap();
    DumperOptions options= new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    PrintWriter writer = new PrintWriter(new File(orgDirectory.toString() + "/organization.yml"));
    yaml.dump(map, writer);

Gives me the yaml file:
uuid: '123'
name: test1
document_vault: null

What I want:
uuid: 123
name: test1
document_vault:

A: Override representMapping method of Representer class.
Map<String, Object> map = org.createOrgYamlMap();

Representer representer = new Representer() {
        @Override
        protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
            List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
            MappingNode node = new MappingNode(tag, value, flowStyle);
            representedObjects.put(objectToRepresent, node);
            boolean bestStyle = true;
            for (Map.Entry<?, ?> entry : mapping.entrySet()) {
                Node nodeKey = representData(entry.getKey());
                //If value is null then treat it as empty string.
                Node nodeValue = entry.getValue() == null ?
                        representData("") : representData(entry.getValue());
                if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) {
                    bestStyle = false;
                }
                if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
                    bestStyle = false;
                }
                value.add(new NodeTuple(nodeKey, nodeValue));
            }
            if (flowStyle == null) {
                if (defaultFlowStyle != FlowStyle.AUTO) {
                    node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
                } else {
                    node.setFlowStyle(bestStyle);
                }
            }
            return node;
        }
    };

DumperOptions options= new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(representer, options);
PrintWriter writer = new PrintWriter(new File(orgDirectory.toString() + "/organization.yml"));
yaml.dump(map, writer);

Test code:
public static void main(String[] args) throws FileNotFoundException {
    Map<String, Object> lhm = new LinkedHashMap<>();

    lhm.put("c", null);

    DumperOptions options = new DumperOptions();
    Representer representer = new Representer() {
        @Override
        protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
            List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
            MappingNode node = new MappingNode(tag, value, flowStyle);
            representedObjects.put(objectToRepresent, node);
            boolean bestStyle = true;
            for (Map.Entry<?, ?> entry : mapping.entrySet()) {
                Node nodeKey = representData(entry.getKey());
                Node nodeValue = entry.getValue() == null ?
                        representData("") : representData(entry.getValue());
                if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) {
                    bestStyle = false;
                }
                if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
                    bestStyle = false;
                }
                value.add(new NodeTuple(nodeKey, nodeValue));
            }
            if (flowStyle == null) {
                if (defaultFlowStyle != FlowStyle.AUTO) {
                    node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
                } else {
                    node.setFlowStyle(bestStyle);
                }
            }
            return node;
        }
    };

    options.setDefaultFlowStyle(FlowStyle.BLOCK);

    Yaml yaml = new Yaml(representer, options);
    String s = yaml.dump(lhm);
    System.out.println(s);
}

Output:
c: ''

A: Just debated myself with this same question where I wanted null to be printed as ~ instead of null.
As per their tests, you can easily achive by
    public void test() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(FlowStyle.BLOCK);
        Yaml yaml = new Yaml(new NullRepresenter(), options);
        Map<String, String> map = new HashMap<String, String>();
        map.put("uuid", "123");
        map.put("document_vault", null);
        String output = yaml.dump(map);
        assertEquals("uuid: 123\ndocument_vault: ~\n", output);
    }

    private class NullRepresenter extends Representer {
        public NullRepresenter() {
            super();
            // null representer is exceptional and it is stored as an instance variable.
            this.nullRepresenter = new RepresentNull();
        }

        private class RepresentNull implements Represent {
            public Node representData(Object data) {
                return representScalar(Tag.NULL, "~");
            }
        }
    }

Since '' is not part of the allowed values it will be prepended the null tag.
document_vault: !!null ''


text:
Q: How can I use JavaScript in Razor for google maps API I am trying to use a 'foreach' loop to place a series of markers on the map using coordinates from a database. The retrieval of the data is not an issue so for now I'm not bothered about the map showing the correct locations. The issue is that when inside the 'foreach' loop, any code for the marker placement is immediately passed over. Any ideas?
Here is the current code:
<script>
    function myMap() {
        var lat = 52.4283381;
        var lng = -1.601519;
        var myLatLng = { lat: 52.428381, lng: -1.601519 };
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: new google.maps.LatLng(lat, lng)
        });
    }
</script>

<script>
    @foreach (var mapVars in ViewData.Model)
    {
        <text>
        var marker = new google.maps.Marker
        ({
            position: new google.maps.LatLng (52.428381 , -1.601519),
            map: map,
            title: "" + i,
        });

        </text>
    }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>

A: Try serialize your ViewData.Model to a javascript object and than loop from there.
Something like this:
<script>
    function myMap() {
        var lat = 52.4283381;
        var lng = -1.601519;
        var myLatLng = { lat: 52.428381, lng: -1.601519 };
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: new google.maps.LatLng(lat, lng)
        });
    }
</script>

<script>
    window.data = @(Html.Raw(js.Serialize(ViewData.Model)));
    var markers = [];
    for(i = 0; i < window.data.length; i++)
    {
        markers.push(new google.maps.Marker
        ({
            position: new google.maps.LatLng (52.428381 , -1.601519),
            map: map,
            title: "" + i,
        }));
    }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>


text:
Q: Xcode 9.2 certificate used to sign is either expired or revoke I used to run an app on my device with no problem using automatic signing of Xcode. Now suddenly it's giving me this error when running the app:
 the certificate used to sign "app name" has either expired or has been revoked. An updated certificate is required to sign and install the application.
I am using Xcode 9.2 . I have already tried deleting all of "My Certificates" from keychain , deleting all provisioning profiles. cleaning project but none of them helped.
I have seen so many people have this problem solved by Going To Preferences->Accounts->Team -> View Details and Reset the profile. But there is no View Details in my case (Xcode 9.2)
Any ideas what may help?

A: OK I figured it out. The error message was not helping at all.
This was a project actually exported from Unity3D. In Unity3D I have some post build scripts that modifies Xcode project. It was adding a framework as embedded framework in post build script. I just removed the framework from embedded frameworks and add it again (in the general tab) and it fixed the problem.


text:
Q: How to use a 'global' variable in python? In my problem I have a python code that is being started by a user, like:
# file main.py
import sys
import mymodule
config = sys.argv[1]

which imports another module containing functions, classes etc. like
# module.py
def check_config():
    # do something with the content of 'config'
class Module(object):
    # does something with the content of 'config'

How can I access the value of 'config' from within module.py? Should I use a 'global' variable here? Or is there a more sophisticated, pythonic way to solve this problem?
Also, I do not want to define an argument 'config' to each function and class I use in other modules...
Further remark: main.py imports other modules, not the other way around...

A: Instead of trying to wrangle global into performing this you should pass config as a parameter.
file main.py
import sys
import mymodule
config = sys.argv[1]

checked = mymodule.check_config(config)
mod = mymodule.Module(config)

module.py
def check_config(config):
    # do something with the content of 'config'
class Module(object):
    # does something with the content of 'config'
    def __init__(self, config):
        # initialise with config

Always avoid usingglobal when you can. If you need to modify config just have a module function return it.
config = change_config(config)

module.py
def change_config(config):
    ...
    return config

However, an alternative method is to define a value within module.py which will store this information that holds nothing by default. Then as soon as file main.py has imported module.py and the config data is ready, you could assign the data to module.py's config name. Like this:
file main.py
import sys
import mymodule
config = sys.argv[1]

mymodule.config = config

mymodule.test_config()
mymodule.check_config()
mymodule.Module()

module.py
config = None

def test_config():
    print config
    # this will refer to the value supplied from file main.py

Note however, that the values in the module and main file will not be joined. If you reassign config in file main.py for any reason you have to pass that value to the module again. However if you pass a mutable value like a dict or list then you can modify it in file main.py and the values will be shared.

A: I don't recommend using a global variable, but here's the design you should use if you do. config needs to be defined in mymodule; after you import the module, you can set the value of mymodule.config the way you are currently setting config.
# file main.py
import sys
import mymodule
mymodule.config = sys.argv[1]

# module.py
# The exact value doesn't matter, as long as we create the name.
# None is good as it conveys the lack of a value; it's part of your
# module's contract, presumably, that a proper value must be assigned
# before you can use the rest of the module.
config = None
def check_config():
    # do something with the content of 'config'
class Module(object):
    # does something with the content of 'config'

A: A global variable is almost never the answer. Just allow the functions and classes in your "library" (module.py or mymodule.py, you seem to use both) to accept arguments. So:
mymodule.py
def check_config(configuration):
    pass

class Module(object):
    def __init__(self, configuration):
        self.config = configuration

class ConfigError(Exception):
    pass

Then when you want to use them in your "application" code:
main.py
import sys
import mymodule

config = sys.argv[1]

if mymodule.check_config(config):
    myobject = mymodule.Module(config)
else:
    raise mymodule.ConfigError('Unrecognized configuration format.')

A: Could you describe that you app should to do? Because now it's not clear, why you want it.
Maybe environment variable could help you?
Btw, you can read config file in one place (module), and import all stuff you need from it.
config.py
   import os
   if os.environ['sys'] == 'load_1':
        import load_1 as load
        i = 12
   else:
        import load_2 as load
        i = 13

main.py
   import config

   config.load("some_data")
   print config.i


text:
Q: How do I obtain joint distribution of uniform random variables conditioned on a sum constrain? Let us say, we have two random variables,
x1 --> U(10,20) i.e. x1 is uniformly distributed between 10 and 20, and
x2 --> U(20,40) i.e. x2 is uniformly distributed between 20 and 40.
Moreover, it has to be ensured that x1+x2 = 40 always.
How do I compute the joint distribution P(X1,X2|X1+X2=40)?
In other words, how do I find joint distribution based on a sum constraint?

A: The joint density function of continuous random variables $X$ and $Y$ conditioned on $X+Y=a$ does not exist. Conditioned on $X+Y=a$, the random point $(X.Y)$ is constrained to lie on the straight line through $(a,0)$ and $(0,a)$ and so doesn't have a joint density in the sense of $f_{X,Y}(x,y)$ telling you how dense the probability mass is in the vicinity of $(x,y)$: the units are probability mass per unit area and since $(X,Y)$ is constrained to lie on a line (which has zero area!), the only nonzero "value" we can ascribe to the joint density is $\infty$.  What we do have is a line density measured in probability mass per unit length.


text:
Q: Terms related to eye vision What is the particular word we use when we talk about focusing to read a word using our eyes with more stress?
What I want to ask is that there is a piece of writing that is blurred or the light is poor that doesn't allow me to read things clearly so I have to contract my eyes or go closer to the screen, for instance. I have to use more of the natural strength of vision.
Such as when the brightness of the mobile screen is very high or fonts size in a document is very small, or there is direct light on our eyes while we're reading, our eyes have to work harder to read the text to understand words, either by partly closing our eyes or widening them.

A: I would suggest using the word 'strain'.  An example would be:
I had to strain [my eyes] to be able to read the small print.

You could leave out 'my eyes' since very few people would have any difficulty in understanding that you meant your eyes - it is implicit if you leave that out.
Hope that helps,
Alan.


text:
Q: Visibilidade de e-mail e senha após submit (Facebook) Estou com uma duvida em relação à senhas. Resolvi fazer uma "experiência" para ver a segurança dos dados enviados por formulários, e mesmo usando protocolo de segurança notei que é possível literalmente LER e VER a senha enviada.
O navegador envia tudo de forma limpa. Ignorante que sou com o tema segurança, sempre pensei que o navegador enviasse os dados 'obfuscados' ou criptografia e reversão usando SSL.
Usei o Facebook para testar, em outras palavras, é possível encontrar o login e a senha de acesso de uma conta que esteja aberta em uma maquina. Dei um printscreen no console para ilustrar os dados encontrados.

Naturalmente ocultei alguns campos e alterei a senha
Mas a senha exibida no console é a mesma da minha conta no Facebook

Pergunta

*

*O que é possível fazer para se evitar esse tipo de coisa?

*O protocolo de segurança não resolve esse tipo de situação?


text:
Q: How to get C++ code coverage using Bazel? I have a C++ project, and I want to use bazel coverage to get its code coverage information.
However, after running the command, I find the file coverage.dat inside  bazel-testlogs does not contain anything.
So am I looking at the right place? Or is there some problem with Bazel?
I am using Bazel 1.0.0.
Complete Example
WORKSPACE
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

git_repository(
    name = "gtest",
    remote = "https://github.com/google/googletest",
    commit = "3306848f697568aacf4bcca330f6bdd5ce671899",
)

lib/a.cc
int f(int x) {
    if (x == 0)
        return x + 1;
    else
        return 1 + x;
}

lib/BUILD
cc_library(
    name = "a",
    srcs = ["a.cc"],
    visibility = ["//test:__pkg__"],
)

test/my_test.cc
#include "gtest/gtest.h"

TEST(FactorialTest, Negative) {
  EXPECT_EQ(1, 1);
}

test/BUILD
cc_test(
    name = "my_test",
    srcs = ["my_test.cc"],
    copts = ["-Iexternal/gtest"],
    deps = ["@gtest//:gtest_main", "//lib:a"],
)

After I run bazel coverage //test:my_test, I see a file at bazel-testlogs/test/my_test/coverage.dat generated, but it is empty (0 bytes).

A: Currently Bazel coverage <> is only support for Linux.
I created a project using bazel for exporting C++ code coverage (https://github.com/hohaidang/STM32-from-scratch/tree/master/004_SPI_driver_CPP)
Open the unit_test folder for more details about BUILD file
Bazel version 3.5.0
$ bazel coverage unit_test:ut_gpio --combined_report=lcov
$ genhtml bazel-out/_coverage/_coverage_report.dat -o test_coverage
Note: you should put all test files and source files in the same folder. If different folder it will generate invalid .dat file. I still don't know how to fix yet.

A: Run bazel coverage this way:
bazel coverage -s \
    --instrument_test_targets \
    --experimental_cc_coverage \
    --combined_report=lcov \
    --coverage_report_generator=@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main \
    //...


text:
Q: Typescript cannot infer extending type in generics
Typescript cannot infer extending type in generics properly.
But it works as expected with interface.
It shows error only with generics.
Is the extends in interface and generics different?
How can I make the type of second 'const a' to be inferred as boolean?
Playground Link


text:
Q: BackgroundDownloadAsync not downloading? I'm trying to use LiveConnectClient.BackgroundDownloadAsync to copy a file from Skydrive onto my computer. My code is below (this is a C# Metro app running on Win8).
var copy = connect.BackgroundDownloadAsync(f.id, dest);
LiveDownloadOperationResult result = await copy;

The result I get back contains no error, yet when I go have a look I see only the first 1K of my file. So my questions are:

*

*Has someone used BackgroundDownloadAsync successfully?

*Can someone suggest something I might have missed, that would match the symptoms?

Thanks!

A: The answer is to add "/content" to the ID of the file you want to download. Otherwise, you get the metadata.


text:
Q: Custome AngularJS route change page with end of animation callback I created animation whitch is run during route change page. Such like Scotch described here http://scotch.io/tutorials/javascript/animating-angularjs-apps-ngview
It's very good tut but i need to expand this solution by adding there callbacks on end of animation. I could't find easy way to solve my issue. Could you help me with this ?
Best Regards,
Kuba


text:
Q: d3.max doesn't return highest value from csv file I have a small csv file, containing this data:
Organisational Unit,Service Division Label,Category Internal Name,Purpose,Detailed Expenditure Code,Date,Amount,Capital Or Revenue,Benificiary Name
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Operational Materials,205,02/01/2015,35.20,R,A & A Electrical Distributors Ltd
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Operational Materials,205,12/01/2015,72.67,R,A & A Electrical Distributors Ltd
Environment & Housing,Environmental Health,Capital,Construction,3,12/01/2015,72.00,C,A & P Crontractors Ltd
Childrens Services,Safeguarding Targeted & Specialist,Third Party Payments,Section 17,551,02/01/2015,550.00,R,A Ahmadi
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Operational Materials,205,21/01/2015,26.35,R,A Andrews & Sons (Marbles & Tiles)
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Operational Materials,205,21/01/2015,33.32,R,A Andrews & Sons (Marbles & Tiles)
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Operational Materials,205,21/01/2015,51.84,R,A Andrews & Sons (Marbles & Tiles)
Central & Corporate,Commercial Services Trading Services,Supplies and Services,Stores - Central And Other Depots,5,21/01/2015,706.80,R,A Andrews & Sons (Marbles & Tiles)
City Development,Employment & Skills,Supplies and Services,Other Hired And Contracted Services,265,30/01/2015,248.19,R,REDACTED PERSONAL DATA
City Development,Employment & Skills,Supplies and Services,Other Hired And Contracted Services,265,09/01/2015,248.19,R,REDACTED PERSONAL DATA

And also JS code to draw a graph out of this data:
svg = d3.select("body").append("svg").attr({
    width: window.innerWidth - 40,
    height: window.innerHeight
});

var padding = 10,
    radius = 4;

var parse = d3.time.format("%d/%m/%Y").parse;

d3.csv("./spending-small.csv", function(d) { d.Date = parse(d.Date); return d; }, function(data) {

    var max = d3.max(data, function(d) { return d.Amount; });
    console.log(max);

    var dateScale = d3.time.scale()
        .domain(d3.extent(data, function(d) { return d.Date; }))
        .range([50, window.innerWidth - 50]);

    var amountScale = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return d.Amount; })])
        .range([50, window.innerHeight - 50]);

    // Define date Axis
    var dateAxis = d3.svg.axis().scale(dateScale)
        //.tickSize(100 - window.innerHeight)
        .tickSize(1)
        .orient("bottom");

    // Draw date Axis
    svg.append("g")
        .attr({
            "class": "date-axis",
            "transform": "translate(" + [0, window.innerHeight -50] + ")"
        }).call(dateAxis);

    // Define amount Axis
    var amountAxis = d3.svg.axis().scale(amountScale)
        //.tickSize(100 - window.innerHeight)
        .tickSize(1)
        .orient("left");

    // Draw amount Axis
    svg.append("g")
        .attr({
            "class": "amount-axis",
            "transform": "translate(" + 50 + ",0)"
        }).call(amountAxis);

    svg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr({
            cx: function(d) { return dateScale(d.Date); },
            cy: function(d) { return window.innerHeight - amountScale(d.Amount); },
            r: 3,
            fill: "#fff",
            stroke: "#78B446",
            "stroke-width": 2,
            "title": function (d) { return d.Amount; },
            "data-date": function (d) { return d.Date; }
        });

});

Highest value for "Amount" column in my csv file is 706.80, yet
d3.max(data, function(d) { return d.Amount; })

function returns 72.67.
I've checked if data is perhaps corrupted or malformed, but can't see anything wrong with it. What can be a problem here?

A: It turned out that, amount data coming from csv file is an array of strings, rather than numbers, and javascript treats it as this, so for example:
var arr = ["35.20", "72.67", "550.00", "248.19"];
console.log(d3.max(arr));

will return "72.67", but
var arr = [35.20, 72.67, 550.00, 248.19];
console.log(d3.max(arr));

will return 550.00
Hint to that I found here on d3.max documentation.
So solution to that will be to parseFloat(d.Amount) before "maxing" it with d3, as here:
svg = d3.select("body").append("svg").attr({
    width: window.innerWidth - 40,
    height: window.innerHeight
});

var padding = 10,
    radius = 4;

var parse = d3.time.format("%d/%m/%Y").parse;

d3.csv("./spending-small.csv", function(d) { d.Date = parse(d.Date); d.Amount = parseFloat(d.Amount); return d; }, function(data) {

    // var arr = [35.20, 72.67, 550.00, 248.19];
    // console.log(d3.max(arr));

    // var max = d3.max(data, function(d) { return d.Amount; });
    // console.log(max);

    var dateScale = d3.time.scale()
        .domain(d3.extent(data, function(d) { return d.Date; }))
        .range([50, window.innerWidth - 50]);

    var amountScale = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return d.Amount; })])
        .range([window.innerHeight - 50, 50]);

    // Define date Axis
    var dateAxis = d3.svg.axis().scale(dateScale)
        //.tickSize(100 - window.innerHeight)
        .tickSize(1)
        .orient("bottom");

    // Draw date Axis
    svg.append("g")
        .attr({
            "class": "date-axis",
            "transform": "translate(" + [0, window.innerHeight -50] + ")"
        }).call(dateAxis);

    // Define amount Axis
    var amountAxis = d3.svg.axis().scale(amountScale)
        //.tickSize(100 - window.innerHeight)
        .tickSize(1)
        .orient("left");

    // Draw amount Axis
    svg.append("g")
        .attr({
            "class": "amount-axis",
            "transform": "translate(" + 50 + ",0)"
        }).call(amountAxis);

    svg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr({
            cx: function(d) { return dateScale(d.Date); },
            cy: function(d) { return amountScale(d.Amount); },
            r: 3,
            fill: "#fff",
            stroke: "#78B446",
            "stroke-width": 2,
            "title": function (d) { return d.Amount; },
            "data-date": function (d) { return d.Date; }
        });

});


text:
Q: Let $X$ and $Y$.A function $f: X \longrightarrow Y$ is continous if and only if $f^{-1}(C)$ is closed in $C$ for every closed set $C \subset Y$
4.2 Let $X$ and $Y$ topological spaces.A function $f: X \longrightarrow Y$ is continous if and only if $f^{-1}(C)$ is closed in $C$ for every closed set $C \subset Y$

A:
Remark:

Theorem1.2:  Let $f: A \longrightarrow B$, $Y \subset B$ then $f^{-1}(B^{c})=(f^{-1}(B))^{c}$

proof

Let $x\in f^{-1}(B^{c})$ then $f(x)\in B^{c}$, then $f(x)\not \in B$ and therefore $f(x)\not \in f^{-1}(B) \therefore x \in (f^{-1}(B))^{c}$.\
Conversely let $x\in (f^{-1}(B))^{c}$ by definition of pre image $f(x)\in (f^{-1}(B))$ then $f(x) \not \in B$ and $f(x)\in B^{c} \therefore x\in f^{-1}(B^{c})$.

Proof of theorem1.2

Suppose $f: X \longrightarrow Y$ is continuous, by definition consider $W$ open in $Y$ then $f^{-1}(W)=V$ is open in $X$, consider $W/Y$ is close in $Y$ and notice that $f^{-1}(W/Y)=f^{-1}(W)/X=V/X$ (by Remark) which is closed in $X$.
Conversely suppose $C$ is arbitrary closed set in $Y$ and $f^{-1}(C)$ closed set in $X$.\
Since $C$ is closed in $Y$ then $W=C/Y$ is open in $Y$ and $f^{-1}(W)=f^{-1}(C/Y)=f^{-1}(C)/X=V$ which is open in $X$ since $f^{-1}(C)$ is closed in $X$  then their complement is open. Since $C$ was arbitrary closed in $Y$ $f$ is a continuous function.


text:
Q: внешний ключ для полей Varchar. MySQL Пытаюсь добавить внешний ключ в таблицу, но не удается и не понимаю почему.
CREATE TABLE `one` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `имя` VARCHAR(255)
)ENGINE=INNODB;

CREATE TABLE `two` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `имя` VARCHAR(255),
    `фамилия` VARCHAR(255),
    INDEX ind_name (`имя`)
)ENGINE=INNODB;

ALTER TABLE `two` ADD
    FOREIGN KEY (`имя`) REFERENCES `one`(`имя`)

выдает ошибку
#1822 - Failed to add the foreign key constraint. Missing index for constraint 'two_ibfk_1' in the referenced table 'one'

A: Колонка, на которую ссылаются из другой таблицы через foreign key должна иметь индекс, о чём, собственно, текст и говорит

Missing index for constraint 'two_ibfk_1' in the referenced table 'one'

A: Лучший способ понять инструмент, которым пользуешься -- прочитать инструкцию. Иногда кажется, что и так понятно как всё работает, и в документацию можно не заглядывать. Но научитесь начинать расследование неожиданного поведения программы с чтения документации.
У MySQL отличная документация. И в ней сказано:

remember to first create an index on the column(s) referenced by the foreign key

Кроме того там сказано, что такие индексы при необходимости будут созданы автоматически при добавлении ограничения во время создания таблицы. Видимо это поведение и ввело вас в заблуждение.


text:
Q: Wait for process in container to be up before signalling to dependent containers they can start I have a GraphQL container, hitting an Elasticsearch container. Now, in the compose file I have:
depends_on:
      - elasticsearch

but the thing is, the elasticsearch server (being a JVM process) takes time to come up. However, as far as docker is concerned it appears that this makes no difference, so compose then moves on the the GraphQL container...even though the ES is not ready. So, if a user hits the site before the ES is ready the graphql bugs out and crashes..
So, is there a way to signal to dependent containers to check a process is up, maybe first? Or must this be done in the GraphQL code...

A: You can do this via a bash script, and 2 compose files.
You can use curl against elasticsearch to determine its up.
Then use second compose file to bring up the second container(s).