问:
JavaScript Function that creates 4 random numbers that push to an array?
Instead of doing this:

```<code>var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),
</code>```

How can I create a function that returns 4 random numbers?

答:
Use a for loop.

Try this:

```<code>var crystalValues = [];

for(var i = 0;i < 4;i++){
  crystalValues.push(Math.floor(Math.random()*12+1))
}

console.log(crystalValues);
</code>```

Body:
Instead of doing this:

var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),

How can I create a function that returns 4 random numbers?

Body:
Use a for loop.

Try this:

var crystalValues = [];

for(var i = 0;i < 4;i++){
  crystalValues.push(Math.floor(Math.random()*12+1))
}

console.log(crystalValues);


来源: stackexchange

答:
The function below creates an array of random ints.

The count sets how many, min and max set the min and max random values

    function createRandomArray(count,min,max){
        const rand = () =>  Math.floor( Math.random() * (max - min) + min);
        const vals = [];
        while(count-- > 0){ vals.push(rand()) }
        return vals;
    }
    console.log(createRandomArray(4,1,13));

    ```
</div>
</div>
</p>

<p>You can assign them to another array as follows</p>

```const crystalValues = [];
crystalValues.push(...createRandomArray(4,1,13))
```

<p>Or just directly assign them</p>

```const crystalValues = createRandomArray(4,1,13);
```

ContentLicense: CC BY-SA 3.0

Title: JavaScript Function that creates 4 random numbers that push to an array?

Body:
The function below creates an array of random ints.

The count sets how many, min and max set the min and max random values

    function createRandomArray(count,min,max){
        const rand = () =>  Math.floor( Math.random() * (max - min) + min);
        const vals = [];
        while(count-- > 0){ vals.push(rand()) }
        return vals;
    }
    console.log(createRandomArray(4,1,13));

You can assign them to another array as follows

const crystalValues = [];
crystalValues.push(...createRandomArray(4,1,13))

Or just directly assign them

const crystalValues = createRandomArray(4,1,13);


问:
Gitflow, releases and bugs oh my
I'm currently getting my head around gitflow and how releases work in terms of having them deployed to a test server for another team to test and find bugs.

Let's say I have a release version of 1.5 that contains a few small features.

The features are merged into the develop branch and I have now branched from develop to release/1.5.0.

This release branch is now deployed to our test server.

The testing team check the site against the tickets for the features and report back. They find a bug with one of the features.

Now, here is the issue I can see - if I fix the bug, where does that bugfix go? Should I fold it into release/1.5.0 and re-deploy? Or does it get flagged in a new ticket, and added to a fix version of release/1.5.1 to do in a weeks time?

With the later, it would mean that a release gets signed off with bugs intact until they can be addressed further down the road.

The former seems plausible, but then I was under the impression all bugs etc get folded into develop? Meaning release/1.5.0 cannot be re-deployed unless you re-merged develop but that would then encapsulate other bug fixes and features?

All this comes from wanting to utilise JIRA releases, and I was unsure as to when you say a version is ready to be flagged as released and whether you can release it with bugs in tact, knowing they'll be fixed later on?

Do you fix bugs in a currently tested release until they are gone and then release the version?

I'd assume then when you back merge the release branch into develop, the bug fixes are in there also?

答:
With git-flow:

you may add bugfixes to the release branch. You may add them at the same time to a bugfix branch from develop, to merge them into develop ASAP not waiting for the release branch to be merged back.

You may also create a feature-branch for the bugfix, merge that to develop, and merge that to the release branch, or also cherry-pick the bugfix commits.

I believe both adding a patch to the release branch as well as adding it to develop are important, but several options are valid, so you still need to compare options.

Title: Gitflow, releases and bugs oh my


问:
Implementing parental control on websites using java
I want to code a standalone app in java to control access to restricted websites while kids use internet when parents are not around. The main idea is to block the adult/unwanted websites based on the person who is browsing. The use-case goes like this:

1.The user opens a browser.
2.Our app (which is running in the background) should pop up an authentication box and ask the user to enter a password.
3.Based on the password entered, the app would identify the user as an adult or a kid.
4.If adult, there will be no restriction on websites.
5.If kid, then the following things must happen,
(a)All the requested URLs from the browser must be logged in a log file.
(b)Adult/unwanted websites must be blocked from opening and a warning page must be displayed in the browser.

My question is: can this app be implemented in java? If yes how? How can i monitor the responses and filter them based my conditions? I thought it might be possible by using socket programming in java.

Help of any kind is appreciated.

答:
Well, you could write an HTTP proxy in Java, and that would probably work okay... until your kids are old enough to figure out how to change the proxy in their browser.

Of course, you'd have to determine what counts as an "adult/unwanted website" which has historically proven tricky... a whitelist may be the easiest approach here.

I wouldn't be surprised to hear that such things already exist. Writing a robust HTTP proxy yourself (including streaming etc) could be tricky. Far from impossible, but probably not a good use of your time unless you wanted to do it for the educational value.

ContentLicense: CC BY-SA 2.5


问:
Printing floating point value using memory mapped IO
I am building a calculator using MIPS and the result needs to be in floating point round to two decimal places.
This is my subroutine for printing out anything into the MIPS display:

```<code>mmOut:
lui $t0, 0xffff

mmOutLoop:

