问:
How to update row if exist and meet more than one condition and insert it otherwise in SQL Server
I'm trying to perform the below code which I have found it in a thread here

```<code>UPDATE MyGuests
SET lastname = 'Doe'
WHERE id = 2

IF ROW_COUNT() = 0
   INSERT INTO MyGuests (lastname, id)
   VALUES ('Doe', 2)
</code>```

The problem is that I need to do the same thing but with the SQL Server query.
My main thought here is that if the new read has the same BoxNo and the same SSCC and the same StyleBarcode, then the value in Qty column will be updated by +1. Otherwise, it'll make a new insert.

I'm thinking to make something like the following code:

```<code>UPDATE MyTable
SET Qty = Qty + 1
WHERE BoxNo = 1
  AND SSCC = 15210049000887900
  AND StyleBarcode = 5210132138457

IF ROW_COUNT() = 0
   INSERT INTO MyTable (SSCC, StyleBarcode, Qty)
   VALUES (15210049000887900, 5210132138457, 1)
</code>```

But I couldn't make it because I don't have something like the ROW_COUNT() in SQL Server.

Or I don't know if you can make have it done in another way?

Thanks in advance.

My table:

答:
SQL Server implements the merge syntax, which seems relevant for your use case.

This statement lets you insert or update from one table into a given table , according to well-defined predicates.

For your question, that would be:

```<code>merge mytable as t
using (values (15210049000887900,5210132138457,1)) as s(sscc, styleBarcode, qty)
on (t.sscc = s.sscc and t.styleBarcode = s.styleBarcode)
when matched then
    update set t.qty = t.qty + 1  -- or t.qty = t.qty + s.qty?
when not matched then
    insert(sscc,styleBarcode,qty) values(s.sscc, s.styleBarcode, s.qty)
;
</code>```

Body:
I'm trying to perform the below code which I have found it in a thread here

UPDATE MyGuests
SET lastname = 'Doe'
WHERE id = 2

IF ROW_COUNT() = 0
   INSERT INTO MyGuests (lastname, id)
   VALUES ('Doe', 2)

The problem is that I need to do the same thing but with the SQL Server query.
My main thought here is that if the new read has the same BoxNo and the same SSCC and the same StyleBarcode, then the value in Qty column will be updated by +1. Otherwise, it'll make a new insert.

I'm thinking to make something like the following code:

UPDATE MyTable
SET Qty = Qty + 1
WHERE BoxNo = 1
  AND SSCC = 15210049000887900
  AND StyleBarcode = 5210132138457

IF ROW_COUNT() = 0
   INSERT INTO MyTable (SSCC, StyleBarcode, Qty)
   VALUES (15210049000887900, 5210132138457, 1)

But I couldn't make it because I don't have something like the ROW_COUNT() in SQL Server.

Or I don't know if you can make have it done in another way?

Thanks in advance.

My table:

Body:
SQL Server implements the merge syntax, which seems relevant for your use case.

This statement lets you insert or update from one table into a given table , according to well-defined predicates.

For your question, that would be:

merge mytable as t
using (values (15210049000887900,5210132138457,1)) as s(sscc, styleBarcode, qty)
on (t.sscc = s.sscc and t.styleBarcode = s.styleBarcode)
when matched then
    update set t.qty = t.qty + 1  -- or t.qty = t.qty + s.qty?
when not matched then
    insert(sscc,styleBarcode,qty) values(s.sscc, s.styleBarcode, s.qty)
;


来源: stackexchange

问:
How to stop console from repeating loop over and over?
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?</p>

```<code>    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;
</code>```

答:
There are two problems with your code:

You have used != to compare strings, which is not correct. Note that == or != compares the references, not the content.

You haven't placed the input part in the while loop so that in case of wrong input, the user can be asked to enter the password again.

Do it as follows:

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

class Main {
    public static void main(String args[]) {
        Scanner passwordScan = new Scanner(System.in);
        String pass = "";
        String password = "JohnnyRoberts123";

        while (!password.equals(pass)) {
            System.out.println("What is the password?");
            pass = passwordScan.nextLine();
            if (!password.equals(pass)) {
                System.out.println("Wrong password!");
                System.out.println("Try again, what is the password?");
                continue;
            }
        }
        // ...rest of code
    }
}
</code>```

A sample run:

```<code>What is the password?
hello
Wrong password!
Try again, what is the password?
What is the password?
hi
Wrong password!
Try again, what is the password?
What is the password?
JohnnyRoberts123
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?

    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;

Body:
There are two problems with your code:

You have used != to compare strings, which is not correct. Note that == or != compares the references, not the content.

You haven't placed the input part in the while loop so that in case of wrong input, the user can be asked to enter the password again.

Do it as follows:

import java.util.Scanner;

class Main {
    public static void main(String args[]) {
        Scanner passwordScan = new Scanner(System.in);
        String pass = "";
        String password = "JohnnyRoberts123";

        while (!password.equals(pass)) {
            System.out.println("What is the password?");
            pass = passwordScan.nextLine();
            if (!password.equals(pass)) {
                System.out.println("Wrong password!");
                System.out.println("Try again, what is the password?");
                continue;
            }
        }
        // ...rest of code
    }
}

A sample run:

What is the password?
hello
Wrong password!
Try again, what is the password?
What is the password?
hi
Wrong password!
Try again, what is the password?
What is the password?
JohnnyRoberts123


问:
will an in clause always return the same order in mysql
ok so i have this query

```<code>select price from product where product_id in (49, 50, 51)
</code>```

and I want to know if the three records returned will be in the same order as my in clause. SO for example

```<code>100.0000
166.0000
55.0000
</code>```

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51

答:
If you want to preserve the same order you have specified within in clause you have to use field() function.</p>

```<code>select price from product where product_id in (49, 50, 51)
order by field(product_id,49,50,51)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
ok so i have this query

select price from product where product_id in (49, 50, 51)

and I want to know if the three records returned will be in the same order as my in clause. SO for example

100.0000
166.0000
55.0000

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51

Body:
If you want to preserve the same order you have specified within in clause you have to use field() function.

select price from product where product_id in (49, 50, 51)
order by field(product_id,49,50,51)


问:
What is x[:,:,::-1] in python
```<code>import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img=cv.imread("content.jpg")
x=np.array(img,dtype=np.uint8)
y=x[:,:,::-1]
plt.imshow(x,interpolation='nearest')
plt.show()
plt.imshow(y,interpolation='nearest')
plt.show()
</code>```

I have some doubts regarding this code

What y=x[:,:,::-1] doing in this code.

The plot of image x is different from the original image, why is it so?

The plot of image
y is same as the original image, what is the reason?

答:
cv2 reads image as BGR, that is, the pixels are in BGR order. On the other hand plt.imshow() uses the more common RBG settings.

x[:,:,::-1] essentially inverts the order of color, so BGR becomes RGB.

So the command

```<code>y = x[:,:,::-1]
</code>```

is equivalent to cv2.cvtColor:

```<code>y = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)
</code>```

Title: What is x[:,:,::-1] in python

Body:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img=cv.imread("content.jpg")
x=np.array(img,dtype=np.uint8)
y=x[:,:,::-1]
plt.imshow(x,interpolation='nearest')
plt.show()
plt.imshow(y,interpolation='nearest')
plt.show()

I have some doubts regarding this code

What y=x[:,:,::-1] doing in this code.

The plot of image x is different from the original image, why is it so?

The plot of image
y is same as the original image, what is the reason?

Body:
cv2 reads image as BGR, that is, the pixels are in BGR order. On the other hand plt.imshow() uses the more common RBG settings.

x[:,:,::-1] essentially inverts the order of color, so BGR becomes RGB.

So the command

y = x[:,:,::-1]

is equivalent to cv2.cvtColor:

y = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)


问:
Coordinates Upload and CRS conversion
I'm pretty new to working in R and I'm currently struggling on converting lat/long coordinates I uploaded into R from an xlsx document into the CRS of the raster I want to plot my coordinates on. I'm using RStudio Version 1.2.5033. Instead of linking the coordinates file, here are the lat/long coordinates I have uploaded (lat first then long):
1 Allequash (46.03323 -89.60874)
2 Bassett   (44.99034 -93.27385)
3 Chippewa  (44.93223 -91.38599)
4 Como      (45.10457 -91.53066)
5 Flambeau  (45.41387 -91.21639)
6 Minnehaha   (44.918 -93.22536)
7 Red Cedar (44.88263 -91.93599)
8 Shingle   (45.03322 -93.28645)
9 Trout     (45.09951 -91.65159)

I'll post my code first and then go into what problems I'm running into

```<code>site_coordinates<-read_excel(coordinates,sheet=1) #Proj=longlat datum=WGS84
rm(coordinates)
site_coordinates_crs<-CRS("+proj=longlat +datum=WGS84")

