问:
How to avoid duplicate database connection in java?
I have 2 classes. C_DB and C_Test.

In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.

Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.

C_DB

```<code>public class C_DB {
    Connection con;

    public C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public Connection getConnection() {
        return con;
    }
}
</code>```

C_Test

```<code>public class C_Test {

    public static void main(String[] args) throws Exception {
        Connection con1 = new C_DB().getConnection(); // new connection
        Connection con2 = new C_DB().getConnection(); // new duplicate connection
        Connection con3 = new C_DB().getConnection(); // new duplicate connection
    }

}
</code>```

答:
You can use Connection Pool and set it max pool size to 1 as @Elliott pointed out in the comment or you can implement something like this.</p>

```<code>public class C_DB {

    private static C_DB instance;

    private Connection con;

    private C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";
        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public static Connection getConnection(){
        if(instance == null){
           instance = new C_DB();
        }
        return instance.con;
    }

}
</code>```

Body:
I have 2 classes. C_DB and C_Test.

In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.

Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.

C_DB

public class C_DB {
    Connection con;

    public C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public Connection getConnection() {
        return con;
    }
}

C_Test

public class C_Test {

    public static void main(String[] args) throws Exception {
        Connection con1 = new C_DB().getConnection(); // new connection
        Connection con2 = new C_DB().getConnection(); // new duplicate connection
        Connection con3 = new C_DB().getConnection(); // new duplicate connection
    }

}

Body:
You can use Connection Pool and set it max pool size to 1 as @Elliott pointed out in the comment or you can implement something like this.

public class C_DB {

    private static C_DB instance;

    private Connection con;

    private C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";
        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public static Connection getConnection(){
        if(instance == null){
           instance = new C_DB();
        }
        return instance.con;
    }

}


来源: stackexchange

问:
abstraction can be done without inheritance? java
Is abstraction possible without inheritance? This is my code

```<code>     abstract class whatever
{
    abstract void disp1();
    abstract void disp2();
    abstract void disp3();
}

 class what {

    void disp1()
    {
        System.out.println("This is disp1");
    }
}

public class threeClasses {

    public static void main (String args[])
    {
        what obj =new what();
        obj.disp1();

    }

}
</code>```

Please note above, how i:

did not extend the class "what" from abstract class "whatever" and yet the code runs perfectly with no errors

