问:
I am unable to run my angular application
I cloned the ever repo and i was trying to run the admin site but it didn't. The first problem was related to symlinks or shortcuts, implying the developers only had linux in mind and not windows. So i manually created and got it to work. But another error happened when i try to run the admin site made in angular

```<code>ERROR in app/@core/auth/auth.module.ts:6:29 - error TS2307: Cannot find module 'environments/environment'.

6 import { environment } from 'environments/environment';
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

This is the error and others just like this one. When i looked for the file, it didn't exist. So can anyone tell me if the file is generated on compile time. And this project worked fine on ubuntu before without any of the problems mentioned above.

答:
The issue is due to the environment.ts file doesn't exist on the repo, instead, they have model.ts inside environment folder. Replace the import statement in app/@core/auth/auth.module.ts.

EDIT
Read the documentation about how to run each project as stated comment.

Run yarn ts-node ./scripts/configure.ts
  and configure.ts generates automatically environment.ts file with setting defined in .env file (or default if you don't have .env.ts file at all)

Body:
I cloned the ever repo and i was trying to run the admin site but it didn't. The first problem was related to symlinks or shortcuts, implying the developers only had linux in mind and not windows. So i manually created and got it to work. But another error happened when i try to run the admin site made in angular

ERROR in app/@core/auth/auth.module.ts:6:29 - error TS2307: Cannot find module 'environments/environment'.

6 import { environment } from 'environments/environment';
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~

This is the error and others just like this one. When i looked for the file, it didn't exist. So can anyone tell me if the file is generated on compile time. And this project worked fine on ubuntu before without any of the problems mentioned above.


来源: stackexchange

问:
Visual Studio Error: 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
I try to link my access database with visual Studio but I always receive this error. I installed Access database engine 2010 and 2016 but it doesn't change anything. I also tried to build my C# application with both CPU (x86 and x64) but I still receive the same error.</p>

答:
If you build as x86, then having installed Access 2010 this should work.

I have a tiny ready to go .exe file here:

There are both a x86, and a x64 bit version in the zip file. Unzip, run and browse to a accDB or mdb file. If you can open and browse to a accDB file, then .net is working and you have the ACE database engine installed.

You did not post your code (just post the connection string part).

You also do NOT mention if you are using the .net oleDB provider, or the .net ODBC provider. And of course you cannot use the sqlprovider.

So, we need more information then my car is broken. We are quite much shooting in the dark here and making wild guesses. We don't know what you attempted. We don't know if you using JET or ACE. We don't know if you are using the ODBC provider, or the oleDB one. We don't know what you code looks like so far.

If you using oleDB, then .net code as vb.net will look like this:

```<code>Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\test\testdb.accdb"
Dim mycon As New OleDb.OleDbConnection(strCon)
Dim dataRead As New OleDb.OleDbDataAdapter("select * from tblCustomers", mycon)
Dim rst As New DataTable
dataRead.Fill(rst)
</code>```

Or as c#, it will look somthing like this:

```<code>string strCon = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\test\testdb.accdb";
OleDb.OleDbConnection mycon = new OleDb.OleDbConnection(strCon);
OleDb.OleDbDataAdapter dataRead = new OleDb.OleDbDataAdapter("select * from tblCustomers", mycon);
DataTable rst = new DataTable();
dataRead.Fill(rst);
</code>```

As noted, if you want to test/try that JET or ace is working, then you can download this already working sample here:

Just unzip and run both the x64 example, and the x86 example. If neither work, then you don't have the Access database engine installed, or it not exposed for your use:

https://1drv.ms/u/s!Avrwal_LV4qxhpdA1Z2344l9CnhwyQ?e=QeTPrs

ContentLicense: CC BY-SA 4.0

Body:
If you build as x86, then having installed Access 2010 this should work.

I have a tiny ready to go .exe file here:

There are both a x86, and a x64 bit version in the zip file. Unzip, run and browse to a accDB or mdb file. If you can open and browse to a accDB file, then .net is working and you have the ACE database engine installed.

You did not post your code (just post the connection string part).

You also do NOT mention if you are using the .net oleDB provider, or the .net ODBC provider. And of course you cannot use the sqlprovider.

So, we need more information then my car is broken. We are quite much shooting in the dark here and making wild guesses. We don't know what you attempted. We don't know if you using JET or ACE. We don't know if you are using the ODBC provider, or the oleDB one. We don't know what you code looks like so far.

If you using oleDB, then .net code as vb.net will look like this:

Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\test\testdb.accdb"
Dim mycon As New OleDb.OleDbConnection(strCon)
Dim dataRead As New OleDb.OleDbDataAdapter("select * from tblCustomers", mycon)
Dim rst As New DataTable
dataRead.Fill(rst)

Or as c#, it will look somthing like this:

string strCon = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\test\testdb.accdb";
OleDb.OleDbConnection mycon = new OleDb.OleDbConnection(strCon);
OleDb.OleDbDataAdapter dataRead = new OleDb.OleDbDataAdapter("select * from tblCustomers", mycon);
DataTable rst = new DataTable();
dataRead.Fill(rst);

As noted, if you want to test/try that JET or ace is working, then you can download this already working sample here:

Just unzip and run both the x64 example, and the x86 example. If neither work, then you don't have the Access database engine installed, or it not exposed for your use:

https://1drv.ms/u/s!Avrwal_LV4qxhpdA1Z2344l9CnhwyQ?e=QeTPrs


问:
using file command in bash script error using variable
I have a file named "file" in my current directory. I want to check the type of this using file command and variables. I created this script:

```<code>name="file"
file $name
</code>```

but it is giving this error:

```<code>: cannot open `file\015\015' (No such file or directory)
</code>```

答:
I think the problem is that you named your file as file.

So rename your file as file2, then

```<code>name="file2"
file $name
</code>```

Explanation

The problem with the name file is bash is trying to RUN your file against itself, when you have your current directory in your PATH.

Body:
I have a file named "file" in my current directory. I want to check the type of this using file command and variables. I created this script:

name="file"
file $name

but it is giving this error:

: cannot open `file\015\015' (No such file or directory)

Body:
I think the problem is that you named your file as file.

So rename your file as file2, then

name="file2"
file $name

Explanation

The problem with the name file is bash is trying to RUN your file against itself, when you have your current directory in your PATH.


问:
SUM data over several sheets depending on condition
I want to sum all values in a column on a number of sheets (a specific number of sheets, not all sheets. In this case the sheets "Employee...") depending on the content of another column "Uppdrag".

For each employee (represented by a worksheet) I want to sum the allocated time (per week) to a specific project on a summary sheet "Projekt". I want to place the sum of the allocated time to a project for all employees in one cell for each week.

I have tried the SUMIFS, INDEX, INDIRECT, named ranges and you name it without getting it to work. Perhaps someone with deeper skill than I have got some Ideas?

See attached images and maybe you understand what I want to accomplish.

Regards

答:
The SUMIFS function should work. But I prefer use SUMPRODUCT:

```<code>=SUMPRODUCT(SUM((A2=Sheet2!$A$2:$A$4)*(Sheet2!$B$2:$B$4);(A2=Sheet3!$A$2:$A$4)*(Sheet3!$B$2:$B$4)))
</code>```

Body:
The SUMIFS function should work. But I prefer use SUMPRODUCT:

=SUMPRODUCT(SUM((A2=Sheet2!$A$2:$A$4)*(Sheet2!$B$2:$B$4);(A2=Sheet3!$A$2:$A$4)*(Sheet3!$B$2:$B$4)))


问:
How can I save a GeoDataFrame to disk in Python?
I have an GeoDataFrame called merged and I'm having a very hard time saving it to disk.

merged is obtained through this loop:

```<code>import pandas as pd
import geopandas as gpd
import osmnx as ox

city=gpd.read_file('C:/folder/city.json')
circ=[]

for i in (0, 1):
    graph = ox.graph_from_polygon(city.geometry[i])
    stat = ox.basic_stats(graph)
    circ.append(stat['circuity_avg'])

circ=pd.Series(circ)
merged=pd.concat([city, circ], axis=1)
</code>```

I simply want to save merged to a file, as a json file or another format that preserves the geometry, so that I can then use the data in R. Here are the methods I've tried:

1.

```<code>merged.to_file('merged.json', driver='GeoJSON')
</code>```

which gives

Attribute Error 'int' object has no attribute 'encode'

Does anyone know why merged is classed as 'int' while it is a GeoDataFrame (that's what's indicated when I do type(merged))?

2.

```<code>with open('x.geojson', 'w') as f:
        f.write(merged_short.to_json())
</code>```

This creates a x.geojson file in my Jupyter Lab environment but it doesn't save it to disk. That's understandable since I don't specify a path to save to. However, I on't know how to add a path.

3.

```<code>merged.to_csv("C:/folder/merged.cs")
</code>```

This works but, since the data is saved as csv, the geometry is not preserved.

4.

```<code>merged.to_json("C:/folder/merged.cs")
</code>```

But that gives ValueError: Unknown na method.

I'm very surprised I haven't found a simple way to save GeoDataFrames to a file on my computer. Is there a simple method to save GeoDataFrames?

Solution

```<code>with open('C:/folder/merged.json', 'w') as f:
        f.write(merged_short.to_json())
</code>```

Meaning I just needed to specify the full path.

答:
Your version 2 will save a file, but to a relative location. Try providing an absolute path: </p>

```<code>with open('C:/folder/x.geojson', 'w') as f:
    f.write(merged_short.to_json())