coordinates<-st_as_sf(site_coordinates,coords=c("Latitude","Longitude"),crs=site_coordinates_crs)
st_crs(coordinates)
coordinates_aes<-st_transform(coordinates,crs(nlcd))
# nlcd is the raster I'm plotting the coordinates on top of, uploaded online nlcd 2016 land use raster
</code>```

The problems I'm running into:
1. When I check my coordinates after uploading them and then assigning them the crs using st_as_sf, I get the following warning message and I'm not sure why:
In st_is_longlat(x) :
  bounding box has potentially an invalid value range for longlat data

When I then go to transform my coordinate data to match that of the raster using st_transform, I then only get the first site converted (Allequash, and even this conversion doesn't seem correct) while the other site coordinates remain empty.

Any help is appreciated!

答: The coords format is coords = c("x", "y")so just reverse your lat and long coordinates and it should work.

Title: Coordinates Upload and CRS conversion

Body:
I'm pretty new to working in R and I'm currently struggling on converting lat/long coordinates I uploaded into R from an xlsx document into the CRS of the raster I want to plot my coordinates on. I'm using RStudio Version 1.2.5033. Instead of linking the coordinates file, here are the lat/long coordinates I have uploaded (lat first then long):
1 Allequash (46.03323 -89.60874)
2 Bassett   (44.99034 -93.27385)
3 Chippewa  (44.93223 -91.38599)
4 Como      (45.10457 -91.53066)
5 Flambeau  (45.41387 -91.21639)
6 Minnehaha   (44.918 -93.22536)
7 Red Cedar (44.88263 -91.93599)
8 Shingle   (45.03322 -93.28645)
9 Trout     (45.09951 -91.65159)

I'll post my code first and then go into what problems I'm running into

site_coordinates<-read_excel(coordinates,sheet=1) #Proj=longlat datum=WGS84
rm(coordinates)
site_coordinates_crs<-CRS("+proj=longlat +datum=WGS84")

coordinates<-st_as_sf(site_coordinates,coords=c("Latitude","Longitude"),crs=site_coordinates_crs)
st_crs(coordinates)
coordinates_aes<-st_transform(coordinates,crs(nlcd))
# nlcd is the raster I'm plotting the coordinates on top of, uploaded online nlcd 2016 land use raster

The problems I'm running into:
1. When I check my coordinates after uploading them and then assigning them the crs using st_as_sf, I get the following warning message and I'm not sure why:
In st_is_longlat(x) :
  bounding box has potentially an invalid value range for longlat data

When I then go to transform my coordinate data to match that of the raster using st_transform, I then only get the first site converted (Allequash, and even this conversion doesn't seem correct) while the other site coordinates remain empty.

Any help is appreciated!


问:
Change color of Navigation Drawer Icon in Android Studio default template
The new default Navigation Drawer Activity template in Android Studio

defines its titles and icons in a menu file activity_main_drawer like this:

```<code><group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camara"
        android:icon="@drawable/ic_action_emo_cool"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@android:drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@android:drawable/ic_menu_slideshow"
        android:title="Slideshow" />
        ...
</code>```

The first item in my example uses a red icon:

but when I run the app, the color of the icon remains black.I have tested this for blue, green, yellow and purple icons, but the result is the same.

I read somewhere that the toolbar should use ThemeOverlay.AppCompat.Dark.ActionBar and my app already uses this in the styles.xml file:

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

Initially I thought this had something to do with Android Studio's cache feature so I invalidated cache and restarted Android Studio with no luck.

答:
I called this method navigationView.setItemIconTintList(null); in the onCreate so that i can override the default color of the icon items in navigation drawer like this

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places);
    drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setItemIconTintList(null);
}
</code>```

Then i changed the color of each icon in navigation drawer using this android:iconTint="@color/metallic_blue" in activity_places_drawer.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/invite"
        android:icon="@drawable/ic_people_orange_24dp"
        android:title="@string/menu_invite"
        android:fontFamily="@font/roboto_medium" />
</group>
</code>```

Hope this answer helps.

Body:
The new default Navigation Drawer Activity template in Android Studio

defines its titles and icons in a menu file activity_main_drawer like this:

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camara"
        android:icon="@drawable/ic_action_emo_cool"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@android:drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@android:drawable/ic_menu_slideshow"
        android:title="Slideshow" />
        ...

The first item in my example uses a red icon:

but when I run the app, the color of the icon remains black.I have tested this for blue, green, yellow and purple icons, but the result is the same.

I read somewhere that the toolbar should use ThemeOverlay.AppCompat.Dark.ActionBar and my app already uses this in the styles.xml file:

<resources>

Body:
I called this method navigationView.setItemIconTintList(null); in the onCreate so that i can override the default color of the icon items in navigation drawer like this

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places);
    drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setItemIconTintList(null);
}

Then i changed the color of each icon in navigation drawer using this android:iconTint="@color/metallic_blue" in activity_places_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/invite"
        android:icon="@drawable/ic_people_orange_24dp"
        android:title="@string/menu_invite"
        android:fontFamily="@font/roboto_medium" />
</group>

Hope this answer helps.


问:
What has to be done in order to activate the partition plugin for MySQL 8 under Debian?
I have this relatively new MySQL 8 install on Debian 10, and I'm anticipating some tables to grow quite large (a new feature is only 3 months old and there are already a few thousands row in a few tables), so I was looking ahead for possibly partition these tables. However the plugin seems to be missing in my installation.

How can I verify that it's actually there?

How can I install/activate it?

I have tried SHOW PLUGINS but it's not listed.

答:
https://dev.mysql.com/doc/refman/5.7/en/partitioning.html says:

As of MySQL 5.7.17, the generic partitioning handler in the MySQL server is deprecated, and is removed in MySQL 8.0, when the storage engine used for a given table is expected to provide its own (“native”) partitioning handler. Currently, only the InnoDB and NDB storage engines do this.

So it's normal in MySQL 8.0 that the partition plugin is not present. It's no longer a feature of MySQL to have storage-engine independent partitioning.

PS: A few thousand rows in three months is not rapid data growth by most standards. Probably not enough to require use of partitioning anyway.


问:
Prevent "Not Responding"
When running code on a Form, sometimes (usually when looping) the program title displays "Not Responding" even though its still running fine.

In my case, I'm looping and filling an array > array to DataTable > DataTable to DataGridView.

example:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim ArrayNew(1000001, 2) As Object

    For i = 0 To 1000000
        For j = 0 To 1
            ArrayNew(i, j) = "TEST"
        Next j
    Next i

    Table1 = New DataTable("EXAMPLETABLE")
    Table1.Columns.Add("COLUMN1")
    Table1.Columns.Add("COLUMN2")
    Table1.Columns.Add("COLUMN3")

    Dim RowNo As Integer = 0
    Do
        Table1.Rows.Add(New String() {RowNo + 1, ArrayNew(RowNo, 0), ArrayNew(RowNo, 1)})
        RowNo = RowNo + 1
    Loop Until ArrayNew(RowNo, 1) = ""

    DataGridView1.DataSource = Table1

End Sub
```

I read somewhere that I should be using threads? or BackgroundWorker but I'm unsure how to use these here like a lot of questions point to BackgroundWorker Class.

But I don't understand C#.

答:
The first thing to do is to drop a BackgroundWorker component onto the form. Click on the component and setup handlers for the DoWork, RunWorkerCompleted, and ProgressChanged events. Then, assuming you use all the default names, your code will look like this:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    backgroundWorker1.RunWorkerAsync()
End Sub

Private Sub backgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
    Dim worker As BackgroundWorker = DirectCast(sender, BackgroundWorker)
    Dim Table1 As New DataTable("EXAMPLETABLE")
    Table1.Columns.Add("COLUMN1")
    Table1.Columns.Add("COLUMN2")
    Table1.Columns.Add("COLUMN3")

    Dim Size As Integer = 1000000
    For i As Integer = 1 To Size
        Table1.Rows.Add(New String() {i.ToString(), "Test", "Test"})
        If i Mod 50 = 0 Then
            worker.ReportProgress(i * 100.0 / Size) 'Report as a percentage of the total
        End If
    Next
    e.Result = Table1
End Sub

Private Sub backgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
    DataGridView1.DataSource = DirectCast(e.Result, DataTable)
End Sub

Private Sub backgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
        'Check e.ProgressPercentage here