Did not declare class "what" as abstract (since it's not declaring the other two methods disp2() and disp3())

I am very confused. Please help.

答:
You aren't using whatever (and Java naming conventions should be respected). The idea behind an abstract class (and inheritance) is that there is an interface contract. Let's examine it with a more practical example,

```<code>abstract class Whatever {
    abstract void disp1();

    void disp2() {
        System.out.println("disp2");
    }

    void disp3() {
        System.out.println("disp3");
    }
}
</code>```

Then make What extend it. Override two methods for demonstration (the annotation is a useful compile time safety check)

```<code>class What extends Whatever {
    @Override
    void disp1() {
        System.out.println("This is disp1");
    }

    @Override
    void disp2() {
        System.out.println("This is disp2");
    }
}
</code>```

Finally, invoke methods on a What instance through the Whatever contract

```<code>public static void main(String args[]) {
    Whatever obj = new What();
    obj.disp1();
    obj.disp2();
    obj.disp3();
}
</code>```

Which outputs

```<code>This is disp1
This is disp2
disp3
</code>```

Note that What is providing the implementation for disp1 and disp2 while Whatever provides disp3.

ContentLicense: CC BY-SA 3.0

Body:
Is abstraction possible without inheritance? This is my code

     abstract class whatever
{
    abstract void disp1();
    abstract void disp2();
    abstract void disp3();
}

 class what {

    void disp1()
    {
        System.out.println("This is disp1");
    }
}

public class threeClasses {

    public static void main (String args[])
    {
        what obj =new what();
        obj.disp1();

    }

}

Please note above, how i:

did not extend the class "what" from abstract class "whatever" and yet the code runs perfectly with no errors

Did not declare class "what" as abstract (since it's not declaring the other two methods disp2() and disp3())

I am very confused. Please help.

Body:
You aren't using whatever (and Java naming conventions should be respected). The idea behind an abstract class (and inheritance) is that there is an interface contract. Let's examine it with a more practical example,

abstract class Whatever {
    abstract void disp1();

    void disp2() {
        System.out.println("disp2");
    }

    void disp3() {
        System.out.println("disp3");
    }
}

Then make What extend it. Override two methods for demonstration (the annotation is a useful compile time safety check)

class What extends Whatever {
    @Override
    void disp1() {
        System.out.println("This is disp1");
    }

    @Override
    void disp2() {
        System.out.println("This is disp2");
    }
}

Finally, invoke methods on a What instance through the Whatever contract

public static void main(String args[]) {
    Whatever obj = new What();
    obj.disp1();
    obj.disp2();
    obj.disp3();
}

Which outputs

This is disp1
This is disp2
disp3

Note that What is providing the implementation for disp1 and disp2 while Whatever provides disp3.


问:
Filtering based on a second data.table with a negation the command
I am very new to R and especially data.table and I'm stuck with the following.

I have 2 data.tables, say "Canteen" and "Saladconsumer".
The data.table "Canteen" contains the ID, date, time and items bought of every person.

The second data.table "Saladconsumer"contains the ID, date and time of people who have bought a salad and is basically a subset of "Canteen".

Now I'd like to filter "Canteen" by "Saladconsumer" so that I get the people that have bought a salad on that day and made an other purchase the same day in the canteen. Therefore the filtering must contain a negation: Canteen[, ID]==Saladconsumer[, ID] & Canteen[, date]==Saladconsumer[, date] & Canteen[, time]!=Saladconsumer[, time].

I have only found examples for overlaps and merge/join if all the criteria are the same. It seems to be so simple but I just can't figure out what my mistake is...

```<code>NewDT<- Canteen[, Canteen[, ID ] == Saladconsumer [, ID ] & Canteen[, date ] == Saladconsumer[, date ] & Canteen[, time ] == Saladconsumer [, time ]]
</code>```

This what the data looks like and what the results are I'm looking for:

```<code>Canteen
ID  Date    Time
00b47c5d83a5490e860086eb080f1f50    26.06.14    12:36:29
00b47c898875483fb9fa0113d334e500    06.01.14    16:28:56
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
00b64cef0230b7480fc96dfcad9b8394    07.05.14    11:43:34
00b8b859987af5c89d90130d1206c579    03.01.14    13:35:15
0205996c0139e0b909903c2ebacb5a77    07.01.14    14:48:13
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
0208cfa78e51231cf30842ea0f8abdf4    10.04.14    10:06:43

Salad consumer
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
020e53bd2076a9db4c9770662793602b    04.02.14    10:38:41
020ed0685aa70b543981cbb6a7f0c737    16.01.14    15:40:02
020aa996e0f4b6e886a82ce83d406e92    23.01.14    14:23:43
020ac1d718ff47f5aaa2d684434bae93    30.06.14    13:47:45
020b20874ae29027ddac149ab3d5a395    09.04.14    09:34:32

Results
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27
</code>```

答:
I would invite you to the tidyverse (which includes the package dplyr) and recommend a left join followed by an anti-join.

I also recommend looking at the RStudio cheat sheets on data manipulation: https://www.rstudio.com/resources/cheatsheets/

This should do the trick (although I may have miss interpreted what you are looking for - in which case I am happy to help further):

```<code>library(tidyverse)

SaladPeople <- select(Saladconsumer, ID) %>% left_join(Canteen)
</code>```

Now you have only the salad consumers at the canteen.  If I understand what you are looking for then you can do an anti-join:

```<code>yourData <- anti_join(SaladPeople, Saladconsumer)
</code>```

Or as one would do this in the tidyverse:

```<code>yourData <- select(Saladconsumer, ID) %>%
  left_join(Canteen, by="ID") %>%
  anti_join(Saladconsumer))
</code>```

Body:
I am very new to R and especially data.table and I'm stuck with the following.

I have 2 data.tables, say "Canteen" and "Saladconsumer".
The data.table "Canteen" contains the ID, date, time and items bought of every person.

The second data.table "Saladconsumer"contains the ID, date and time of people who have bought a salad and is basically a subset of "Canteen".

Now I'd like to filter "Canteen" by "Saladconsumer" so that I get the people that have bought a salad on that day and made an other purchase the same day in the canteen. Therefore the filtering must contain a negation: Canteen[, ID]==Saladconsumer[, ID] & Canteen[, date]==Saladconsumer[, date] & Canteen[, time]!=Saladconsumer[, time].

I have only found examples for overlaps and merge/join if all the criteria are the same. It seems to be so simple but I just can't figure out what my mistake is...

NewDT<- Canteen[, Canteen[, ID ] == Saladconsumer [, ID ] & Canteen[, date ] == Saladconsumer[, date ] & Canteen[, time ] == Saladconsumer [, time ]]

This what the data looks like and what the results are I'm looking for:

Canteen
ID  Date    Time
00b47c5d83a5490e860086eb080f1f50    26.06.14    12:36:29
00b47c898875483fb9fa0113d334e500    06.01.14    16:28:56
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
00b64cef0230b7480fc96dfcad9b8394    07.05.14    11:43:34
00b8b859987af5c89d90130d1206c579    03.01.14    13:35:15
0205996c0139e0b909903c2ebacb5a77    07.01.14    14:48:13
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
0208cfa78e51231cf30842ea0f8abdf4    10.04.14    10:06:43

Salad consumer
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
020e53bd2076a9db4c9770662793602b    04.02.14    10:38:41
020ed0685aa70b543981cbb6a7f0c737    16.01.14    15:40:02
020aa996e0f4b6e886a82ce83d406e92    23.01.14    14:23:43
020ac1d718ff47f5aaa2d684434bae93    30.06.14    13:47:45
020b20874ae29027ddac149ab3d5a395    09.04.14    09:34:32

Results
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27

Body:
I would invite you to the tidyverse (which includes the package dplyr) and recommend a left join followed by an anti-join.

I also recommend looking at the RStudio cheat sheets on data manipulation: https://www.rstudio.com/resources/cheatsheets/

This should do the trick (although I may have miss interpreted what you are looking for - in which case I am happy to help further):

library(tidyverse)

SaladPeople <- select(Saladconsumer, ID) %>% left_join(Canteen)

Now you have only the salad consumers at the canteen.  If I understand what you are looking for then you can do an anti-join:

yourData <- anti_join(SaladPeople, Saladconsumer)

Or as one would do this in the tidyverse:

yourData <- select(Saladconsumer, ID) %>%
  left_join(Canteen, by="ID") %>%
  anti_join(Saladconsumer))


问:
upgrading 10 g to 11g checklist
There are plenty of stored procedure on 10g platform . ( Almost 500 SPs)
Each SP might have loop, fetch and etc.

I'd like to ask you if there is a cool method to control all the SPs which are currently running on 10g, and guarantee that it works on 11 g.

I have a development server 1 which is 10 g and the other development server is 11 g.
I can use both of them to testify the propose above.

For instance I know that on 10 g if you use loop, and during the loop the update statements do not affect the loop data but 11g.
There might be more cases that I have to consider. Please tell me if you have any brillant idea , otherwise I will check them up one by one manually and it is a lot of time and human control might be weak sometimes.

important note:   It is said that if you select some data from a table or tables, and if you use it in a loop, then during de loop, if you update and commit between loop case, it affects the selected data in cursor.(@11g) But this did not happen @10g version. Please correct me if you heard something like that.

The Example Case;

```<code>CREATE TABLE vty_musteri(
  musterino    NUMBER  NOT NULL,
  subeadi      VARCHAR2(61),
  kayitzamani  VARCHAR2(20)
);

INSERT INTO vty_musteri (musterino, subeadi, kayitzamani )
  VALUES (12345, 'AMSTERDAM', '05/30/2012 15:11:13');
COMMIT;

CREATE UNIQUE INDEX vty_musteri_idx ON vty_musteri (musterino);

SELECT * FROM vty_musteri;

CREATE OR REPLACE PROCEDURE krd_upd_silseomusteri_sp(RC1 in out  SYS_REFCURSOR) AS
  v_musterino NUMBER := 12345;

BEGIN

 OPEN RC1 FOR
    SELECT  m.musterino, m.subeadi, m.kayitzamani
      FROM vty_musteri m
     WHERE m.musterino = v_musterino;

   update vty_musteri
     set subeadi     = 'PORTO',
         kayitzamani = (SELECT TO_CHAR(SYSDATE, 'MM/DD/YYYY HH24:MI:SS')
                          FROM dual)
   where musterino = v_musterino;

  COMMIT;
</code>```

After all run this test on PLSQL:

```<code>    DECLARE
       --test
       vRecTip   SYS_REFCURSOR;
       TYPE vRecTipK IS RECORD(
          musterino   NUMBER,
          subeadi     VARCHAR2(61),
          kayitzamani VARCHAR2(20)

          );
       v_SeoTip vRecTipK;
    BEGIN

       krd_upd_silseomusteri_sp(rc1 => vRecTip);

       IF vRecTip%ISOPEN THEN
          LOOP
             FETCH vRecTip
                INTO v_SeoTip;
             EXIT WHEN vRecTip%NOTFOUND;

             dbms_output.put_line('The Value : ' || v_SeoTip.musterino || ' - ' || v_SeoTip.subeadi || ' - ' || v_SeoTip.kayitzamani);

          END LOOP;
       END IF;
       COMMIT;
    END;
END;
</code>```

If you run this on 10g you will see AMSTERDAM, but on 11G, it is PORTO.

To fix it; I put a hint in the sp like the following:

```<code>  SELECT /*+ full(m)*/ m.musterino, m.subeadi, m.kayitzamani
</code>```

Isn't it weird? any alternative sugesstion to get AMSTERDAM ?

答: Recently I have done migration to Oracle 11g. Faced few unprecedented issues. I have written a blog post on this. Have a look http://learncodewrite.blogspot.in/2017/04/migrating-to-oracle-11g-from-oracle-10g.html?m=1.</p>

Title: upgrading 10 g to 11g checklist

Body:
There are plenty of stored procedure on 10g platform . ( Almost 500 SPs)
Each SP might have loop, fetch and etc.

I'd like to ask you if there is a cool method to control all the SPs which are currently running on 10g, and guarantee that it works on 11 g.

I have a development server 1 which is 10 g and the other development server is 11 g.
I can use both of them to testify the propose above.

For instance I know that on 10 g if you use loop, and during the loop the update statements do not affect the loop data but 11g.
There might be more cases that I have to consider. Please tell me if you have any brillant idea , otherwise I will check them up one by one manually and it is a lot of time and human control might be weak sometimes.

important note:   It is said that if you select some data from a table or tables, and if you use it in a loop, then during de loop, if you update and commit between loop case, it affects the selected data in cursor.(@11g) But this did not happen @10g version. Please correct me if you heard something like that.

The Example Case;

CREATE TABLE vty_musteri(
  musterino    NUMBER  NOT NULL,
  subeadi      VARCHAR2(61),
  kayitzamani  VARCHAR2(20)
);

INSERT INTO vty_musteri (musterino, subeadi, kayitzamani )
  VALUES (12345, 'AMSTERDAM', '05/30/2012 15:11:13');
COMMIT;

CREATE UNIQUE INDEX vty_musteri_idx ON vty_musteri (musterino);

SELECT * FROM vty_musteri;

CREATE OR REPLACE PROCEDURE krd_upd_silseomusteri_sp(RC1 in out  SYS_REFCURSOR) AS
  v_musterino NUMBER := 12345;

BEGIN

 OPEN RC1 FOR
    SELECT  m.musterino, m.subeadi, m.kayitzamani
      FROM vty_musteri m
     WHERE m.musterino = v_musterino;

   update vty_musteri
     set subeadi     = 'PORTO',
         kayitzamani = (SELECT TO_CHAR(SYSDATE, 'MM/DD/YYYY HH24:MI:SS')
                          FROM dual)
   where musterino = v_musterino;

  COMMIT;

After all run this test on PLSQL:

    DECLARE
       --test
       vRecTip   SYS_REFCURSOR;
       TYPE vRecTipK IS RECORD(
          musterino   NUMBER,
          subeadi     VARCHAR2(61),
          kayitzamani VARCHAR2(20)

          );
       v_SeoTip vRecTipK;
    BEGIN

       krd_upd_silseomusteri_sp(rc1 => vRecTip);

       IF vRecTip%ISOPEN THEN
          LOOP
             FETCH vRecTip
                INTO v_SeoTip;
             EXIT WHEN vRecTip%NOTFOUND;

             dbms_output.put_line('The Value : ' || v_SeoTip.musterino || ' - ' || v_SeoTip.subeadi || ' - ' || v_SeoTip.kayitzamani);

          END LOOP;
       END IF;
       COMMIT;
    END;
END;

If you run this on 10g you will see AMSTERDAM, but on 11G, it is PORTO.

To fix it; I put a hint in the sp like the following:

  SELECT /*+ full(m)*/ m.musterino, m.subeadi, m.kayitzamani

Isn't it weird? any alternative sugesstion to get AMSTERDAM ?


问:
Simple c# directX example
I try to start c# directX programming with this tutorial:
http://www.riemers.net/eng/Tutorials/DirectX/Csharp/Series1/tut2.php
I'm using visual Studion Community 2015, my code is like this:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace DirecxTest01
{
    public partial class Form1 : Form
    {
        private Device device;
        public Form1()
        {
            InitializeComponent();
            InitializeDevice();
        }
        private void InitializeDevice()
        {
            PresentParameters presentParams = new PresentParameters();
            presentParams.Windowed = true;
            presentParams.SwapEffect = SwapEffect.Discard;
            device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0);
            device.Present();
        }
    }
}
</code>```

I also addesd References to all the DirectX dll's. Whe I run the Programm nothing happened, not even the Form Window appers. No error message, just nothing. I tried to comment out the DirectX Stuff line by line. Even with this code the Programm hangs up:

```<code>private void InitializeDevice()
    {
        PresentParameters presentParams = new PresentParameters();
        //presentParams.Windowed = true;
        //presentParams.SwapEffect = SwapEffect.Discard;
        //device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
        }