</code>```

Body:
I have an GeoDataFrame called merged and I'm having a very hard time saving it to disk.

merged is obtained through this loop:

import pandas as pd
import geopandas as gpd
import osmnx as ox

city=gpd.read_file('C:/folder/city.json')
circ=[]

for i in (0, 1):
    graph = ox.graph_from_polygon(city.geometry[i])
    stat = ox.basic_stats(graph)
    circ.append(stat['circuity_avg'])

circ=pd.Series(circ)
merged=pd.concat([city, circ], axis=1)

I simply want to save merged to a file, as a json file or another format that preserves the geometry, so that I can then use the data in R. Here are the methods I've tried:

1.

merged.to_file('merged.json', driver='GeoJSON')

which gives

Attribute Error 'int' object has no attribute 'encode'

Does anyone know why merged is classed as 'int' while it is a GeoDataFrame (that's what's indicated when I do type(merged))?

2.

with open('x.geojson', 'w') as f:
        f.write(merged_short.to_json())

This creates a x.geojson file in my Jupyter Lab environment but it doesn't save it to disk. That's understandable since I don't specify a path to save to. However, I on't know how to add a path.

3.

merged.to_csv("C:/folder/merged.cs")

This works but, since the data is saved as csv, the geometry is not preserved.

4.

merged.to_json("C:/folder/merged.cs")

But that gives ValueError: Unknown na method.

I'm very surprised I haven't found a simple way to save GeoDataFrames to a file on my computer. Is there a simple method to save GeoDataFrames?

Solution

with open('C:/folder/merged.json', 'w') as f:
        f.write(merged_short.to_json())

Meaning I just needed to specify the full path.

Body:
Your version 2 will save a file, but to a relative location. Try providing an absolute path:

with open('C:/folder/x.geojson', 'w') as f:
    f.write(merged_short.to_json())


问:
css justify content issue in footer
I have a footer and want that my list items are left justified with my h3. Is there a way to do it?

Now company and social and other are a bit more left than the rest. I already put justify-content: center but it seems like the headers have a different center than my list items. Hope somebody can help me.

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: #5490dd;
  /*Hintergrundfarbe*/
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
}

.footer-column {
  z-index: 2;
  width: 33.33%;
  /*drittelt den Platz im footer*/
  text-align: center;
}

.footer-column ul {
  list-style: none;
  /*entfernt Anstriche*/
}

.footer-column ul li {
  margin: 0;
  padding-top: 5px;
}

.footer-column ul li a {
  text-decoration: none;
  /*entfernt das die Links unterstrichen sind*/
  color: rgb(230, 230, 230);
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="footer-items">

    <div class="footer-column">
      <h3 class="company">Company</h3>
      <ul>
        <li>Kontakt</li>
        <li>Über Uns</li>
        <li>Impressum</li>
      </ul>
    </div>

    <div class="footer-column">
      <h3 class="social">Social</h3>
      <ul>
        <li><a>Twitter</a></li>
        <li><a>Instagram</a></li>
        <li><a>Reddit</a></li>
      </ul>
    </div>

    <div class="footer-column">
      <h3 class="other">other</h3>
      <ul>
        <li><a>other1</a></li>
        <li><a>other2</a></li>
      </ul>
    </div>

  </div></code>```

答:
Why do you need ul li without their styles? Aslo ul has its defaults, which maybe you don't want to use. Use div.

Look into the snippet.

I added padding-bottom to .footer-column and changed ul li to div in html and css

If you want left alignment - remove text-align: center;

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: #5490dd;
  /*Hintergrundfarbe*/
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
}

.footer-column {
  z-index: 2;
  width: 33.33%;
  /*drittelt den Platz im footer*/
  /*text-align: center;*/
  padding-bottom: 16px;
}

.footer-column div {
  margin: 0;
  padding-top: 5px;
}