End Sub
</code>```

This is the basic example. You can also use this to do things like report progress and make sure it's not already busy before starting it. More information (including samples in C#, but translates to VB.Net easily) is here:

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netcore-3.1

Title: Prevent "Not Responding"

Body:
When running code on a Form, sometimes (usually when looping) the program title displays "Not Responding" even though its still running fine.

In my case, I'm looping and filling an array > array to DataTable > DataTable to DataGridView.

example:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim ArrayNew(1000001, 2) As Object

    For i = 0 To 1000000
        For j = 0 To 1
            ArrayNew(i, j) = "TEST"
        Next j
    Next i

    Table1 = New DataTable("EXAMPLETABLE")
    Table1.Columns.Add("COLUMN1")
    Table1.Columns.Add("COLUMN2")
    Table1.Columns.Add("COLUMN3")

    Dim RowNo As Integer = 0
    Do
        Table1.Rows.Add(New String() {RowNo + 1, ArrayNew(RowNo, 0), ArrayNew(RowNo, 1)})
        RowNo = RowNo + 1
    Loop Until ArrayNew(RowNo, 1) = ""

    DataGridView1.DataSource = Table1

End Sub

I read somewhere that I should be using threads? or BackgroundWorker but I'm unsure how to use these here like a lot of questions point to BackgroundWorker Class.

But I don't understand C#.

Body:
The first thing to do is to drop a BackgroundWorker component onto the form. Click on the component and setup handlers for the DoWork, RunWorkerCompleted, and ProgressChanged events. Then, assuming you use all the default names, your code will look like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    backgroundWorker1.RunWorkerAsync()
End Sub

Private Sub backgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
    Dim worker As BackgroundWorker = DirectCast(sender, BackgroundWorker)
    Dim Table1 As New DataTable("EXAMPLETABLE")
    Table1.Columns.Add("COLUMN1")
    Table1.Columns.Add("COLUMN2")
    Table1.Columns.Add("COLUMN3")

    Dim Size As Integer = 1000000
    For i As Integer = 1 To Size
        Table1.Rows.Add(New String() {i.ToString(), "Test", "Test"})
        If i Mod 50 = 0 Then
            worker.ReportProgress(i * 100.0 / Size) 'Report as a percentage of the total
        End If
    Next
    e.Result = Table1
End Sub

Private Sub backgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
    DataGridView1.DataSource = DirectCast(e.Result, DataTable)
End Sub

Private Sub backgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
        'Check e.ProgressPercentage here
End Sub

This is the basic example. You can also use this to do things like report progress and make sure it's not already busy before starting it. More information (including samples in C#, but translates to VB.Net easily) is here:

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netcore-3.1


问:
Server on Azure IOT Edge Linux Ubuntu VM - Want to access the device from outside of the VM
I have a server on a linux vm hosted in an Edge module. I want to access the server on my host machine (Windows), but as far as I'm aware the Edge modules ip address is the localhost of my Linux VM.

How can I change the assignment of the ip address of the Edge modules, so that it takes on the ip address of my linux vm instead of the local host (172...)?

答:
if I understand your question correctly, you want to access a server running inside an Edge module from a different computer.  Therefore, the port that the server is listening to has to be exposed on the host, right?

If so, there is a better way than changing the IoT Edge networking.  Through 'port mapping', you can take a port exposed from your container/module, and 'map' it such that it gets exposed at the host level, and therefore your other machine can just use the host's IP and your server's port to connect.

For example, let's just say that that the 'server' you are running in your module is web server listening on port 80.  If you want to expose that listener on port 80 out to the host, you would do something like this in the "Container Create Options" of your module...

```<code>    {
    "PortBindings": {
      "80/tcp": [
        {
          "HostPort": "80"
        }
      ]
    }
  }
}
</code>```

That will listen for incoming traffic to the host on port 80, and then forward that traffic to your module on port 80.  You could even change the 'host port' to something else if you wanted to  (e.g. listen on port 8081 and then 'forward' to port 80 in your module).

One thing to note, if you need to use ports 443, 8883, or 5671, by default those are already mapped by IoT Edge itself.  There is a way around that.  If you need it, let me know.

Body:
if I understand your question correctly, you want to access a server running inside an Edge module from a different computer.  Therefore, the port that the server is listening to has to be exposed on the host, right?

If so, there is a better way than changing the IoT Edge networking.  Through 'port mapping', you can take a port exposed from your container/module, and 'map' it such that it gets exposed at the host level, and therefore your other machine can just use the host's IP and your server's port to connect.

For example, let's just say that that the 'server' you are running in your module is web server listening on port 80.  If you want to expose that listener on port 80 out to the host, you would do something like this in the "Container Create Options" of your module...

    {
    "PortBindings": {
      "80/tcp": [
        {
          "HostPort": "80"
        }
      ]
    }
  }
}

That will listen for incoming traffic to the host on port 80, and then forward that traffic to your module on port 80.  You could even change the 'host port' to something else if you wanted to  (e.g. listen on port 8081 and then 'forward' to port 80 in your module).

One thing to note, if you need to use ports 443, 8883, or 5671, by default those are already mapped by IoT Edge itself.  There is a way around that.  If you need it, let me know.


问:
Using TMDb c# api to pass info to TextBlock
Has anyone ever worked with TMdb for C# before?

https://github.com/LordMike/TMDbLib/

 I'm using the API library to connect with my WPF app and would like to display some cast members in a TextBlock but every time I use it I only get one name, whereas according to the API I should be getting way more names. I'm using a foreach loop like this;

```<code>foreach (Cast cast in movie.Credits.Cast)
            {
                MovieCast = cast.Name;
            }
</code>```

I don't know if maybe I'm doing something wrong?

Here's the full code;

ViewModel

```<code>#region Fields

        private Window mWindow;

        #endregion

        #region Properties

        public string MovieName { get; set; }

        public string MovieDescription { get; set; }

        public string MovieCast { get; set; }

        public string MovieImage { get; set; }

        #endregion

        #region Commands

        /// <summary>
        /// The command to close the window
        /// </summary>
        public ICommand CloseCommand { get; set; }

        /// <summary>
        /// The command to minimize the window
        /// </summary>
        public ICommand MinimizeCommand { get; set; }

        /// <summary>
        /// The command to maximize the window
        /// </summary>
        public ICommand MaximizeCommand { get; set; }
        #endregion

        #region Constructor
        /// <summary>
        /// Main Constructor
        /// </summary>
        public MainWindowViewModel(Window window)
        {
            mWindow = window;

            // Window Buttons Commands
            CloseCommand = new RelayCommand(() => mWindow.Close());
            MinimizeCommand = new RelayCommand(() => mWindow.WindowState = WindowState.Minimized);
            MaximizeCommand = new RelayCommand(() => mWindow.WindowState ^= WindowState.Maximized);

            //This is The Movie Database API Client
            TMDbClient client = new TMDbClient("c807e25e9945dcb331636165896edb32");
            Movie movie = client.GetMovieAsync("141052", MovieMethods.Credits | MovieMethods.Images).Result;

            MovieName = movie.Title;
            MovieDescription = movie.Overview;
            foreach (ImageData image in movie.Images.Backdrops)
            {
                MovieImage = "https://image.tmdb.org/t/p/original"+image.FilePath;
            }

            foreach (Cast cast in movie.Credits.Cast)
            {
                MovieCast = cast.Name;
            }

        }
        #endregion
    }
</code>```

XAML portion

```<code>                                    <TextBlock Text="{Binding MovieName}" FontSize="40" FontWeight="Bold"/>
                                    <TextBlock Text="{Binding MovieDescription}" FontSize="15" FontWeight="DemiBold" TextWrapping="Wrap" Width="700" HorizontalAlignment="Left"/>
                                    <TextBlock Text="{Binding MovieCast}" FontSize="14"/>