</code>```

When I out comment

//PresentParameters presentParams = new PresentParameters();

to, at least the Windowas Form apperears.

Whats wrong with my code?

答:
The tutorial you are using is for the deprecated Managed DirectX 1.1 assemblies. They were written for .NET 1.1, and are not compatible with .NET 4.0 or later--although there are some hacks out there to try to make them work.

Since the last version of D3DX9 supported by Managed DirectX 1.1 is April 2006, it makes use of a very outdated version of the HLSL compiler.

The Managed DirectX 1.1 assemblies are 32-bit only, so you cannot use them from an x64 native .NET application (/platform:anycpu on a Windows x64 system). You must build with /platform:x86 and stay within the limits of the 2 GB memory space of 32-bit applications.

The assemblies only support the legacy DirectX API set, with no support for Direct3D9Ex, Direct3D 10.x, Direct3D 11, Direct2D, DirectWrite, DXGI, D3DX10, D3DX11, XAUDIO2, XACT, XINPUT, etc.

Since Managed DirectX 2.0 was never released in production form, the Managed DirectX 1.1 assemblies still reflect .NET 1.1 design principles and does not support or make use of .NET 2.0 constructs.

Managed DirectX 1.1 while compatible with .NET 2.0 (and the .NET 3.0 and .NET 3.5 extensions of the 2.0 runtime), is not compatible with .NET 4.0

The Managed DirectX 1.1 assemblies are only deployed by the legacy DirectSetup and the legacy DirectX SDK.

In short: Don't use them. Use something more modern like SharpDX, SlimDX, or Unity3D.

See DirectX and .NET and Where is the DirectX SDK?

Title: Simple c# directX example

Body:
I try to start c# directX programming with this tutorial:
http://www.riemers.net/eng/Tutorials/DirectX/Csharp/Series1/tut2.php
I'm using visual Studion Community 2015, my code is like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace DirecxTest01
{
    public partial class Form1 : Form
    {
        private Device device;
        public Form1()
        {
            InitializeComponent();
            InitializeDevice();
        }
        private void InitializeDevice()
        {
            PresentParameters presentParams = new PresentParameters();
            presentParams.Windowed = true;
            presentParams.SwapEffect = SwapEffect.Discard;
            device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0);
            device.Present();
        }
    }
}

I also addesd References to all the DirectX dll's. Whe I run the Programm nothing happened, not even the Form Window appers. No error message, just nothing. I tried to comment out the DirectX Stuff line by line. Even with this code the Programm hangs up:

private void InitializeDevice()
    {
        PresentParameters presentParams = new PresentParameters();
        //presentParams.Windowed = true;
        //presentParams.SwapEffect = SwapEffect.Discard;
        //device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
        }

When I out comment

//PresentParameters presentParams = new PresentParameters();

to, at least the Windowas Form apperears.

Whats wrong with my code?

ContentLicense: CC BY-SA 4.0


答:
There is no relationship between your abstract class and your concrete class. Whatever your definition of "abstraction", it actually represents a relationship between types. The abstract keyword does not establish that relationship between classes, it represents that relationship, and not by itself. The relationship needs to be extended from both sides.

abstract is a declaration from one side about a promise that must be kept, for an inheriting type either to implement abstract methods or to ask for that promise from its inheriting types.

The other side makes the promise by being a class that inherits from the abstract type. Without inheritance, the concrete type loses the is-a connection.

You will get the compiler error you're complaining about missing if you correct one major mistake you made. You failed to use the @Override annotation. Always use the @Override annotation when you intend to override a method, or you will forever enjoy just the sort of bug you show here.

Title: abstraction can be done without inheritance? java


问:
Draw trajectory of an object in OpenGL
I want to make the codes that draw trajectory as the object's moving when I clicked any position on the screen.

I set the initial center point as a starting point. And I want to set the other point with mouse button clicked (destination point) as variables but I can't figure out how to do this.

```<code>float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };
</code>```

This is the initial position of the object. (6-point star with 2 triangles)

```<code>float px, py;
float center_s[3] = { 0.0f, 0.0f, 0.0f };
float center_d[3] = { px, py, 0.0f };
</code>```

center_s is the starting point and center_d is the destination point with variable px, py.

```<code>void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex3fv(center_s);

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex3fv(center_s);
    glVertex3fv(center_d);
}
</code>```

This function draws trajectory with red lines from center_s to center_d. Also it draws a center point.

```<code>case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        x = mx;
        y = glutGet(GLUT_WINDOW_HEIGHT) - my;
        px = x + 35.0;
        py = y + 42.5;
        glutIdleFunc(lines);
    }
    glutPostRedisplay();
    break;
</code>```

Here is the problem. When the left mouse button is pressed, the star has to move to the clicked position and calculates the center point of the position and draw the line. But if I run these codes, the movement trajectory is not drawn.

Please let me know what the problem is. Plus, the star must move at a constant speed to the clicked location. (Not teleportation)

Following is the full codes:

```<code>#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };

float px, py;
float center_s[3] = { 0.0f, 0.0f, 0.0f };
float center_d[3] = { px, py, 0.0f };

static GLfloat spin = 0.0;

float x = 400.0f, y = 442.5f;

float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;
int rotate = 1;

void init(void);
void triangle_1(void);
void triangle_2(void);
void lines(void);
void display(void);
void spinDisplay_1(void);
void spinDisplay_2(void);
void reshape(int, int);
void changeColor(int);
void mouse(int, int, int, int);

////////////////////////////////////////////////////////////////////

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}

////////////////////////////////////////////////////////////////////

void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void triangle_1(void) {
    glColor3fv(color1);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {
    glColor3fv(color2);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex3fv(center_s);

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex3fv(center_s);
    glVertex3fv(center_d);
}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();

    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void spinDisplay_1(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void spinDisplay_2(void) {
    spin = spin - 2.0;

    if (spin < 360.0) {
        spin = spin + 360.0;
    }

    glutPostRedisplay();
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void changeColor(int n) {
    if (n == 1) {
        color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
        color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
    }
    else if (n == 2) {
        color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
        color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
    }
}

void mouse(int button, int state, int mx, int my) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN) {
            x = mx;
            y = glutGet(GLUT_WINDOW_HEIGHT) - my;
            px = x + 35.0;
            py = y + 42.5;
            glutIdleFunc(lines);
        }
        glutPostRedisplay();
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN) {
            if (mode == 1) {
                changeColor(mode);
                mode = 2;
            }
            else if (mode == 2) {
                changeColor(mode);
                mode = 1;
            }
        }
        glutPostRedisplay();
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            if (rotate == 1) {
                glutIdleFunc(spinDisplay_1);
                rotate = 2;
            }
            else if (rotate == 2) {
                glutIdleFunc(spinDisplay_2);
                rotate = 1;
            }
        break;
    default:
        break;
    }
}
</code>```

答:
You're missing a few glEnd() and unless you have other plans for center_s and center_d then you don't need them. As x and y is center_s, while px and py is center_d.

So first of all in mouse() just assign the mouse position to px and py instead of x and y.

```<code>case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        px = mx;
        py = glutGet(GLUT_WINDOW_HEIGHT) - my;
    }
</code>```

Now next you need a way to obtain the delta time. Delta time is the time passed since the last frame. For ease I added the following code to the top of display().

```<code>int timeNow = glutGet(GLUT_ELAPSED_TIME);
float delta = (float)(timeNow - timeLastFrame) / 1000.0f;
timeLastFrame = timeNow;
</code>```

Remember to declare int timeLastFrame = 0; among your global variables.

Now (still in display()) we can calculate the direction of the travel path. We do this by calculating the difference between the two points. Then calculate the length and normalize the difference.

```<code>float dx = px - x;
float dy = py - y;

float length = sqrt(dx * dx + dy * dy);