.footer-column div a {
  text-decoration: none;
  /*entfernt das die Links unterstrichen sind*/
  color: rgb(230, 230, 230);
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="footer-items">

    <div class="footer-column">
      <h3 class="company">Company</h3>
      <div>Kontakt</div>
      <div>Über Uns</div>
      <div>Impressum</div>

    </div>

    <div class="footer-column">
      <h3 class="social">Social</h3>

      <div><a>Twitter</a></div>
      <div><a>Instagram</a></div>
      <div><a>Reddit</a></div>

    </div>

    <div class="footer-column">
      <h3 class="other">other</h3>

      <div><a>other1</a></div>
      <div><a>other2</a></div>

    </div>

  </div></code>```

Title: css justify content issue in footer

Body:
I have a footer and want that my list items are left justified with my h3. Is there a way to do it?

Now company and social and other are a bit more left than the rest. I already put justify-content: center but it seems like the headers have a different center than my list items. Hope somebody can help me.

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: #5490dd;
  /*Hintergrundfarbe*/
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
}

.footer-column {
  z-index: 2;
  width: 33.33%;
  /*drittelt den Platz im footer*/
  text-align: center;
}

.footer-column ul {
  list-style: none;
  /*entfernt Anstriche*/
}

.footer-column ul li {
  margin: 0;
  padding-top: 5px;
}

.footer-column ul li a {
  text-decoration: none;
  /*entfernt das die Links unterstrichen sind*/
  color: rgb(230, 230, 230);
  list-style: none;
}

Company

Kontakt

Über Uns

Impressum

Social

Twitter

Instagram

Reddit

other

other1

other2

Body:
Why do you need ul li without their styles? Aslo ul has its defaults, which maybe you don't want to use. Use div.

Look into the snippet.

I added padding-bottom to .footer-column and changed ul li to div in html and css

If you want left alignment - remove text-align: center;

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: #5490dd;
  /*Hintergrundfarbe*/
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
}

.footer-column {
  z-index: 2;
  width: 33.33%;
  /*drittelt den Platz im footer*/
  /*text-align: center;*/
  padding-bottom: 16px;
}

.footer-column div {
  margin: 0;
  padding-top: 5px;
}

.footer-column div a {
  text-decoration: none;
  /*entfernt das die Links unterstrichen sind*/
  color: rgb(230, 230, 230);
  list-style: none;
}

<footer>

  <div class="footer-items">

    <div class="footer-column">
      <h3 class="company">Company</h3>
      <div><a href="kontakt.html">Kontakt</a></div>
      <div><a href="about.html">Über Uns</a></div>
      <div><a href="impressum.html">Impressum</a></div>

    </div>

    <div class="footer-column">
      <h3 class="social">Social</h3>

      <div><a>Twitter</a></div>
      <div><a>Instagram</a></div>
      <div><a>Reddit</a></div>

    </div>

    <div class="footer-column">
      <h3 class="other">other</h3>

      <div><a>other1</a></div>
      <div><a>other2</a></div>

    </div>

  </div>


问:
PHP, POST data from one row only (id) from WHILE loop, when SUBMIT
Issue, how can I POST needed data (id,username, etc.) only for one row, from while loop, when submit?

Code (I am using POST as call "function" delete_member, with if condition, what is better way?).

```<code>if(isset($_POST["delete_member"]))
{
# Delete member
echo $id=$_POST["id"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message($status);
}

$select_members = mysqli_query($db,"select * from members");
while($row = mysqli_fetch_array($select_members))
{
echo('
<tr>
<td><input type="text name="id" value="'.$row['id'].'" readonly></td>
<td><input type="text name="username" value="'.$row['username'].'" readonly></td>
<td><input type="text name="password" value="'.$row['password'].'" readonly></td>
<td><input type="text name="active" value="'.$row['active'].'" readonly></td>
<td><input type="submit" name="delete_member" value="Smazat"></td>
<td><input type="submit" name="send_email" value="Odeslat email"></td>
<tr>
');
}
</code>```

Nothing stored in echo $id=$_POST["id"];. Is possible send id from input type="submit"? For example like this.

```<code><input type="submit" name="delete_member" id=".$row['id']." value="Smazat">
</code>```

Thanks.

答:
at the end, best method is change input to button, where value is not displayed, so value can be $row['id'] and name is between tags<button>NAME</button>.

```<code>if(isset($_POST["deleteMember"]))
{
# Delete member
$id=$_POST["deleteMember"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message("Smazání člena",$status);
}

while($row = mysqli_fetch_array($select_members))
{
echo('
<tr>
<td><input type="text name="id[]" value="'.$row['id'].'" readonly></td>
<td><input type="text name="username[]" value="'.$row['username'].'" readonly></td>
<td><input type="text name="password[]" value="'.$row['password'].'" readonly></td>
<td><input type="text name="active[]" value="'.$row['active'].'" readonly></td>
<td><input type="text name="sentEmailAll" value="'.$row['email_sent'].'" readonly></td>
<td><button type="submit" name="deleteMember" value="'.$row['id'].'">Vymazat člena</button></td>
<tr>
');
}

</code>```

But I thing this is not elegant, I believe there is better way to solve similar things.

Body:
Issue, how can I POST needed data (id,username, etc.) only for one row, from while loop, when submit?

Code (I am using POST as call "function" delete_member, with if condition, what is better way?).

if(isset($_POST["delete_member"]))
{
# Delete member
echo $id=$_POST["id"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message($status);
}

$select_members = mysqli_query($db,"select * from members");
while($row = mysqli_fetch_array($select_members))
{
echo('

<input type="text name="id" value="'.$row['id'].'" readonly>
<input type="text name="username" value="'.$row['username'].'" readonly>
<input type="text name="password" value="'.$row['password'].'" readonly>
<input type="text name="active" value="'.$row['active'].'" readonly>
<input type="submit" name="delete_member" value="Smazat">
<input type="submit" name="send_email" value="Odeslat email">

');
}

Nothing stored in echo $id=$_POST["id"];. Is possible send id from input type="submit"? For example like this.

<input type="submit" name="delete_member" id=".$row['id']." value="Smazat">

Thanks.

Body:
at the end, best method is change input to button, where value is not displayed, so value can be $row['id'] and name is between tags<button>NAME</button>.

if(isset($_POST["deleteMember"]))
{
# Delete member
$id=$_POST["deleteMember"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message("Smazání člena",$status);
}

while($row = mysqli_fetch_array($select_members))
{
echo('
<tr>
<td><input type="text name="id[]" value="'.$row['id'].'" readonly></td>
<td><input type="text name="username[]" value="'.$row['username'].'" readonly></td>
<td><input type="text name="password[]" value="'.$row['password'].'" readonly></td>
<td><input type="text name="active[]" value="'.$row['active'].'" readonly></td>
<td><input type="text name="sentEmailAll" value="'.$row['email_sent'].'" readonly></td>
<td><button type="submit" name="deleteMember" value="'.$row['id'].'">Vymazat člena</button></td>
<tr>
');
}

But I thing this is not elegant, I believe there is better way to solve similar things.


问:
Reuse pre-allocated opencv Mat/Python object for resize
I am trying to resize an OpenCV image Mat object to a smaller size as show below:

```<code>small = cv2.resize(big, (small_height, small_width))
</code>```

This works perfectly fine, however, it ends up creating a new small OpenCV Mat object every time this line of code is called.

Therefore, I am trying to find a way in which I can avoid creation of a new small Mat object every time. Does anyone have an idea if it even possible to reuse a preallocated Mat object for resize output?

答:
Instead of using small = cv2.resize(...), you can pass the output object by reference: cv2.resize(big, (w, h), small).

I can't say I really understand what happens under the hoods, but I almost certain that the following method can be used for reusing pre-allocated Python object for resize:

```<code># Pre-allocate object (assume output format is uint8 BGR):
small = np.zeros((small_height, small_width, 3), np.uint8)

# Pass output ndarray by reference:
cv2.resize(big, (small_width, small_height), small)
</code>```

Note:

The OpenCV convention is (width, height) and not (height, width) as in your sample code.

Update:

It's actually simple to check if cv2.resize creates a new object, or reuses the existing one.

Here is a simple test that shows that the OpenCV reuses the existing object:

```<code>import cv2
import numpy as np

big = cv2.imread('chelsea.png', cv2.IMREAD_COLOR)

small_width, small_height = 160, 90

# Allocate as twice as much rows (allocate small_height*2 rows istead of small_height rows)
small = np.zeros((small_height*2, small_width, 3), np.uint8)

small[:, :, 1] = 255 # Fill small image with green color
small_slice = small[small_height//2:small_height*3//2, :, :] #Get a slice in the expected size of resized output

# Pass small_slice by reference
cv2.resize(big, (small_width, small_height), small_slice)

cv2.imshow('small', small)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Result:

As you can see the green color is preserved from the original object, and the slice is filled by the output of resize.

Body:
I am trying to resize an OpenCV image Mat object to a smaller size as show below:

small = cv2.resize(big, (small_height, small_width))

This works perfectly fine, however, it ends up creating a new small OpenCV Mat object every time this line of code is called.

Therefore, I am trying to find a way in which I can avoid creation of a new small Mat object every time. Does anyone have an idea if it even possible to reuse a preallocated Mat object for resize output?

Body:
Instead of using small = cv2.resize(...), you can pass the output object by reference: cv2.resize(big, (w, h), small).

I can't say I really understand what happens under the hoods, but I almost certain that the following method can be used for reusing pre-allocated Python object for resize:

# Pre-allocate object (assume output format is uint8 BGR):
small = np.zeros((small_height, small_width, 3), np.uint8)

# Pass output ndarray by reference:
cv2.resize(big, (small_width, small_height), small)

Note:

The OpenCV convention is (width, height) and not (height, width) as in your sample code.

Update:

It's actually simple to check if cv2.resize creates a new object, or reuses the existing one.

Here is a simple test that shows that the OpenCV reuses the existing object:

import cv2
import numpy as np

big = cv2.imread('chelsea.png', cv2.IMREAD_COLOR)

small_width, small_height = 160, 90

# Allocate as twice as much rows (allocate small_height*2 rows istead of small_height rows)
small = np.zeros((small_height*2, small_width, 3), np.uint8)

small[:, :, 1] = 255 # Fill small image with green color
small_slice = small[small_height//2:small_height*3//2, :, :] #Get a slice in the expected size of resized output

# Pass small_slice by reference
cv2.resize(big, (small_width, small_height), small_slice)

cv2.imshow('small', small)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

As you can see the green color is preserved from the original object, and the slice is filled by the output of resize.


问:
How do I package and run a simple command-line application with dependencies using maven?
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

```<code>java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App
</code>```

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

答:
You can use the maven-shade-plugin which will create an executable uber war with all dependencies.

OR

Use the appassembler-plugin which creates a script that imports all dependencies and lets you execute a main class from the command line.

ContentLicense: CC BY-SA 3.0

Body:
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.


问:
'virtualenv' won't activate on Windows
Essentially I cannot seem to activate my virtualenv environment which I create.

I'm doing this inside of Windows PowerShell through using

```<code>scripts\activate
</code>```

but I get an error message:

"cannot be loaded because the execution of scripts is disabled on this
system".

Could this be because I don't carry administrator privileges on my computer?

答:
Based on the answers found here, I created a short tutorial for this with screenshots.

Python 3.7

Windows 10 64bits

PowerShell

I hope it can help: How to setup Python 3 virtual environment on Windows 10

Title: 'virtualenv' won't activate on Windows

Body:
Essentially I cannot seem to activate my virtualenv environment which I create.

I'm doing this inside of Windows PowerShell through using

scripts\activate

but I get an error message:

"cannot be loaded because the execution of scripts is disabled on this
system".

Could this be because I don't carry administrator privileges on my computer?


问:
Angular ngrx design - add new item to the list and not reload the list from the backend
I have a list of notes and a textbox/button to create a new note. When the page loads, I fetch the list of notes from the backend. When the user presses the button to create a new note, we post this new note to the backend. Question is about general UI design best practices.. is it okay to just add the new note to the store slice on the UI such that shows up in the list of notes.. or would it be better practice to now reload the notes list from the backend and have it update that way?

Assume no push notifications in this application

Thank you!

答:
It depends, this isn't something we can't decide based on the information in this question.

If it's just one person using the app, it will be fine to just append the note.
If the application is used by many users and these users update notes, it might be a good idea to refresh the whole list. But also perhaps not.

You can also append the note to the list on the client side because this is fast, then wait for the backend to response with the new list to update the current state.


问:
How to add x days to current time and then get days, hours, minutes from the calculated time
Here's my code, but the result is different than expected. It shows 14 days instead of 30, I want it to show days,hours, minutes remaining until time >= System.currentTimeMillis() (until the calculated timestamp is higher or same as current time in milliseconds)</p>

```<code>int time = (int)System.currentTimeMillis() + 30 * 24 * 60 * 60); //current Time + 30 days

int day = (int)TimeUnit.MILLISECONDS.toDays(time);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time) - (day * 24);
int min = (int) ((int)TimeUnit.MILLISECONDS.toMinutes(time) - (TimeUnit.MILLISECONDS.toHours(time) * 60));

</code>```

答:
There are various things going wrong here.

```<code>int time = (int)System.currentTimeMillis() + (30 * 24 * 60 * 60)
</code>```

In this line you're adding minutes to milliseconds. (30 for days, 24 for hours, 60 for minutes, and 60 for seconds).

Furthermore you're casting everything to a int, while the function is returning a long. At the moment of speaking the value which this function should return is: 1580097230808 (it is returning the time since epoch in milliseconds).

The max value of a int is 2,147,483,647 which is smaller than 1.580.097.230.808, so that will basically cause a overflow (it will overflow multiple times).

Also the value which needs to be added to the time variable (30 * 24 * 60 * 60 * 1000) should be casted to a long first, because it is to large for a int.

So when we do all these steps, this will result in the following code:

```<code>long time = System.currentTimeMillis() + ((long) 30*24*60*60*1000);

System.out.println(time);

int day = (int)TimeUnit.MILLISECONDS.toDays(time);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time) - (day * 24);
int min = (int) ((int)TimeUnit.MILLISECONDS.toMinutes(time) - (TimeUnit.MILLISECONDS.toHours(time) * 60));
System.out.println(day);
System.out.println(hour);
System.out.println(min);
</code>```

Which prints the following results:

```<code>1584393882681 // time in milliseconds since epoch
18337 // number of days since epoch (not the right output)
21 // not the right output
24 // not the right output
</code>```

To get the right output:

```<code>long currentTime = System.currentTimeMillis();
long time = System.currentTimeMillis() + ((long) 30*24*60*60*1000);

System.out.println(time);

int day = (int)TimeUnit.MILLISECONDS.toDays(time - currentTime);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time - currentTime);
int min = (int) TimeUnit.MILLISECONDS.toMinutes(time - currentTime);
System.out.println(day);
System.out.println(hour);
System.out.println(min);
</code>```

prints:

```<code>1584394180556 // time since epoch in milliseconds
30 // days left
720 // hours left
43200 // minutes left
</code>```

So for the last functions you need to give them a time in milliseconds, so you don't have to do any conversion yourself. Basically we did the timestamp we calculated minus the current time, and these functions will calculate the days, hours and minutes based on value (time - currentTime).

Body:
Here's my code, but the result is different than expected. It shows 14 days instead of 30, I want it to show days,hours, minutes remaining until time >= System.currentTimeMillis() (until the calculated timestamp is higher or same as current time in milliseconds)

int time = (int)System.currentTimeMillis() + 30 * 24 * 60 * 60); //current Time + 30 days

int day = (int)TimeUnit.MILLISECONDS.toDays(time);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time) - (day * 24);
int min = (int) ((int)TimeUnit.MILLISECONDS.toMinutes(time) - (TimeUnit.MILLISECONDS.toHours(time) * 60));

Body:
There are various things going wrong here.

int time = (int)System.currentTimeMillis() + (30 * 24 * 60 * 60)

In this line you're adding minutes to milliseconds. (30 for days, 24 for hours, 60 for minutes, and 60 for seconds).

Furthermore you're casting everything to a int, while the function is returning a long. At the moment of speaking the value which this function should return is: 1580097230808 (it is returning the time since epoch in milliseconds).

The max value of a int is 2,147,483,647 which is smaller than 1.580.097.230.808, so that will basically cause a overflow (it will overflow multiple times).

Also the value which needs to be added to the time variable (30 * 24 * 60 * 60 * 1000) should be casted to a long first, because it is to large for a int.

So when we do all these steps, this will result in the following code:

long time = System.currentTimeMillis() + ((long) 30*24*60*60*1000);

System.out.println(time);

int day = (int)TimeUnit.MILLISECONDS.toDays(time);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time) - (day * 24);
int min = (int) ((int)TimeUnit.MILLISECONDS.toMinutes(time) - (TimeUnit.MILLISECONDS.toHours(time) * 60));
System.out.println(day);
System.out.println(hour);
System.out.println(min);

Which prints the following results:

1584393882681 // time in milliseconds since epoch
18337 // number of days since epoch (not the right output)
21 // not the right output
24 // not the right output

To get the right output:

long currentTime = System.currentTimeMillis();
long time = System.currentTimeMillis() + ((long) 30*24*60*60*1000);

System.out.println(time);

int day = (int)TimeUnit.MILLISECONDS.toDays(time - currentTime);
int hour = (int) TimeUnit.MILLISECONDS.toHours(time - currentTime);
int min = (int) TimeUnit.MILLISECONDS.toMinutes(time - currentTime);
System.out.println(day);
System.out.println(hour);
System.out.println(min);

prints:

1584394180556 // time since epoch in milliseconds
30 // days left
720 // hours left
43200 // minutes left

So for the last functions you need to give them a time in milliseconds, so you don't have to do any conversion yourself. Basically we did the timestamp we calculated minus the current time, and these functions will calculate the days, hours and minutes based on value (time - currentTime).


问:
How to iterate 2 data of 2-dimensional arrays with zip in python?
I have 2 data (datatrain and datatest) with id, letter, and answer as the columns:

```<code>import pandas as pd

datatrain = pd.DataFrame([[1,'A','Yes'],[2,'B','No'],[3,'C','Yes'],[4,'A','No'],[5,'B','Yes']], columns=['id','letter','answer'])
datatest = pd.DataFrame([[1,'B',''],[2,'B',''],[3,'B','']], columns=['id','letter','answer'])
</code>```

When I iterate them with zip...

```<code>for (no_train, data_train), (no_test, data_test) in zip(datatrain.groupby('letter'),datatest.groupby('letter')):
    print(data_train.values)
    print(data_test.values)
    // bnb.fit(data_train['id','letter'], data_train['answer'])
    // pred = bnb.predict(data_test['id','letter'])
</code>```

The print(data_test.values) work as intended, but I'll only get the first letter of groupby on print(data_train.values), I want to print all groupby letters of data_train.

Result of print(data_train.values):

```<code>[[1,'A','Yes']
 [4,'A','No']]
</code>```

Expected result of print(data_train.values):

```<code>[[1,'A','Yes']
 [4,'A','No']]
[[2,'B','No']
 [5,'B','Yes']]
[[3,'C','Yes']]
</code>```

How do I iterate 2 data of 2-dimensional arrays with zip? I want to implement Naive Bayes classifier at the same time so I can't separate datatrain and datatest in different loops or nest datatest loop inside of datatrain loop

答:
If you want all 3 letter types in data_train, make sure you have all those 3 types in
datatest.

for example, this should give your expected result

```<code>import pandas as pd

datatrain = pd.DataFrame([[1,'A','Yes'],[2,'B','No'],[3,'C','Yes'],[4,'A','No'],[5,'B','Yes']], columns=['id','letter','answer'])

datatest = pd.DataFrame([[1,'B','xx'],[2,'B','xx'],[3,'B','xx'], [3,'A','yy'], [3,'C','yy']], columns=['id','letter','answer'])

for (no_train, data_train), (no_test, data_test) in zip(datatrain.groupby('letter'), datatest.groupby('letter')):
    print(data_train.values)
</code>```

Result:

```<code>[[1 'A' 'Yes']
 [4 'A' 'No']]
[[2 'B' 'No']
 [5 'B' 'Yes']]
[[3 'C' 'Yes']]
</code>```

this happens because of the way zip() works.

Body:
I have 2 data (datatrain and datatest) with id, letter, and answer as the columns:

import pandas as pd

datatrain = pd.DataFrame([[1,'A','Yes'],[2,'B','No'],[3,'C','Yes'],[4,'A','No'],[5,'B','Yes']], columns=['id','letter','answer'])
datatest = pd.DataFrame([[1,'B',''],[2,'B',''],[3,'B','']], columns=['id','letter','answer'])

When I iterate them with zip...

for (no_train, data_train), (no_test, data_test) in zip(datatrain.groupby('letter'),datatest.groupby('letter')):
    print(data_train.values)
    print(data_test.values)
    // bnb.fit(data_train['id','letter'], data_train['answer'])
    // pred = bnb.predict(data_test['id','letter'])

The print(data_test.values) work as intended, but I'll only get the first letter of groupby on print(data_train.values), I want to print all groupby letters of data_train.

Result of print(data_train.values):

[[1,'A','Yes']
 [4,'A','No']]

Expected result of print(data_train.values):

[[1,'A','Yes']
 [4,'A','No']]
[[2,'B','No']
 [5,'B','Yes']]
[[3,'C','Yes']]

How do I iterate 2 data of 2-dimensional arrays with zip? I want to implement Naive Bayes classifier at the same time so I can't separate datatrain and datatest in different loops or nest datatest loop inside of datatrain loop

Body:
If you want all 3 letter types in data_train, make sure you have all those 3 types in
datatest.

for example, this should give your expected result

import pandas as pd

datatrain = pd.DataFrame([[1,'A','Yes'],[2,'B','No'],[3,'C','Yes'],[4,'A','No'],[5,'B','Yes']], columns=['id','letter','answer'])

datatest = pd.DataFrame([[1,'B','xx'],[2,'B','xx'],[3,'B','xx'], [3,'A','yy'], [3,'C','yy']], columns=['id','letter','answer'])

for (no_train, data_train), (no_test, data_test) in zip(datatrain.groupby('letter'), datatest.groupby('letter')):
    print(data_train.values)

Result:

[[1 'A' 'Yes']
 [4 'A' 'No']]
[[2 'B' 'No']
 [5 'B' 'Yes']]
[[3 'C' 'Yes']]

this happens because of the way zip() works.


问:
Service Worker is grabbing everything
I have just recently started fiddling with service workers and am having a situation where no matter what file(s) I tell it to add to the cache, it is adding everything. Now, this would normally mean less work for me toward an offline application, but I am a bit confused. So the cache seems to have two methods of adding requests to it, .add() and .addAll(), with the latter being capable of receiving an array of requests, but even with just .add() with a request hardcoded into it, absolutely all requests seem to end up in the cache.

The code I have is as follows:

```<code>    if ('serviceWorker' in navigator) {
        //console.log('CLIENT: service worker registration in progress.');
        navigator.serviceWorker.register('/sw.js').then(function() {
            //console.log('CLIENT: service worker registration complete.');
        }, function() {
            //console.log('CLIENT: service worker registration failure.');
    });
    } else {
        console.log('CLIENT: service worker is not supported.');
    }
</code>```

... this being in the actual page calling the service worker, and the service worker itself:

```<code>var cacheName = 'cache';

self.addEventListener('install', (e) => {
    console.log('[Service Worker] Install');
var appShellFiles = [
];

e.waitUntil(
    caches.open(cacheName).then((cache) => {
          console.log('[Service Worker] Caching all: app shell and content');
      return cache.add('assets/images/boy.svg').then(function() {
        // requests have been added to the cache
        console.log('added')
      });
    })
  );
});

self.addEventListener('fetch', (e) => {
    e.respondWith(
      caches.match(e.request).then((r) => {
            console.log('[Service Worker] Fetching resource: '+e.request.url);
        return r || fetch(e.request).then((response) => {
                  return caches.open(cacheName).then((cache) => {
            console.log('[Service Worker] Caching new resource: '+e.request.url);
            cache.put(e.request, response.clone());
            return response;
          });
        });
      })
    );
  });

self.addEventListener('activate', (e) => {
    e.waitUntil(
      caches.keys().then((keyList) => {
            return Promise.all(keyList.map((key) => {
          if(key !== cacheName) {
            return caches.delete(key);
          }
        }));
      })
    );
  });
</code>```

... but in here .add('assets/images/boy.svg') used to be .addAll(appShellFiles), which itself used to contain individual files, but seemed to ignore the list and still cache everything. What am I missing?

答:
It's very simple. Look at this code:

```<code>self.addEventListener('fetch', (e) => {
    e.respondWith(
      caches.match(e.request).then((r) => {
            console.log('[Service Worker] Fetching resource: '+e.request.url);
        return r || fetch(e.request).then((response) => {
                  return caches.open(cacheName).then((cache) => {
            console.log('[Service Worker] Caching new resource: '+e.request.url);
            cache.put(e.request, response.clone());
            return response;
          });
        });
      })
    );
  });
</code>```

It saves everything in the cache dynamically/on the fly/automatically. Your code is correct – initially it only caches the one file you mentioned. But immediately as the app starts up, the SW caches everything.

Another way to look at this problem of "caching everything": caching everything doesn't even mean anything. The browser has no way of knowing what that "everything" means for a particular site. It could be 4 or 4000 assets. Once this is realized, it is only a matter of finding the correct piece of code.

Title: Service Worker is grabbing everything

Body:
I have just recently started fiddling with service workers and am having a situation where no matter what file(s) I tell it to add to the cache, it is adding everything. Now, this would normally mean less work for me toward an offline application, but I am a bit confused. So the cache seems to have two methods of adding requests to it, .add() and .addAll(), with the latter being capable of receiving an array of requests, but even with just .add() with a request hardcoded into it, absolutely all requests seem to end up in the cache.

The code I have is as follows:

    if ('serviceWorker' in navigator) {
        //console.log('CLIENT: service worker registration in progress.');
        navigator.serviceWorker.register('/sw.js').then(function() {
            //console.log('CLIENT: service worker registration complete.');
        }, function() {
            //console.log('CLIENT: service worker registration failure.');
    });
    } else {
        console.log('CLIENT: service worker is not supported.');
    }

... this being in the actual page calling the service worker, and the service worker itself:

var cacheName = 'cache';

self.addEventListener('install', (e) => {
    console.log('[Service Worker] Install');
var appShellFiles = [
];

e.waitUntil(
    caches.open(cacheName).then((cache) => {
          console.log('[Service Worker] Caching all: app shell and content');
      return cache.add('assets/images/boy.svg').then(function() {
        // requests have been added to the cache
        console.log('added')
      });
    })
  );
});

self.addEventListener('fetch', (e) => {
    e.respondWith(
      caches.match(e.request).then((r) => {
            console.log('[Service Worker] Fetching resource: '+e.request.url);
        return r || fetch(e.request).then((response) => {
                  return caches.open(cacheName).then((cache) => {
            console.log('[Service Worker] Caching new resource: '+e.request.url);
            cache.put(e.request, response.clone());
            return response;
          });
        });
      })
    );
  });

self.addEventListener('activate', (e) => {
    e.waitUntil(
      caches.keys().then((keyList) => {
            return Promise.all(keyList.map((key) => {
          if(key !== cacheName) {
            return caches.delete(key);
          }
        }));
      })
    );
  });

... but in here .add('assets/images/boy.svg') used to be .addAll(appShellFiles), which itself used to contain individual files, but seemed to ignore the list and still cache everything. What am I missing?

Body:
It's very simple. Look at this code:

self.addEventListener('fetch', (e) => {
    e.respondWith(
      caches.match(e.request).then((r) => {
            console.log('[Service Worker] Fetching resource: '+e.request.url);
        return r || fetch(e.request).then((response) => {
                  return caches.open(cacheName).then((cache) => {
            console.log('[Service Worker] Caching new resource: '+e.request.url);
            cache.put(e.request, response.clone());
            return response;
          });
        });
      })
    );
  });

It saves everything in the cache dynamically/on the fly/automatically. Your code is correct – initially it only caches the one file you mentioned. But immediately as the app starts up, the SW caches everything.

Another way to look at this problem of "caching everything": caching everything doesn't even mean anything. The browser has no way of knowing what that "everything" means for a particular site. It could be 4 or 4000 assets. Once this is realized, it is only a matter of finding the correct piece of code.


问:
Cannot find added elements in Tabbed Activity
I created a Tabbed Activity template project using Android Studio.
Then I created a LinearLayout with a nested TextView on it:

```<code>    <LinearLayout
        android:id="@+id/updateView"

        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_marginTop="707dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/updateTextView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="right"
            android:text="TextView" />
    </LinearLayout>
</code>```

This view is shown on preview, but there's none of it in the built app.

When I try to get a reference to it from my code:

```<code>LinearLayout lastUpdate = findViewById(R.id.updateView)
</code>```

I get null in runtime.
So, how can I modify the code?

Preview screenshot

答: I solved my problem by moving xml code of LinearLayout upper, than code of AppBarLayout, and modification of dynamic pixels (dp) of ViewPager and my textView</p>

Body:
I created a Tabbed Activity template project using Android Studio.
Then I created a LinearLayout with a nested TextView on it:

    <LinearLayout
        android:id="@+id/updateView"

        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_marginTop="707dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/updateTextView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="right"
            android:text="TextView" />
    </LinearLayout>

This view is shown on preview, but there's none of it in the built app.

When I try to get a reference to it from my code:

LinearLayout lastUpdate = findViewById(R.id.updateView)

I get null in runtime.
So, how can I modify the code?

Preview screenshot


问:
template webform submission page
I'm new to drupal and theming and I want to design the following page for webform submission.
webform/my_form/submissions
Is there a file I should override in my theme?

Thanks in advance.

答:
I set the debug to true in services.yml file to check the names of the files. I found

then I override it in my theme.

Title: template webform submission page

Body:
I set the debug to true in services.yml file to check the names of the files. I found
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/dataset/table.html.twig' -->
then I override it in my theme.


问:
Java min() method Not Returning Minimum Value in Array
I know that there's other strategies that I can use (e.g. sorting the array and then just returning the array's index at [0]), but I am just practicing other techniques to find the min value in an array.

```<code>import java.util.Arrays;

public class ArrayUtils {

    static int[] integers = new int[] {1, 3, 2, 10, 15, 30};

    public static int max(int[] integers) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] > i)
                max = integers[i];
        }
        return max;
    }

    public static int min(int[] integers) {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] < i) {
                min = integers[i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(integers));
        System.out.println("Max value: " + max(integers));
        System.out.println("Min value: " + min(integers));
    }
}
</code>```

Output:

```<code>[1, 3, 2, 10, 15, 30]
Max value: 30
Min value: 2147483647
</code>```

Why does my logic work for the max(int[] integers) method but not my min(int[] integers) method?

答:
Both of your functions are incorrect as you are comparing integers[i] to i. You need to compare to min or max. For min() try the following:

```<code>public static int min(int[] integers) {
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < integers.length; i++) {
        if (integers[i] < min) {  // <-- change here
            min = integers[i];
        }
    }
    return min;
}
</code>```

You also need to make a similar change to max(). It was simply luck that it was producing a correct result with your integers.

Body:
I know that there's other strategies that I can use (e.g. sorting the array and then just returning the array's index at [0]), but I am just practicing other techniques to find the min value in an array.

import java.util.Arrays;

public class ArrayUtils {

    static int[] integers = new int[] {1, 3, 2, 10, 15, 30};

    public static int max(int[] integers) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] > i)
                max = integers[i];
        }
        return max;
    }

    public static int min(int[] integers) {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] < i) {
                min = integers[i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(integers));
        System.out.println("Max value: " + max(integers));
        System.out.println("Min value: " + min(integers));
    }
}