</code>```

答:
even if movie.Credits.Cast has many items, MovieCast is reassigned in a loop and will be the last one of them. use collection, e.g. ObservableColection<string> and display it in ItemsControl, or alternatively, join all items in a single string which can be shown in TextBlock:

```<code>MovieCast = string.Join(Environment.NewLine, movie.Credits.Cast);
</code>```

Body:
Has anyone ever worked with TMdb for C# before?

https://github.com/LordMike/TMDbLib/

 I'm using the API library to connect with my WPF app and would like to display some cast members in a TextBlock but every time I use it I only get one name, whereas according to the API I should be getting way more names. I'm using a foreach loop like this;

foreach (Cast cast in movie.Credits.Cast)
            {
                MovieCast = cast.Name;
            }

I don't know if maybe I'm doing something wrong?

Here's the full code;

ViewModel

#region Fields

        private Window mWindow;

        #endregion

        #region Properties

        public string MovieName { get; set; }

        public string MovieDescription { get; set; }

        public string MovieCast { get; set; }

        public string MovieImage { get; set; }

        #endregion

        #region Commands

        ///
        /// The command to close the window
        ///
        public ICommand CloseCommand { get; set; }

        ///
        /// The command to minimize the window
        ///
        public ICommand MinimizeCommand { get; set; }

        ///
        /// The command to maximize the window
        ///
        public ICommand MaximizeCommand { get; set; }
        #endregion

        #region Constructor
        ///
        /// Main Constructor
        ///
        public MainWindowViewModel(Window window)
        {
            mWindow = window;

            // Window Buttons Commands
            CloseCommand = new RelayCommand(() => mWindow.Close());
            MinimizeCommand = new RelayCommand(() => mWindow.WindowState = WindowState.Minimized);
            MaximizeCommand = new RelayCommand(() => mWindow.WindowState ^= WindowState.Maximized);

            //This is The Movie Database API Client
            TMDbClient client = new TMDbClient("c807e25e9945dcb331636165896edb32");
            Movie movie = client.GetMovieAsync("141052", MovieMethods.Credits | MovieMethods.Images).Result;

            MovieName = movie.Title;
            MovieDescription = movie.Overview;
            foreach (ImageData image in movie.Images.Backdrops)
            {
                MovieImage = "https://image.tmdb.org/t/p/original"+image.FilePath;
            }

            foreach (Cast cast in movie.Credits.Cast)
            {
                MovieCast = cast.Name;
            }

        }
        #endregion
    }

XAML portion

                                    <TextBlock Text="{Binding MovieName}" FontSize="40" FontWeight="Bold"/>
                                    <TextBlock Text="{Binding MovieDescription}" FontSize="15" FontWeight="DemiBold" TextWrapping="Wrap" Width="700" HorizontalAlignment="Left"/>
                                    <TextBlock Text="{Binding MovieCast}" FontSize="14"/>

Body:
even if movie.Credits.Cast has many items, MovieCast is reassigned in a loop and will be the last one of them. use collection, e.g. ObservableColection<string> and display it in ItemsControl, or alternatively, join all items in a single string which can be shown in TextBlock:

MovieCast = string.Join(Environment.NewLine, movie.Credits.Cast);


问:
Why this React CRUD goes back to initial state?
I'm practicing react and I'm working on a simple crud. The problem I'm facing is that when I insert a new element, my app is going back to the initial state. I'm not sure how to fix this. Here is the code:

```<code>import React, { Component, Fragment } from "react";
import "./App.css";
import Tabela from "./Tabela";

import Form from "./Formulario";

class App extends Component {
  state = {
    autores: [
      {
        nome: "Paulo",
        livro: "React",
        preco: "1000",
      },
      {
        nome: "Daniel",
        livro: "Java",
        preco: "99",
      },
      {
        nome: "Marcos",
        livro: "Design",
        preco: "150",
      },
      {
        nome: "Bruno",
        livro: "DevOps",
        preco: "100",
      },
    ],
  };

  removeAutor = (index) => {
    const { autores } = this.state;

this.setState({
  autores: autores.filter((autor, posAtual) => {
    return posAtual !== index;
  }),
});
  };

  escutadorDeSubmit = autor => {
    this.setState({ autores: [...this.state.autores, autor]})
  }

  render() {
    return (
      <Fragment>
        <Tabela autores={this.state.autores} removeAutor={this.removeAutor} />
        <Form escutadorDeSubmit = {this.escutadorDeSubmit} />
      </Fragment>
    );
  }
}

export default App;
</code>```

and this is the other class Formulario.js:

```<code>import React, { Component } from 'react';

class Formulario extends Component {

constructor(props) {
    super(props);

    this.stateInicial = {
        nome:'',
        livro:'',
        preco:''
    }

    this.state = this.stateInicial;
}

escutadorDeInput = event => {
    const { name, value } = event.target;

    this.setState({
        [name] : value
    });
}

submitFormulario = () => {
    this.props.escutadorDeSubmit(this.state);
    this.setState(this.stateInicial);
}

render() {

    const { nome, livro, preco } = this.state;

    return (
        <form>

            <label htmlFor="nome">Nome</label>
            <input
                id="nome"
                type="text"
                name="nome"
                value={nome}
                onChange= {this.escutadorDeInput} />
            <label htmlFor="livro">Livro</label>
            <input
                id="livro"
                type="text"
                name="livro"
                value={livro}
                onChange= {this.escutadorDeInput} />
            <label htmlFor="preco">Preco</label>
            <input
                id="preco"
                type="text"
                name="preco"
                value={preco}
                onChange= {this.escutadorDeInput} />
            <button onClick={this.submitFormulario}>Salvar</button>
        </form>
    );
}
}
export default Formulario;
</code>```

When I insert the new author, the app shows the new input for a second and then reloads to the initial state. I'd like to keep the record that I just inserted and not lose it.

答:
The problem is in your submit function for the form. As the button is in the form, it gets implicitly the type="submit" attribute. This means, when you click on it, the form tries to submit it's values to some url, as it its default behaviour. You can prevent this, by using preventDefault() in your submit function:

```<code>submitFormulario = (e) => {
    e.preventDefault()
    this.props.escutadorDeSubmit(this.state);
    this.setState(this.stateInicial);
}
</code>```

An alternative would be to take the button out of the form or give it explicitly the type="button" attribute.

Body:
I'm practicing react and I'm working on a simple crud. The problem I'm facing is that when I insert a new element, my app is going back to the initial state. I'm not sure how to fix this. Here is the code:

import React, { Component, Fragment } from "react";
import "./App.css";
import Tabela from "./Tabela";

import Form from "./Formulario";

class App extends Component {
  state = {
    autores: [
      {
        nome: "Paulo",
        livro: "React",
        preco: "1000",
      },
      {
        nome: "Daniel",
        livro: "Java",
        preco: "99",
      },
      {
        nome: "Marcos",
        livro: "Design",
        preco: "150",
      },
      {
        nome: "Bruno",
        livro: "DevOps",
        preco: "100",
      },
    ],
  };

  removeAutor = (index) => {
    const { autores } = this.state;

this.setState({
  autores: autores.filter((autor, posAtual) => {
    return posAtual !== index;
  }),
});
  };

  escutadorDeSubmit = autor => {
    this.setState({ autores: [...this.state.autores, autor]})
  }

  render() {
    return (
      <Fragment>
        <Tabela autores={this.state.autores} removeAutor={this.removeAutor} />
        <Form escutadorDeSubmit = {this.escutadorDeSubmit} />
      </Fragment>
    );
  }
}

export default App;

and this is the other class Formulario.js:

import React, { Component } from 'react';

class Formulario extends Component {

constructor(props) {
    super(props);

    this.stateInicial = {
        nome:'',
        livro:'',
        preco:''
    }

    this.state = this.stateInicial;
}

escutadorDeInput = event => {
    const { name, value } = event.target;

    this.setState({
        [name] : value
    });
}

submitFormulario = () => {
    this.props.escutadorDeSubmit(this.state);
    this.setState(this.stateInicial);
}

render() {

    const { nome, livro, preco } = this.state;

    return (
        <form>

            Nome
            <input
                id="nome"
                type="text"
                name="nome"
                value={nome}
                onChange= {this.escutadorDeInput} />
            Livro
            <input
                id="livro"
                type="text"
                name="livro"
                value={livro}
                onChange= {this.escutadorDeInput} />
            Preco
            <input
                id="preco"
                type="text"
                name="preco"
                value={preco}
                onChange= {this.escutadorDeInput} />
            <button onClick={this.submitFormulario}>Salvar</button>
        </form>
    );
}
}
export default Formulario;

When I insert the new author, the app shows the new input for a second and then reloads to the initial state. I'd like to keep the record that I just inserted and not lose it.

Body:
The problem is in your submit function for the form. As the button is in the form, it gets implicitly the type="submit" attribute. This means, when you click on it, the form tries to submit it's values to some url, as it its default behaviour. You can prevent this, by using preventDefault() in your submit function:

submitFormulario = (e) => {
    e.preventDefault()
    this.props.escutadorDeSubmit(this.state);
    this.setState(this.stateInicial);
}

An alternative would be to take the button out of the form or give it explicitly the type="button" attribute.


问:
VBA - Loop through multiple subfolders on a network location with date search criteria/ Improve search speed
Purpose of my question and of the VBA code:
Get specific data (a couple columns) from each one of the "table.csv" file in a network directory. Each networkdirectory/subfolders01/subfolders02 contains one "table.csv" file but 100 other subfolders are included in each network/subfolders01. The other folders are not needed, the only one we are interested in is subfolder02 for each subfolder01. The number of subfolders01 in the network directory is about 15000. However I only need subfolders01 from Jan2020 to Apr2020,for example (200 subfolders).
Final purpose is to trend data.

Issue:
I am trying to understand how I could improve the VBA code that I am currently using.
This code goes through each subfolder one by one and then check the date and file name.
I am wondering if there is a way to add any search filters criteria for subfolder date and name to have a faster loop.
How can we avoid the code to go through each subfolders?

Please see below the code I am using,
I really appreciate your time and hope my request is clear.

'''

```<code>Function GetFiles(startPath As String) As Collection
Dim fso As Object, rv As New Collection, colFolders As New Collection, fpath As String
Dim subFolder As Object, f, dMinfold, dtMod
Set fso = CreateObject("Scripting.FileSystemObject")

dMinfold = ThisWorkbook.Sheets("Enter_Date").Cells(2, 1)

colFolders.Add startPath