dx /= length;
dy /= length;
</code>```

Now you just put it all together.

```<code>if (length > 1.0f) {
    x += dx * speed * delta;
    y += dy * speed * delta;
}
</code>```

So while length > 1.0 then we move towards px and py at the speed of float speed = 100.0f; (declare this among your global variables as well).

Just to reemphasize. Yes, do delete glutIdleFunc(lines) from mouse(). Then we add it in display() instead. The full extend of display() should look like this now:

```<code>void display(void) {
    int timeNow = glutGet(GLUT_ELAPSED_TIME);
    float delta = (float)(timeNow - timeLastFrame) / 1000.0f;
    timeLastFrame = timeNow;

    float dx = px - x;
    float dy = py - y;

    float length = sqrt(dx * dx + dy * dy);

    dx /= length;
    dy /= length;

    if (length > 1.0f) {
        x += dx * speed * delta;
        y += dy * speed * delta;
    }

    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix();
    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);
    triangle_1();
    triangle_2();
    glPopMatrix();

    lines();

    glutSwapBuffers();

    glutPostRedisplay();
}
</code>```

Remember glutPostRedisplay(). If not then it won't redraw and thus not animate. Also remember to #include <math.h> for sqrt().

Everything before glClear() could be moved to your glutIdleFunc() callback.

Since there was no need for center_s and center_d then lines() can be boiled down to:

```<code>void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex2f(px, py);
    glEnd();

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex2f(x, y);
    glVertex2f(px, py);
    glEnd();
}
</code>```

The result should look something like this:

For future reference. If you don't want to do the linear algebra by hand. Then you can use something like GLM.

Title: Draw trajectory of an object in OpenGL

Body:
I want to make the codes that draw trajectory as the object's moving when I clicked any position on the screen.

I set the initial center point as a starting point. And I want to set the other point with mouse button clicked (destination point) as variables but I can't figure out how to do this.

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };

This is the initial position of the object. (6-point star with 2 triangles)

float px, py;
float center_s[3] = { 0.0f, 0.0f, 0.0f };
float center_d[3] = { px, py, 0.0f };

center_s is the starting point and center_d is the destination point with variable px, py.

void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex3fv(center_s);

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex3fv(center_s);
    glVertex3fv(center_d);
}

This function draws trajectory with red lines from center_s to center_d. Also it draws a center point.

case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        x = mx;
        y = glutGet(GLUT_WINDOW_HEIGHT) - my;
        px = x + 35.0;
        py = y + 42.5;
        glutIdleFunc(lines);
    }
    glutPostRedisplay();
    break;

Here is the problem. When the left mouse button is pressed, the star has to move to the clicked position and calculates the center point of the position and draw the line. But if I run these codes, the movement trajectory is not drawn.

Please let me know what the problem is. Plus, the star must move at a constant speed to the clicked location. (Not teleportation)

Following is the full codes:

#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };

float px, py;
float center_s[3] = { 0.0f, 0.0f, 0.0f };
float center_d[3] = { px, py, 0.0f };

static GLfloat spin = 0.0;

float x = 400.0f, y = 442.5f;

float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;
int rotate = 1;

void init(void);
void triangle_1(void);
void triangle_2(void);
void lines(void);
void display(void);
void spinDisplay_1(void);
void spinDisplay_2(void);
void reshape(int, int);
void changeColor(int);
void mouse(int, int, int, int);

////////////////////////////////////////////////////////////////////

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}

////////////////////////////////////////////////////////////////////

void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void triangle_1(void) {
    glColor3fv(color1);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {
    glColor3fv(color2);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex3fv(center_s);

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex3fv(center_s);
    glVertex3fv(center_d);
}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();

    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void spinDisplay_1(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void spinDisplay_2(void) {
    spin = spin - 2.0;

    if (spin < 360.0) {
        spin = spin + 360.0;
    }

    glutPostRedisplay();
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void changeColor(int n) {
    if (n == 1) {
        color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
        color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
    }
    else if (n == 2) {
        color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
        color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
    }
}

void mouse(int button, int state, int mx, int my) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN) {
            x = mx;
            y = glutGet(GLUT_WINDOW_HEIGHT) - my;
            px = x + 35.0;
            py = y + 42.5;
            glutIdleFunc(lines);
        }
        glutPostRedisplay();
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN) {
            if (mode == 1) {
                changeColor(mode);
                mode = 2;
            }
            else if (mode == 2) {
                changeColor(mode);
                mode = 1;
            }
        }
        glutPostRedisplay();
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            if (rotate == 1) {
                glutIdleFunc(spinDisplay_1);
                rotate = 2;
            }
            else if (rotate == 2) {
                glutIdleFunc(spinDisplay_2);
                rotate = 1;
            }
        break;
    default:
        break;
    }
}

Body:
You're missing a few glEnd() and unless you have other plans for center_s and center_d then you don't need them. As x and y is center_s, while px and py is center_d.

So first of all in mouse() just assign the mouse position to px and py instead of x and y.

case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        px = mx;
        py = glutGet(GLUT_WINDOW_HEIGHT) - my;
    }

Now next you need a way to obtain the delta time. Delta time is the time passed since the last frame. For ease I added the following code to the top of display().

int timeNow = glutGet(GLUT_ELAPSED_TIME);
float delta = (float)(timeNow - timeLastFrame) / 1000.0f;
timeLastFrame = timeNow;

Remember to declare int timeLastFrame = 0; among your global variables.

Now (still in display()) we can calculate the direction of the travel path. We do this by calculating the difference between the two points. Then calculate the length and normalize the difference.

float dx = px - x;
float dy = py - y;

float length = sqrt(dx * dx + dy * dy);

dx /= length;
dy /= length;

Now you just put it all together.

if (length > 1.0f) {
    x += dx * speed * delta;
    y += dy * speed * delta;
}

So while length > 1.0 then we move towards px and py at the speed of float speed = 100.0f; (declare this among your global variables as well).

Just to reemphasize. Yes, do delete glutIdleFunc(lines) from mouse(). Then we add it in display() instead. The full extend of display() should look like this now:

void display(void) {
    int timeNow = glutGet(GLUT_ELAPSED_TIME);
    float delta = (float)(timeNow - timeLastFrame) / 1000.0f;
    timeLastFrame = timeNow;

    float dx = px - x;
    float dy = py - y;

    float length = sqrt(dx * dx + dy * dy);

    dx /= length;
    dy /= length;

    if (length > 1.0f) {
        x += dx * speed * delta;
        y += dy * speed * delta;
    }

    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix();
    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);
    triangle_1();
    triangle_2();
    glPopMatrix();

    lines();

    glutSwapBuffers();

    glutPostRedisplay();
}

Remember glutPostRedisplay(). If not then it won't redraw and thus not animate. Also remember to #include <math.h> for sqrt().

Everything before glClear() could be moved to your glutIdleFunc() callback.

Since there was no need for center_s and center_d then lines() can be boiled down to:

void lines(void) {
    glColor3f(1.0, 0.0, 0.0);

    glPointSize(5);
    glBegin(GL_POINTS);
    glVertex2f(px, py);
    glEnd();

    glLineWidth(1);
    glBegin(GL_LINES);
    glVertex2f(x, y);
    glVertex2f(px, py);
    glEnd();
}

The result should look something like this:

For future reference. If you don't want to do the linear algebra by hand. Then you can use something like GLM.


问:
Taking on value of a tuple in an array?
so I am creating a non-visible grid for a text based game. I have created an array of coordinates in a 10 by 10 grid. How do I access a single x and y value in the array?

----------Swift 3 Code!!

```<code>var gameArea: [(Int, Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append(x, y)
    }
}

var position = gameArea[5]

position.y
</code>```

答:
If you want to access it like .x and .y you have to change a little bit your code also you can access it wit .0 and .1

```<code>var gameArea: [(x: Int, y: Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append((x,y))
    }
}

var position = gameArea[5]

position.0 // x value
position.1 // y value

position.x // x value
position.y // y value
</code>```

Title: Taking on value of a tuple in an array?

Body:
so I am creating a non-visible grid for a text based game. I have created an array of coordinates in a 10 by 10 grid. How do I access a single x and y value in the array?

----------Swift 3 Code!!

var gameArea: [(Int, Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append(x, y)
    }
}

var position = gameArea[5]

position.y

Body:
If you want to access it like .x and .y you have to change a little bit your code also you can access it wit .0 and .1

var gameArea: [(x: Int, y: Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append((x,y))
    }
}

var position = gameArea[5]

position.0 // x value
position.1 // y value

position.x // x value
position.y // y value


问:
Choosing an IDE/Editor for Clojure coding
I'm looking for an editor or an IDE for my Clojure coding and I found this thread:

Clojure editor/IDE recommendations on Mac OS X

However I have a couple of questions:

Which IDE offers the best Clojure environment (right now): IntelliJ, Eclipse or NetBeans?

What are the advantages of Aquamacs (I read Rick is using it) over the previous heavy-weight IDEs?

答: VS Code does it for me on Linux platform. Looked at Light Table and pretty much similar to VS Code - built off the same engine, I believe. Go with an IDE that is closest with what you are already familiar with would be my take on this. If you are used to JetBrains IDE then Cursive - watch the License terms though.</p>

ContentLicense: CC BY-SA 2.5


问:
Python - passing pointers between C and Python with ctypes
I'm trying to write a small, modular program in Python that will dynamically load C functions and use them to execute computationally intensive code. In this program I am creating a couple of large matrices that I will be passing back and forth between my Python code to different C functions. I would prefer to pass these matrices by reference to avoid additional computational overhead.

I've tried reading through the Python docs for ctypes, but it doesn't seem to explain how to do this. I understand, for instance, that I can use byref() or pointer() to pass a pointer from Python to a C function, but how to I pass a pointer from an external C function back to Python? Given that variables are names in Python, is this just done "automatically" (for lack of a better term) when Python receives a value from a C function?

As a concrete example, this is what I'm trying to do (in pseudo-code):

```<code>foo = ctypes.CDLL("pathToFoo")
bar = ctypes.CDLL("pathToBar")

# Generate a large matrix by calling a C function.
reallyBigMatrix = foo.generateReallyBigMatrix()

# Pass reallyBigMatrix to another function and perform some operation
# on it. Since the matrix is really big, I would prefer to pass a
# reference to this matrix to my next C function rather than passing
# the matrix by value.
modifiedReallyBigMatrix = bar.modifyReallyBigMatrix(reallBigMatrix)
</code>```

Alternatively, I'm using Python and C in conjunction as I need an easy way to dynamically load C functions in my program. I may pass paths to different C files to my Python program so that the Python program will execute the same code on different functions. As an example, I may want to run my program two different ways: keep the same "generateReallyBigMatrix" function in both runs, but used a different "modifyReallyBigMatrix" program between run 1 and run 2. If there is an easy, cross-platform way to do this in C or C++ I would be happy to implement that solution rather than using ctypes and Python. However, I haven't been able to find a simple, cross-platform solution.

答:
You've mentioned that you are writing all the code, both Python and C, from yourself.  I suggest not using ctypes for this, as ctypes is best suited for using C libraries that cannot be modified.

Instead, write a module in C using the Python C API.  It will expose a single function to start with, like this:

```<code>PyObject* generateReallyBigMatrix(void);
</code>```

Now, instead of trying to return a raw C pointer, you can return any Python object that you like.  Good choices here would be to return a NumPy array (using the NumPy C API), or to return a Python "buffer" (from which a NumPy array can be constructed in Python if desired).

Either way, once this function is written in C using the appropriate APIs, your Python code will be simple:

```<code>import foo
reallyBigMatrix = foo.generateReallyBigMatrix()
</code>```

To do it using the NumPy C API, your C code will look like this:

```<code>PyObject* generateReallyBigMatrix(void)
{
    npy_intp dimension = 100;
    PyArray_Descr* descr;
    PyArray_DescrAlignConverter2("float64", &descr); // use any dtype

    PyObject* array = PyArray_Empty(1, &dimension, descr, 0/*fortran*/);
    Py_DECREF(descr);

    void* data = PyArray_DATA(array);
    // TODO: populate data

    return array;
}