Output:

[1, 3, 2, 10, 15, 30]
Max value: 30
Min value: 2147483647

Why does my logic work for the max(int[] integers) method but not my min(int[] integers) method?

Body:
Both of your functions are incorrect as you are comparing integers[i] to i. You need to compare to min or max. For min() try the following:

public static int min(int[] integers) {
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < integers.length; i++) {
        if (integers[i] < min) {  // <-- change here
            min = integers[i];
        }
    }
    return min;
}

You also need to make a similar change to max(). It was simply luck that it was producing a correct result with your integers.


问:
Select a column value with the fewest occurrences
I'm not sure if it is possible to do it in the SQL itself with just one query but that's why I'm asking.

Is there a way to get the column value with the least occurrence in table?

A table would look like:

```<code>| Id | Value |
--------------
| 1  | Banana|
| 2  | Carrot|
| 3  | Apple |
| 4  | Apple |
| 5  | Banana|
| 6  | Apple |
| 7  | Apple |
| 8  | Banana|
| 9  | Apple |
</code>```

Now that there's a "Carrot" value with the least occurrences, how would a SQL look like to get the value with the least occurrences? Kinda confusing and maybe you won't understand on the first try. Thanks.

答:
you can also try this, even though it is more complicated and less elegant :</p>

```<code>select value from(select value, count(*) c from mytable group by value having c = (select max(c) from(select value, count(*) c from mytable group by value) b )) a
</code>```