Do While colFolders.Count > 0
    fpath = colFolders(1)
    colFolders.Remove 1
    'process subfolders
    For Each subFolder In fso.getfolder(fpath).subfolders
        If subFolder.DateLastModified >= dMinfold Then
            colFolders.Add subFolder.Path
        End If
    Next subFolder
    'process files
    f = Dir(fso.buildpath(fpath, "*Table.csv"), vbNormal)
    Do While f <> ""
        f = fso.buildpath(fpath, f)
        dtMod = FileDateTime(f)
        If dtMod >= dMinfold And Right(f, 3) = "csv" Then
            rv.Add f
        End If

        f = Dir()
    Loop
Loop
Set GetFiles = rv
End Function'''
</code>```

Then I have my code to get transfer data from each file.
Thank you.

答:
I'll put in screenshots to clear up the Get & Transform method, since it is the GUI approach rather than code.

It is possible to filter before loading contents, which will speed things up significantly.
I tried with a few thousand subfolders filtered down to 20, loads instantly.

Here's the initial screen for get data from folder

You can then filter on path. In your case it will be based on the date from the folder name.

Now that it's filtered you can expand the content using the header button.

Inside content, you'll have to expand again to convert from csv to excel table

Choose/rename columns as needed, then hit "close and load" to drop it into excel.
Default is to a new table, but you can "load to" if something more custom is needed.

Here's your output. You can right-click refresh or refresh from vba as needed.

Edit- Just noticed that I used .txt rather than .csv for the files. Might change how a step or two looks in the middle, but the general idea is the same.

Body:
Purpose of my question and of the VBA code:
Get specific data (a couple columns) from each one of the "table.csv" file in a network directory. Each networkdirectory/subfolders01/subfolders02 contains one "table.csv" file but 100 other subfolders are included in each network/subfolders01. The other folders are not needed, the only one we are interested in is subfolder02 for each subfolder01. The number of subfolders01 in the network directory is about 15000. However I only need subfolders01 from Jan2020 to Apr2020,for example (200 subfolders).
Final purpose is to trend data.

Issue:
I am trying to understand how I could improve the VBA code that I am currently using.
This code goes through each subfolder one by one and then check the date and file name.
I am wondering if there is a way to add any search filters criteria for subfolder date and name to have a faster loop.
How can we avoid the code to go through each subfolders?

Please see below the code I am using,
I really appreciate your time and hope my request is clear.

'''

Function GetFiles(startPath As String) As Collection
Dim fso As Object, rv As New Collection, colFolders As New Collection, fpath As String
Dim subFolder As Object, f, dMinfold, dtMod
Set fso = CreateObject("Scripting.FileSystemObject")

dMinfold = ThisWorkbook.Sheets("Enter_Date").Cells(2, 1)

colFolders.Add startPath

Do While colFolders.Count > 0
    fpath = colFolders(1)
    colFolders.Remove 1
    'process subfolders
    For Each subFolder In fso.getfolder(fpath).subfolders
        If subFolder.DateLastModified >= dMinfold Then
            colFolders.Add subFolder.Path
        End If
    Next subFolder
    'process files
    f = Dir(fso.buildpath(fpath, "*Table.csv"), vbNormal)
    Do While f <> ""
        f = fso.buildpath(fpath, f)
        dtMod = FileDateTime(f)
        If dtMod >= dMinfold And Right(f, 3) = "csv" Then
            rv.Add f
        End If

        f = Dir()
    Loop