static PyMethodDef methods[] = {
    {"generateReallyBigMatrix", generateReallyBigMatrix, METH_VARARGS, "doc"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initfoo(void)
{
    import_array(); // enable NumPy C API
    Py_InitModule("foo", methods);
}
</code>```

Note that the NumPy C API requires a slightly strange initialization ritual.  See also Numpy C API: Link several object files

You then compile the code as a shared library called foo.so (no lib prefix).

Body:
I'm trying to write a small, modular program in Python that will dynamically load C functions and use them to execute computationally intensive code. In this program I am creating a couple of large matrices that I will be passing back and forth between my Python code to different C functions. I would prefer to pass these matrices by reference to avoid additional computational overhead.

I've tried reading through the Python docs for ctypes, but it doesn't seem to explain how to do this. I understand, for instance, that I can use byref() or pointer() to pass a pointer from Python to a C function, but how to I pass a pointer from an external C function back to Python? Given that variables are names in Python, is this just done "automatically" (for lack of a better term) when Python receives a value from a C function?

As a concrete example, this is what I'm trying to do (in pseudo-code):

foo = ctypes.CDLL("pathToFoo")
bar = ctypes.CDLL("pathToBar")

# Generate a large matrix by calling a C function.
reallyBigMatrix = foo.generateReallyBigMatrix()

# Pass reallyBigMatrix to another function and perform some operation
# on it. Since the matrix is really big, I would prefer to pass a
# reference to this matrix to my next C function rather than passing
# the matrix by value.
modifiedReallyBigMatrix = bar.modifyReallyBigMatrix(reallBigMatrix)

Alternatively, I'm using Python and C in conjunction as I need an easy way to dynamically load C functions in my program. I may pass paths to different C files to my Python program so that the Python program will execute the same code on different functions. As an example, I may want to run my program two different ways: keep the same "generateReallyBigMatrix" function in both runs, but used a different "modifyReallyBigMatrix" program between run 1 and run 2. If there is an easy, cross-platform way to do this in C or C++ I would be happy to implement that solution rather than using ctypes and Python. However, I haven't been able to find a simple, cross-platform solution.

Body:
You've mentioned that you are writing all the code, both Python and C, from yourself.  I suggest not using ctypes for this, as ctypes is best suited for using C libraries that cannot be modified.

Instead, write a module in C using the Python C API.  It will expose a single function to start with, like this:

PyObject* generateReallyBigMatrix(void);

Now, instead of trying to return a raw C pointer, you can return any Python object that you like.  Good choices here would be to return a NumPy array (using the NumPy C API), or to return a Python "buffer" (from which a NumPy array can be constructed in Python if desired).

Either way, once this function is written in C using the appropriate APIs, your Python code will be simple:

import foo
reallyBigMatrix = foo.generateReallyBigMatrix()

To do it using the NumPy C API, your C code will look like this:

PyObject* generateReallyBigMatrix(void)
{
    npy_intp dimension = 100;
    PyArray_Descr* descr;
    PyArray_DescrAlignConverter2("float64", &descr); // use any dtype

    PyObject* array = PyArray_Empty(1, &dimension, descr, 0/*fortran*/);
    Py_DECREF(descr);

    void* data = PyArray_DATA(array);
    // TODO: populate data

    return array;
}

static PyMethodDef methods[] = {
    {"generateReallyBigMatrix", generateReallyBigMatrix, METH_VARARGS, "doc"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initfoo(void)
{
    import_array(); // enable NumPy C API
    Py_InitModule("foo", methods);
}

Note that the NumPy C API requires a slightly strange initialization ritual.  See also Numpy C API: Link several object files

You then compile the code as a shared library called foo.so (no lib prefix).


问:
Rank rows in a column under conditions on a different column
I have the following dataset:

```<code> id |   date   | state
-----------------------
  1 | 01/01/17 | high
  1 | 02/01/17 | high
  1 | 03/01/17 | high
  1 | 04/01/17 | miss
  1 | 05/01/17 | high
  2 | 01/01/17 | miss
  2 | 02/01/17 | high
  2 | 03/01/17 | high
  2 | 04/01/17 | miss
  2 | 05/01/17 | miss
  2 | 06/01/17 | high
</code>```

I want to create a column rank_state which ranks, within groups of id, the entries as per increasing date (starting from rank 0) which do not have the state of "miss". Furthermore, the rank repeats itself if the entry has a state of "miss". The output should look like:

```<code> id |   date   | state | rank_state
------------------------------------
  1 | 01/01/17 | high  |    0
  1 | 02/01/17 | high  |    1
  1 | 03/01/17 | high  |    2
  1 | 04/01/17 | miss  |    2
  1 | 05/01/17 | high  |    3
  2 | 01/01/17 | miss  |    0
  2 | 02/01/17 | high  |    0
  2 | 03/01/17 | high  |    1
  2 | 04/01/17 | miss  |    1
  2 | 05/01/17 | miss  |    1
  2 | 06/01/17 | high  |    2
</code>```

For example, the 4th row has a rank of 2 since it's state is "miss", i.e. it repeats the rank of row 3 (the same applies to rows 9 and 10). Please note that rows 6 and 7 should have rank 0.

I have tried the following:
,(case when state is not in ('miss') then (rank() over (partition by id order by date desc) - 1) end) as state_rank
and
,rank() over (partition by id order by case when state is not in ('miss') then date end) as state_rank
but neither give me the desired result. Any ideas would be very helpful.

答:
More than likely you want:

```<code>SELECT *,
       GREATEST(
         COUNT(case when state != 'miss' then 1 else null end)
           OVER(PARTITION BY id ORDER BY date) - 1,
         0
       ) as "state_rank"
FROM tbl;
</code>```

SQL Fiddle

Basically:

make your window frame (partition) overid

only count the ones that aren't 'miss'

because it could be a negative number if starting the record, you can slap on the GREATEST to use 0 (preventing negatives)

Body:
I have the following dataset:

 id |   date   | state
-----------------------
  1 | 01/01/17 | high
  1 | 02/01/17 | high
  1 | 03/01/17 | high
  1 | 04/01/17 | miss
  1 | 05/01/17 | high
  2 | 01/01/17 | miss
  2 | 02/01/17 | high
  2 | 03/01/17 | high
  2 | 04/01/17 | miss
  2 | 05/01/17 | miss
  2 | 06/01/17 | high

I want to create a column rank_state which ranks, within groups of id, the entries as per increasing date (starting from rank 0) which do not have the state of "miss". Furthermore, the rank repeats itself if the entry has a state of "miss". The output should look like:

 id |   date   | state | rank_state
------------------------------------
  1 | 01/01/17 | high  |    0
  1 | 02/01/17 | high  |    1
  1 | 03/01/17 | high  |    2
  1 | 04/01/17 | miss  |    2
  1 | 05/01/17 | high  |    3
  2 | 01/01/17 | miss  |    0
  2 | 02/01/17 | high  |    0
  2 | 03/01/17 | high  |    1
  2 | 04/01/17 | miss  |    1
  2 | 05/01/17 | miss  |    1
  2 | 06/01/17 | high  |    2

For example, the 4th row has a rank of 2 since it's state is "miss", i.e. it repeats the rank of row 3 (the same applies to rows 9 and 10). Please note that rows 6 and 7 should have rank 0.

I have tried the following:
,(case when state is not in ('miss') then (rank() over (partition by id order by date desc) - 1) end) as state_rank
and
,rank() over (partition by id order by case when state is not in ('miss') then date end) as state_rank
but neither give me the desired result. Any ideas would be very helpful.

Body:
More than likely you want:

SELECT *,
       GREATEST(
         COUNT(case when state != 'miss' then 1 else null end)
           OVER(PARTITION BY id ORDER BY date) - 1,
         0
       ) as "state_rank"
FROM tbl;

SQL Fiddle

Basically:

make your window frame (partition) overid

only count the ones that aren't 'miss'

because it could be a negative number if starting the record, you can slap on the GREATEST to use 0 (preventing negatives)


问:
Why is this semaphore code failing?
```<code>#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}
</code>```

<p>I'm getting: </p>

```<code>/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status
</code>```

答: As stated in the man page, you have to link with either -lrt or -pthread.

Title: Why is this semaphore code failing?

Body:
#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}

I'm getting:

/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status


问:
What version of UI Bootstrap works with Angular 1.6.3?
I am using AngularJS v1.6.3 and am trying to find a version of UI.bootstrap that works with it (in terms of Bootstrap's Javascript functionality, such as popover).

This Plunker uses UI.Bootstrap v0.12.0 and the popover works:
http://plnkr.co/edit/6ris13k1kZCGLvO7CP4B?p=preview

This Plunker uses UI.Bootstrap v2.5.0 and the popover does not work:
http://plnkr.co/edit/NS8OLrKXCfKdHrQ8TRwK?p=preview

This is the popover code that does not work in the latter:

```<code><p><a href="#" popover-placement="right" popover="On the Right!">Click me and see popover on the right.</a></p>
</code>```

I suspect I am doing something wrong. Thanks!

答:
In newer versions of Angular UI Bootstrap, the directive name has been changed from popover to uib-popover. This is a fork of your 2nd Plunker in which the popover is displayed on the right of the link.

You can find the new directive name here

Body:
I am using AngularJS v1.6.3 and am trying to find a version of UI.bootstrap that works with it (in terms of Bootstrap's Javascript functionality, such as popover).

This Plunker uses UI.Bootstrap v0.12.0 and the popover works:
http://plnkr.co/edit/6ris13k1kZCGLvO7CP4B?p=preview

This Plunker uses UI.Bootstrap v2.5.0 and the popover does not work:
http://plnkr.co/edit/NS8OLrKXCfKdHrQ8TRwK?p=preview

This is the popover code that does not work in the latter:

Click me and see popover on the right.

I suspect I am doing something wrong. Thanks!


问:
Multiple reset passwords in django
I have a project which have a personal app, where the login takes place, and a question app which also includes a profile page. I have managed to reset pasword from the login page, but when I try to do the same in the question app (using different templates, because I do not want the same on these pages), it just goes directly to the login reset template.

I thought it would be enough to just add a new registration folder in the questions app, but it still goes searching in the personal app I think.

Is it possible to just fix this using the django auth views or do I have to create my own views for the questions app?

答:
You will need to create separate views, as well as separate templates.

First, make sure that you understand the User model, and how authentication works in Django.  The core docs have plenty of information on that.

Second, look at what you are trying to do and create a view specifically for the template you are creating.  Make sure that view processes the data the way that you want to, and that it redirects where you want the user to be redirected to after making the update.

One question to ask yourself though, before you go through this trouble is "Do I really need to have two places to do this?"

Having more than one location to handle password resets is not likely to end up being what you actually want in the long run.  I would personally keep all of the account manipulation views in one place so that you don't mess something up if you decide to change something in one place and forget in another.

Two principles that are important when developing any kind of site are KISS and DRY.  KISS is just the traditional keep it simple.

DRY means don't repeat yourself.

Unless there is a NEED to have the code be in two different places, it is a bad idea.  ESPECIALLY with account related things.

Title: Multiple reset passwords in django


问:
PHP Search Result Concatenation
I'm trying to find a method in php to concat all related search return results from mysql DB into a single string separated by a comma. See below for DB table php output formats and php code.

Beach table:

```<code>bname    length  city_name
Beach A  4       City Z
Beach B  3       City X
Beach C  7       City E
</code>```

Beach_Act_Type table:

```<code>bname        act_type
Beach A      Swimming
Beach A      Surfing
Beach B      Surfing
Beach C      Swimming
Beach C      Fishing
Beach C      Surfing
</code>```

Output I'm looking for:

```<code>`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming, Fishing, Surfing
</code>```

Instead of this output format:

```<code>`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming
 Beach C           Fishing
 Beach C           Surfing
</code>```

My php code:

```<code>$conn = new mysqli('localhost','test','','beachproject');

if (!$conn) {
    die('DB Connection Error');
}

$search = $_POST['search'];
$search_sql="select `beach`.`bname`, `beach_act_type`.`act_type`
from `beach` inner join `beach_act_types`
on `beach`.`bname`=`beach_act_type`.`bname`
where `beach`.`bname`='$search'";
$search_query=$conn->query($search_sql);

if ($search_query->num_rows > 0) {
    while($row = $search_query->fetch_assoc()) {
        echo "<table border='1' cellpadding='4'>
        <tr>
        <th>Beach Name</th>
        <th>Beach Activity Allowed</th>
        </tr>";

        echo "<tr>";
        echo "<td>" . $row['bname'] . "</td>";
        echo "<td>" . $row['act_type'] . "</td>";
        echo "</tr>";

        echo "</table>";
    }
} else {
    echo "No Search Results";
}
</code>```

答:
The function you're looking for is GROUP_CONCAT.

```<code>SELECT
    `beach`.`bname`,
    GROUP_CONCAT(`beach_act_types`.`act_type`) types
FROM
    `beach`
INNER JOIN
    `beach_act_types` ON
        `beach`.`bname` = `beach_act_types`.`bname`
WHERE
    `beach`.`bname` = '$search'
</code>```

PS. You should be warned that you have SQL injection present, consider switching to prepared statements instead.

Title: PHP Search Result Concatenation

Body:
I'm trying to find a method in php to concat all related search return results from mysql DB into a single string separated by a comma. See below for DB table php output formats and php code.

Beach table:

bname    length  city_name
Beach A  4       City Z
Beach B  3       City X
Beach C  7       City E

Beach_Act_Type table:

bname        act_type
Beach A      Swimming
Beach A      Surfing
Beach B      Surfing
Beach C      Swimming
Beach C      Fishing
Beach C      Surfing

Output I'm looking for:

`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming, Fishing, Surfing

Instead of this output format:

`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming
 Beach C           Fishing
 Beach C           Surfing

My php code:

$conn = new mysqli('localhost','test','','beachproject');

if (!$conn) {
    die('DB Connection Error');
}

$search = $_POST['search'];
$search_sql="select `beach`.`bname`, `beach_act_type`.`act_type`
from `beach` inner join `beach_act_types`
on `beach`.`bname`=`beach_act_type`.`bname`
where `beach`.`bname`='$search'";
$search_query=$conn->query($search_sql);

if ($search_query->num_rows > 0) {
    while($row = $search_query->fetch_assoc()) {
        echo "

        Beach Name
        Beach Activity Allowed

";

        echo "
";
        echo "" . $row['bname'] . "	";
        echo "" . $row['act_type'] . "	";
        echo "
";

        echo "
";
    }
} else {
    echo "No Search Results";
}

Body:
The function you're looking for is GROUP_CONCAT.

SELECT
    `beach`.`bname`,
    GROUP_CONCAT(`beach_act_types`.`act_type`) types
FROM
    `beach`
INNER JOIN
    `beach_act_types` ON
        `beach`.`bname` = `beach_act_types`.`bname`
WHERE
    `beach`.`bname` = '$search'

PS. You should be warned that you have SQL injection present, consider switching to prepared statements instead.


问:
Collaborative Paint App
I am in the early stages of learning nodejs client/server programming, for my first application I just want to make a simple collaborative drawing app like paint. So far I have this code and the only thing that seems to work is that my click properly calls in my console.log but no rectangle draws at the click location. Any help? I am pretty new to this.

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){

 SOCKET_LIST[socket.id] = socket;

 var self = {
  x:0,
  y:0,
  cx:0,
  cy:0,
 }

 socket.on('mousePos', function(data){
  self.x = data.x;
  self.y = data.y;
  //console.log('x:' + self.x + ' y:' + self.y);
 });

 socket.on('mouseClick', function(data){
  self.cx = data.x;
  self.cy = data.y;
  console.log('x:' + self.cx + ' y:' + self.cy);
 });

 socket.emit('paint', {x:self.cx, y:self.cy});

 /*for (var i in SOCKET_LIST){
  var socket = SOCKET_LIST[i];
  socket.emit('paint', {x:self.cx, y:self.cy});
 }*/

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

<div id="gameCanvasDiv">
 <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
</div>

<script>
 var socket = io();

 var ctx = document.getElementById("ctx").getContext("2d");

 ctx.fillStyle = "#FF0000";

 setInterval(function(){

    },40);

 document.onmousedown = function(event){

  socket.emit('mouseClick', {x:event.clientX, y:event.clientY});

 }

 document.onmouseup = function(event){

  socket.on('paint', function(data){
   ctx.fillRect(data.x,data.y,10,10);
  });

 }

 document.onmousemove = function(event){
        socket.emit('mousePos', {x:event.clientX, y:event.clientY});
    }

</script></code>```

答:
```<code>document.onmouseup = function(event){
    socket.on('paint', function(data){
        ctx.fillRect(data.x,data.y,10,10);
    });
}
</code>```

Here you only subscribing to event. So you saying - "When mouse up, please, add one more handler for paint event" (so this code will be executed multiple times). So where paint event generated? Who send it? You send it only once, when connection established. So what you have to do, is to:

Mode paint event listener on frontend to outside of event listener.

Remove emit('paint') from onConnection event.

Add onMouseUp event listener to nodejs.

Then send this event to nodejs from onMouseUp event on client side.

Then update coordinates in node and generate paint event.

On frontend listen for paint event and draw image.

Title: Collaborative Paint App

Body:
I am in the early stages of learning nodejs client/server programming, for my first application I just want to make a simple collaborative drawing app like paint. So far I have this code and the only thing that seems to work is that my click properly calls in my console.log but no rectangle draws at the click location. Any help? I am pretty new to this.

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){

 SOCKET_LIST[socket.id] = socket;

 var self = {
  x:0,
  y:0,
  cx:0,
  cy:0,
 }

 socket.on('mousePos', function(data){
  self.x = data.x;
  self.y = data.y;
  //console.log('x:' + self.x + ' y:' + self.y);
 });

 socket.on('mouseClick', function(data){
  self.cx = data.x;
  self.cy = data.y;
  console.log('x:' + self.cx + ' y:' + self.cy);
 });

 socket.emit('paint', {x:self.cx, y:self.cy});

 /*for (var i in SOCKET_LIST){
  var socket = SOCKET_LIST[i];
  socket.emit('paint', {x:self.cx, y:self.cy});
 }*/

});

 <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>