Body:
I'm not sure if it is possible to do it in the SQL itself with just one query but that's why I'm asking.

Is there a way to get the column value with the least occurrence in table?

A table would look like:

| Id | Value |
--------------
| 1  | Banana|
| 2  | Carrot|
| 3  | Apple |
| 4  | Apple |
| 5  | Banana|
| 6  | Apple |
| 7  | Apple |
| 8  | Banana|
| 9  | Apple |

Now that there's a "Carrot" value with the least occurrences, how would a SQL look like to get the value with the least occurrences? Kinda confusing and maybe you won't understand on the first try. Thanks.

Body:
you can also try this, even though it is more complicated and less elegant :

select value from(select value, count(*) c from mytable group by value having c = (select max(c) from(select value, count(*) c from mytable group by value) b )) a


答:
In both min(...) and max(...), you compare integers[i] against i in the if-clause. You most probably intended to compare them against min and max respectively.

A remark on the comment you made: "I know that there's other strategies that I can use (e.g. sorting the array and then just returning the array's index at [0])..." - This solution is slower (time complexity of O(n log n) vs O(n)).

Title: Java min() method Not Returning Minimum Value in Array


问:
PHP — Information on the zip:// protocol
I am using ZipArchive class to unzip a file and put its contents somewhere useful. Using information derived from the comments on php.net, I ended up writing this function:

```<code>function unzip(string $zipFile, string $destination) {
    $zip = new ZipArchive();
    $zip->open($zipFile);
    for($i=0; $i<$zip->numFiles; $i++) {
         $file=$zip->getNameIndex($i);
         if(substr($file,-1) == '/') continue;  //  skip containing folder
         $name=basename($file);
         copy("zip://$zipFile#$file","$destination/$name");
     }
    $zip->close();
}
</code>```

This is to copy the individual files without the folder structure.

I can understand most of the code, but I cannot get any information on the following expression:

```<code>"zip://$zipFile#$file"
</code>```

I know what it doing (obviously it is extracting one of the files from the Zip archive), but can anyone tell me more about the zip:// protocol, and why it uses the # to reference a particular file?

答:
Check out source of Zip extension
https://github.com/php/php-src/blob/master/ext/zip/zip_stream.c

line 135. fragment = strchr(path, '#');

get pointer of entry in path/to/zip#entry

line 141.

```<code>if (strncasecmp("zip://", path, 6) == 0)
{
   path += 6;
}
</code>```

if zip:// is equal first 6 characters of path

I won't go into the logic of this code. It just exists here (zip_stream.c) and maybe somewhere else.

It seems like this extension "creates" zip:// protocol over php executable that is laying over apache server.

Body:
I am using ZipArchive class to unzip a file and put its contents somewhere useful. Using information derived from the comments on php.net, I ended up writing this function:

function unzip(string $zipFile, string $destination) {
    $zip = new ZipArchive();
    $zip->open($zipFile);
    for($i=0; $i<$zip->numFiles; $i++) {
         $file=$zip->getNameIndex($i);
         if(substr($file,-1) == '/') continue;  //  skip containing folder
         $name=basename($file);
         copy("zip://$zipFile#$file","$destination/$name");
     }
    $zip->close();
}

This is to copy the individual files without the folder structure.

I can understand most of the code, but I cannot get any information on the following expression:

"zip://$zipFile#$file"

I know what it doing (obviously it is extracting one of the files from the Zip archive), but can anyone tell me more about the zip:// protocol, and why it uses the # to reference a particular file?

Body:
Check out source of Zip extension
https://github.com/php/php-src/blob/master/ext/zip/zip_stream.c

line 135. fragment = strchr(path, '#');

get pointer of entry in path/to/zip#entry

line 141.

if (strncasecmp("zip://", path, 6) == 0)
{
   path += 6;
}

if zip:// is equal first 6 characters of path

I won't go into the logic of this code. It just exists here (zip_stream.c) and maybe somewhere else.

It seems like this extension "creates" zip:// protocol over php executable that is laying over apache server.


答:
You're comparing the values in the array to their index, not to the current minimum/maximum. Update your min function to include the follwoing statement in the for loop:

```<code>if (integers[i] < min) {
    min = integers[i];
}

</code>```

You will want to do likewise with max.