Loop
Set GetFiles = rv
End Function'''

Then I have my code to get transfer data from each file.
Thank you.


问:
Unable to access js and style sheet using Play
Here I import from view file:

```<code>    <script src='javascripts/tic-tac-toe/main.js'></script>
    <link rel="stylesheet" type="text/css" href=stylesheets/tic-tac-toe/style.css'>
</code>```

public folder structure:

[]

routes file:

```<code>GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)
</code>```

When I try to access the view page I receive following error in firefox console and the files are not loaded :

The resource from
  “http://localhost:9000/assets/stylesheets/tic-tac-toe/style.css'” was
  blocked due to MIME type (“text/html”) mismatch
  (X-Content-Type-Options: nosniff).

How to access js and css resources from view file ?

I can browse directly locally to the files on the browser via the address bar:

http://localhost:9000/assets/javascripts/tic-tac-toe/main.js

http://localhost:9000/assets/stylesheets/tic-tac-toe/style.css

答:
Seems I need to prepend with "assets":</p>

```<code><script src='/assets/javascripts/tic-tac-toe/main.js'></script>
<link rel="stylesheet" type="text/css" href='/assets/stylesheets/tic-tac-toe/style.css'>
</code>```

Body:
Here I import from view file:

    <link rel="stylesheet" type="text/css" href=stylesheets/tic-tac-toe/style.css'>

public folder structure:

[]

routes file:

GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

When I try to access the view page I receive following error in firefox console and the files are not loaded :

The resource from
  “http://localhost:9000/assets/stylesheets/tic-tac-toe/style.css'” was
  blocked due to MIME type (“text/html”) mismatch
  (X-Content-Type-Options: nosniff).

How to access js and css resources from view file ?

I can browse directly locally to the files on the browser via the address bar:

http://localhost:9000/assets/javascripts/tic-tac-toe/main.js

http://localhost:9000/assets/stylesheets/tic-tac-toe/style.css

Body:
Seems I need to prepend with "assets":

<script src='/assets/javascripts/tic-tac-toe/main.js'></script>
<link rel="stylesheet" type="text/css" href='/assets/stylesheets/tic-tac-toe/style.css'>


问:
CoffeeScript+processing.js draw image fails
I try to load image with processing.js using CoffeeScript and write this simple code:

```<code>canvas1_proc = (ps) ->
    ps.setup = ->
        ps.noLoop()
        ps.size(550, 400)
        @img = ps.loadImage('1.png')
    ps.draw = ->
        ps.image(@img, 0, 0)

$(document).ready () ->
    canvas1 = document.getElementById 'canvas-1'
    processing = new Processing(canvas1, canvas1_proc)
</code>```

CoffeeScript code is compiled into the code

```<code>var canvas1_proc;
canvas1_proc = function(ps) {
  ps.setup = function() {
    ps.noLoop();
    ps.size(550, 400);
    return this.img = ps.loadImage('1.png');
  };
  return ps.draw = function() {
    return ps.image(this.img, 0, 0);
  };
};
$(document).ready(function() {
  var canvas1, processing;
  canvas1 = document.getElementById('canvas-1');
  return processing = new Processing(canvas1, canvas1_proc);
});
</code>```

The image is not displayed and no errors in js console. Where is my mistake?

答:
David Humphrey's code, ported to Coffeescript.  Works like a charm:</p>

```<code>canvas1_proc = (ps) ->
    ps.setup = () ->
        ps.noLoop()
        ps.size 550, 400
        this.img = ps.loadImage '1.png'

    ps.draw = () ->
        ps.image this.img, 0, 0

$(document).ready () ->
    sketch = new Processing.Sketch canvas1_proc
    sketch.imageCache.add '1.png'
    canvas1 = document.getElementById 'canvas-1'
    p = new Processing canvas1, sketch
</code>```

Body:
I try to load image with processing.js using CoffeeScript and write this simple code:

canvas1_proc = (ps) ->
    ps.setup = ->
        ps.noLoop()
        ps.size(550, 400)
        @img = ps.loadImage('1.png')
    ps.draw = ->
        ps.image(@img, 0, 0)

$(document).ready () ->
    canvas1 = document.getElementById 'canvas-1'
    processing = new Processing(canvas1, canvas1_proc)

CoffeeScript code is compiled into the code

var canvas1_proc;
canvas1_proc = function(ps) {
  ps.setup = function() {
    ps.noLoop();
    ps.size(550, 400);
    return this.img = ps.loadImage('1.png');
  };
  return ps.draw = function() {
    return ps.image(this.img, 0, 0);
  };
};
$(document).ready(function() {
  var canvas1, processing;
  canvas1 = document.getElementById('canvas-1');
  return processing = new Processing(canvas1, canvas1_proc);
});

The image is not displayed and no errors in js console. Where is my mistake?

Body:
David Humphrey's code, ported to Coffeescript.  Works like a charm:

canvas1_proc = (ps) ->
    ps.setup = () ->
        ps.noLoop()
        ps.size 550, 400
        this.img = ps.loadImage '1.png'

    ps.draw = () ->
        ps.image this.img, 0, 0

$(document).ready () ->
    sketch = new Processing.Sketch canvas1_proc
    sketch.imageCache.add '1.png'
    canvas1 = document.getElementById 'canvas-1'
    p = new Processing canvas1, sketch


问:
Size Inspector missing options in xcode 11.3.1
I am trying to replicate a GitHub project to practise using constraints. The new project I've created displays the following in the size inspector:

The GitHub Project displays the following in the size inspector. The section below 'Layout Margins' is missing from my project. How can I get this missing section to display?

答: Add any constraint to the view and that section will be visible as per the GitHub project displays.</p>


问:
Usage of TimeBasedTriggeringPolicy in log4j2 configuration
I am trying to use TimeBasedTriggeringPolicy with log4j-2.13.2 which comes embedded with spring-boot 2.3.0.RELEASE (spring-boot-started-log4j2).
The expected functionality is that a log file should be created for each day.

My configuration file looks like this:

```<code>appender.rolling.type = RollingFile
appender.rolling.name = fileAppender
appender.rolling.fileName = ${basePath}/log-${date:yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}/log-${date:yyyyMMdd}-%i.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
</code>```

However, when starting the application, the following exception is thrown:

```<code>2020-05-28 23:39:07,991 main ERROR Could not create plugin of type class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile: java.lang.IllegalStateException: Pattern does not contain a date java.lang.IllegalStateException: Pattern does not contain a date
    at org.apache.logging.log4j.core.appender.rolling.PatternProcessor.getNextTime(PatternProcessor.java:154)
    at org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy.initialize(TimeBasedTriggeringPolicy.java:117)
    at org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy.initialize(CompositeTriggeringPolicy.java:54)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.initialize(RollingFileManager.java:158)
    at org.apache.logging.log4j.core.appender.RollingFileAppender$Builder.build(RollingFileAppender.java:153)
    at org.apache.logging.log4j.core.appender.RollingFileAppender$Builder.build(RollingFileAppender.java:62)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:122)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:1002)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:942)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:934)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:552)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:241)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:288)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:618)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:295)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:240)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:159)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:131)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:101)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:188)
</code>```

If I change the file pattern:

```<code>appender.rolling.fileName = ${basePath}/log-%d{yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}/log-%d{yyyyMMdd}-%i.log
</code>```

the exception is not thrown anymore, but the name of the file is "log-%d{yyyyMMdd}.log" instead of "log-20200528.log" (for example).

How should I specify the filePattern property in order to achieve the expected behavior (generate a log file for each day, with the current date enclosed in the filename)?

答:
It seems a combination of the two approaches is needed in order to achieve the expected behavior:</p>

```<code>appender.rolling.fileName = ${basePath}/log-${date:yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}log-%d{yyyyMMdd}-%i.log
</code>```

Body:
I am trying to use TimeBasedTriggeringPolicy with log4j-2.13.2 which comes embedded with spring-boot 2.3.0.RELEASE (spring-boot-started-log4j2).
The expected functionality is that a log file should be created for each day.

My configuration file looks like this:

appender.rolling.type = RollingFile
appender.rolling.name = fileAppender
appender.rolling.fileName = ${basePath}/log-${date:yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}/log-${date:yyyyMMdd}-%i.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true

However, when starting the application, the following exception is thrown:

2020-05-28 23:39:07,991 main ERROR Could not create plugin of type class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile: java.lang.IllegalStateException: Pattern does not contain a date java.lang.IllegalStateException: Pattern does not contain a date
    at org.apache.logging.log4j.core.appender.rolling.PatternProcessor.getNextTime(PatternProcessor.java:154)
    at org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy.initialize(TimeBasedTriggeringPolicy.java:117)
    at org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy.initialize(CompositeTriggeringPolicy.java:54)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.initialize(RollingFileManager.java:158)
    at org.apache.logging.log4j.core.appender.RollingFileAppender$Builder.build(RollingFileAppender.java:153)
    at org.apache.logging.log4j.core.appender.RollingFileAppender$Builder.build(RollingFileAppender.java:62)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:122)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:1002)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:942)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:934)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:552)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:241)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:288)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:618)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:295)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:240)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:159)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:131)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:101)
    at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:188)

If I change the file pattern:

appender.rolling.fileName = ${basePath}/log-%d{yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}/log-%d{yyyyMMdd}-%i.log

the exception is not thrown anymore, but the name of the file is "log-%d{yyyyMMdd}.log" instead of "log-20200528.log" (for example).

How should I specify the filePattern property in order to achieve the expected behavior (generate a log file for each day, with the current date enclosed in the filename)?

Body:
It seems a combination of the two approaches is needed in order to achieve the expected behavior:

appender.rolling.fileName = ${basePath}/log-${date:yyyyMMdd}.log
appender.rolling.filePattern = ${basePath}log-%d{yyyyMMdd}-%i.log


问:
Go through sub tags of IsoMsg and get values for jPOS
I have a jPOS project and I want to loop through sub tags of a field to get it's values. I have the following code and I don't know if it does the job:

    Map<String, String> subTagMap = new HashMap<>();
    ISOMsg champ11 = (ISOMsg)isoMsg.getComponent(11);
    int i = 1;
    while(i < 15) {
        if (champ11  != null) {
            ISOTaggedField subtTag = findTag(champ11, (i < 10) ? "0" + i : String.valueOf(i));
            if (subtTag != null) {
                LOGGER.debug("Champ11x" + i +"trouvé");
                subTagMap.put(subtTag.getTag(), subtTag.getValue().toString());
            }
        }
i++;
    }
    return subTagMap;
}

private ISOTaggedField findTag(ISOComponent component, String tagName) {
        if (component instanceof ISOTaggedField) {
            component = ((ISOTaggedField) component).getDelegate();
        }

        @SuppressWarnings("unchecked")
        Map<Integer, Object> children = component.getChildren();

        for (Map.Entry<Integer, Object> entry : children.entrySet()) {
            if (entry.getValue() instanceof ISOTaggedField) {
                ISOTaggedField tag = (ISOTaggedField) entry.getValue();

                if (tag.getTag().equals(tagName)) {
                    return tag;
                }
            }
        }

        return null;
    }
```

答:
This should work:

Map<String, String> subTagMap=new HashMap<>();
ISOMsg champ11 = (ISOMsg) isoMsg.getComponent(119);

if (champ != null) {
    for (Object v : champ.getChildren().values()) {
        if (!(v instanceof ISOTaggedField)) continue;
        ISOTaggedField subTag = (ISOTaggedField) v;
        subTagMap.put(subTag.getTag(), (String)subTag.getValue());
    }
}
return subTagMap;
```


问:
MemoryError in python- Is there any possible modification to fix it?
I am trying to run the following code in sublime text:

```<code>def max_prime_factor(num):
    divisibles=[]
    prime_facors=[]
    for i in range(1,num):
        if num%i==0:
            divisibles.append(i)
        else:
            continue
    for j in divisibles:
        for k in range(2,j):
            if j%k==0:
                break
            else:
                continue

        prime_facors.append(j)
    return(max(prime_facors))

print(max_prime_factor(600851475143))
</code>```

using a machine equipped with:

and getting the following error in the sublime text. Do I have to modify the code, because it is overwhelming? Tnx in advance!

答: From the comments it sounds like you're using Python 2. In that case you will need to use xrange instead or range. xrange works the same as range, but it is more memory efficent. See What is the difference between range and xrange functions in Python 2.X?</p>

Body:
I am trying to run the following code in sublime text:

def max_prime_factor(num):
    divisibles=[]
    prime_facors=[]
    for i in range(1,num):
        if num%i==0:
            divisibles.append(i)
        else:
            continue
    for j in divisibles:
        for k in range(2,j):
            if j%k==0:
                break
            else:
                continue

        prime_facors.append(j)
    return(max(prime_facors))

print(max_prime_factor(600851475143))

using a machine equipped with:

and getting the following error in the sublime text. Do I have to modify the code, because it is overwhelming? Tnx in advance!


问:
How to properly handle client "Connection: close" request on HTTP file server?
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

```<code>CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr
</code>```

Client/ApacheServer Comunication:

```<code>CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.
</code>```

答:
May I ask why are you using http 1.0 in the request?
There were no persistent connections in http 1.0, so the server is supposed to terminate the TCP connection after the response, whether you send Connection: close or not.

Body:
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr

Client/ApacheServer Comunication:

CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.


问:
How to wait for an element to be contain the attribute style="display:none;" using Selenium and Python
When using Selenium/Python, I need to wait/pause until: style="display:none;" is displayed for a <div id="notification"..

After clicking a button, the following is displayed (Loading...)

Loading...

Then after a dataset is loaded in the web page, the Loading... goes away (by changing display:none), and the following is present:

Loading...

How would this be done (to check or wait on the value of style="display: none;")?

Because there are many <divs> in the page with style=display, I need to wait on both the id of the div, and the style display.

答:
Once you click the desired button the element with text as Loading... becomes visible. Hence you see the element within the HTML DOM as:

```<code><div id="notification" class="notification_info" style="opacity: 1; display: inline-block;">Loading...</div>
</code>```

Once the loading completes the the element with text as Loading... is made invisible by changing the display property of the style attribute as:

```<code>style="display: none;"
</code>```

Hence the WebElement is represented in the DOM Tree as:

```<code><div id="notification" class="notification_info" style="display: none;">Loading...</div>
</code>```

Solution

Using Selenium to wait for the the element with text as Loading... to turn as style="display: none;" you need to induce WebDriverWait for the invisibility_of_element() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.invisibility_of_element((By.CSS_SELECTOR, "div.notification_info#notification")))
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "//div[@class='notification_info' and @id='notification']")))
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant detailed discussions in:

How to click on anchor element with selenium using python?

Selenium invisibilityOf(element) method throwing NoSuchElementException + WebDriverWait.ignoring(NoSuchElementException.class) is not working

Body:
Once you click the desired button the element with text as Loading... becomes visible. Hence you see the element within the HTML DOM as:

<div id="notification" class="notification_info" style="opacity: 1; display: inline-block;">Loading...</div>

Once the loading completes the the element with text as Loading... is made invisible by changing the display property of the style attribute as:

style="display: none;"

Hence the WebElement is represented in the DOM Tree as:

<div id="notification" class="notification_info" style="display: none;">Loading...</div>

Solution

Using Selenium to wait for the the element with text as Loading... to turn as style="display: none;" you need to induce WebDriverWait for the invisibility_of_element() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.invisibility_of_element((By.CSS_SELECTOR, "div.notification_info#notification")))

Using XPATH:

WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "//div[@class='notification_info' and @id='notification']")))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant detailed discussions in:

How to click on anchor element with selenium using python?

Selenium invisibilityOf(element) method throwing NoSuchElementException + WebDriverWait.ignoring(NoSuchElementException.class) is not working


问:
Spring Ownership based access
Please don't mark this as duplicate as provided solutions available contains security issues and do not cover all CRUD-cases!

I want to secure certain objects by comparing the stored userId of an object with SecurityContextHolder.getContext().authentication.

I am aware that I have to fetch the object before doing operations since this is the only way to get the userId.

I want to secure controller-methods like this one:

@GetMapping("/deliveryAddresses/{id}")
    fun getDeliveryAddressById(@PathVariable(value = "id") deliveryAddressId : Long):
        ResponseEntity<BasicDeliveryAddress> {
            return deliveryAddressService.findById(deliveryAddressId)?.let { ResponseEntity.ok(it) }
                ?: ResponseEntity.notFound().build()
    }
```

<p>What is the best-practice approach to secure this object? I don't want to have multiple duplicate ownership-checks accross my code. Also please suggest where to add the check (Controller, Service, ... ?)</p>

<p>This is exactly what I want to avoid (pseudo-code):</p>

```fetchById(id) {
    val myObject = ...
    if(myObject.userId == authUser.userId) {
        ...
    }
}
```

<p>Please provide a clean solution for this problem.</p>

<h2>UPDATE - PART OF SOLUTION</h2>

<p>I was not aware that I am able to directly get the object inside the method header by only passing the ID.</p>

<pre class="lang-kotlin prettyprint-override"><code>@GetMapping("/something/{id}")
fun getSomethingByID(@PathVariable(value = "id") something: Something): ResponseEntity<BasicDeliveryAddress> { ... }
</code>```

With this additional information and the answer (accepted one) provided by @Ken Chan you should be able to easily implement the ownership based security!

答:
Use @PreAuthorize which allows you to define a SpEL which will be evaluated as boolean to see if a method is allow to be executed.

You have several options:

(1) Use SpEL to refer to bean method that perform the checking :

```<code>@PreAuthorize("@authzService.isAllowToDo(#deliveryAddressId)")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(Long deliveryAddressId {

}

@Service
public class AuthzService{

    public boolean isAllowToDo(Long deliveryAddressId){
        //Do the checking here....
    }
}
</code>```

(2) Use the built-in hasPermission expression  :

```<code>@PreAuthorize("hasPermission(#deliveryAddressId, 'read')")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(Long deliveryAddressId{

}
</code>```

It requires to customise PermissionEvaluator to work. Same idea as (1) but it is a built-in solution.

(3) If the evaluation logic is simple and the method signature is
    allowed, you can directly expressed it using SpEL :

```<code>@PreAuthorize("#deliveryAddress.userId == authentication.userId")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(BasicDeliveryAddress deliveryAddress){

}
</code>```

authentication is one of the built-in expression to access the Authentication object in the SecurityContextHolder and I assume you have already customised it to include userId.

Title: Spring Ownership based access

Body:
Please don't mark this as duplicate as provided solutions available contains security issues and do not cover all CRUD-cases!

I want to secure certain objects by comparing the stored userId of an object with SecurityContextHolder.getContext().authentication.

I am aware that I have to fetch the object before doing operations since this is the only way to get the userId.

I want to secure controller-methods like this one:

@GetMapping("/deliveryAddresses/{id}")
    fun getDeliveryAddressById(@PathVariable(value = "id") deliveryAddressId : Long):
        ResponseEntity<BasicDeliveryAddress> {
            return deliveryAddressService.findById(deliveryAddressId)?.let { ResponseEntity.ok(it) }
                ?: ResponseEntity.notFound().build()
    }

What is the best-practice approach to secure this object? I don't want to have multiple duplicate ownership-checks accross my code. Also please suggest where to add the check (Controller, Service, ... ?)

This is exactly what I want to avoid (pseudo-code):

fetchById(id) {
    val myObject = ...
    if(myObject.userId == authUser.userId) {
        ...
    }
}

Please provide a clean solution for this problem.

UPDATE - PART OF SOLUTION

I was not aware that I am able to directly get the object inside the method header by only passing the ID.

@GetMapping("/something/{id}")
fun getSomethingByID(@PathVariable(value = "id") something: Something): ResponseEntity<BasicDeliveryAddress> { ... }

With this additional information and the answer (accepted one) provided by @Ken Chan you should be able to easily implement the ownership based security!

Body:
Use @PreAuthorize which allows you to define a SpEL which will be evaluated as boolean to see if a method is allow to be executed.

You have several options:

(1) Use SpEL to refer to bean method that perform the checking :

@PreAuthorize("@authzService.isAllowToDo(#deliveryAddressId)")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(Long deliveryAddressId {

}

@Service
public class AuthzService{

    public boolean isAllowToDo(Long deliveryAddressId){
        //Do the checking here....
    }
}

(2) Use the built-in hasPermission expression  :

@PreAuthorize("hasPermission(#deliveryAddressId, 'read')")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(Long deliveryAddressId{

}

It requires to customise PermissionEvaluator to work. Same idea as (1) but it is a built-in solution.

(3) If the evaluation logic is simple and the method signature is
    allowed, you can directly expressed it using SpEL :

@PreAuthorize("#deliveryAddress.userId == authentication.userId")
public ResponseEntity<BasicDeliveryAddress> getDeliveryAddressById(BasicDeliveryAddress deliveryAddress){

}

authentication is one of the built-in expression to access the Authentication object in the SecurityContextHolder and I assume you have already customised it to include userId.


问:
How to fix: No executable found matching command "dotnet-dslc"?
I am conducting a literature survey for my thesis and was trying PROSE SDK by Microsoft. However, whenever I try to build the dependencies of the project from their sample [repo] (https://github.com/microsoft/prose), I get this error:

```<code>Target CompileGrammar:
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    No executable found matching command "dotnet-dslc"
</code>```

I followed installation instructions from here

Here's the information regarding dotnet configuration:

macOS: High Sierra Version 10.13.6
Visual Studio 2019 for Mac version 8.0.9
dotnet --info

```<code>.NET Core SDK (reflecting any global.json):
 Version:   2.2.106
 Commit:    aa79b139a8

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.13
 OS Platform: Darwin
 RID:         osx.10.13-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.2.106/

Host (useful for support):
  Version: 2.2.4
  Commit:  f95848e524

.NET Core SDKs installed:
  2.2.105 [/usr/local/share/dotnet/sdk]
  2.2.106 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
</code>```

And here is .csproj file:

ProseSample.Substrings.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net45</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\ProseSample.Substrings.Semantics\ProseSample.Substrings.Semantics.csproj" />
    <PackageReference Include="Microsoft.ProgramSynthesis.Common" Version="6.20.0" />
    <PackageReference Include="Microsoft.ProgramSynthesis.DslcTargets" Version="6.20.0" />
    <DotNetCliToolReference Include="Microsoft.ProgramSynthesis.Dslc" Version="6.20.0" />
  </ItemGroup>

</Project>
```

<p>Build Output:</p>

```Building ProseSample (Debug)
Build started 6/1/2019 5:53:06 PM.
__________________________________________________
Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (Build target(s)):

Target GenerateTargetFrameworkMonikerAttribute:
  Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
Target CoreGenerateAssemblyInfo:
  Skipping target "CoreGenerateAssemblyInfo" because all output files are up-to-date with respect to the input files.
Target CoreCompile:
  Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
Target _CopyFilesMarkedCopyLocal:
    Touching "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/obj/Debug/net45/ProseSample.Substrings.Semantics.csproj.CopyComplete".
Target CopyFilesToOutputDirectory:
    ProseSample.Substrings.Semantics -> /Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/bin/Debug/net45/ProseSample.Substrings.Semantics.dll
__________________________________________________
Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" (Build target(s)):

Target _GetProjectReferenceTargetFrameworkProperties:
    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetTargetFrameworks target(s)):

Target ResolveProjectReferences:
    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetTargetPath target(s)):

    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetNativeManifest target(s)):

Target GenerateTargetFrameworkMonikerAttribute:
  Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
Target CompileGrammar:
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    No executable found matching command "dotnet-dslc"
    /Users/username/.nuget/packages/microsoft.programsynthesis.dslctargets/6.20.0/build/Microsoft.ProgramSynthesis.DslcTargets.targets(82,9): error MSB3073: The command "dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"" exited with code 1.
Done building target "CompileGrammar" in project "ProseSample.Substrings.csproj" -- FAILED.

Done building project "ProseSample.Substrings.csproj" -- FAILED.

Build FAILED.

/Users/username/.nuget/packages/microsoft.programsynthesis.dslctargets/6.20.0/build/Microsoft.ProgramSynthesis.DslcTargets.targets(82,9): error MSB3073: The command "dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"" exited with code 1.
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:01.21

========== Build: 1 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Build: 1 error, 0 warnings
```

Thank you in advance!

答:
With the latest PROSE v7.11.1 and the steps below, the build seems to pass on macOS now.

The build failure is trigeered by dotnet dslc tool failing to run on your environment.

First, this tool seems to be a part of the NuGet package that needs to be installed

$ cd ProseSample
$ dotnet add package Microsoft.ProgramSynthesis.Dslc --version 7.11.1
```

<p>Next, it seems that the cross-platform way to run this tool responsible for mandatory step of DSL code generation is different - <code>dotnet run dslc</code>.</p>

<pre class="lang-sh prettyprint-override"><code>$ dotnet run dslc
$ dotnet build

Build succeeded.
    0 Warning(s)
    0 Error(s)
</code>```

I presume that in order for build to work in IDE, one also have to edit ~.nuget/packages/microsoft.programsynthesis.dslctargets/7.11.1/build/Microsoft.ProgramSynthesis.DslcTargets.targets and replace all 2 occurrence of dotnet dslc with the dotnet run dslc.

Hope this helps!

Body:
I am conducting a literature survey for my thesis and was trying PROSE SDK by Microsoft. However, whenever I try to build the dependencies of the project from their sample [repo] (https://github.com/microsoft/prose), I get this error:

Target CompileGrammar:
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    No executable found matching command "dotnet-dslc"

I followed installation instructions from here

Here's the information regarding dotnet configuration:

macOS: High Sierra Version 10.13.6
Visual Studio 2019 for Mac version 8.0.9
dotnet --info

.NET Core SDK (reflecting any global.json):
 Version:   2.2.106
 Commit:    aa79b139a8

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.13
 OS Platform: Darwin
 RID:         osx.10.13-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.2.106/

Host (useful for support):
  Version: 2.2.4
  Commit:  f95848e524

.NET Core SDKs installed:
  2.2.105 [/usr/local/share/dotnet/sdk]
  2.2.106 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.2.4 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

And here is .csproj file:

ProseSample.Substrings.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net45</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\ProseSample.Substrings.Semantics\ProseSample.Substrings.Semantics.csproj" />
    <PackageReference Include="Microsoft.ProgramSynthesis.Common" Version="6.20.0" />
    <PackageReference Include="Microsoft.ProgramSynthesis.DslcTargets" Version="6.20.0" />
    <DotNetCliToolReference Include="Microsoft.ProgramSynthesis.Dslc" Version="6.20.0" />
  </ItemGroup>

</Project>

Build Output:

Building ProseSample (Debug)
Build started 6/1/2019 5:53:06 PM.
__________________________________________________
Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (Build target(s)):

Target GenerateTargetFrameworkMonikerAttribute:
  Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
Target CoreGenerateAssemblyInfo:
  Skipping target "CoreGenerateAssemblyInfo" because all output files are up-to-date with respect to the input files.
Target CoreCompile:
  Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
Target _CopyFilesMarkedCopyLocal:
    Touching "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/obj/Debug/net45/ProseSample.Substrings.Semantics.csproj.CopyComplete".
Target CopyFilesToOutputDirectory:
    ProseSample.Substrings.Semantics -> /Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/bin/Debug/net45/ProseSample.Substrings.Semantics.dll
__________________________________________________
Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" (Build target(s)):

Target _GetProjectReferenceTargetFrameworkProperties:
    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetTargetFrameworks target(s)):

Target ResolveProjectReferences:
    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetTargetPath target(s)):

    __________________________________________________
    Project "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/ProseSample.Substrings.csproj" is building "/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings.Semantics/ProseSample.Substrings.Semantics.csproj" (GetNativeManifest target(s)):

Target GenerateTargetFrameworkMonikerAttribute:
  Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
Target CompileGrammar:
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"
    No executable found matching command "dotnet-dslc"
    /Users/username/.nuget/packages/microsoft.programsynthesis.dslctargets/6.20.0/build/Microsoft.ProgramSynthesis.DslcTargets.targets(82,9): error MSB3073: The command "dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"" exited with code 1.
Done building target "CompileGrammar" in project "ProseSample.Substrings.csproj" -- FAILED.

Done building project "ProseSample.Substrings.csproj" -- FAILED.

Build FAILED.

/Users/username/.nuget/packages/microsoft.programsynthesis.dslctargets/6.20.0/build/Microsoft.ProgramSynthesis.DslcTargets.targets(82,9): error MSB3073: The command "dotnet dslc  "@/Users/username/test/prose/ProgramSynthesis/ProseSample.Substrings/obj/ProseSample.Substrings.rsp"" exited with code 1.
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:01.21

========== Build: 1 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Build: 1 error, 0 warnings

Thank you in advance!

Body:
With the latest PROSE v7.11.1 and the steps below, the build seems to pass on macOS now.

The build failure is trigeered by dotnet dslc tool failing to run on your environment.

First, this tool seems to be a part of the NuGet package that needs to be installed

$ cd ProseSample
$ dotnet add package Microsoft.ProgramSynthesis.Dslc --version 7.11.1

Next, it seems that the cross-platform way to run this tool responsible for mandatory step of DSL code generation is different - dotnet run dslc.

$ dotnet run dslc
$ dotnet build

Build succeeded.
    0 Warning(s)
    0 Error(s)

I presume that in order for build to work in IDE, one also have to edit ~.nuget/packages/microsoft.programsynthesis.dslctargets/7.11.1/build/Microsoft.ProgramSynthesis.DslcTargets.targets and replace all 2 occurrence of dotnet dslc with the dotnet run dslc.

Hope this helps!


问:
Flex: Use Text File as Input Stream
So I've used flex to generate a c file from my lex code, and then used gcc to create the corresponding actual parser .exe. However, I can't figure out how to get it to read from anything other than my own typed input. I am trying to get it to parse a huge dictionary file. Can anyone help?</p>

答:
In UBUNTU
Position terminal in folder where is .l file then type following:

```<code>flex nameOfFile.l
</code>```

then

```<code>gcc lex.yy.c
</code>```

then ./a.out <nameOfFileYouWantToPass.extension (eg. ./a.out <test.txt)

.l file and test.txt should be in same folder

Title: Flex: Use Text File as Input Stream

Body:
In UBUNTU
Position terminal in folder where is .l file then type following:

flex nameOfFile.l

then

gcc lex.yy.c

then ./a.out <nameOfFileYouWantToPass.extension (eg. ./a.out <test.txt)

.l file and test.txt should be in same folder


问:
Is there a way to make the discord bot reply to someone's dm that it is prohibited to send private messages?
I want my discord bot to send something like "Youre not allowed to send messages here" whenever someone DMs it

Here is what I have so far:

```<code>if(message.channel instanceof Discord.DMChannel){
   return;
}
</code>```

Any help would be greatly appreciated :)

答:
you can either reply to the message or send a message in the same channel as the message (DM channel)

if(message.channel instanceof Discord.DMChannel && !message.author.bot) {
  return message.reply('You can not message me through DMs')
}
```

<p>Or</p>

<pre class="lang-js prettyprint-override"><code>if(message.channel instanceof Discord.DMChannel && !message.author.bot) {
  return message.channel.send('You can not message me through DMs')
}
</code>```

Body:
I want my discord bot to send something like "Youre not allowed to send messages here" whenever someone DMs it

Here is what I have so far:

if(message.channel instanceof Discord.DMChannel){
   return;
}

Any help would be greatly appreciated :)

Body:
you can either reply to the message or send a message in the same channel as the message (DM channel)

if(message.channel instanceof Discord.DMChannel && !message.author.bot) {
  return message.reply('You can not message me through DMs')
}

Or

if(message.channel instanceof Discord.DMChannel && !message.author.bot) {
  return message.channel.send('You can not message me through DMs')
}