Body:
document.onmouseup = function(event){
    socket.on('paint', function(data){
        ctx.fillRect(data.x,data.y,10,10);
    });
}

Here you only subscribing to event. So you saying - "When mouse up, please, add one more handler for paint event" (so this code will be executed multiple times). So where paint event generated? Who send it? You send it only once, when connection established. So what you have to do, is to:

Mode paint event listener on frontend to outside of event listener.

Remove emit('paint') from onConnection event.

Add onMouseUp event listener to nodejs.

Then send this event to nodejs from onMouseUp event on client side.

Then update coordinates in node and generate paint event.

On frontend listen for paint event and draw image.


问:
Hashset size operation
How is the size operation of a HashSet constant time operation?

I read that the contains and size operation is constant time.

Although I understand how contains is a constant-time operation, wouldn't size operation be proportionate (not linear) with number of elements?

答:
The short answer - it's cached.

The longer answer:
HashSet is a Set implementation that holds a HashMap, where all the values are the same "dummy value". It's size() method just returns the map's size(). If you look into HashMap's implementation, you'll see it has a size member. Adding elements to the map (e.g., by using put or putAll) increase the size and removing elements from it reduce the size. This way, as size is always kept up to date, it can simply be returned when size() is called, guaranteeing a constant time execution.

Title: Hashset size operation


答:
HashSet internally stores how many elements it has.

wouldnt size operation be proportionate(not linear) with number of elements?

If this weren't stored in a field for record keeping, size() would be proportionate to the size of the backing hash table, not the number of elements, since you'd have to scan over all entries to see if something's there. These tend to be the ~same (within 2x), except for when the hash table was either allocated to be significantly too big or a lot of elements were deleted.

Title: Hashset size operation

Body:
How is the size operation of a HashSet constant time operation?

I read that the contains and size operation is constant time.