lw      $t1, 8($t0)
andi    $t1, $t1,0x0001
beq     $t1, $zero, mmOutLoop
sw      $a0, 12($t0)    //$a0 has the result I wish to print
jr      $ra //return address of mmOut
</code>```

Currently I am storing my results (from the calculation) onto a stack and then converting it in to ASCII. How should I implement the same procedure using floating point values?

答:
As I commented, writing the result to memory-mapped I/O has nothing to do with the problem of float->string conversion.  Those are basically two separate steps.  For parts of the algorithm that generate results in printing order, you could send them to MMIO directly instead of storing to a string in memory if you want.

This could overlap time spent calculating with time spend waiting for the low bit of 0xffff + 8 to become zero, which apparently means the MMIO register at0xffff + 12 is ready to accept another store, according to the loop in your code.

Related: How to input and output real numbers in assembly language.  I only answered the input (string->float) part, unfortunately.

float->string may be easier.  Probably you want to split into integer and fractional parts.

Get the integer part (as a float, in case it's too big for a 32-bit integer) and maybe divide by a large power of 10 until it fits in an int.  Then you can convert to int and use a fast integer conversion for that chunk of digits.  I guess use an FP remainder / modulo calculation to get the least significant part of the integer part, if you had to divide by 10^9 or something to make it fit.  (It may take more than one division by 10^9 to get it down to fitting in 2^32).

For the fractional part, implement this in asm:

```<code>print a '.'
while(frac != 0) {
    frac *= 10.0;
    double intpart = floor(frac);  // or trunc, frac should be non-negative
    frac -= intpart;
    store or print intpart (as a single ASCII decimal digit)
}
</code>```

You probably want to use a counter to limit the number of digits printed (because it could be an infinite .999999... or something, I think).

Use a do{}while structure if you always want to print .0 instead of just . when there's no fractional part.

Most FPUs directly support all of those operations with a single instruction.  I'm not familiar with MIPS's FPU instruction, but I assume floor or trunc are available in hardware at least by converting to integer and back.

You could make this faster by multiplying by frac by 100 or 10000 and using faster integer stuff.  (A 2-digit integer can be split up quickly using a multiplicative inverse with an integer multiply.)

Body:
I am building a calculator using MIPS and the result needs to be in floating point round to two decimal places.
This is my subroutine for printing out anything into the MIPS display:

mmOut:
lui $t0, 0xffff

mmOutLoop:

lw      $t1, 8($t0)
andi    $t1, $t1,0x0001
beq     $t1, $zero, mmOutLoop
sw      $a0, 12($t0)    //$a0 has the result I wish to print
jr      $ra //return address of mmOut

Currently I am storing my results (from the calculation) onto a stack and then converting it in to ASCII. How should I implement the same procedure using floating point values?

Body:
As I commented, writing the result to memory-mapped I/O has nothing to do with the problem of float->string conversion.  Those are basically two separate steps.  For parts of the algorithm that generate results in printing order, you could send them to MMIO directly instead of storing to a string in memory if you want.

This could overlap time spent calculating with time spend waiting for the low bit of 0xffff + 8 to become zero, which apparently means the MMIO register at0xffff + 12 is ready to accept another store, according to the loop in your code.

Related: How to input and output real numbers in assembly language.  I only answered the input (string->float) part, unfortunately.

float->string may be easier.  Probably you want to split into integer and fractional parts.

Get the integer part (as a float, in case it's too big for a 32-bit integer) and maybe divide by a large power of 10 until it fits in an int.  Then you can convert to int and use a fast integer conversion for that chunk of digits.  I guess use an FP remainder / modulo calculation to get the least significant part of the integer part, if you had to divide by 10^9 or something to make it fit.  (It may take more than one division by 10^9 to get it down to fitting in 2^32).

For the fractional part, implement this in asm:

print a '.'
while(frac != 0) {
    frac *= 10.0;
    double intpart = floor(frac);  // or trunc, frac should be non-negative
    frac -= intpart;
    store or print intpart (as a single ASCII decimal digit)
}

You probably want to use a counter to limit the number of digits printed (because it could be an infinite .999999... or something, I think).

Use a do{}while structure if you always want to print .0 instead of just . when there's no fractional part.

Most FPUs directly support all of those operations with a single instruction.  I'm not familiar with MIPS's FPU instruction, but I assume floor or trunc are available in hardware at least by converting to integer and back.

You could make this faster by multiplying by frac by 100 or 10000 and using faster integer stuff.  (A 2-digit integer can be split up quickly using a multiplicative inverse with an integer multiply.)


问:
Insert data in mysql using flaskext .mysql
I am making a simple web form but i try to run this code its gives me an error I am new to python i don't know what this error means and could not find  solution online. here is a code:

```<code>from flaskext.mysql import MySQL
from datetime import date
from dateutil import parser
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'mraghib'
app.config['MYSQL_DATABASE_PASSWORD'] = 'raghib10'
app.config['MYSQL_DATABASE_DB'] = 'fyp'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

if __name__ == ("__main__"):
    cursor = mysql.connect().cursor()
    print(cursor.execute("select * from companylist"))
    addcompanyList= ("INSERT INTO CompanyList (Ticker, CompanyName, SECP_Sector_Code, SectorName,OutstandingShares,DemoSheetName,Years) ""VALUES (%s, %s ,%int, %s,%int, %s, %s)")
    datacompanyList = ("sdasd","adsda",142,"daasda",32,"sdadas",date(1977, 6, 14))

    cursor.execute (addcompanyList,datacompanyList)
</code>```

答:
Try this:</p>

```<code>ddcompanyList= ("""INSERT INTO CompanyList (Ticker, CompanyName,SECP_Sector_Code, SectorName,OutstandingShares,DemoSheetName,Years) VALUES(%s, %s ,%s, %s, %s, %s, %s)""")
</code>```

Body:
I am making a simple web form but i try to run this code its gives me an error I am new to python i don't know what this error means and could not find  solution online. here is a code:

from flaskext.mysql import MySQL
from datetime import date
from dateutil import parser
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'mraghib'
app.config['MYSQL_DATABASE_PASSWORD'] = 'raghib10'
app.config['MYSQL_DATABASE_DB'] = 'fyp'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

if __name__ == ("__main__"):
    cursor = mysql.connect().cursor()
    print(cursor.execute("select * from companylist"))
    addcompanyList= ("INSERT INTO CompanyList (Ticker, CompanyName, SECP_Sector_Code, SectorName,OutstandingShares,DemoSheetName,Years) ""VALUES (%s, %s ,%int, %s,%int, %s, %s)")
    datacompanyList = ("sdasd","adsda",142,"daasda",32,"sdadas",date(1977, 6, 14))

    cursor.execute (addcompanyList,datacompanyList)

Body:
Try this:

ddcompanyList= ("""INSERT INTO CompanyList (Ticker, CompanyName,SECP_Sector_Code, SectorName,OutstandingShares,DemoSheetName,Years) VALUES(%s, %s ,%s, %s, %s, %s, %s)""")


问:
How to send data from express backend to ejs front end?
I am trying out a Tutorials website and in that some of my pages need to send tutorials object, video object, user object depending on which route they landed. So, is it necessary to send null object even if I don't need them on the front end? I am extracting these backend objects in script tag and assign it to window object for use in angular client.

Here are some sample codes.

```<code>// layout.ejs   common to all front end views
<script>
window.user = <%- typeof user !== 'undefined'? JSON.stringify(user) : null %>
</script>
</code>```

Backend sends this type of code:

```<code>res.render('/partials/index', {
    title: 'Title'
});
</code>```

But when I don't send user as null, it throws ReferenceError: user not defined. Why is it so? I am checking in the script tag if it is undefined, I am using null. Is it wrong?

If we need to explicitly send null from backend, then it seems awkward to send null everytime even though I don't need it. What is right way to do it?

答:
Sorry, but I found an answer. We can set this using this. Yes it is using null as a string. That seems different.

```<code>window.user = <%- typeof user === 'undefined' ? 'null': JSON.stringify(user) %>
</code>```

I hope it may help someone else.

Body:
I am trying out a Tutorials website and in that some of my pages need to send tutorials object, video object, user object depending on which route they landed. So, is it necessary to send null object even if I don't need them on the front end? I am extracting these backend objects in script tag and assign it to window object for use in angular client.

Here are some sample codes.

// layout.ejs   common to all front end views

Backend sends this type of code:

res.render('/partials/index', {
    title: 'Title'
});

But when I don't send user as null, it throws ReferenceError: user not defined. Why is it so? I am checking in the script tag if it is undefined, I am using null. Is it wrong?

If we need to explicitly send null from backend, then it seems awkward to send null everytime even though I don't need it. What is right way to do it?

Body:
Sorry, but I found an answer. We can set this using this. Yes it is using null as a string. That seems different.

window.user = <%- typeof user === 'undefined' ? 'null': JSON.stringify(user) %>

I hope it may help someone else.


问:
How to find ratio between two columns in a dataframe?
For example

```<code>df