Body:
You're comparing the values in the array to their index, not to the current minimum/maximum. Update your min function to include the follwoing statement in the for loop:

if (integers[i] < min) {
    min = integers[i];
}

You will want to do likewise with max.


问:
Angular redirects when I hit enter in an input field
I have the following application with an input field. When I type in and hit enter, the app forwards to http://example.org/?. Rather than firing the onEnter event. The onKey event work fine. How can I stop this redirecting happening?

here is the html:

```<code><mat-card>
  <form class="example-form">
    <mat-form-field class="example-full-width">
      <input matInput placeholder="How can I help" (keyup)="onKey($event)">
      <mat-icon matSuffix>?</mat-icon>
    </mat-form-field>
  </form>
</mat-card>
</code>```

and the ts:

```<code>import { Component, OnInit } from '@angular/core';

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

  onKey(event) {
    console.log(event.target.value)
  }
}
</code>```

答:
The form is submitting when you hit enter. This behavior is the default.  By definition, a form is submittable. Given that, register a submit handler for your form to  control what it means for the form to be submitted.

```<code>@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent {
  onSubmit() {

  }
  onKey(event) {
    console.log(event.target.value)
  }
}
</code>```

Now, in your template

```<code><form (ngSubmit)="onSubmit()">
<form>
</code>```

Body:
I have the following application with an input field. When I type in and hit enter, the app forwards to http://example.org/?. Rather than firing the onEnter event. The onKey event work fine. How can I stop this redirecting happening?

here is the html:

<mat-card>
  <form class="example-form">
    <mat-form-field class="example-full-width">
      <input matInput placeholder="How can I help" (keyup)="onKey($event)">
      <mat-icon matSuffix>?</mat-icon>
    </mat-form-field>
  </form>
</mat-card>

and the ts:

import { Component, OnInit } from '@angular/core';

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

  onKey(event) {
    console.log(event.target.value)
  }
}

Body:
The form is submitting when you hit enter. This behavior is the default.  By definition, a form is submittable. Given that, register a submit handler for your form to  control what it means for the form to be submitted.

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent {
  onSubmit() {

  }
  onKey(event) {
    console.log(event.target.value)
  }
}

Now, in your template

<form (ngSubmit)="onSubmit()">
<form>


问:
how to calculate different number of days a date column has
I have a dataframe that has multiple rows with many dates.How to calculate number of rows matching a date and number of unique dates we have :</p>

```<code>linear_acceleration 2017-06-29 07:47:21
gravity 2017-06-29 07:47:21
pressure 2017-06-30 07:47:22
heart_rate 2017-07-01 07:47:22
magnetometer 2017-07-02 07:47:22
</code>```

答:
If the dates are all in a single column called date and your data frame is called df you can do this:

length(table(substr(as.character(df$date), 1, 10)))
```

<p>to get the number of unique dates.</p>

<p>If you have a date called <code>test_date</code> you wish to match and you want to work in base R you can do:</p>

```which(substr(as.character(df$date), 1, 10) == as.character(test_date))
```

Body:
I have a dataframe that has multiple rows with many dates.How to calculate number of rows matching a date and number of unique dates we have :

linear_acceleration 2017-06-29 07:47:21
gravity 2017-06-29 07:47:21
pressure 2017-06-30 07:47:22
heart_rate 2017-07-01 07:47:22
magnetometer 2017-07-02 07:47:22

Body:
If the dates are all in a single column called date and your data frame is called df you can do this:

length(table(substr(as.character(df$date), 1, 10)))

to get the number of unique dates.

If you have a date called test_date you wish to match and you want to work in base R you can do:

which(substr(as.character(df$date), 1, 10) == as.character(test_date))


问:
How to replace string in angular 2?
I have used with below interpolation in html page.

```<code><div>{{config.CompanyAddress.replace('\n','<br />')}}</div>
</code>```

and also used

```<code><div>{{config.CompanyAddress.toString().replace('\n','<br />')}}</div>
</code>```

But both are showing text as below

```<code>{{config.CompanyAddress.replace('\n','<br />')}}
{{config.CompanyAddress.toString().replace('\n','<br />')}}
</code>```

答:
I was looking for an approach for replacing a sub-string in a variable in an angular template, but passing both the substring and the replacement by parameter to the pipe.

```<code>//TS
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "replaceSubstring" })
export class ReplaceSubstring implements PipeTransform {
  transform(subject: string, substring: string, replacement: string): string {

    //notice the need to instantiate a RegExp object, since passing
    //'substring' directly will NOT work, for example
    //subject.replace(substring, replacement) and
    //subject.replace(`/${substring}/`, replacement) don't work

    return subject.replace(new RegExp(substring), replacement);
  }
}

<!--HTML-->
<!--Example: remove a dot and the numbers after it, from the end of 'variable'-->
<!--Parameters in this case are "\\.\\d*`$" and "",
    you can pass as many as you want, separated by colons ':'-->

{{ variable | replaceSubstring: "\\.\\d*`$" : "" }}
</code>```

Title: How to replace string in angular 2?

Body:
I have used with below interpolation in html page.

{{config.CompanyAddress.replace('\n','
')}}

and also used

{{config.CompanyAddress.toString().replace('\n','
')}}

But both are showing text as below

{{config.CompanyAddress.replace('\n','
')}}
{{config.CompanyAddress.toString().replace('\n','
')}}

Body:
I was looking for an approach for replacing a sub-string in a variable in an angular template, but passing both the substring and the replacement by parameter to the pipe.

//TS
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "replaceSubstring" })
export class ReplaceSubstring implements PipeTransform {
  transform(subject: string, substring: string, replacement: string): string {

    //notice the need to instantiate a RegExp object, since passing
    //'substring' directly will NOT work, for example
    //subject.replace(substring, replacement) and
    //subject.replace(`/${substring}/`, replacement) don't work

    return subject.replace(new RegExp(substring), replacement);
  }
}

<!--HTML-->
<!--Example: remove a dot and the numbers after it, from the end of 'variable'-->
<!--Parameters in this case are "\\.\\d*`$" and "",
    you can pass as many as you want, separated by colons ':'-->

{{ variable | replaceSubstring: "\\.\\d*`$" : "" }}


问:
git add on a file excluded by .gitignore
Is there a way to track a new file in git that is excluded by a rule present in .gitignore? I would like to do this without adding a single file/directory exclusion in my .gitignore rules.</p>

答:
```<code>Use -f if you really want to add them.
</code>```

With Git 2.26 (Q1 2020), this is now an "hint", controlled with two new help messages given when "git add" notices the user gave it nothing to add.

That means, make sure git config advice.addIgnoredFile is not set to true (which is indeed the case by default: its default value is false), or you would not realize a git add -f is needed here.

See commit 887a0fd (06 Feb 2020), and commit bf66db3 (07 Jan 2020) by Heba Waly (HebaWaly).

(Merged by Junio C Hamano -- gitster -- in commit daef1b3, 14 Feb 2020)

add: change advice config variables used by the add API

Signed-off-by: Heba Waly

advice.addNothing config variable is used to control the visibility of two advice messages in the add library.

  This config variable is replaced by two new variables, whose names are more clear and relevant to the two cases.

Also add the two new variables to the documentation.

addIgnoredFile:

  Advice shown if a user attempts to add an ignored file to the index.

addEmptyPathspec:

  Advice shown if a user runs the add command without providing the pathspec parameter.

The hints now are:

```<code>Use -f if you really want to add them.
Turn this message off by running
"git config advice.addIgnoredFile false"
</code>```

And:

```<code>Maybe you wanted to say 'git add .'?
Turn this message off by running
"git config advice.addEmptyPathspec false"
</code>```

Body:
Use -f if you really want to add them.

With Git 2.26 (Q1 2020), this is now an "hint", controlled with two new help messages given when "git add" notices the user gave it nothing to add.

That means, make sure git config advice.addIgnoredFile is not set to true (which is indeed the case by default: its default value is false), or you would not realize a git add -f is needed here.

See commit 887a0fd (06 Feb 2020), and commit bf66db3 (07 Jan 2020) by Heba Waly (HebaWaly).

(Merged by Junio C Hamano -- gitster -- in commit daef1b3, 14 Feb 2020)

add: change advice config variables used by the add API

Signed-off-by: Heba Waly

advice.addNothing config variable is used to control the visibility of two advice messages in the add library.

  This config variable is replaced by two new variables, whose names are more clear and relevant to the two cases.

Also add the two new variables to the documentation.

addIgnoredFile:

  Advice shown if a user attempts to add an ignored file to the index.

addEmptyPathspec:

  Advice shown if a user runs the add command without providing the pathspec parameter.

The hints now are:

Use -f if you really want to add them.
Turn this message off by running
"git config advice.addIgnoredFile false"

And:

Maybe you wanted to say 'git add .'?
Turn this message off by running
"git config advice.addEmptyPathspec false"


问:
Why are my service workers not working offline
Everything seems to be right and the files are being cached but it just doesn't work offline. Am I missing something obvious?

the cache.addAll did not want to work with my const FILES_TO_CACHE but do work when I put them in directly. Thus the repeated code.

Here is my service worker file:

```<code>const FILES_TO_CACHE = [
  "/",
  "/index.html",
  "/style.css",
  "/db.js",
  "/index.js",
  "/manifest.webmanifest"
];

const CACHE_NAME = "static-cache-v2";
const DATA_CACHE_NAME = "data-cache-v1";

// install
self.addEventListener("install", function(evt) {
  evt.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      console.log("Your files were pre-cached successfully!");
      return cache.addAll([
        "/",
        "/index.html",
        "/style.css",
        "/db.js",
        "/index.js",
        "/manifest.webmanifest"
      ]);
    })
  );

  self.skipWaiting();
});

// activate
self.addEventListener("activate", function(evt) {
  console.log("activated");
  evt.waitUntil(
    caches.keys().then(keyList => {
      return Promise.all(
        keyList.map(key => {
          if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) {
            console.log("Removing old cache data", key);
            return caches.delete(key);
          }
        })
      ).catch(err => console.log(err));
    })
  );

  self.clients.claim();
});

// fetch
self.addEventListener("fetch", function(evt) {
  console.log("fetched", evt.request.url);

  if (evt.request.url.includes("/api/")) {
    evt.respondWith(
      caches
        .open(FILES_TO_CACHE)
        .then(cache => {
          return fetch(evt.request)
            .then(response => {
              // If the response was good, clone it and store it in the cache.
              if (response.status === 200) {
                cache.put(evt.request.url, response.clone());
              }

              return response;
            })
            .catch(err => {
              // Network request failed, try to get it from the cache.
              return cache.match(evt.request);
            });
        })
        .catch(err => console.log(err))
    );

    return;
  }
});
</code>```