Although I understand how contains is a constant-time operation, wouldn't size operation be proportionate (not linear) with number of elements?


问:
Write data.table syntax as its dplyr equivalent to fix 9218868437227407266's integer64
I have the integer64 issue that instead of NA it shows 9218868437227407266 as it's described here: fread() fails with missing values in integer64 columns

I have loaded bit64 package that with data.table 1.9.5 or greater supposedly displays NAs instead of 9218868437227407266s but it doesn't work. The issue is described here and is a bit64 issue: https://github.com/Rdatatable/data.table/issues/488

I wrote this as a "solution":

```<code>dt[as.character(my_col) == "9218868437227407266", my_col := as.integer64(NA)]
</code>```

It works but I wonder how I can write that in dplyr syntax to use the %>% without unexpected crashes.

Many thanks in advance !

答:
We can use replace

```<code>library(dplyr)
dt %>%
   mutate(my_col = replace(my_col, as.character(my_col) == "9218868437227407266",
                         as.integer64(NA))
</code>```

Body:
I have the integer64 issue that instead of NA it shows 9218868437227407266 as it's described here: fread() fails with missing values in integer64 columns

I have loaded bit64 package that with data.table 1.9.5 or greater supposedly displays NAs instead of 9218868437227407266s but it doesn't work. The issue is described here and is a bit64 issue: https://github.com/Rdatatable/data.table/issues/488

I wrote this as a "solution":

dt[as.character(my_col) == "9218868437227407266", my_col := as.integer64(NA)]

It works but I wonder how I can write that in dplyr syntax to use the %>% without unexpected crashes.

Many thanks in advance !

Body:
We can use replace

library(dplyr)
dt %>%
   mutate(my_col = replace(my_col, as.character(my_col) == "9218868437227407266",
                         as.integer64(NA))


问:
Is it more performant to use Proxygen or NGINX + FastCGI local socket with HHVM?
HHVM has a built in Server, Proxygen.  You can run HHVM with the Proxygen server or run it in FastCGI mode, using another server such as nginx or apache to handle web requests.

I cannot find any benchmarks or authoritative source that provides any indication of which of the two option performs best.  Obviously I could provision two systems an manually test various loads under different concurrency combinations and put together a benchmark, but I'd rather avoid the work if someone has already done such a comparison.

Does anyone know in general which is the better option from a sheer performance standpoint?

答: I have not done any measurement.  But in theory, proxygen server would be more performant because it runs in the same process as the php worker threads, thus avoiding some overhead inter-process communication.  Proxygen server is used at Facebook and some efforts are made to make it more reliable, e.g., protection mechanisms when the JIT compiler isn't fully warmed up.  However, these should not matter much for other users.  If you already have your favorite apache/nginx setup and do not want to spend the time to tune settings for another http server, use FastCGI.</p>


问:
Error in using 'import' in webpack.config.babel.js
```<code>(function (exports, require, module, __filename, __dirname) { import path from 'path'
                                                              ^^^^^^
SyntaxError: Unexpected token import
</code>```

This error occurs when I use webpack-dev-server --hot.

It seems like this occurs because it can't read import or webpack doesn't support import. I tried to use babel-register but it doesn't work. Is there any way to solve this problem? Refer to the code below.

webpack.config.babel.js

```<code>import path from 'path'
import webpack from 'webpack'
import HtmlPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'

const vueLoaders = {
  html: 'pug-loader',
  css: ExtractTextPlugin.extract({
    use: 'css-loader',
    fallback: 'vue-style-loader'
  }),
  scss: 'vue-style-loader!css-loader!sass-loader',
  sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}

export default {
  entry: './client/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },

  plugins: [
    new ExtractTextPlugin('bundle.css'),
    new HtmlPlugin({
      title: 'sex',
      template: 'client/assets/index.pug'
    })
  ],

  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader', fallback: 'style-loader'
        })
      }, {
        test: /\.s[a|c]ss$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader', 'sass-loader'], fallback: 'style-loader'
        })
      }, {
        test: /\.pug$/,
        loader: 'pug-loader'
      }, {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }, {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: { loaders: vueLoaders }
      }, {
        test: /\.(png|jpe?g|gif|svg|ttf|woff2?|eot)$/,
        loader: 'file-loader',
        options: { name: '[name].[ext]?[hash]' }
      }
    ]
  },

  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },

  devServer: {
    host: '0.0.0.0',
    historyApiFallback: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: '"production"' }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: { warnings: false }
    }),
    new webpack.LoaderOptionsPlugin({ minimize: true })
  ])
}
</code>```

答:
Node does not support ES6 import syntax at the moment. Use CommonJS require syntax in the meanwhile.

```<code>const path = require('path')
const webpack = require('webpack')
const HtmlPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
</code>```

Body:
(function (exports, require, module, __filename, __dirname) { import path from 'path'
                                                              ^^^^^^
SyntaxError: Unexpected token import

This error occurs when I use webpack-dev-server --hot.

It seems like this occurs because it can't read import or webpack doesn't support import. I tried to use babel-register but it doesn't work. Is there any way to solve this problem? Refer to the code below.

webpack.config.babel.js

import path from 'path'
import webpack from 'webpack'
import HtmlPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'

const vueLoaders = {
  html: 'pug-loader',
  css: ExtractTextPlugin.extract({
    use: 'css-loader',
    fallback: 'vue-style-loader'
  }),
  scss: 'vue-style-loader!css-loader!sass-loader',
  sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}

export default {
  entry: './client/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },

  plugins: [
    new ExtractTextPlugin('bundle.css'),
    new HtmlPlugin({
      title: 'sex',
      template: 'client/assets/index.pug'
    })
  ],

  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader', fallback: 'style-loader'
        })
      }, {
        test: /\.s[a|c]ss$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader', 'sass-loader'], fallback: 'style-loader'
        })
      }, {
        test: /\.pug$/,
        loader: 'pug-loader'
      }, {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }, {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: { loaders: vueLoaders }
      }, {
        test: /\.(png|jpe?g|gif|svg|ttf|woff2?|eot)$/,
        loader: 'file-loader',
        options: { name: '[name].[ext]?[hash]' }
      }
    ]
  },

  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },

  devServer: {
    host: '0.0.0.0',
    historyApiFallback: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: '"production"' }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: { warnings: false }
    }),
    new webpack.LoaderOptionsPlugin({ minimize: true })
  ])
}

Body:
Node does not support ES6 import syntax at the moment. Use CommonJS require syntax in the meanwhile.

const path = require('path')
const webpack = require('webpack')
const HtmlPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')


问:
What's the meaning of gcc '-c' and gcc '-o'?
When I created makefile, I wrote

test: main.o 1.o
  gcc -o test main.o 1.o

main.o: main.c a.h
  gcc -c main.c

1.o: 1.c a.h
  gcc -c 1.c
```

but I don't get why I use -o in the first line and -c in the second, third line.

What's the difference between them?

答:
Those options do very different things:

-c tells GCC to compile a source file into a .o object file.  Without that option, it'll default to compiling and linking the code into a complete executable program, which only works if you give it all your .c files at the same time.  To compile files individually so they can be linked later, you need -c.

-o sets the name of the output file that GCC produces.  You're using it when linking object files to make a complete program, and the default output filename for that is a.out.  If you don't want your program to be called a.out, you use -o to specify a different name.

Body:
When I created makefile, I wrote

test: main.o 1.o
  gcc -o test main.o 1.o

main.o: main.c a.h
  gcc -c main.c

1.o: 1.c a.h
  gcc -c 1.c

but I don't get why I use -o in the first line and -c in the second, third line.

What's the difference between them?


问:
UIAlertController for large amount of text with scrolling functionality?
UIAlertController show small strings. when the size of string become larger. then some text from this alert is missing. is there any scrolling functionality available so that to scroll to the remaining text?

```<code>var alert = UIAlertController(title: "title here", message: "about 30 line text here", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
</code>```

how to make an alert that show me text larger then 30 lines.  i use swift.

答:
It works without effort in the Playgrounds:

```<code>import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
let window = UIWindow()
let viewController = UIViewController()
window.rootViewController = viewController
window.makeKeyAndVisible()

let message = (1...1000).reduce("") { $0 + "\($1)\n" }

let alert = UIAlertController(title: "title here", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "action here", style: .default, handler: nil))
viewController.present(alert, animated: true, completion: nil)
PlaygroundPage.current.liveView = window
</code>```

I got 1000 scrollable lines:

Body:
UIAlertController show small strings. when the size of string become larger. then some text from this alert is missing. is there any scrolling functionality available so that to scroll to the remaining text?

var alert = UIAlertController(title: "title here", message: "about 30 line text here", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)

how to make an alert that show me text larger then 30 lines.  i use swift.

Body:
It works without effort in the Playgrounds:

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
let window = UIWindow()
let viewController = UIViewController()
window.rootViewController = viewController
window.makeKeyAndVisible()

let message = (1...1000).reduce("") { $0 + "\($1)\n" }

let alert = UIAlertController(title: "title here", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "action here", style: .default, handler: nil))
viewController.present(alert, animated: true, completion: nil)
PlaygroundPage.current.liveView = window

I got 1000 scrollable lines:


问:
Test devise after_inactive_sign_up_path_for confirmable redirect
My devise user is :confirmable, and I want to test that the user is redirected to the devise login page after signing up. It works when I manually test it, but fails in rspec/capybara feature spec. I'm following these instructions to setup the redirect.

```<code># registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
    protected

    def after_inactive_sign_up_path_for(_resource)
        new_user_session_path # redirect to login
    end
end