Cars             Male   female
Ford focus        23      64
vw golf           76      12
ford ka           34      55
renault megane    12      83
</code>```

How do i find the ratio of male to female for every car >0.5

答:
You might try a which() function:

```<code>df[which(df[,2]/df[,3]>0.5),1]
</code>```

Good luck!

Body:
For example

df

Cars             Male   female
Ford focus        23      64
vw golf           76      12
ford ka           34      55
renault megane    12      83

How do i find the ratio of male to female for every car >0.5

Body:
You might try a which() function:

df[which(df[,2]/df[,3]>0.5),1]

Good luck!


问:
How to use jQuery array results and compare them with div IDs?
I have html looking like this. But it contains much more boxes and more entries in the "related" attribute - they are being dynamically loaded from the database according to the backend logic.

```<code><div id="container">

    <div id="134" class=box>
        <h3 related="157,202">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="157" class=box>
        <h3 related="134,202">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="167" class=box>
        <h3 related="205,210">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="202" class=box>
        <h3 related="134,157">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

</div>
</code>```

What I want to do is to mark the related boxes with some class upon the input click on one of them. For example, if I click on #134 input - #157 and #202 boxes should get "related" class.

I generally understand what needs to be done but I'm having trouble with using the results I have in array to compare them with box IDs.

What I have so far:

```<code>$('.box input').click(function () {
if (this.checked) {

var array = $(this).closest(".box").find("h3").attr('related').split(",");

$.each(array, function (i) {
   console.log(array[i]);
});

} else {

/* do something else */

}

}
</code>```

Thank you.

答:
I would simply do, so you can also remove back when uncheck...

simply create a method that received an array of related id's

loop through all

and for each, find the checkbox and mark it, either checked or not

$('.box input').click(function () {
  var relatedIds = $(this)         // the clicked checkbox
           .closest(".box")        // the wrapper div
           .toggleClass('clicked') // let's add/remove a class
           .find("h3")             // the h3 with the properties
           .attr('related')
           .split(",");

  markAllRelated(relatedIds, $(this).is(":checked"));
});

function markAllRelated(relatedIds, check) {
    $.each(relatedIds, function (index, val) {
      $('#'+val)                        // the related element
         .toggleClass("marked")         // add/remove the class
         .find("input[type=checkbox]")  // the input box
         .prop("checked", check);       // let's mark it
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  display: inline-block;
  width: 130px;
  background-color: #ccc;
}
.clicked {
  background-color: #ff0;
}
.marked {
  background-color: #f00;
}</code>```

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

```

Body:
I have html looking like this. But it contains much more boxes and more entries in the "related" attribute - they are being dynamically loaded from the database according to the backend logic.

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

Title

bla bla bla

        <input name="" value="" type="checkbox">

What I want to do is to mark the related boxes with some class upon the input click on one of them. For example, if I click on #134 input - #157 and #202 boxes should get "related" class.

I generally understand what needs to be done but I'm having trouble with using the results I have in array to compare them with box IDs.

What I have so far:

$('.box input').click(function () {
if (this.checked) {

var array = $(this).closest(".box").find("h3").attr('related').split(",");

$.each(array, function (i) {
   console.log(array[i]);
});

} else {

/* do something else */

}

}

Thank you.

Body:
I would simply do, so you can also remove back when uncheck...

simply create a method that received an array of related id's

loop through all

and for each, find the checkbox and mark it, either checked or not

$('.box input').click(function () {
  var relatedIds = $(this)         // the clicked checkbox
           .closest(".box")        // the wrapper div
           .toggleClass('clicked') // let's add/remove a class
           .find("h3")             // the h3 with the properties
           .attr('related')
           .split(",");

  markAllRelated(relatedIds, $(this).is(":checked"));
});

function markAllRelated(relatedIds, check) {
    $.each(relatedIds, function (index, val) {
      $('#'+val)                        // the related element
         .toggleClass("marked")         // add/remove the class
         .find("input[type=checkbox]")  // the input box
         .prop("checked", check);       // let's mark it
    });
}

.box {
  display: inline-block;
  width: 130px;
  background-color: #ccc;
}
.clicked {
  background-color: #ff0;
}
.marked {
  background-color: #f00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

    <div id="134" class=box>
        <h3 related="157,202">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="157" class=box>
        <h3 related="134,202">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="167" class=box>
        <h3 related="205,210">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

    <div id="202" class=box>
        <h3 related="134,157">Title</h3>
        <p>bla bla bla</p>
        <input name="" value="" type="checkbox">
    </div>

</div>


问:
How to access mysql datadir folder of host machine through docker centos container
I am using docker on windows 10 pro and I installed the following

centos

mysql

nginx

The container inside docker and mysql databases is also installed on my host machine.

Now I want to access the datadir folder of host's mysql database from docker centos
container

答:
Map both containers to the same host-volume and both containers should be able to see the data stored there.

Create your volume:
https://docs.docker.com/engine/admin/volumes/volumes/#create-and-manage-volumes

```<code>docker volume create mysqldata
</code>```

Start your containers mapped to the volume: https://docs.docker.com/engine/admin/volumes/volumes/#start-a-container-with-a-volume

```<code>docker run -d --mount source= mysqldata,target=/var/lib/mysql mysql
docker run -d --mount source= mysqldata,target=/var/lib/mysql centos
</code>```

Body:
Map both containers to the same host-volume and both containers should be able to see the data stored there.

Create your volume:
https://docs.docker.com/engine/admin/volumes/volumes/#create-and-manage-volumes

docker volume create mysqldata

Start your containers mapped to the volume: https://docs.docker.com/engine/admin/volumes/volumes/#start-a-container-with-a-volume

docker run -d --mount source= mysqldata,target=/var/lib/mysql mysql
docker run -d --mount source= mysqldata,target=/var/lib/mysql centos


问:
VS2008 to VS 2010 migration - a breaking change?
I encountered a problem when migrating our C++ code from VS2008 to VS2010. I can't find an explanation for the reason of it so far and will appreciate your help.

We have a custom memory allocator and it resides in a dll. In the rest of the code we use the preprocessor to redirect the allocations to our functions. Thie following simple code compiles correctly in VS2008, but does not in VS2010.

in stdafh.h:

```<code>#define free my_free
#include <string>
</code>```

In VS2010 I get:

```<code>1>d:\program files\microsoft visual studio 10.0\vc\include\xdebug(62): error C3861: 'free': identifier not found
</code>```

Coming from the line:

```<code>template<class _Ty>
    void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr)
    {   // delete from the debug CRT heap even if operator delete exists
    if (_Ptr != 0)
        {   // worth deleting
        _Ptr->~_Ty();
        // delete as _NORMAL_BLOCK, not _CRT_BLOCK, since we might have
        // facets allocated by normal new.
        free(_Ptr);
</code>```

Any help or ideas will be highly appreciated!

Moshe

答:
After some investigation using the /P option to create the preprocessor files and studying them I've found the root cause of the issue.

The xdebug header, which describes itself as "debug heap support header for Microsoft", contains the following lines:

```<code>#pragma push_macro("free")
#undef free
</code>```

which obviously defeat our attempts to redefine it. So this is not something new to the compiler, just plain #undef that happens to occur with the functions we try to redefine

Body:
I encountered a problem when migrating our C++ code from VS2008 to VS2010. I can't find an explanation for the reason of it so far and will appreciate your help.

We have a custom memory allocator and it resides in a dll. In the rest of the code we use the preprocessor to redirect the allocations to our functions. Thie following simple code compiles correctly in VS2008, but does not in VS2010.

in stdafh.h:

#define free my_free
#include <string>

In VS2010 I get:

1>d:\program files\microsoft visual studio 10.0\vc\include\xdebug(62): error C3861: 'free': identifier not found

Coming from the line:

template<class _Ty>
    void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr)
    {   // delete from the debug CRT heap even if operator delete exists
    if (_Ptr != 0)
        {   // worth deleting
        _Ptr->~_Ty();
        // delete as _NORMAL_BLOCK, not _CRT_BLOCK, since we might have
        // facets allocated by normal new.
        free(_Ptr);

Any help or ideas will be highly appreciated!

Moshe

Body:
After some investigation using the /P option to create the preprocessor files and studying them I've found the root cause of the issue.

The xdebug header, which describes itself as "debug heap support header for Microsoft", contains the following lines:

#pragma push_macro("free")
#undef free

which obviously defeat our attempts to redefine it. So this is not something new to the compiler, just plain #undef that happens to occur with the functions we try to redefine


问:
Add element to sublist of a list
I have the following code:

```<code>let numbers = [[1],[2],[3],[4]]
</code>```

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

```<code>(numbers !! 2) ++ [3]
</code>```

to get this:

```<code>numbers = [[1],[2],[3,3],[4]]
</code>```

But Im very confused :P Any idea?

答:
As others have noted, in Haskell you don't normally modify a data structure in place.  Instead, you break it apart, introduce your modification, and put it back together to create a new data structure that incorporates the change.

For making changes to a specific list element, I've found the splitAt function to be useful for breaking apart lists.  For example, if you split your list at index 2, it produces the following pair of lists:

```<code>> splitAt 2 numbers
( [[1],[2]] , [[3],[4]] )  -- spaces added to make it clearer
</code>```

Note that the element you want to change is the first element of the second list.  You can use Haskell's pattern matching to process this pair conveniently:

```<code>> let (a, x:b) = splitAt 2 numbers
> a          -- initial part of list
[[1],[2]]
> x          -- element to change
[3]
> b          -- rest of list
[[4]]
> a ++ x : b              -- put list back together unchanged
[[1],[2],[3],[4]]
> a ++ (x ++ [3]) : b     -- put list together w/ modification
[[1],[2],[3,3],[4]]
</code>```

If this was turned into a Haskell function, it would probably look like:

```<code>appendSublist :: Int -> [a] -> [[a]] -> [[a]]
appendSublist idx y lst
  = let (a, x:b) = splitAt idx lst
    in  a ++ (x ++ y) : b
</code>```

which you'd use like this:

```<code>> appendSublist 2 [3] numbers
[[1],[2],[3,3],[4]]
</code>```

This basic pattern:

```<code>let (a, x:b) = splitAt idx lst in a ++ (...replacement for x...) : b
</code>```

is worth memorizing, since it's pretty useful.

Eventually, you'll probably want to learn to use the lens library for this kind of thing.  Lenses are more concise and more flexible (i.e., work for all sorts of things, not just specific list items), but there's a pretty big learning curve, as you can maybe guess from @leftaroundabout's answer.

Title: Add element to sublist of a list

Body:
I have the following code:

let numbers = [[1],[2],[3],[4]]

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

(numbers !! 2) ++ [3]

to get this:

numbers = [[1],[2],[3,3],[4]]

But Im very confused :P Any idea?

Body:
As others have noted, in Haskell you don't normally modify a data structure in place.  Instead, you break it apart, introduce your modification, and put it back together to create a new data structure that incorporates the change.

For making changes to a specific list element, I've found the splitAt function to be useful for breaking apart lists.  For example, if you split your list at index 2, it produces the following pair of lists:

> splitAt 2 numbers
( [[1],[2]] , [[3],[4]] )  -- spaces added to make it clearer

Note that the element you want to change is the first element of the second list.  You can use Haskell's pattern matching to process this pair conveniently:

> let (a, x:b) = splitAt 2 numbers
> a          -- initial part of list
[[1],[2]]
> x          -- element to change
[3]
> b          -- rest of list
[[4]]
> a ++ x : b              -- put list back together unchanged
[[1],[2],[3],[4]]
> a ++ (x ++ [3]) : b     -- put list together w/ modification
[[1],[2],[3,3],[4]]

If this was turned into a Haskell function, it would probably look like:

appendSublist :: Int -> [a] -> [[a]] -> [[a]]
appendSublist idx y lst
  = let (a, x:b) = splitAt idx lst
    in  a ++ (x ++ y) : b

which you'd use like this:

> appendSublist 2 [3] numbers
[[1],[2],[3,3],[4]]

This basic pattern:

let (a, x:b) = splitAt idx lst in a ++ (...replacement for x...) : b

is worth memorizing, since it's pretty useful.

Eventually, you'll probably want to learn to use the lens library for this kind of thing.  Lenses are more concise and more flexible (i.e., work for all sorts of things, not just specific list items), but there's a pretty big learning curve, as you can maybe guess from @leftaroundabout's answer.


问:
What is/how does the "search" command work?
Put briefly, can I use the 'search' command to search through file contents? If so, how?

I am trying to find an easier way to search through file contents in Linux Mint than having to type

```<code>grep -rnw . -e 'my search text'
</code>```

I just noticed there is a 'search' command

```<code>$ which search
/usr/local/bin/search
</code>```

However, when I look at its help text; I am presented with this:

```<code>usage: search [arguments] [options]
arguments:
     for text
     in directory
</code>```

I am unable to make sense of this, any arguments I try passing in seem to inevitably lead me to the same text.

There is also no man page entry, I tried that as well.

I have tried e.g.

```<code>$ search "my search text" .
$ search . "test"
$ search . . . .
</code>```

Lacking a way to get this to work, I may opt for an alias. Sadly though, 'search' is already taken..

答:
I just did a clean install, and went to have a look at this 'search' executable. Turns out, it is in fact a shell command with the following resulting command:

```<code>find $directory -type f -exec grep -$case$verbose "$text" --color=auto -n {} \;
</code>```

The four $variables above are respectively populated with the search directory, case-sensitivity, verbosity and ultimately the single word search text.

I have no idea why this facility exists, but as the manual suggests, you can only use it to search for a single word (no spaces), and in the specified following directory.

An example looking for (case insensitive) and without verbosity would thus be:

```<code>search for bar in ~/home/foo
</code>```

The command was apparently added in Linux mint in 2008, as indicated in this post that also details its use.

Body:
Put briefly, can I use the 'search' command to search through file contents? If so, how?

I am trying to find an easier way to search through file contents in Linux Mint than having to type

grep -rnw . -e 'my search text'

I just noticed there is a 'search' command

$ which search
/usr/local/bin/search

However, when I look at its help text; I am presented with this:

usage: search [arguments] [options]
arguments:
     for text
     in directory

I am unable to make sense of this, any arguments I try passing in seem to inevitably lead me to the same text.

There is also no man page entry, I tried that as well.

I have tried e.g.

$ search "my search text" .
$ search . "test"
$ search . . . .

Lacking a way to get this to work, I may opt for an alias. Sadly though, 'search' is already taken..

Body:
I just did a clean install, and went to have a look at this 'search' executable. Turns out, it is in fact a shell command with the following resulting command:

find $directory -type f -exec grep -$case$verbose "$text" --color=auto -n {} \;

The four $variables above are respectively populated with the search directory, case-sensitivity, verbosity and ultimately the single word search text.

I have no idea why this facility exists, but as the manual suggests, you can only use it to search for a single word (no spaces), and in the specified following directory.

An example looking for (case insensitive) and without verbosity would thus be:

search for bar in ~/home/foo

The command was apparently added in Linux mint in 2008, as indicated in this post that also details its use.


问:
how to hide a form in angular
I have been trying to hide my form and making it appear only when user click on the button. but for some reason, the function I have created never work is there something wrong with my code? and I saw quite a few example that uses angular.module and I tried it but I always get an error message.

transfer.component.html

```<code><form [formGroup]="AddRiciverForm" id="AddRiciverForm" (ngSubmit)="addRiciverFunc()" *ngIf="show">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        <p><input type="email" id="emailTo" formControlName="emailTo"  placeholder="Reciver Email" [(ngModel)]="this.AddRiciverForm.value.emailTo" required></p>
      </div>
    </div>
     <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        <p><button class="btn btn-primary" type="submit" [disabled]="!transferForm.form.valid">Add</button> </p>
      </div>
    </div>
   </div>
  </form>
<button ng-click="AddEmailFunc()">add user</button>
</code>```

transfer.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  addRiciver = {};
  recivers: any;
  AddRiciverForm: FormGroup;
  transferForm: FormGroup;
  public userEmail: string;
  show=false;
  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.AddRiciverForm = this.fb.group({
      emailTo: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllReciver().subscribe(reciver => {
      this.recivers = reciver;
    });
  }
  transFunds(){

  }
  addRiciverFunc(){
        this.addRiciver={
          emailFrom: this.userEmail,
          emailTo: this.AddRiciverForm.value.emailTo
        }
        this.http.post('/transfer', this.addRiciver)
        .subscribe(res => {
            let id = res['_id'];

          }, (err) => {
            console.log(err);
          }
        );

  }

  AddEmailFunc(){
  if(!this.show){
    this.show = true;
  }

  }
}
</code>```

答:
You are mixing angularjs (1.x) and angular (>2)

the ng-click in Angular should be:

```<code><button (click)="AddEmailFunc()">add user</button>
</code>```

If this does not solve your issue please post the full component.

Title: how to hide a form in angular

Body:
I have been trying to hide my form and making it appear only when user click on the button. but for some reason, the function I have created never work is there something wrong with my code? and I saw quite a few example that uses angular.module and I tried it but I always get an error message.

transfer.component.html

<form [formGroup]="AddRiciverForm" id="AddRiciverForm" (ngSubmit)="addRiciverFunc()" *ngIf="show">

<input type="email" id="emailTo" formControlName="emailTo"  placeholder="Reciver Email" [(ngModel)]="this.AddRiciverForm.value.emailTo" required>

<button class="btn btn-primary" type="submit" [disabled]="!transferForm.form.valid">Add</button>

  </form>
<button ng-click="AddEmailFunc()">add user</button>

transfer.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  addRiciver = {};
  recivers: any;
  AddRiciverForm: FormGroup;
  transferForm: FormGroup;
  public userEmail: string;
  show=false;
  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.AddRiciverForm = this.fb.group({
      emailTo: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllReciver().subscribe(reciver => {
      this.recivers = reciver;
    });
  }
  transFunds(){

  }
  addRiciverFunc(){
        this.addRiciver={
          emailFrom: this.userEmail,
          emailTo: this.AddRiciverForm.value.emailTo
        }
        this.http.post('/transfer', this.addRiciver)
        .subscribe(res => {
            let id = res['_id'];

          }, (err) => {
            console.log(err);
          }
        );

  }

  AddEmailFunc(){
  if(!this.show){
    this.show = true;
  }

  }
}

Body:
You are mixing angularjs (1.x) and angular (>2)

the ng-click in Angular should be:

<button (click)="AddEmailFunc()">add user</button>

If this does not solve your issue please post the full component.


问:
How to convert Associative array to a simple string array of values in javascript
So I want to convert this array retrieved from a database to just an array of string values:

Array:[{"userid":"c"},{"userid":"d"}]

Expected results:["c","d"]

答:
A simpler way would be </p>

```<code>const results = myArray.map(item => item.userId);
</code>```

Body:
A simpler way would be

const results = myArray.map(item => item.userId);


问:
PHP- how to allow only letters in a text field. Also how to only allow numbers in a text field
How do I add a input field that only accepts letters. Also how do I add a input field that only accepts numbers. And once the user inputs say letters in a text field that only accepts numbers it gives an error. </p>

```<code>if(empty($_POST['firstname']))
        {
            $errors['firstname1'] = " Required";
        }

    if(empty($_POST['zip']))
        {
            $errors['zip1'] = " Required";
        }

    <!-- Letters only for firstname -->

    <p>
                <label for="firstname" class="label"><font color="#040404">*First Name:</font></label>
                <input class="textinput" id="firstname" type="text" name="firstname" value="<?php if(isset($_POST['firstname'])) echo $_POST['firstname']; ?>" /><?php if(isset($errors['firstname1'])) echo $errors['firstname1']; ?>
            </p>
    <!-- Letters only for zip -->

    <p>

                    <label for="zip" class="label"><font color="#040404">*Zip Code:</font></label>
                    <input id="zip" type="text" name="zip" value="<?php if(isset($_POST['zip'])) echo $_POST['zip']; ?>" /><?php if(isset($errors['zip1'])) echo $errors['zip1']; ?> <?php if(isset($errors['zip2'])) echo $errors['zip2']; ?>
                </p>
</code>```

答:
You do not need to write any extra code to satisfy your requirement

Following is a example which allows only letters (both small and capital in any sequence).

```<code><input id="my_id" type="text" pattern="[A-Za-z]*" class="validate">
</code>```

Or you can give more constraints like allow only first letter to be capital and reaming in small caps with pattern="[A-Z][a-z]*"

To allow only numbers use pattern="[0-9]*" and to allow only fix number (say 10) of numbers use pattern="[0-9]{10}"

Body:
How do I add a input field that only accepts letters. Also how do I add a input field that only accepts numbers. And once the user inputs say letters in a text field that only accepts numbers it gives an error.

if(empty($_POST['firstname']))
        {
            $errors['firstname1'] = " Required";
        }

    if(empty($_POST['zip']))
        {
            $errors['zip1'] = " Required";
        }

                *First Name:
                <input class="textinput" id="firstname" type="text" name="firstname" value="<?php if(isset($_POST['firstname'])) echo $_POST['firstname']; ?>" /><?php if(isset($errors['firstname1'])) echo $errors['firstname1']; ?>

                    *Zip Code:
                    <input id="zip" type="text" name="zip" value="<?php if(isset($_POST['zip'])) echo $_POST['zip']; ?>" /><?php if(isset($errors['zip1'])) echo $errors['zip1']; ?> <?php if(isset($errors['zip2'])) echo $errors['zip2']; ?>

Body:
You do not need to write any extra code to satisfy your requirement

Following is a example which allows only letters (both small and capital in any sequence).

<input id="my_id" type="text" pattern="[A-Za-z]*" class="validate">

Or you can give more constraints like allow only first letter to be capital and reaming in small caps with pattern="[A-Z][a-z]*"

To allow only numbers use pattern="[0-9]*" and to allow only fix number (say 10) of numbers use pattern="[0-9]{10}"


答:
What you need should look something like this, it adds class to div.box according to the ids in the h3 related attribute and removes on unchecked

$('.box input').click(function() {
  var array = $(this).closest(".box").find("h3").attr('related').split(",");
  $.each(array, function(i) {
    $('#' + array[i]).toggleClass('someClass');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.someClass {
  color: red;
}</code>```

Title

bla bla bla

    <input name="" value="" type="checkbox">

Title

bla bla bla

    <input name="" value="" type="checkbox">

Title

bla bla bla

    <input name="" value="" type="checkbox">

Title

bla bla bla

    <input name="" value="" type="checkbox">

```

Title: How to use jQuery array results and compare them with div IDs?

Body:
What you need should look something like this, it adds class to div.box according to the ids in the h3 related attribute and removes on unchecked

$('.box input').click(function() {
  var array = $(this).closest(".box").find("h3").attr('related').split(",");
  $.each(array, function(i) {
    $('#' + array[i]).toggleClass('someClass');
  });
});

.someClass {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">

  <div id="134" class=box>
    <h3 related="157,202">Title</h3>
    <p>bla bla bla</p>
    <input name="" value="" type="checkbox">
  </div>

  <div id="157" class=box>
    <h3 related="134,202">Title</h3>
    <p>bla bla bla</p>
    <input name="" value="" type="checkbox">
  </div>

  <div id="167" class=box>
    <h3 related="205,210">Title</h3>
    <p>bla bla bla</p>
    <input name="" value="" type="checkbox">
  </div>

  <div id="202" class=box>
    <h3 related="134,157">Title</h3>
    <p>bla bla bla</p>
    <input name="" value="" type="checkbox">
  </div>

</div>

ContentLicense: CC BY-SA 4.0


问:
Setting numpy array values to be more precise
I have an array which has values, if calcualted precisely: [3.056565 3.924560] however in python it prints rounded numbers and the array is [3.06, 3.93]. The array is the used to calculate something else and the result is different than expected. How can I make that array to stop rounding itself?

Here is the code where you can see that array is not precisely calcualted:

```<code>import datetime
import math
import numpy as np

def numGradient(f, x, h):

  n = len(x)
  g = [0]*n
  g = np.array(g)

  for i in range(n):
    e = [0]*n
    e[i] = 1
    e=np.array(e)

    g[i] = (f(x+e*h)-f(x-e*h))//(2*h)

  return(g)

def myFun(x) :
    return ( 0.6 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )
x_old=(3,4)

xthis = x_old - 0.01*numGradient(myFun, x_old, 10**(-6))

print(xthis)
</code>```

答:
There are several issues with your code. It probably does not compute what you expect it to compute.

First, this is the wrong way to initialize a NumPy array

```<code>  g = [0]*n
  g = np.array(g)
</code>```

Replace it with

```<code>  g = np.zeros(n)
</code>```

Second, do the same with e.

```<code>for i in range(n):
    e = np.zeros(n)
    e[i] = 1
</code>```

And most importantly replace

```<code>g[i] = (f(x+e*h)-f(x-e*h))//(2*h)
</code>```

with

```<code>g[i] = (f(x+e*h)-f(x-e*h))/(2*h)
</code>```

This is floating point division after all. And // is the so-called integer division in Python 3.

After the changes you will get

```<code>[ 3.056565  3.92456 ]
</code>```

Which is probably what you should be getting.

Here is the complete code after the changes:

```<code>import datetime
import math
import numpy as np

def numGradient(f, x, h):

  n = len(x)
  g = np.zeros(n)

  for i in range(n):
    e = np.zeros(n)
    e[i] = 1
    g[i] = (f(x+e*h)-f(x-e*h))/(2*h)

  return(g)

def myFun(x) :
    return ( 0.6 +
       ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )

x_old=(3,4)

np.set_printoptions(precision=6)

xthis = x_old - 0.01*numGradient(myFun, x_old, 10**(-6))

print(xthis)
</code>```

Body:
I have an array which has values, if calcualted precisely: [3.056565 3.924560] however in python it prints rounded numbers and the array is [3.06, 3.93]. The array is the used to calculate something else and the result is different than expected. How can I make that array to stop rounding itself?

Here is the code where you can see that array is not precisely calcualted:

import datetime
import math
import numpy as np

def numGradient(f, x, h):

  n = len(x)
  g = [0]*n
  g = np.array(g)

  for i in range(n):
    e = [0]*n
    e[i] = 1
    e=np.array(e)

    g[i] = (f(x+e*h)-f(x-e*h))//(2*h)

  return(g)

def myFun(x) :
    return ( 0.6 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )
x_old=(3,4)

xthis = x_old - 0.01*numGradient(myFun, x_old, 10**(-6))

print(xthis)

Body:
There are several issues with your code. It probably does not compute what you expect it to compute.

First, this is the wrong way to initialize a NumPy array

  g = [0]*n
  g = np.array(g)

Replace it with

  g = np.zeros(n)

Second, do the same with e.

for i in range(n):
    e = np.zeros(n)
    e[i] = 1

And most importantly replace

g[i] = (f(x+e*h)-f(x-e*h))//(2*h)

with

g[i] = (f(x+e*h)-f(x-e*h))/(2*h)

This is floating point division after all. And // is the so-called integer division in Python 3.

After the changes you will get

[ 3.056565  3.92456 ]

Which is probably what you should be getting.

Here is the complete code after the changes:

import datetime
import math
import numpy as np

def numGradient(f, x, h):

  n = len(x)
  g = np.zeros(n)

  for i in range(n):
    e = np.zeros(n)
    e[i] = 1
    g[i] = (f(x+e*h)-f(x-e*h))/(2*h)

  return(g)

def myFun(x) :
    return ( 0.6 +
       ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )

x_old=(3,4)

np.set_printoptions(precision=6)

xthis = x_old - 0.01*numGradient(myFun, x_old, 10**(-6))

print(xthis)


问:
Get details of a currently logged in user
I have am trying to get the admin rights of a user which is either true or false. I do not think i am getting the current logged in users details, the below code is what i have but when i debug it, it seems that it loops through all the users in the firebase table and if any are true it sets the buttons to visible</p>

```<code> databaseUsers = FirebaseDatabase.getInstance().getReference("users");
    //  buttonAddProducts.setVisibility(View.GONE);
    //   buttonAddBeverages.setVisibility(View.GONE);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference currentUserReference = databaseUsers.child(uid);
    currentUserReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot userSnapshot) {
            if (userSnapshot.exists()) {
                User user = userSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }
            else{
                Log.i("myInfoTag", "Connection problem");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore exceptions
        }
    });
</code>```

答:
You're listening for all users, then loop over them, and if any of them is an admin, you show the buttons.

If you only want to show the buttons for the current user, you should only query the current users. Within your current data model that can be something like:

```<code>String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference currentUserReference = databaseUsers.child(uid);
currentUserReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            User user = venueSnapshot.getValue(User.class);

            if(user.getAdminUser() == true)
            {
                buttonAddProducts.setVisibility(View.VISIBLE);
                buttonAddBeverages.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore exceptions
    }
});
</code>```

Not only will that give you the behavior you want, it also drastically reduces the bandwidth your app uses.

Body:
I have am trying to get the admin rights of a user which is either true or false. I do not think i am getting the current logged in users details, the below code is what i have but when i debug it, it seems that it loops through all the users in the firebase table and if any are true it sets the buttons to visible

 databaseUsers = FirebaseDatabase.getInstance().getReference("users");
    //  buttonAddProducts.setVisibility(View.GONE);
    //   buttonAddBeverages.setVisibility(View.GONE);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference currentUserReference = databaseUsers.child(uid);
    currentUserReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot userSnapshot) {
            if (userSnapshot.exists()) {
                User user = userSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }
            else{
                Log.i("myInfoTag", "Connection problem");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore exceptions
        }
    });

Body:
You're listening for all users, then loop over them, and if any of them is an admin, you show the buttons.

If you only want to show the buttons for the current user, you should only query the current users. Within your current data model that can be something like:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference currentUserReference = databaseUsers.child(uid);
currentUserReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            User user = venueSnapshot.getValue(User.class);

            if(user.getAdminUser() == true)
            {
                buttonAddProducts.setVisibility(View.VISIBLE);
                buttonAddBeverages.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore exceptions
    }
});

Not only will that give you the behavior you want, it also drastically reduces the bandwidth your app uses.


问:
Simple Android SearchView not functioning properly
I am trying to follow the search interface manual from android.com. I have few problems and I am not sure what I did wrong exactly.

If you want to look, here is the project as zip file.

1- The android:hint is not visible when I touch search icon. It comes empty. Why? If I set it programmatically it works eg.                 searchView.setQueryHint(getString(R.string.search_hint)); Why it doesn't work from XML?

2- Search field does not get focus and keyboard does not appear automatically when I touch search icon. I need to touch to the search textfield to get focus. I believe it should get focus automatically?

3- When I write something and touch the search icon on the keyboard. I do not see any log entries logged at logcat window. What is missing?

4- (SOLVED) I tried android:iconifiedByDefault="false" in XML and also searchView.setIconifiedByDefault(false); and it is always iconified when I start the application. Why is that happening?

I found out that iI need to remove collapseActionView from app:showAsAction otherwise setIconifiedByDefault(false) does not work. Also if you remove collapseActionView and set setIconifiedByDefault(false) then it never collapses.

I am guessing I missed something somewhere but I am not sure exactly what...

So below are the steps I followed:

I started a new project with 'Basic Activity' in Android Studio 3.
It has a ready toolbar and 'Hello World' in the middle.

Then to xml folder I added the searchable.xml file with contents:

```<code><?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Search hint text"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer">
</searchable>
</code>```

Then changed AndroidManifest.xml file and added an activity:

```<code><activity android:name=".SearchableActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable"/>
</activity>
</code>```

Then created a simple SearchableActivity.class. Just to log some lines.

```<code>package com.test.myapplication;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class SearchableActivity extends ListActivity {
    private static String TAG = SearchableActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        Log.d(TAG, "handleIntent");
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //use the query to search your data somehow
        }
    }
}
</code>```

Then added to existing menu_main.xml the necessary item:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.test.myapplication.MainActivity">
    <item android:id="@+id/search"
        android:title="@string/app_name"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.widget.SearchView" />
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>
</code>```

Update: If I change to app:actionViewClass="android.support.v7.widget.SearchView" and also in MainActivity.class if I import import android.support.v7.widget.SearchView; then when I click on the search icon, it shows default Search... text gets focus automatically. But does NOT show hint from XML and still there are no log entries when I submit any information.

UPDATE:

I realized that if I put the intent-filter and the meta part under MainActivity I am getting the search intent inside main activity. But I don't understand why it does not start the SearchableActivity. Because manual page for SearchView clearly says:

When a user executes a search from the search dialog or widget, the system starts your searchable activity and sends it a ACTION_SEARCH intent.

答:
Use this

```<code>app:actionViewClass="android.support.v7.widget.SearchView"
</code>```

Instead of this

```<code>app:actionViewClass="android.widget.SearchView"
</code>```

Body:
I am trying to follow the search interface manual from android.com. I have few problems and I am not sure what I did wrong exactly.

If you want to look, here is the project as zip file.

1- The android:hint is not visible when I touch search icon. It comes empty. Why? If I set it programmatically it works eg.                 searchView.setQueryHint(getString(R.string.search_hint)); Why it doesn't work from XML?

2- Search field does not get focus and keyboard does not appear automatically when I touch search icon. I need to touch to the search textfield to get focus. I believe it should get focus automatically?

3- When I write something and touch the search icon on the keyboard. I do not see any log entries logged at logcat window. What is missing?

4- (SOLVED) I tried android:iconifiedByDefault="false" in XML and also searchView.setIconifiedByDefault(false); and it is always iconified when I start the application. Why is that happening?

I found out that iI need to remove collapseActionView from app:showAsAction otherwise setIconifiedByDefault(false) does not work. Also if you remove collapseActionView and set setIconifiedByDefault(false) then it never collapses.

I am guessing I missed something somewhere but I am not sure exactly what...

So below are the steps I followed:

I started a new project with 'Basic Activity' in Android Studio 3.
It has a ready toolbar and 'Hello World' in the middle.

Then to xml folder I added the searchable.xml file with contents:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Search hint text"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer">
</searchable>

Then changed AndroidManifest.xml file and added an activity:

<activity android:name=".SearchableActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable"/>
</activity>

Then created a simple SearchableActivity.class. Just to log some lines.

package com.test.myapplication;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class SearchableActivity extends ListActivity {
    private static String TAG = SearchableActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        Log.d(TAG, "handleIntent");
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //use the query to search your data somehow
        }
    }
}

Then added to existing menu_main.xml the necessary item:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.test.myapplication.MainActivity">
    <item android:id="@+id/search"
        android:title="@string/app_name"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.widget.SearchView" />
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

Update: If I change to app:actionViewClass="android.support.v7.widget.SearchView" and also in MainActivity.class if I import import android.support.v7.widget.SearchView; then when I click on the search icon, it shows default Search... text gets focus automatically. But does NOT show hint from XML and still there are no log entries when I submit any information.

UPDATE:

I realized that if I put the intent-filter and the meta part under MainActivity I am getting the search intent inside main activity. But I don't understand why it does not start the SearchableActivity. Because manual page for SearchView clearly says:

When a user executes a search from the search dialog or widget, the system starts your searchable activity and sends it a ACTION_SEARCH intent.

Body:
Use this

app:actionViewClass="android.support.v7.widget.SearchView"

Instead of this

app:actionViewClass="android.widget.SearchView"


问:
How do I read data from an SQLite database?
I am trying to read a row using a column name as key but I am somehow unable to get it.

Example I entered a string "name"

the list just shows "1" in the ListView

here's my insert code

```<code>public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }
</code>```

And here's how I query the data:

```<code>public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();
        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {

                allStudents.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        return allStudents;
    }
</code>```

```<code>package test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDBAdapter {
    public static final String DATABASE_NAME = "data";

    private Context mContext;
    private MyDBHelper mDbHelper;
    private SQLiteDatabase mSqliteDatabase;
    private int DATABASE_VERSION = 1;

    public MyDBAdapter(Context context){
        this.mContext = context;
        mDbHelper = new MyDBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void open(){
        mSqliteDatabase = mDbHelper.getWritableDatabase();
    }

    public class MyDBHelper extends SQLiteOpenHelper{
        public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db){
            String query = "CREATE TABLE students(id integer primary key autoincrement, name text, faculty integer);";
            db.execSQL(query);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            String query = "DROP TABLE IF EXISTS students;";
            db.execSQL(query);
            onCreate(db);
        }
    }

    public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

//    public List<String> selectAllStudents(){
//        List<String> allStudents = new ArrayList<>();
//        Cursor cursor = mSqliteDatabase.query("students", null, null, null, null, null, null);
//        if(cursor != null && cursor.moveToFirst()){
//            do {
//                allStudents.add(cursor.getString(1));
//            } while (cursor.moveToNext());
//        }
//        return allStudents;
//    }

    public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();

        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {
                if(cursor.getString(cursor.getColumnIndex("faculty")).equals("1")){
                    allStudents.add(cursor.getString(cursor.getColumnIndex("name")));
                }
//                allStudents.add(cursor.getString(0));

            } while (cursor.moveToNext());
        }
        return allStudents;
    }

    public void deleteAllEngineers(){
        mSqliteDatabase.delete("students", null, null);
    }
}
</code>```

I added my DB java file please see it.

答:
using zero in cursor.getString(0) returns 1 as your query contains only one column "faculty" which is integer as per your table specification. But agree with Zoe that this is bad practice and leads to difficult to maintain and debug code.

in order to have a query with names and faculty you need to include both in the columns array string of your query, I recommend this way (more readable code):

```<code>String[] columns = {"name","faculty"};
Cursor cursor = mSqliteDatabase.query("students", columns, null, null, null, null, null);
</code>```

or your way:

```<code>Cursor cursor = mSqliteDatabase.query("students", new String[]  {"name","faculty"}, null, null, null, null, null);
</code>```

in this way you need to change the arraylist to  a map for example (collection that accept a key and a value) or implement your table columns as a class and use arraylist of that class type, or make your list of type string array like:

```<code>ArrayList<String[]> allStudents  = new ArrayList();
allStudents.add(new String[] {"put here faculty integer","put here student name"});
</code>```

hope this may help you.

Body:
I am trying to read a row using a column name as key but I am somehow unable to get it.

Example I entered a string "name"

the list just shows "1" in the ListView

here's my insert code

public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

And here's how I query the data:

public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();
        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {

                allStudents.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        return allStudents;
    }

package test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDBAdapter {
    public static final String DATABASE_NAME = "data";

    private Context mContext;
    private MyDBHelper mDbHelper;
    private SQLiteDatabase mSqliteDatabase;
    private int DATABASE_VERSION = 1;

    public MyDBAdapter(Context context){
        this.mContext = context;
        mDbHelper = new MyDBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void open(){
        mSqliteDatabase = mDbHelper.getWritableDatabase();
    }

    public class MyDBHelper extends SQLiteOpenHelper{
        public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db){
            String query = "CREATE TABLE students(id integer primary key autoincrement, name text, faculty integer);";
            db.execSQL(query);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            String query = "DROP TABLE IF EXISTS students;";
            db.execSQL(query);
            onCreate(db);
        }
    }

    public void insertStudent(String name, int faculty){
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("faculty", faculty);
        mSqliteDatabase.insert("students", null, cv);
    }

//    public List<String> selectAllStudents(){
//        List<String> allStudents = new ArrayList<>();
//        Cursor cursor = mSqliteDatabase.query("students", null, null, null, null, null, null);
//        if(cursor != null && cursor.moveToFirst()){
//            do {
//                allStudents.add(cursor.getString(1));
//            } while (cursor.moveToNext());
//        }
//        return allStudents;
//    }

    public List<String> selectAllEngg(){
        List<String> allStudents = new ArrayList<>();

        Cursor cursor = mSqliteDatabase.query("students", new String[]{"faculty"}, null, null, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            do {
                if(cursor.getString(cursor.getColumnIndex("faculty")).equals("1")){
                    allStudents.add(cursor.getString(cursor.getColumnIndex("name")));
                }
//                allStudents.add(cursor.getString(0));

            } while (cursor.moveToNext());
        }
        return allStudents;
    }

    public void deleteAllEngineers(){
        mSqliteDatabase.delete("students", null, null);
    }
}

I added my DB java file please see it.

Body:
using zero in cursor.getString(0) returns 1 as your query contains only one column "faculty" which is integer as per your table specification. But agree with Zoe that this is bad practice and leads to difficult to maintain and debug code.

in order to have a query with names and faculty you need to include both in the columns array string of your query, I recommend this way (more readable code):

String[] columns = {"name","faculty"};
Cursor cursor = mSqliteDatabase.query("students", columns, null, null, null, null, null);

or your way:

Cursor cursor = mSqliteDatabase.query("students", new String[]  {"name","faculty"}, null, null, null, null, null);

in this way you need to change the arraylist to  a map for example (collection that accept a key and a value) or implement your table columns as a class and use arraylist of that class type, or make your list of type string array like:

ArrayList<String[]> allStudents  = new ArrayList();
allStudents.add(new String[] {"put here faculty integer","put here student name"});

hope this may help you.