link in html:

```<code><script>
      if ("serviceWorker" in navigator) {
        navigator.serviceWorker.register("/service-worker.js").then(function() {
          console.log("Service Worker Registered");
        });
      }
    </script>
</code>```

I also have my manifest linked in the HTML file.

Thank you in advance for any help you can provide!

答:
If you look at the last line of code here:

```<code>// fetch
self.addEventListener("fetch", function(evt) {
  console.log("fetched", evt.request.url);

  if (evt.request.url.includes("/api/")) {
</code>```

you see that there's a very simple mistake – your Service Worker is ONLY responding to requests that start with "/api/". If they don't, the SW doesn't touch them. Thus only "/api/" calls work offline (which doesn't make any sense :-), apis being mostly dynamic, right?).

(It is possible that there's another bug in the code of course, but this is a good point to start making changes.)

Body:
Everything seems to be right and the files are being cached but it just doesn't work offline. Am I missing something obvious?

the cache.addAll did not want to work with my const FILES_TO_CACHE but do work when I put them in directly. Thus the repeated code.

Here is my service worker file:

const FILES_TO_CACHE = [
  "/",
  "/index.html",
  "/style.css",
  "/db.js",
  "/index.js",
  "/manifest.webmanifest"
];

const CACHE_NAME = "static-cache-v2";
const DATA_CACHE_NAME = "data-cache-v1";

// install
self.addEventListener("install", function(evt) {
  evt.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      console.log("Your files were pre-cached successfully!");
      return cache.addAll([
        "/",
        "/index.html",
        "/style.css",
        "/db.js",
        "/index.js",
        "/manifest.webmanifest"
      ]);
    })
  );

  self.skipWaiting();
});

// activate
self.addEventListener("activate", function(evt) {
  console.log("activated");
  evt.waitUntil(
    caches.keys().then(keyList => {
      return Promise.all(
        keyList.map(key => {
          if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) {
            console.log("Removing old cache data", key);
            return caches.delete(key);
          }
        })
      ).catch(err => console.log(err));
    })
  );

  self.clients.claim();
});

// fetch
self.addEventListener("fetch", function(evt) {
  console.log("fetched", evt.request.url);

  if (evt.request.url.includes("/api/")) {
    evt.respondWith(
      caches
        .open(FILES_TO_CACHE)
        .then(cache => {
          return fetch(evt.request)
            .then(response => {
              // If the response was good, clone it and store it in the cache.
              if (response.status === 200) {
                cache.put(evt.request.url, response.clone());
              }

              return response;
            })
            .catch(err => {
              // Network request failed, try to get it from the cache.
              return cache.match(evt.request);
            });
        })
        .catch(err => console.log(err))
    );

    return;
  }
});

link in html:

I also have my manifest linked in the HTML file.

Thank you in advance for any help you can provide!

Body:
If you look at the last line of code here:

// fetch
self.addEventListener("fetch", function(evt) {
  console.log("fetched", evt.request.url);

  if (evt.request.url.includes("/api/")) {

you see that there's a very simple mistake – your Service Worker is ONLY responding to requests that start with "/api/". If they don't, the SW doesn't touch them. Thus only "/api/" calls work offline (which doesn't make any sense :-), apis being mostly dynamic, right?).

(It is possible that there's another bug in the code of course, but this is a good point to start making changes.)


问:
Permute all unique enumerations of a vector in R
I'm trying to find a function that will permute all the unique permutations of a vector, while not counting juxtapositions within subsets of the same element type. For example:

```<code>dat <- c(1,0,3,4,1,0,0,3,0,4)
</code>```

has

```<code>factorial(10)
> 3628800
</code>```

possible permutations, but only 10!/(2!*2!*4!*2!)

```<code>factorial(10)/(factorial(2)*factorial(2)*factorial(2)*factorial(4))
> 18900
</code>```

unique permutations when ignoring juxtapositions within subsets of the same element type.

I can get this by using unique() and the permn() function from the package combinat

```<code>unique( permn(dat) )
</code>```

but this is computationally very expensive, since it involves enumerating n!, which can be an order of magnitude more permutations than I need. Is there a way to do this without first computing n!?

答:
As this question is old and continues to attract many views, this post is solely meant to inform R users of the current state of the language with regards to performing the popular task outlined by the OP. As @RandyLai alludes to, there are packages developed with this task in mind. They are: arrangements and  RcppAlgos*.

Efficiency

They are very efficient and quite easy to use for generating permutations of a multiset.

```<code>dat <- c(1, 0, 3, 4, 1, 0, 0, 3, 0, 4)
dim(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
[1] 18900    10

microbenchmark(algos = RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)),
               arngmnt = arrangements::permutations(sort(unique(dat)), freq = table(dat)),
               curaccptd = uniqueperm2(dat), unit = "relative")
Unit: relative
     expr       min        lq       mean    median        uq       max neval
    algos  1.000000  1.000000  1.0000000  1.000000  1.000000 1.0000000   100
  arngmnt  1.501262  1.093072  0.8783185  1.089927  1.133112 0.3238829   100
curaccptd 19.847457 12.573657 10.2272080 11.705090 11.872955 3.9007364   100
</code>```

With RcppAlgos we can utilize parallel processing for even better efficiency on larger examples.

```<code>hugeDat <- rep(dat, 2)[-(1:5)]
RcppAlgos::permuteCount(sort(unique(hugeDat)), freqs = table(hugeDat))
[1] 3603600

microbenchmark(algospar = RcppAlgos::permuteGeneral(sort(unique(hugeDat)),
                                                    freqs = table(hugeDat), nThreads = 4),
               arngmnt = arrangements::permutations(sort(unique(hugeDat)), freq = table(hugeDat)),
               curaccptd = uniqueperm2(hugeDat), unit = "relative", times = 10)
Unit: relative
     expr      min        lq      mean    median       uq      max neval
 algospar  1.00000  1.000000  1.000000  1.000000  1.00000  1.00000    10
  arngmnt  3.23193  3.109092  2.427836  2.598058  2.15965  1.79889    10
curaccptd 49.46989 45.910901 34.533521 39.399481 28.87192 22.95247    10
</code>```

Lexicographical Order

A nice benefit of these packages is that the output is in lexicographical order:

```<code>head(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    1    1    3    3    4     4
[2,]    0    0    0    0    1    1    3    4    3     4
[3,]    0    0    0    0    1    1    3    4    4     3
[4,]    0    0    0    0    1    1    4    3    3     4
[5,]    0    0    0    0    1    1    4    3    4     3
[6,]    0    0    0    0    1    1    4    4    3     3

tail(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[18895,]    4    4    3    3    0    1    1    0    0     0
[18896,]    4    4    3    3    1    0    0    0    0     1
[18897,]    4    4    3    3    1    0    0    0    1     0
[18898,]    4    4    3    3    1    0    0    1    0     0
[18899,]    4    4    3    3    1    0    1    0    0     0
[18900,]    4    4    3    3    1    1    0    0    0     0

identical(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)),
      arrangements::permutations(sort(unique(dat)), freq = table(dat)))
[1] TRUE
</code>```

Iterators

Additionally, both packages offer iterators that allow for memory efficient generation of permutation, one by one:

```<code>algosIter <- RcppAlgos::permuteIter(sort(unique(dat)), freqs = table(dat))

algosIter$nextIter()
[1] 0 0 0 0 1 1 3 3 4 4

algosIter$nextNIter(5)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    1    1    3    4    3     4
[2,]    0    0    0    0    1    1    3    4    4     3
[3,]    0    0    0    0    1    1    4    3    3     4
[4,]    0    0    0    0    1    1    4    3    4     3
[5,]    0    0    0    0    1    1    4    4    3     3

## last permutation
algosIter$back()
[1] 4 4 3 3 1 1 0 0 0 0

## use reverse iterator methods
algosIter$prevNIter(5)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    4    4    3    3    1    0    1    0    0     0
[2,]    4    4    3    3    1    0    0    1    0     0
[3,]    4    4    3    3    1    0    0    0    1     0
[4,]    4    4    3    3    1    0    0    0    0     1
[5,]    4    4    3    3    0    1    1    0    0     0
</code>```

* I am the author of RcppAlgos

Body:
I'm trying to find a function that will permute all the unique permutations of a vector, while not counting juxtapositions within subsets of the same element type. For example:

dat <- c(1,0,3,4,1,0,0,3,0,4)

has

factorial(10)
> 3628800

possible permutations, but only 10!/(2!*2!*4!*2!)

factorial(10)/(factorial(2)*factorial(2)*factorial(2)*factorial(4))
> 18900

unique permutations when ignoring juxtapositions within subsets of the same element type.

I can get this by using unique() and the permn() function from the package combinat

unique( permn(dat) )

but this is computationally very expensive, since it involves enumerating n!, which can be an order of magnitude more permutations than I need. Is there a way to do this without first computing n!?

Body:
As this question is old and continues to attract many views, this post is solely meant to inform R users of the current state of the language with regards to performing the popular task outlined by the OP. As @RandyLai alludes to, there are packages developed with this task in mind. They are: arrangements and  RcppAlgos*.

Efficiency

They are very efficient and quite easy to use for generating permutations of a multiset.

dat <- c(1, 0, 3, 4, 1, 0, 0, 3, 0, 4)
dim(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
[1] 18900    10

microbenchmark(algos = RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)),
               arngmnt = arrangements::permutations(sort(unique(dat)), freq = table(dat)),
               curaccptd = uniqueperm2(dat), unit = "relative")
Unit: relative
     expr       min        lq       mean    median        uq       max neval
    algos  1.000000  1.000000  1.0000000  1.000000  1.000000 1.0000000   100
  arngmnt  1.501262  1.093072  0.8783185  1.089927  1.133112 0.3238829   100
curaccptd 19.847457 12.573657 10.2272080 11.705090 11.872955 3.9007364   100

With RcppAlgos we can utilize parallel processing for even better efficiency on larger examples.

hugeDat <- rep(dat, 2)[-(1:5)]
RcppAlgos::permuteCount(sort(unique(hugeDat)), freqs = table(hugeDat))
[1] 3603600

microbenchmark(algospar = RcppAlgos::permuteGeneral(sort(unique(hugeDat)),
                                                    freqs = table(hugeDat), nThreads = 4),
               arngmnt = arrangements::permutations(sort(unique(hugeDat)), freq = table(hugeDat)),
               curaccptd = uniqueperm2(hugeDat), unit = "relative", times = 10)
Unit: relative
     expr      min        lq      mean    median       uq      max neval
 algospar  1.00000  1.000000  1.000000  1.000000  1.00000  1.00000    10
  arngmnt  3.23193  3.109092  2.427836  2.598058  2.15965  1.79889    10
curaccptd 49.46989 45.910901 34.533521 39.399481 28.87192 22.95247    10

Lexicographical Order

A nice benefit of these packages is that the output is in lexicographical order:

head(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    1    1    3    3    4     4
[2,]    0    0    0    0    1    1    3    4    3     4
[3,]    0    0    0    0    1    1    3    4    4     3
[4,]    0    0    0    0    1    1    4    3    3     4
[5,]    0    0    0    0    1    1    4    3    4     3
[6,]    0    0    0    0    1    1    4    4    3     3

tail(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)))
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[18895,]    4    4    3    3    0    1    1    0    0     0
[18896,]    4    4    3    3    1    0    0    0    0     1
[18897,]    4    4    3    3    1    0    0    0    1     0
[18898,]    4    4    3    3    1    0    0    1    0     0
[18899,]    4    4    3    3    1    0    1    0    0     0
[18900,]    4    4    3    3    1    1    0    0    0     0