# registration_spec.rb
RSpec.describe 'registration process', type: feature do
    it 'works' do
        visit new_user_registration_path
        fill_in 'Username', with: 'user123'
        fill_in 'Email', with: 'user123@email.com'
        fill_in 'Password', with: 'password123'
        fill_in 'Password confirmation', with: 'password123'
        click_on 'Sign up'
        expect(User.find_by(username: 'user123')).not_to be_nil # sanity check
        expect(page).to have_current_path(new_user_session_path) # failure here
    end
end
</code>```

Failure returned:

```<code>Failure/Error: expect(page).to have_current_path(new_user_session_path)
       expected "/users" to equal "/users/sign_in"
     # ./spec/features/registration_spec.rb:19:in `block (2 levels) in <top (required)>'
</code>```

It seems like page is stuck in the post path, or is being redirected to /users incorrectly? I know the form is accepting the input because of my sanity check that the user exists.

答:
Most likely your user creation is failing, whether that's due to an existing user or the password not meeting minimum security requirements, etc I'm not sure.  Outputting page.html after the click should show you any validation errors, or your test.log should show them too.

Additionally, click_on can be asynchronous (when using a JS capable driver) so you should swap the last two lines of your test, because have_current_path will wait for the page change to occur which implies the user creation has completed.  That won't fix your current issue, but using the Capybara matchers to make sure actions have completed before running direct database queries will reduce potential flakiness for you in the future (Note, however, that direct database queries are generally a bad code smell in features tests).

Body:
My devise user is :confirmable, and I want to test that the user is redirected to the devise login page after signing up. It works when I manually test it, but fails in rspec/capybara feature spec. I'm following these instructions to setup the redirect.

# registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
    protected

    def after_inactive_sign_up_path_for(_resource)
        new_user_session_path # redirect to login
    end
end

# registration_spec.rb
RSpec.describe 'registration process', type: feature do
    it 'works' do
        visit new_user_registration_path
        fill_in 'Username', with: 'user123'
        fill_in 'Email', with: 'user123@email.com'
        fill_in 'Password', with: 'password123'
        fill_in 'Password confirmation', with: 'password123'
        click_on 'Sign up'
        expect(User.find_by(username: 'user123')).not_to be_nil # sanity check
        expect(page).to have_current_path(new_user_session_path) # failure here
    end
end

Failure returned:

Failure/Error: expect(page).to have_current_path(new_user_session_path)
       expected "/users" to equal "/users/sign_in"
     # ./spec/features/registration_spec.rb:19:in `block (2 levels) in <top (required)>'

It seems like page is stuck in the post path, or is being redirected to /users incorrectly? I know the form is accepting the input because of my sanity check that the user exists.


问:
Converting between an ActionScript Array (Object[]) and a Vector.<Object>
Are there options for converting an Array to a Vector in ActionScript without iterating the array?

What about the other way (converting a Vector to an Array)?

答:
For the Array to Vector, use the Vector.<TYPE>() function that accept an array and will return the vector created :

```<code>var aObjects:Array = [{a:'1'}, {b:'2'}, {c:'3'}];
// use Vector function
var vObjects:Vector.<Object> = Vector.<Object>(aObjects);
</code>```

For the other there is no builtin function, so you  have to do a loop over each Vector item and put then into an Array

Body:
For the Array to Vector, use the Vector.<TYPE>() function that accept an array and will return the vector created :

var aObjects:Array = [{a:'1'}, {b:'2'}, {c:'3'}];
// use Vector function
var vObjects:Vector.<Object> = Vector.<Object>(aObjects);

For the other there is no builtin function, so you  have to do a loop over each Vector item and put then into an Array


问:
How to write to OS system log in Java?
Mac OS has an application called Console, which contains logged messages, errors, and faults. I believe the Windows equivalent is Event Viewer. I'd imagine there is one on Linux as well, but I don't know anything about it or where it is.

Is it possible to get a message from Java output to a system log like this? I'm writing a GUI-based application, so there is nothing running from the command line. The standard System.out or System.err probably won't be of much use in this case, unless I'm missing something.

I have written a simple logging service for my application that writes to a dedicated log file, but I want to have some kind of failsafe in case an I/O error occurs while attempting to write to this file.

I know the IDE will display output via System.out and System.err just fine, but this is for if the end-user encounters a problem like this.

As an example: I've written "codeless language modules" for the application TextWrangler on the Mac. These modules are read by TW at application startup, and if there is an error while processing them, errors get logged and can be viewed in the Mac Console application.

答:
On Linux it is called as syslog. One of the ways that you can achieve logging to console on Mac will be to use log4j 'org.apache.log4j.net.SyslogAppender'.

I think this link should give you some kickstart in this direction.

Title: How to write to OS system log in Java?


问:
Do the empty spaces and comments in HTML code affect page rendering?
I am no expert in coding, so I decided to ask about two things I can't find answers to.

Do the empty spaces and comments in HTML code affect page rendering?
I use a template as my personal website.
In order to understand everything I've done so far in HTML files, I comment a lot.
I also use ENTER SPACES between sections, so I can see everything clearly.

I've read about removing comments from CSS and HTML files, but didn't find a reason to do so.

答:
Inter-element whitespace can affect inline layout in CSS, most (in?)famously demonstrated in questions like How to remove the space between inline-block elements? that seem to treat it as some sort of virulent plague that must be eradicated. As long as you're not abusing inline layout for things it wasn't meant for, though, you'll find whitespace to be an asset rather than a hurdle in inline layout. See also the white-space property.

Inter-element whitespace has no effect on any other kind of layout in CSS. Not block layout, table layout, float layout, flex layout, nada. If it does, it's a browser bug.

Provided there is no inter-element whitespace outside of a comment (between it and any elements), comments should have no effect on any layout. The following fragments are equivalent:

```<code><div></div><!--

Here be dragons

--><div></div>
</code>```

```<code><div></div><div></div>
</code>```

Some versions of Internet Explorer (particularly the older ones) may build DOM trees incorrectly in the presence of comments, but such issues are few and far between and not worth worrying about until you encounter one yourself.

The main reason for stripping comments and insignificant whitespace from HTML is to cut down on file size. Even if you're using tabs and not spaces for indentation, they do add up. However since minifiers don't have knowledge of layout in CSS, they won't be able to tell you if removing a certain space will have adverse effects on layout.

Body:
Inter-element whitespace can affect inline layout in CSS, most (in?)famously demonstrated in questions like How to remove the space between inline-block elements? that seem to treat it as some sort of virulent plague that must be eradicated. As long as you're not abusing inline layout for things it wasn't meant for, though, you'll find whitespace to be an asset rather than a hurdle in inline layout. See also the white-space property.

Inter-element whitespace has no effect on any other kind of layout in CSS. Not block layout, table layout, float layout, flex layout, nada. If it does, it's a browser bug.

Provided there is no inter-element whitespace outside of a comment (between it and any elements), comments should have no effect on any layout. The following fragments are equivalent:

<div></div><!--

Here be dragons

--><div></div>

<div></div><div></div>

Some versions of Internet Explorer (particularly the older ones) may build DOM trees incorrectly in the presence of comments, but such issues are few and far between and not worth worrying about until you encounter one yourself.

The main reason for stripping comments and insignificant whitespace from HTML is to cut down on file size. Even if you're using tabs and not spaces for indentation, they do add up. However since minifiers don't have knowledge of layout in CSS, they won't be able to tell you if removing a certain space will have adverse effects on layout.


问:
strange Cannot be referenced from a static context error in Java
Wondering - why there is such error message during compile:

ClassHierarchyTest1.this Cannot be referenced from a static context

Source code:

```<code>public class ClassHierarchyTest1 {
    class Foo {
        int a;
        Foo(int b) {
            this.a = b;
        }
    }

    public static void main(String[] args) {
        Foo f = new Foo(1); // this line has the error message
    }
}
</code>```

答:
Not at all strange.

Your inner class itself is not static. Thus it always needs an object of the outer enclosing class. Which you don't have in your static main.

So you have to change Foo to be static (of course you then can't use the "outer this"), or you have to create an instance of your outer class first,and call new on that object.

Body:
Wondering - why there is such error message during compile:

ClassHierarchyTest1.this Cannot be referenced from a static context

Source code:

public class ClassHierarchyTest1 {
    class Foo {
        int a;
        Foo(int b) {
            this.a = b;
        }
    }

    public static void main(String[] args) {
        Foo f = new Foo(1); // this line has the error message
    }
}


答:
add static to your class</p>

```<code>public class ClassHierarchyTest1 {

class static Foo {
    int a;
    Foo(int b) {
        this.a = b;
    }
}

public static void main(String[] args) {
    Foo f = new Foo(1); // this line has the error message
}
}
</code>```

Title: strange Cannot be referenced from a static context error in Java

Body:
add static to your class

public class ClassHierarchyTest1 {

class static Foo {
    int a;
    Foo(int b) {
        this.a = b;
    }
}

public static void main(String[] args) {
    Foo f = new Foo(1); // this line has the error message
}
}


答:
Foo is an inner class and therefore you can access it only through instance of ClassHierarchyTest1. Like that:

```<code> Foo f = new ClassHierarchyTest1().new Foo(1);
</code>```

Another option is to define foo as static:

```<code>static class Foo{...}
</code>```

Body:
Foo is an inner class and therefore you can access it only through instance of ClassHierarchyTest1. Like that:

 Foo f = new ClassHierarchyTest1().new Foo(1);

Another option is to define foo as static:

static class Foo{...}


答:
Foo is a member of    ClassHierarchyTest1 . Hence you have to use ClassHierarchyTest1 inorder to access it's members.

Docs of Inner Classes

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

```<code>class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
</code>```

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

```<code>OuterClass.InnerClass innerObject = outerObject.new InnerClass();
</code>```

Body:
Foo is a member of    ClassHierarchyTest1 . Hence you have to use ClassHierarchyTest1 inorder to access it's members.

Docs of Inner Classes

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();