identical(RcppAlgos::permuteGeneral(sort(unique(dat)), freqs = table(dat)),
      arrangements::permutations(sort(unique(dat)), freq = table(dat)))
[1] TRUE

Iterators

Additionally, both packages offer iterators that allow for memory efficient generation of permutation, one by one:

algosIter <- RcppAlgos::permuteIter(sort(unique(dat)), freqs = table(dat))

algosIter$nextIter()
[1] 0 0 0 0 1 1 3 3 4 4

algosIter$nextNIter(5)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    0    1    1    3    4    3     4
[2,]    0    0    0    0    1    1    3    4    4     3
[3,]    0    0    0    0    1    1    4    3    3     4
[4,]    0    0    0    0    1    1    4    3    4     3
[5,]    0    0    0    0    1    1    4    4    3     3

## last permutation
algosIter$back()
[1] 4 4 3 3 1 1 0 0 0 0

## use reverse iterator methods
algosIter$prevNIter(5)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    4    4    3    3    1    0    1    0    0     0
[2,]    4    4    3    3    1    0    0    1    0     0
[3,]    4    4    3    3    1    0    0    0    1     0
[4,]    4    4    3    3    1    0    0    0    0     1
[5,]    4    4    3    3    0    1    1    0    0     0

* I am the author of RcppAlgos


问:
How do I do a manual uninstall of Oracle?
Sometimes my Oracle database on Windows gets hosed. How do I do a manual uninstall of Oracle?</p>

答: This seems way too simple, but in Windows I was able to uninstall Oracle by going into Settings > Apps and Features finding the Oracle database clicking it and then uninstall. I didn't even need a password.

ContentLicense: CC BY-SA 2.5


问:
not able to display in html top object from json in Angular 8
I was able to get the value from the below json format from property but not the above data where I was not able to take the data like name,tags& updated-by.

```<code>        {
      "name" : "abc",
      "tags" : "def",
      "updated-by" : "ijk",
      "property" : {
        "description" : "abcd",
        "type" : "string"
      },
      "sources" : {
        "input" : {
          "type" : "lmn",
          "properties" : {
            "key" : "opq"
          }
        }
      }
    }
</code>```

Please find my ts code

```<code>              ngOnInit() {
            const routestream = this.route.paramMap.subscribe(paramMap =>{
              this.id = paramMap.get('id');
            }
            );
            this.unsubscribe.push(routestream);
                /* initially loading data to display procedure and cost table */
                const empDetails = this.dataService.getDetails(this.id).subscribe(response => {
                  this.dataSource = new MatTableDataSource<details>(response.property);
                  this.dataSource.paginator = this.paginator;
                  this.dataSource.sort = this.sort;
                  this.isLoading = false;
                }, (error) => {
                  this.errorMessage = error;
                  this.isLoading = false;
                });
                this.unsubscribe.push(empDetails);
          }
</code>```

While I am trying to access the top object like below in html

```<code>           <div class="row">
            <div class="rectangle-blue">
               {{element.name}}
                <label class="box-text">Name</label>
            </div>
            <div class="rectangle-blue">
                {{element.tags}}
                <label class="box-text">tags</label>
            </div>
            <div class="rectangle-blue">
                {{element.updated-by}}
                <label class="box-text">Updated By</label>
            </div>
        </div>
</code>```

I am getting error not able to read the property.

Please let me know what I am doing wrong here.

答:
Watch the tutorial of Get data from a server

Define an interface:

```<code>export interface RespData {
  name: string;
  tags: string;
  // ...
}
</code>```

Fetch response:

```<code>myResponse: RespData;

ngOnInit() {
  this.dataService.getDetails(this.id).subscribe((response: RespData) => {
    this.myResponse = response;
  }
}
</code>```

html:

```<code><div class="rectangle-blue">
    {{myResponse.name}}
    <label class="box-text">Name</label>
</div>
<div class="rectangle-blue">
    {{myResponse.tags}}
    <label class="box-text">tags</label>
</div>
</code>```

Body:
I was able to get the value from the below json format from property but not the above data where I was not able to take the data like name,tags& updated-by.

        {
      "name" : "abc",
      "tags" : "def",
      "updated-by" : "ijk",
      "property" : {
        "description" : "abcd",
        "type" : "string"
      },
      "sources" : {
        "input" : {
          "type" : "lmn",
          "properties" : {
            "key" : "opq"
          }
        }
      }
    }

Please find my ts code

              ngOnInit() {
            const routestream = this.route.paramMap.subscribe(paramMap =>{
              this.id = paramMap.get('id');
            }
            );
            this.unsubscribe.push(routestream);
                /* initially loading data to display procedure and cost table */
                const empDetails = this.dataService.getDetails(this.id).subscribe(response => {
                  this.dataSource = new MatTableDataSource(response.property);
                  this.dataSource.paginator = this.paginator;
                  this.dataSource.sort = this.sort;
                  this.isLoading = false;
                }, (error) => {
                  this.errorMessage = error;
                  this.isLoading = false;
                });
                this.unsubscribe.push(empDetails);
          }

While I am trying to access the top object like below in html

               {{element.name}}
                Name

                {{element.tags}}
                tags

                {{element.updated-by}}
                Updated By

I am getting error not able to read the property.

Please let me know what I am doing wrong here.

Body:
Watch the tutorial of Get data from a server

Define an interface:

export interface RespData {
  name: string;
  tags: string;
  // ...
}

Fetch response:

myResponse: RespData;

ngOnInit() {
  this.dataService.getDetails(this.id).subscribe((response: RespData) => {
    this.myResponse = response;
  }
}

html:

<div class="rectangle-blue">
    {{myResponse.name}}
    <label class="box-text">Name</label>
</div>
<div class="rectangle-blue">
    {{myResponse.tags}}
    <label class="box-text">tags</label>
</div>


问:
Unable to add meta_query to woocommerce_product_query
I am trying to add my custom meta_query to WooCommerce main query using the woocommerce_product_query hook.

I tried this code:

```<code>function testing_woo_product_query( $q ){
    $args = array(
      'relation' => 'AND',
      array(
        'meta_key'  => '_price',
        'value'     => 10,
        'compare'   => '>=',
      ),
      array(
        'meta_key'  => '_price',
        'value'     => 30,
        'compare'   => '<=',
      )
    );

    $q->set( 'meta_query', $args );

}
add_action( 'woocommerce_product_query', 'testing_woo_product_query' );
</code>```

But the code doesn't work. Can anybody tell me where is the problem?

答:
Your Meta Query should use key and not meta_key - also you can use "between => array (low number, high number).  You can see the proper format here WP Function Reference meta_query

This will do what you are trying to do above:

```<code>function testing_woo_product_query( $q ){
    $args = array(
      array(
        'key'       => '_price',
        'value'     => array( 10 , 30 ),
        'compare'   => 'BETWEEN',
        'type'      => 'numeric'
      ),
    );

    $q->set( 'meta_query', $args );

}
add_action( 'woocommerce_product_query', 'testing_woo_product_query' );
</code>```

Be warned though, that this will effect shop and archive / category pages unless you qualify your function with specific details.

Body:
I am trying to add my custom meta_query to WooCommerce main query using the woocommerce_product_query hook.

I tried this code:

function testing_woo_product_query( $q ){
    $args = array(
      'relation' => 'AND',
      array(
        'meta_key'  => '_price',
        'value'     => 10,
        'compare'   => '>=',
      ),
      array(
        'meta_key'  => '_price',
        'value'     => 30,
        'compare'   => '<=',
      )
    );

    $q->set( 'meta_query', $args );

}
add_action( 'woocommerce_product_query', 'testing_woo_product_query' );

But the code doesn't work. Can anybody tell me where is the problem?

Body:
Your Meta Query should use key and not meta_key - also you can use "between => array (low number, high number).  You can see the proper format here WP Function Reference meta_query

This will do what you are trying to do above:

function testing_woo_product_query( $q ){
    $args = array(
      array(
        'key'       => '_price',
        'value'     => array( 10 , 30 ),
        'compare'   => 'BETWEEN',
        'type'      => 'numeric'
      ),
    );

    $q->set( 'meta_query', $args );

}
add_action( 'woocommerce_product_query', 'testing_woo_product_query' );

Be warned though, that this will effect shop and archive / category pages unless you qualify your function with specific details.