问:
ORA-00907: missing right parenthesis SQL Developer
I need to know why I get a parenthesis error in this part of the code.</p>

```<code>CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD),
NOMBRE VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE NOT NULL,
NOMBRE_REGION VARCHAR(20) CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL
);
</code>```

答:
When using PRIMARY KEY (COD_CIUDAD) syntax, then constraint must be defined separately from the column or remove (COD_CIUDAD)

You should use the following query:

```<code>CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) ,
NOMBRE VARCHAR2(20)  CONSTRAINT NOTNULL_NOMBRE NOT NULL,
NOMBRE_REGION VARCHAR(20)  CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL,
CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD)
);
</code>```

Also you can ignore naming NOT NULL constraint:

```<code>CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) ,
NOMBRE VARCHAR2(20)  NOT NULL,
NOMBRE_REGION VARCHAR(20)  NOT NULL,
CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD)
);
</code>```

References:

Oracle / PLSQL: Primary Keys

Oracle / PLSQL: CREATE TABLE Statement

Body:
I need to know why I get a parenthesis error in this part of the code.

CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD),
NOMBRE VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE NOT NULL,
NOMBRE_REGION VARCHAR(20) CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL
);

Body:
When using PRIMARY KEY (COD_CIUDAD) syntax, then constraint must be defined separately from the column or remove (COD_CIUDAD)

You should use the following query:

CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) ,
NOMBRE VARCHAR2(20)  CONSTRAINT NOTNULL_NOMBRE NOT NULL,
NOMBRE_REGION VARCHAR(20)  CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL,
CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD)
);

Also you can ignore naming NOT NULL constraint:

CREATE TABLE CIUDAD(
COD_CIUDAD NUMBER(3) ,
NOMBRE VARCHAR2(20)  NOT NULL,
NOMBRE_REGION VARCHAR(20)  NOT NULL,
CONSTRAINT CIUDAD_PK PRIMARY KEY (COD_CIUDAD)
);

References:

Oracle / PLSQL: Primary Keys

Oracle / PLSQL: CREATE TABLE Statement


来源: stackexchange

答:
When you are using an in-line constraint, the PRIMARY KEY automatically refers to the column being declared.  Hence, the (COD_CIUDAD) is not accepted.

Try this:

```<code>CREATE TABLE CIUDAD (
    COD_CIUDAD NUMBER(3) CONSTRAINT CIUDAD_PK PRIMARY KEY,
    NOMBRE VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE NOT NULL,
    NOMBRE_REGION VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL
);
</code>```

I changed the type of NOMBRE_REGION to VARCHAR2().

ContentLicense: CC BY-SA 3.0

Title: ORA-00907: missing right parenthesis SQL Developer

Body:
When you are using an in-line constraint, the PRIMARY KEY automatically refers to the column being declared.  Hence, the (COD_CIUDAD) is not accepted.

Try this:

CREATE TABLE CIUDAD (
    COD_CIUDAD NUMBER(3) CONSTRAINT CIUDAD_PK PRIMARY KEY,
    NOMBRE VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE NOT NULL,
    NOMBRE_REGION VARCHAR2(20) CONSTRAINT NOTNULL_NOMBRE_REGION NOT NULL
);

I changed the type of NOMBRE_REGION to VARCHAR2().


问:
Editing object within arraylist
I have code which requires for the original object values to change within an ArrayList. Here is how the code works now, but I do not believe it will change the values for the original object.

```<code>    for (int i = 0; i < pairedSystems.size(); i++) {
        System sys = (System) pairedSystems.get(i);
        if (sys.id() == system.id()) {
            sys.addPower((int) pairedId.get(i), amount);

        }
    }
</code>```

I would like a type of code which would guarantee the retrieved object is modified within the ArrayList. Any help is appreciated!

答:
You can use ArrayList.set() to set a value at a given index. After modifying the object, set the object at the index:

pairedSystems.set(i, sys)

Title: Editing object within arraylist

Body:
I have code which requires for the original object values to change within an ArrayList. Here is how the code works now, but I do not believe it will change the values for the original object.

    for (int i = 0; i < pairedSystems.size(); i++) {
        System sys = (System) pairedSystems.get(i);
        if (sys.id() == system.id()) {
            sys.addPower((int) pairedId.get(i), amount);

        }
    }

I would like a type of code which would guarantee the retrieved object is modified within the ArrayList. Any help is appreciated!


问:
Django migration sql for conditional triggers
I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.

Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.

```<code>operations = [

    migrations.RunSQL(
        "DROP TRIGGER like_notification",
        """
        CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        IF (select user_id from channel WHERE channel_id IN
            (SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
        BEGIN
            INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
                VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
                    (SELECT user_id from channel WHERE channel_id IN
                        (SELECT channel_id FROM article WHERE article_id = NEW.article_id)
                    )
                )
        END;
        """
    )
]

>>>django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")
</code>```

and

```<code>CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        BEGIN
            DECLARE @user_same Boolean;
            SELECT 1 into @user_same
            FROM channel
            WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
            AND user_id = NEW.user_id;

            IF @user_same <> 1
            THEN
                INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
                VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
                    SELECT user_id from channel WHERE channel_id IN (
                         SELECT channel_id FROM article WHERE article_id = NEW.article_id)
                    )
            END IF;
        END;

>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '@user_same Boolean;\n                SELECT 1 into @user_same\n                FRO' at line 4"
</code>```

and

```<code>CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
        VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
            (
            SELECT user_id from channel WHERE channel_id IN
                (SELECT channel_id FROM article WHERE article_id = NEW.article_id)
            )
        WHERE NOT user_id = NEW.user_id;

>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'WHERE NOT user
</code>```

I don't really understand why none of them work. Any help would be much appreciated!

答:
@variables are not DECLARED.

Either:

```<code>DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...
</code>```

or

```<code>SELECT @user_same := 1 WHERE ...
</code>```

Better yet, this avoids the need for the variable.

```<code>IF (EXISTS SELECT * FROM ...)
</code>```

Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....

(There may be more problems after fixing those.)

Body:
I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.

Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.

operations = [

    migrations.RunSQL(
        "DROP TRIGGER like_notification",
        """
        CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        IF (select user_id from channel WHERE channel_id IN
            (SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
        BEGIN
            INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
                VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
                    (SELECT user_id from channel WHERE channel_id IN
                        (SELECT channel_id FROM article WHERE article_id = NEW.article_id)
                    )
                )
        END;
        """
    )
]

>>>django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")

and

CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        BEGIN
            DECLARE @user_same Boolean;
            SELECT 1 into @user_same
            FROM channel
            WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
            AND user_id = NEW.user_id;

            IF @user_same <> 1
            THEN
                INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
                VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
                    SELECT user_id from channel WHERE channel_id IN (
                         SELECT channel_id FROM article WHERE article_id = NEW.article_id)
                    )
            END IF;
        END;

>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '@user_same Boolean;\n                SELECT 1 into @user_same\n                FRO' at line 4"

and

CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
        FOR EACH ROW
        INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
        VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
            (
            SELECT user_id from channel WHERE channel_id IN
                (SELECT channel_id FROM article WHERE article_id = NEW.article_id)
            )
        WHERE NOT user_id = NEW.user_id;

>>>You have an error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'WHERE NOT user

I don't really understand why none of them work. Any help would be much appreciated!

Body:
@variables are not DECLARED.

Either:

DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...

or

SELECT @user_same := 1 WHERE ...

Better yet, this avoids the need for the variable.

IF (EXISTS SELECT * FROM ...)

Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....

(There may be more problems after fixing those.)


问:
ng2-smart-table not rer-endering after source change
This may look very common. But I am facing this problem for few days.

I am using ng2-smart-table, which is being updated with data from rest API. The data is being loaded for the first time after asynchronous call.

However, after an event in a different component, after emitting, I can see that the same method is called, data is being fetched for the same table, but table is not re-rendered with new data this time.Can anyone help on this?

The code snippet I am using as below for the data table reload.

```<code>private getQuestions()
  {
    this._questionService.getAll().subscribe(data =>

      {
      //this.data = data;
      //this.source.load(slice();
      this.data.load(data);
      this.data.reset();
      //this.data.update()
      this.data.refresh();
      console.log('Data length:'+this.data.count());
      this.cd.markForCheck();
      },
      error=> console.log("Error: "+error));
  }
</code>```

答: You have to clear the source every time the data gets loaded. Most likely it is getting appended.</p>

Body:
This may look very common. But I am facing this problem for few days.

I am using ng2-smart-table, which is being updated with data from rest API. The data is being loaded for the first time after asynchronous call.

However, after an event in a different component, after emitting, I can see that the same method is called, data is being fetched for the same table, but table is not re-rendered with new data this time.Can anyone help on this?

The code snippet I am using as below for the data table reload.

private getQuestions()
  {
    this._questionService.getAll().subscribe(data =>

      {
      //this.data = data;
      //this.source.load(slice();
      this.data.load(data);
      this.data.reset();
      //this.data.update()
      this.data.refresh();
      console.log('Data length:'+this.data.count());
      this.cd.markForCheck();
      },
      error=> console.log("Error: "+error));
  }


问:
Lua alternating a value on a timer
I am in quite a pickle right now.

I have a switch that I need to be able to turn on and off every second but I don't really know how I would do that because it needs to be applied on the same bit/function
If currently have a bit that functions as an on/off for a function, the problem is that I need a way for that function to turn itself on and off every 1 second.
I have tried this so far but it is not working for me.
Could anyone try and solve this issue for me please?

```<code>{$lua}
if not syntaxcheck then

  local On = 1
  local Off = 0
  local Switch = OnOffController

  local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
  end

    OnOff()
    if(Second == nil) then
      Second = createTimer(getMainForm())
      Second.Interval = 1000
      Second.OnTimer = function(timer)
        OnOff()
      end
    end
  Second.setEnabled(true)
  end
</code>```

答:
While there could be more wrong, there's definitely an issue with the OnOff() function:

```<code>local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
end
</code>```

The two nested if statements are not going to do what you want. First off, you're using the assignment operator = rather than the equals operator ==. Even if that were correct though the logic has a problem. If Switch is On going into the first if the flow will bypass both. If Switch is Off going into the first if it'll first get changed to On and then immediately hit the second condition and get changed back to Off.

You probably want something more like:

```<code>local function OnOff()
    if Switch == Off then
        Switch = On
    else
        Switch = Off
    end
end
</code>```

You don't need the second comparison at all assuming Switch can only be true or false.

Other bits of advice I'd give would be to use a boolean type for the Switch variable as that makes it explicit that it can only have two values. You'd probably also want to change its name to something like SwitchedOn or the like to make it obvious what true and false would mean in its context. Likewise a name like ToggleSwitch may make it a bit more obvious what the function presently called OnOff is intended to do.

Title: Lua alternating a value on a timer

Body:
I am in quite a pickle right now.

I have a switch that I need to be able to turn on and off every second but I don't really know how I would do that because it needs to be applied on the same bit/function
If currently have a bit that functions as an on/off for a function, the problem is that I need a way for that function to turn itself on and off every 1 second.
I have tried this so far but it is not working for me.
Could anyone try and solve this issue for me please?

{$lua}
if not syntaxcheck then

  local On = 1
  local Off = 0
  local Switch = OnOffController

  local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
  end

    OnOff()
    if(Second == nil) then
      Second = createTimer(getMainForm())
      Second.Interval = 1000
      Second.OnTimer = function(timer)
        OnOff()
      end
    end
  Second.setEnabled(true)
  end

Body:
While there could be more wrong, there's definitely an issue with the OnOff() function:

local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
end

The two nested if statements are not going to do what you want. First off, you're using the assignment operator = rather than the equals operator ==. Even if that were correct though the logic has a problem. If Switch is On going into the first if the flow will bypass both. If Switch is Off going into the first if it'll first get changed to On and then immediately hit the second condition and get changed back to Off.

You probably want something more like:

local function OnOff()
    if Switch == Off then
        Switch = On
    else
        Switch = Off
    end
end

You don't need the second comparison at all assuming Switch can only be true or false.

Other bits of advice I'd give would be to use a boolean type for the Switch variable as that makes it explicit that it can only have two values. You'd probably also want to change its name to something like SwitchedOn or the like to make it obvious what true and false would mean in its context. Likewise a name like ToggleSwitch may make it a bit more obvious what the function presently called OnOff is intended to do.


问:
How to launch an .exe file by clicking a JButton in GUI?
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

```<code>JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file
</code>```

Thanks in advance

答:
```<code>Runtime.getRuntime().exec( ... );
</code>```

or use the ProcessBuilder class.

You should be able to find example on the web that use these classes.

Edit: For example to start the Notepad exe in Windows you could do:

```<code>Process process = Runtime.getRuntime().exec( "cmd.exe /C start notepad" );
</code>```

If you want to execute a class then you need to invoke the JVM the same way you would invoke it from the command line.

ContentLicense: CC BY-SA 2.5

Body:
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file

Thanks in advance

Body:
Runtime.getRuntime().exec( ... );

or use the ProcessBuilder class.

You should be able to find example on the web that use these classes.

Edit: For example to start the Notepad exe in Windows you could do:

Process process = Runtime.getRuntime().exec( "cmd.exe /C start notepad" );

If you want to execute a class then you need to invoke the JVM the same way you would invoke it from the command line.


问:
How to create JPEG image of 65k x 65k size and 24 bits color deph using .NET and C#?
Problem:

there is no way to create large JPEG image using .NET Framework classes like Bitmap with the following image properties:

width: 65000

height: 65000

color depth: 24 bits

compression: JPEG

Example of problem code:

```<code>Bitmap final = new Bitmap(65000, 65000, PixelFormat.Format24bppRgb);
</code>```

Expected Result:

I would like to find idea for solution or any other codes that could create large with properties mentioned above.

Actual Result:

The example of problem code just throws out of memory exception

答:
To create such an image you need to store it in your RAM. The size of your image is at least 65000*65000*24 bits ~ 12 gigabytes!
Are you sure, that your system has such RAM capacity?

In case you aren't afraid of that big image, I suggest you to create your image by small chunks and save them to ROM memory. But then you can't use .Net Bitmap class.

Body:
Problem:

there is no way to create large JPEG image using .NET Framework classes like Bitmap with the following image properties:

width: 65000

height: 65000

color depth: 24 bits

compression: JPEG

Example of problem code:

Bitmap final = new Bitmap(65000, 65000, PixelFormat.Format24bppRgb);

Expected Result:

I would like to find idea for solution or any other codes that could create large with properties mentioned above.

Actual Result:

The example of problem code just throws out of memory exception


问:
could not broadcast input array from shape (20) into shape (19)
I have a list that looks like this:

```<code>mylist=[26, 26, 26,...., 290, 290,..290]
</code>```

The # of unique numbers in mylist is 262. For every single unique number, there are 19 duplicates. So the # of 26 is 19, the number of 27 is also 19, etc,etc, the number of 290 is also 19.

So I have 262*19 elements in mylist.

I transform mylist into 262/19:

```<code>mylist= np.array(mylist).reshape((262, 19))
</code>```

Now I'm trying to add one more element to every single row:

```<code>   for i in mylist:

    i = np.append(i, i[0])
</code>```

It's saying that could not broadcast input array from shape (20) into shape (19)

答:
i[0] is a row. i is not going to make a difference in mylist. I have no idea what you mean inside etc. etc. But I am just guessing

```<code>mylist = np.outer(np.arange(26,291), np.ones(19))
</code>```

then if you want to add something else as a column

```<code>mylist = np.hstack([mylist, np.arange(26,291)[:, None]])
</code>```

Body:
I have a list that looks like this:

mylist=[26, 26, 26,...., 290, 290,..290]

The # of unique numbers in mylist is 262. For every single unique number, there are 19 duplicates. So the # of 26 is 19, the number of 27 is also 19, etc,etc, the number of 290 is also 19.

So I have 262*19 elements in mylist.

I transform mylist into 262/19:

mylist= np.array(mylist).reshape((262, 19))

Now I'm trying to add one more element to every single row:

   for i in mylist:

    i = np.append(i, i[0])

It's saying that could not broadcast input array from shape (20) into shape (19)

Body:
i[0] is a row. i is not going to make a difference in mylist. I have no idea what you mean inside etc. etc. But I am just guessing

mylist = np.outer(np.arange(26,291), np.ones(19))

then if you want to add something else as a column

mylist = np.hstack([mylist, np.arange(26,291)[:, None]])


问:
Nancy maximum JSON length exception when Binding
I have simple Nancy self hosting C# project which deserializes data in NancyModule like this:

```<code>Post["/build"] = (something) => { var data = this.Bind<Brick>(); }
</code>```

I am getting "Maximum JSON input length has been exceeded." when Request.Body.Length is close to 2MB. I would like to send tens of megabytes of data in the future and 2MB is just too low. Can I remove this limit?

答:
For me Nancy didn't work all together even after applying below settings. As my data was really really huge.

```<code>  Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;
</code>```

I ended up using Json.net (add via nuGet package)

```<code>  JsonConvert.SerializeObject(data)
</code>```

Body:
I have simple Nancy self hosting C# project which deserializes data in NancyModule like this:

Post["/build"] = (something) => { var data = this.Bind<Brick>(); }

I am getting "Maximum JSON input length has been exceeded." when Request.Body.Length is close to 2MB. I would like to send tens of megabytes of data in the future and 2MB is just too low. Can I remove this limit?

Body:
For me Nancy didn't work all together even after applying below settings. As my data was really really huge.

  Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;

I ended up using Json.net (add via nuGet package)

  JsonConvert.SerializeObject(data)


问:
Static factory method common for all subclasses
I have many different subclasses of the same base class, and all of them should be constructed exclusively from a factory method that takes in a JsonNode.

Public constructors aren't convenient in my context due to extremely large (100 and more) fields. Those fields should be populated from the given JsonNode using ObjectMapper. Here is the example.

Base class: AbstractMessage

Subclasses: MessageA, MessageB, MessageC, MessageD, ...

Desired API:

MessageA a = MessageA.fromJson(json); // json of type JsonNode

MessageB b = MessageB.fromJson(json); // json of type JsonNode

MessageC c = MessageC.fromJson(json); // json of type JsonNode

Method from ObjectMapper that does the actual conversion from JsonNode to object takes in a desired class argument, and this is example usage:

```<code>ObjectMapper jsonMapper = new ObjectMapper();
JsonNode json = // ...
MessageA a = jsonMapper.treeToValue(json, MessageA.class);
</code>```

The problem occurs because, obviously, a runtime class is needed in order to instantiate the object of that same class. And I would like to have a static factory method in a base class to create the subclass objects, to avoid duplication etc.

I came up with the following solution:

AbstractMessage, base class

```<code>private static final ObjectMapper jsonMapper = new ObjectMapper();

public static <T extends AbstractMessage> T fromJson(JsonNode json, Class<T> cls) {
        return jsonMapper.treeToValue(json, cls);
}
</code>```

The problem with this is, that client code needs to provide the class, and the following is also possible (which shouldn't be possible):

```<code>JsonNode json = // ...
MessageA a = MessageB.fromJson(json, MessageA.class);
</code>```

... where MessageA is constructed through MessageB.

Is there a way where I could have something like this:

```<code>MessageA a = MessageA.fromJson(json)
</code>```

... in the described context?

答:
As far as I know there is no way to do that. Factory method must know what class to instantiate.
but why it bother you to have it like?

```<code>MessageA a = AbstractMessage.fromJson(json, MessageA.class);
</code>```

client code needs to provide the class

and what? Client code knows that it needs instance of MessageA class and why do not provide its class?

as example in slf4j logger framework:
org.slf4j.Logger logger = LoggerFactory.getLogger(MyClass.class);
 does anybody complain about it?

Body:
I have many different subclasses of the same base class, and all of them should be constructed exclusively from a factory method that takes in a JsonNode.

Public constructors aren't convenient in my context due to extremely large (100 and more) fields. Those fields should be populated from the given JsonNode using ObjectMapper. Here is the example.

Base class: AbstractMessage

Subclasses: MessageA, MessageB, MessageC, MessageD, ...

Desired API:

MessageA a = MessageA.fromJson(json); // json of type JsonNode

MessageB b = MessageB.fromJson(json); // json of type JsonNode

MessageC c = MessageC.fromJson(json); // json of type JsonNode

Method from ObjectMapper that does the actual conversion from JsonNode to object takes in a desired class argument, and this is example usage:

ObjectMapper jsonMapper = new ObjectMapper();
JsonNode json = // ...
MessageA a = jsonMapper.treeToValue(json, MessageA.class);

The problem occurs because, obviously, a runtime class is needed in order to instantiate the object of that same class. And I would like to have a static factory method in a base class to create the subclass objects, to avoid duplication etc.

I came up with the following solution:

AbstractMessage, base class

private static final ObjectMapper jsonMapper = new ObjectMapper();

public static <T extends AbstractMessage> T fromJson(JsonNode json, Class<T> cls) {
        return jsonMapper.treeToValue(json, cls);
}

The problem with this is, that client code needs to provide the class, and the following is also possible (which shouldn't be possible):

JsonNode json = // ...
MessageA a = MessageB.fromJson(json, MessageA.class);

... where MessageA is constructed through MessageB.

Is there a way where I could have something like this:

MessageA a = MessageA.fromJson(json)

... in the described context?

Body:
As far as I know there is no way to do that. Factory method must know what class to instantiate.
but why it bother you to have it like?

MessageA a = AbstractMessage.fromJson(json, MessageA.class);

client code needs to provide the class

and what? Client code knows that it needs instance of MessageA class and why do not provide its class?

as example in slf4j logger framework:
org.slf4j.Logger logger = LoggerFactory.getLogger(MyClass.class);
 does anybody complain about it?


问:
Using href to an id of a div
I'm trying to use href to take me to a particular div with the id corresponding to what is in the a href="#1">.

As an example I have the following three divs.

1.

2.

3.

```

When I have the site in mobile mode, the href's correctly go to the corresponding list item. In normal desktop mode, it doesn't however.

There is a link to the site here. https://what-is-wrong-with-this-css.herokuapp.com/

The links should be coming from the menu icon in the top left hand corner. See how it correctly goes to the list item in mobile but not in desktop. Does anyone know any quick fixes here.

Thanks,

答:
It works on mobile because you're scrolling up and down the page. In your desktop version you're using javascript to handle the left/right movement, but not the menu links.

using href to an element ID is for scrolling afaik. If you want to use it for this horizontal set up, you'll need to listen to the window.hashchange event like so:

```<code>window.addEventListener("hashchange", funcRef, false);
</code>```

And trigger the scrolling based on the new hashvalue.

Title: Using href to an id of a div

Body:
I'm trying to use href to take me to a particular div with the id corresponding to what is in the a href="#1">.

As an example I have the following three divs.

1.

2.

3.

When I have the site in mobile mode, the href's correctly go to the corresponding list item. In normal desktop mode, it doesn't however.

There is a link to the site here. https://what-is-wrong-with-this-css.herokuapp.com/

The links should be coming from the menu icon in the top left hand corner. See how it correctly goes to the list item in mobile but not in desktop. Does anyone know any quick fixes here.

Thanks,

Body:
It works on mobile because you're scrolling up and down the page. In your desktop version you're using javascript to handle the left/right movement, but not the menu links.

using href to an element ID is for scrolling afaik. If you want to use it for this horizontal set up, you'll need to listen to the window.hashchange event like so:

window.addEventListener("hashchange", funcRef, false);

And trigger the scrolling based on the new hashvalue.


答:
You may be interested looking into executing an external process.

This would require either Runtime.getRuntime().exec or the newer ProcessBuilder

Title: How to launch an .exe file by clicking a JButton in GUI?


问:
SCSS partials (@import) vs. Webpack file import?
I'm building a simple app and am setting up my own Webpack configuration to better understand how it works. Currently, I have one main.scss file (where I'm writing all my styles) which I'm importing into my index.js file (which is the entry point I've set for Webpack). So far, so good.

Now I want to split my SCSS into separate, smaller files (normalize, variables, mixins, etc.) Before Webpack, what I'd do was make every file a SCSS partial and then import all of them into my main.scss file. But now that I'm using Webpack, I'm wondering if I should keep doing that or if I should import all of my SCSS files into Webpack instead and forgo partials entirely? Any clarification on the topic would be useful; I haven't found much online about the advantages of one approach over the other.

答:
I came across this situation in a small multi page application I was building. When I got to the point where I started splitting the css based on pages, let's say page-1.scss, page-2.scss, and page-3.scss, I wanted to create a common.bundle.css which contained css used on all pages.

At first, I had an @import '_base'; declaration at the top of each page-*.scss file. I assumed CommonsChunkPlugin would take into account these similar imports and extract them into common.bundle.css. But I found that _base.scss was still duplicated across each page-*.bundle.css. After importing each shared partial in the page's respective entry js file, CommonsChunkPlugin was able to correctly extract each shared partial into common.bundle.css.

It seemed as though using the SCSS @import imported all partials into one css file and then webpack treated that file as one dependency. Using webpack's import treated each partial as a dependency which CommonsChunkPlugin was able to act on.

So, for my one situation, importing through webpack was preferable to SCSS imports. Unfortunately, I do not have any relevant links on this particular situation, as this is all based on personal experience.


问:
MySQL creating derived table from union
Why won't this query run in MySQL? I'm trying to understand this so I can make a larger query with more complicated selects to fill in records, but I've torn it all down to the absolute basic building blocks and it still won't run.

```<code>SELECT *
FROM
(
   (SELECT 'January' as col1 ) as t0
    UNION
   (SELECT 'December'  as col1 ) as t1
) as derivedTable
</code>```

The error is #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't1

I'm expecting it to look like:

```<code>col1
January
December
</code>```

答:
you must change your script to:</p>

```<code>SELECT *
FROM
(
   (SELECT 'January' AS col1 )
    UNION
   (SELECT 'December'  AS col1 )
) AS derivedTable
</code>```

Title: MySQL creating derived table from union

Body:
Why won't this query run in MySQL? I'm trying to understand this so I can make a larger query with more complicated selects to fill in records, but I've torn it all down to the absolute basic building blocks and it still won't run.

SELECT *
FROM
(
   (SELECT 'January' as col1 ) as t0
    UNION
   (SELECT 'December'  as col1 ) as t1
) as derivedTable

The error is #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't1

I'm expecting it to look like:

col1
January
December

Body:
you must change your script to:

SELECT *
FROM
(
   (SELECT 'January' AS col1 )
    UNION
   (SELECT 'December'  AS col1 )
) AS derivedTable


问:
blur fires before data bind angular 4 firefox
I have a bit of angular that provides a date to a function on blur. In Chrome(v62) it works normally but doesn't appear to work with Firefox (57).

//html

```<code><input #expirationDate type="date"  max="2999-12-31" class="form-control" name="ChargeExpirationDate" [ngModel]="charge.ExpirationDate" (blur)="editCharge(charge, 'ExpirationDate', expirationDate.value)"/>
</code>```

//TS component

```<code>editCharge(charge: object, property: string, newValue: any): void {
  console.log(newValue);
  console.log(charge);
  //other stuff
  charge[property] = newValue;
}
</code>```

If you key in a date and the input loses focus

In Chrome: the function is called and the newValue contains a date string.

In Firefox: the function fires but the newValue is set to "". Even more strangely, the result of console.log(charge); will actually contain the string but only if observed after the editCharge function completes.

Is there a way to get newValue to be set correctly before the blur event in Firefox? I didn't want to use ngModelChange because of some unusual behavior we noticed when we tried to key in dates in Chrome with it.

答:
As in the comment, you should be using focusout event instead of blur

```<code><input #expirationDate type="date"
        class="form-control"
        max="2999-12-31"
        name="ChargeExpirationDate"
        [ngModel]="charge.ExpirationDate"
        (focusout)="editCharge(charge, 'ExpirationDate', expirationDate.value)"/>
</code>```

Body:
I have a bit of angular that provides a date to a function on blur. In Chrome(v62) it works normally but doesn't appear to work with Firefox (57).

//html

<input #expirationDate type="date"  max="2999-12-31" class="form-control" name="ChargeExpirationDate" [ngModel]="charge.ExpirationDate" (blur)="editCharge(charge, 'ExpirationDate', expirationDate.value)"/>

//TS component

editCharge(charge: object, property: string, newValue: any): void {
  console.log(newValue);
  console.log(charge);
  //other stuff
  charge[property] = newValue;
}

If you key in a date and the input loses focus

In Chrome: the function is called and the newValue contains a date string.

In Firefox: the function fires but the newValue is set to "". Even more strangely, the result of console.log(charge); will actually contain the string but only if observed after the editCharge function completes.

Is there a way to get newValue to be set correctly before the blur event in Firefox? I didn't want to use ngModelChange because of some unusual behavior we noticed when we tried to key in dates in Chrome with it.

Body:
As in the comment, you should be using focusout event instead of blur

<input #expirationDate type="date"
        class="form-control"
        max="2999-12-31"
        name="ChargeExpirationDate"
        [ngModel]="charge.ExpirationDate"
        (focusout)="editCharge(charge, 'ExpirationDate', expirationDate.value)"/>


问:
Does jQuery have a handleout for .delegate('hover')?
I am trying to use:  </p>

```<code>$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});
</code>```

答:
.delegate() does not have a handle out. Also, you need the specify the element you are targeting with the first parameter.

You could try something like this, however:

```<code>$('table').delegate('tr', 'hover', function() {
    $(this).toggle();
});
</code>```

Body:
I am trying to use:

$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});

Body:
.delegate() does not have a handle out. Also, you need the specify the element you are targeting with the first parameter.

You could try something like this, however:

$('table').delegate('tr', 'hover', function() {
    $(this).toggle();
});


问:
Creating Textview without destroying my GUI
I am making an app for android, something like a cashbox for me and my girlfriend, where we can add bills from shopping or buying stuff for our appartement.

In the xml file of the MainActivity I already created three buttons for adding persons to the cashbox and some other stuff. Every time I add a new person to the cashbox, it should create a new textview within a new LinearLayout. But it moves my whole UI like in the picture.

Does anybody know how to solve this problem?

Here is my layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/mylayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <Button
        android:id="@+id/showDiagram"
        android:text="@string/showDiagram"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>

    <Button
        android:id="@+id/addExpenditure"
        android:text="@string/addExpenditure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>

    <Button
        android:id="@+id/addResident"
        android:text="@string/addResident"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>
</LinearLayout>
</code>```

And here is my MainActivity:

```<code>public class MainActivity extends Activity {

EditText residentName;
int numberOfRes = 0;
DataHandler db = new DataHandler(this);
boolean notShow;
Button add;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button showDiagram = (Button) findViewById(R.id.showDiagram);

    final LinearLayout myLayout = (LinearLayout)findViewById(R.id.mylayout);

    //Ausgabe hinzufügen
    Button addExpenditure = (Button) findViewById(R.id.addExpenditure);
    addExpenditure.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

    //Erstellung eines neuen Mitbewohners für die Kasse
    Button addResident = (Button) findViewById(R.id.addResident);
    addResident.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        final Dialog dialog = createDialog();

        residentName = (EditText)dialog.findViewById(R.id.residentname);

        add =(Button)dialog.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name = String.valueOf(residentName.getText());
                db.insert(name);
                dialog.dismiss();
                myLayout.addView(createResident(name));
                Log.d("debug","mylayout.addview() aufgerufen");
            }
        });
        dialog.show();
        }
    });
}

public Dialog createDialog(){
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle("Dialog");
    return dialog;
}

public LinearLayout createResident(String name){
    LinearLayout newRes = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams newParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,0.5f);
    newRes.setLayoutParams(newParams);
    newRes.setOrientation(LinearLayout.VERTICAL);
    newRes.setBackgroundColor(Color.BLUE);

    TextView res = new TextView(MainActivity.this);
    LinearLayout.LayoutParams newParamsRes = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,0.5f);
    res.setLayoutParams(newParamsRes);
    res.setText(name);
    res.setTextSize(25);
    res.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
    newRes.addView(res);
    return newRes;
    }
}
</code>```

Destroyed UI

答: I went for RelativeLayout instead, and it worked!</p>

Body:
I am making an app for android, something like a cashbox for me and my girlfriend, where we can add bills from shopping or buying stuff for our appartement.

In the xml file of the MainActivity I already created three buttons for adding persons to the cashbox and some other stuff. Every time I add a new person to the cashbox, it should create a new textview within a new LinearLayout. But it moves my whole UI like in the picture.

Does anybody know how to solve this problem?

Here is my layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/mylayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <Button
        android:id="@+id/showDiagram"
        android:text="@string/showDiagram"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>

    <Button
        android:id="@+id/addExpenditure"
        android:text="@string/addExpenditure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>

    <Button
        android:id="@+id/addResident"
        android:text="@string/addResident"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:layout_gravity="bottom"/>
</LinearLayout>

And here is my MainActivity:

public class MainActivity extends Activity {

EditText residentName;
int numberOfRes = 0;
DataHandler db = new DataHandler(this);
boolean notShow;
Button add;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button showDiagram = (Button) findViewById(R.id.showDiagram);

    final LinearLayout myLayout = (LinearLayout)findViewById(R.id.mylayout);

    //Ausgabe hinzufügen
    Button addExpenditure = (Button) findViewById(R.id.addExpenditure);
    addExpenditure.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

    //Erstellung eines neuen Mitbewohners für die Kasse
    Button addResident = (Button) findViewById(R.id.addResident);
    addResident.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        final Dialog dialog = createDialog();

        residentName = (EditText)dialog.findViewById(R.id.residentname);

        add =(Button)dialog.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name = String.valueOf(residentName.getText());
                db.insert(name);
                dialog.dismiss();
                myLayout.addView(createResident(name));
                Log.d("debug","mylayout.addview() aufgerufen");
            }
        });
        dialog.show();
        }
    });
}

public Dialog createDialog(){
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle("Dialog");
    return dialog;
}

public LinearLayout createResident(String name){
    LinearLayout newRes = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams newParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,0.5f);
    newRes.setLayoutParams(newParams);
    newRes.setOrientation(LinearLayout.VERTICAL);
    newRes.setBackgroundColor(Color.BLUE);

    TextView res = new TextView(MainActivity.this);
    LinearLayout.LayoutParams newParamsRes = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,0.5f);
    res.setLayoutParams(newParamsRes);
    res.setText(name);
    res.setTextSize(25);
    res.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
    newRes.addView(res);
    return newRes;
    }
}

Destroyed UI


问:
Pros/cons of placing scripts "inline" in footer or using wp_enqueue_script (wordpress)
I've searched wide and broad but I haven't found any source stating either pros of cons of these two methods, or what the "best" way to enqueue scripts is in Wordpress, with regards to performance and compatibility.

So, my question is the following:

What are the pros and cons of placing scripts inside a

答:
It depends.

Firstly, there's of course the option to use wp_enqueue_script and have your scripts printed inline in the footer if you don't mind getting your hands dirty (or find a plugin to do it for you).

As for "which should I do", I'd say it depends, mostly on a) the kind of site you run and b) who your visitors are.

Is it a site where you don't expect many visitors to return (e.g. affiliate landing page), and you don't expect your visitors to have multiple page views ("I need to know this specific information. OK, thanks, bye")? Inline everything.

Is it a site where your users will return regularly, and will hit multiple pages? Then you really want to take advantage of caching static resources, as it will save bandwidth and you will require less server power.

Are your users primarily tech-savvy people on high-bandwidth landlines? You might profit quite a bit from using google's (or other big player's) CDN because they've probably encountered the jquery lib from that CDN before and have it cached.

Are your users primarily mobile, possibly on the move, aka on high-latency, unstable connections? Every back and forth will hurt, performance wise, and inlining will be/feel much quicker.

If you don't outline any js, and have all your js in your footer, you shouldn't experience any lacking functionality, unless you are encountering very specific circumstances (e.g. a mobile user who has been throttled to GPRS and is now crawling along with 10kb/s) in which case whatever you do, nothing will work unless the user waits a long time for everything to complete.

My advise: build both options (hey, it'll also give you new skills), and compare them for the scenarios you envision your users to be in. Use your browser's dev tools, they can usually simulate a slower connection, and might be able to simulate a bad mobile connection. And don't consider it a final decision. As usage patterns change, the other option might become the  better decision, so keep your mind (and an eye) open.


问:
PostgreSQL: Loading data into Star Schema efficiently
Imagine a table with the following structure on PostgreSQL 9.0:

```<code>create table raw_fact_table (text varchar(1000));
</code>```

For the sake of simplification I only mention one text column, in reality it has a dozen. This table has 10 billion rows and each column has lots of duplicates. The table is created from a flat file (csv) using COPY FROM.

To increase performance I want to convert to the following star schema structure:

```<code>create table dimension_table (id int, text varchar(1000));
</code>```

The fact table would then be replaced with a fact table like the following:

```<code>create table fact_table (dimension_table_id int);
</code>```

My current method is to essentially run the following query to create the dimension table:

```<code>Create table dimension_table (id int, text varchar(1000), primary key(id));
</code>```

then to create fill the dimension table I use:

```<code>insert into dimension_table (select null, text from raw_fact_table group by text);
</code>```

Afterwards I need to run the following query:

```<code>select id into fact_table from dimension inner join raw_fact_table on (dimension.text = raw_fact_table.text);
</code>```

Just imagine the horrible performance I get by comparing all strings to all other strings several times.

On MySQL I could run a stored procedure during the COPY FROM. This could create a hash of a string and all subsequent string comparison is done on the hash instead of the long raw string. This does not seem to be possible on PostgreSQL, what do I do then?

Sample data would be a CSV file containing something like this (I use quotes also around integers and doubles):

```<code>"lots and lots of text";"3";"1";"2.4";"lots of text";"blabla"
"sometext";"30";"10";"1.0";"lots of text";"blabla"
"somemoretext";"30";"10";"1.0";"lots of text";"fooooooo"
</code>```

答:
Just imagine the horrible performance
  I get by comparing all strings to all
  other strings several times.

When you've been doing this a while, you stop imagining performance, and you start measuring it. "Premature optimization is the root of all evil."

What does "billion" mean to you? To me, in the USA, it means 1,000,000,000 (or 1e9). If that's also true for you, you're probably looking at between 1 and 7 terabytes of data.

My current method is to essentially
  run the following query to create the
  dimension table:

```<code>Create table dimension_table (id int, text varchar(1000), primary key(id));
</code>```

How are you gonna fit 10 billion rows into a table that uses an integer for a primary key? Let's even say that half the rows are duplicates. How does that arithmetic work when you do it?

Don't imagine. Read first. Then test.

Read Data Warehousing with PostgreSQL. I suspect these presentation slides will give you some ideas.

Also read Populating a Database, and consider which suggestions to implement.

Test with a million (1e6) rows, following a "divide and conquer" process. That is, don't try to load a million at a time; write a procedure that breaks it up into smaller chunks. Run

```<code>EXPLAIN <sql statement>
</code>```

You've said you estimate at least 99% duplicate rows. Broadly speaking, there are two ways to get rid of the dupes

Inside a database, not necessarily the same platform you use for production.

Outside a database, in the filesystem, not necessarily the same filesystem you use for production.

If you still have the text files that you loaded, I'd consider first trying outside the database. This awk one-liner will output unique lines from each file. It's relatively economical, in that it makes only one pass over the data.

```<code>awk '!arr[$0]++' file_with_dupes > file_without_dupes
</code>```

If you really have 99% dupes, by the end of this process you should have reduced your 1 to 7 terabytes down to about 50 gigs. And, having done that, you can also number each unique line and create a tab-delimited file before copying it into the data warehouse. That's another one-liner:

```<code>awk '{printf("%d\t%s\n", NR, $0);}' file_without_dupes > tab_delimited_file
</code>```

If you have to do this under Windows, I'd use Cygwin.

If you have to do this in a database, I'd try to avoid using your production database or your production server. But maybe I'm being too cautious. Moving several terabytes around is an expensive thing to do.

But I'd test

```<code>SELECT DISTINCT ...
</code>```

before using GROUP BY. I might be able to do some tests on a large data set for you, but probably not this week. (I don't usually work with terabyte-sized files. It's kind of interesting. If you can wait.)

Body:
Imagine a table with the following structure on PostgreSQL 9.0:

create table raw_fact_table (text varchar(1000));

For the sake of simplification I only mention one text column, in reality it has a dozen. This table has 10 billion rows and each column has lots of duplicates. The table is created from a flat file (csv) using COPY FROM.

To increase performance I want to convert to the following star schema structure:

create table dimension_table (id int, text varchar(1000));

The fact table would then be replaced with a fact table like the following:

create table fact_table (dimension_table_id int);

My current method is to essentially run the following query to create the dimension table:

Create table dimension_table (id int, text varchar(1000), primary key(id));

then to create fill the dimension table I use:

insert into dimension_table (select null, text from raw_fact_table group by text);

Afterwards I need to run the following query:

select id into fact_table from dimension inner join raw_fact_table on (dimension.text = raw_fact_table.text);

Just imagine the horrible performance I get by comparing all strings to all other strings several times.

On MySQL I could run a stored procedure during the COPY FROM. This could create a hash of a string and all subsequent string comparison is done on the hash instead of the long raw string. This does not seem to be possible on PostgreSQL, what do I do then?

Sample data would be a CSV file containing something like this (I use quotes also around integers and doubles):

"lots and lots of text";"3";"1";"2.4";"lots of text";"blabla"
"sometext";"30";"10";"1.0";"lots of text";"blabla"
"somemoretext";"30";"10";"1.0";"lots of text";"fooooooo"

Body:
Just imagine the horrible performance
  I get by comparing all strings to all
  other strings several times.

When you've been doing this a while, you stop imagining performance, and you start measuring it. "Premature optimization is the root of all evil."

What does "billion" mean to you? To me, in the USA, it means 1,000,000,000 (or 1e9). If that's also true for you, you're probably looking at between 1 and 7 terabytes of data.

My current method is to essentially
  run the following query to create the
  dimension table:

Create table dimension_table (id int, text varchar(1000), primary key(id));

How are you gonna fit 10 billion rows into a table that uses an integer for a primary key? Let's even say that half the rows are duplicates. How does that arithmetic work when you do it?

Don't imagine. Read first. Then test.

Read Data Warehousing with PostgreSQL. I suspect these presentation slides will give you some ideas.

Also read Populating a Database, and consider which suggestions to implement.

Test with a million (1e6) rows, following a "divide and conquer" process. That is, don't try to load a million at a time; write a procedure that breaks it up into smaller chunks. Run

EXPLAIN <sql statement>

You've said you estimate at least 99% duplicate rows. Broadly speaking, there are two ways to get rid of the dupes

Inside a database, not necessarily the same platform you use for production.

Outside a database, in the filesystem, not necessarily the same filesystem you use for production.

If you still have the text files that you loaded, I'd consider first trying outside the database. This awk one-liner will output unique lines from each file. It's relatively economical, in that it makes only one pass over the data.

awk '!arr[$0]++' file_with_dupes > file_without_dupes

If you really have 99% dupes, by the end of this process you should have reduced your 1 to 7 terabytes down to about 50 gigs. And, having done that, you can also number each unique line and create a tab-delimited file before copying it into the data warehouse. That's another one-liner:

awk '{printf("%d\t%s\n", NR, $0);}' file_without_dupes > tab_delimited_file

If you have to do this under Windows, I'd use Cygwin.

If you have to do this in a database, I'd try to avoid using your production database or your production server. But maybe I'm being too cautious. Moving several terabytes around is an expensive thing to do.

But I'd test

SELECT DISTINCT ...

before using GROUP BY. I might be able to do some tests on a large data set for you, but probably not this week. (I don't usually work with terabyte-sized files. It's kind of interesting. If you can wait.)


问:
Update Access Database (.mdb) using GridView where ID column is not visible
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query.

I have a GridView in which I am displaying the following:

```<code><asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false"
runat="server" DataKeyNames="ID"
OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
    </Columns>
</asp:GridView>
</code>```

My database has an ID field that I am not displaying on the GridView.

When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database.

My Button Click event is the following:

```<code>protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        con.Open();
        string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>...";
        OleDBCommand updateCommand = new OleDBCommand(updateQuery,con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGrid();    // Method to populate and display the GridView on the screen.
    }
</code>```

I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner:

```<code>protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int rowID = Convert.ToInt32(e.CommandArgument);
        }
    }
</code>```

In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update.

I am trying to do what David mentioned in his answer here:

https://stackoverflow.com/a/19824029/8930129

But "row" is getting a null value, because of which I am getting an System.NullReferenceException.

```<code>// ****Update Command **** //
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
    try
    {
        int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex;
        int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]);
        con.Open();
        string ConnString = GetConnString();
        string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + "";
        using (OleDbConnection conn = new OleDbConnection(ConnString))
        {
            using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn))
            {
                commandUpdate.CommandType = CommandType.Text;
                commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
                commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
                commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
                commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue);
                commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue);
            }
        }
        OleDbCommand updateCommand = new OleDbCommand(updateQuery, con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGridView();    // Function to populate data in GridView
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        // Some code...
    }
    finally
    {
        // Some code...
    }
}
</code>```

答:
I was able to make it work in the following way:

```<code>string updateQuery = "UPDATE " + table_name + " SET creditorName = ?, amount = ?, interestRate = ?, ... WHERE savingsID = ?";
                    using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, con))
    {
        updateCommand.CommandType = CommandType.Text;
        updateCommand.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
        updateCommand.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
        updateCommand.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
        updateCommand.Parameters.AddWithValue("savingsID", tupleID);

        updateCommand.ExecuteNonQuery();
        con.Close();
    }
}
</code>```

and I am getting the value of tupleID in the following way:

```<code>int tupleID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);
</code>```

Source: Comments from @Matt-9000 and https://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access

Body:
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query.

I have a GridView in which I am displaying the following:

<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false"
runat="server" DataKeyNames="ID"
OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
    </Columns>
</asp:GridView>

My database has an ID field that I am not displaying on the GridView.

When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database.

My Button Click event is the following:

protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        con.Open();
        string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>...";
        OleDBCommand updateCommand = new OleDBCommand(updateQuery,con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGrid();    // Method to populate and display the GridView on the screen.
    }

I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner:

protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int rowID = Convert.ToInt32(e.CommandArgument);
        }
    }

In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update.

I am trying to do what David mentioned in his answer here:

https://stackoverflow.com/a/19824029/8930129

But "row" is getting a null value, because of which I am getting an System.NullReferenceException.

// ****Update Command **** //
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
    try
    {
        int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex;
        int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]);
        con.Open();
        string ConnString = GetConnString();
        string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + "";
        using (OleDbConnection conn = new OleDbConnection(ConnString))
        {
            using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn))
            {
                commandUpdate.CommandType = CommandType.Text;
                commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
                commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
                commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
                commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue);
                commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue);
            }
        }
        OleDbCommand updateCommand = new OleDbCommand(updateQuery, con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGridView();    // Function to populate data in GridView
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        // Some code...
    }
    finally
    {
        // Some code...
    }
}

Body:
I was able to make it work in the following way:

string updateQuery = "UPDATE " + table_name + " SET creditorName = ?, amount = ?, interestRate = ?, ... WHERE savingsID = ?";
                    using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, con))
    {
        updateCommand.CommandType = CommandType.Text;
        updateCommand.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
        updateCommand.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
        updateCommand.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
        updateCommand.Parameters.AddWithValue("savingsID", tupleID);

        updateCommand.ExecuteNonQuery();
        con.Close();
    }
}

and I am getting the value of tupleID in the following way:

int tupleID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);

Source: Comments from @Matt-9000 and https://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access


问:
Is it possible to copy data from one framebuffer to another in OpenGL?
I guess it is somehow possible since this:

```<code>glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, _multisampleFramebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, _framebuffer);
glResolveMultisampleFramebufferAPPLE();
</code>```

does exactly that, and on top resolves the multisampling. However, it's an Apple extension and I was wondering if there is something similar that copies all the logical buffers from one framebuffer to another and doesn't do the multisampling part in the vanilla implementation. GL_READ_FRAMEBUFFER doesn't seem to be a valid target, so I'm guessing there is no direct way? How about workarounds?

EDIT: Seems it's possible to use glCopyImageSubData in OpenGL 4, unfortunately not in my case since I'm using OpenGL ES 2.0 on iPhone, which seems to be lacking that function. Any other way?

答:
You can do it directly with OpenGL ES 2.0, and it seems that there is no extension neither.

I am not really sure of what your are trying to achieve but in a general way, simply remove attachements of the FBO in which you have accomplish your off-screen rendering. Then bind the default FBO to be able to draw on screen, here you can simply draw a quad with an orthographic camera that fill the screen and a shader that takes your off-screen generated textures as input.
You will be able to do the resolve too if you are using multi-sampled textures.

```<code>glBindFramebuffer(GL_FRAMEBUFFER, off_screenFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);

glBindFramebuffer(GL_FRAMEBUFFER, 0); // Default FBO, on iOS it is 1 if I am correct

// Set the viewport at the size of screen
// Use your compositing shader (it doesn't have to manage any transform)
// Active and bind your textures
// Sent textures uniforms
// Draw your quad
</code>```

Here is an exemple of the shader:

```<code>// Vertex
attribute vec2 in_position2D;
attribute vec2 in_texCoord0;
varying lowp vec2 v_texCoord0;
void main()
{
   v_texCoord0 = in_texCoord0;
   gl_Position = vec4(in_position2D, 0.0, 1.0);
}

// Fragment
uniform sampler2D u_texture0;
varying lowp vec2 v_texCoord0;

void main()
{
    gl_FragColor =  texture2D(u_texture0, v_texCoord0);
}
</code>```

Body:
I guess it is somehow possible since this:

glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, _multisampleFramebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, _framebuffer);
glResolveMultisampleFramebufferAPPLE();

does exactly that, and on top resolves the multisampling. However, it's an Apple extension and I was wondering if there is something similar that copies all the logical buffers from one framebuffer to another and doesn't do the multisampling part in the vanilla implementation. GL_READ_FRAMEBUFFER doesn't seem to be a valid target, so I'm guessing there is no direct way? How about workarounds?

EDIT: Seems it's possible to use glCopyImageSubData in OpenGL 4, unfortunately not in my case since I'm using OpenGL ES 2.0 on iPhone, which seems to be lacking that function. Any other way?

Body:
You can do it directly with OpenGL ES 2.0, and it seems that there is no extension neither.

I am not really sure of what your are trying to achieve but in a general way, simply remove attachements of the FBO in which you have accomplish your off-screen rendering. Then bind the default FBO to be able to draw on screen, here you can simply draw a quad with an orthographic camera that fill the screen and a shader that takes your off-screen generated textures as input.
You will be able to do the resolve too if you are using multi-sampled textures.

glBindFramebuffer(GL_FRAMEBUFFER, off_screenFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);

glBindFramebuffer(GL_FRAMEBUFFER, 0); // Default FBO, on iOS it is 1 if I am correct

// Set the viewport at the size of screen
// Use your compositing shader (it doesn't have to manage any transform)
// Active and bind your textures
// Sent textures uniforms
// Draw your quad

Here is an exemple of the shader:

// Vertex
attribute vec2 in_position2D;
attribute vec2 in_texCoord0;
varying lowp vec2 v_texCoord0;
void main()
{
   v_texCoord0 = in_texCoord0;
   gl_Position = vec4(in_position2D, 0.0, 1.0);
}

// Fragment
uniform sampler2D u_texture0;
varying lowp vec2 v_texCoord0;

void main()
{
    gl_FragColor =  texture2D(u_texture0, v_texCoord0);
}


问:
Difference between cat filename and cat < filename in unix
Suppose I have a file named "file1". I want to display the contents of "file1" using the cat command in Unix.

Both cat file1 and cat < file1 are working similarly. What is the difference between them?

答:
cat opens a file, and cat > fileName tells the shell to open the file in the cat standard input.

Here is a link with more detailed information/answer:
https://unix.stackexchange.com/questions/258931/difference-between-cat-and-cat

ContentLicense: CC BY-SA 4.0


问:
Image Gallery: how to remove and add class when clicking an image

Beginner here.

I have a small image gallery, with two classes declared in CSS:

imagem: selected image, with border

imagem-activa: all the others, without border

How can i use JavaScript to add/remove the classes when the user clicks one image? I already know how to do it in jQuery, but want to learn also pure JS.

HTML

```<code>     <div class="exercicio">
        <h2 class="titulo">
            Exercício 4
        </h2>
        <img src="img/imagem1.jpg" class="imagem imagem-activa" />
        <img src="img/imagem2.jpg" class="imagem" />
        <img src="img/imagem3.jpg" class="imagem" />
        <img src="img/imagem4.jpg" class="imagem" />

    </div>
</code>```

CSS

```<code>.imagem{border:5px solid #000;opacity:0.5;cursor: pointer;}
.imagem-activa{border:5px solid #ff0066;opacity:1;}
</code>```

JS

This part i can't make it work. Can someone help me?

```<code>    var imagens = document.getElementsByClassName("imagem");
    var imagemActual = 0;
    for(var i = 0; i < imagens.length; i++) {
      imagens[i].addEventListener("click", function() {
          imagens[imagemActual].classList.remove("imagem-activa");
          this.classList.add("imagem-activa");
          imagemActual = i;
      });
    }
</code>```

This is my working jQuery solution

```<code>    $(".imagem").click(function() {
      $(".imagem").removeClass("imagem-activa");
      $(this).addClass("imagem-activa");
    });
</code>```

答:
So, what is happening here is that anytime any of your click handlers is invoked, your variable imageActual gets set to the current value of i which will always be 4 because this is the final value of i after the for loop. For the first click, you might not run into any errors and you might get the expected result. But as soon as any of your event listeners has run, the value of imagemActual will be 4 and that will cause an error on any future invocation of your event listeners because imagens[4] will be undefined.

There are a few ways to solve this.

1) bind

You can bind the (temporary) value of i inside the loop to the event listener function:

var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
  imagens[i].addEventListener("click", function(index) {
      imagens[imagemActual].classList.remove("imagem-activa");
      this.classList.add("imagem-activa");
      imagemActual = index;
  }.bind(imagens[i], i));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imagem {
  width: 20px;
  height: 20px;
  background-color: blue;
}

.imagem.imagem-activa {
  background-color: red;
}</code>```

        Exercício 4

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

<p>2) <strong>let</strong></p>

<p>If you can use ES6, you can use <code>let</code> which will make sure that your counting variable is a unique instance for every value that is applied:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const imagens = document.getElementsByClassName("imagem");
let imagemActual = 0;
for(let i = 0; i < imagens.length; i++) {
  imagens[i].addEventListener("click", function() {
      imagens[imagemActual].classList.remove("imagem-activa");
      this.classList.add("imagem-activa");
      imagemActual = i;
  });
}</code>```

.imagem {
  width: 20px;
  height: 20px;
  background-color: blue;
}

.imagem.imagem-activa {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="exercicio">
    <h2 class="titulo">
        Exercício 4
    </h2>
    <img src="" class="imagem imagem-activa" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
</div></code>```

Body:
Beginner here.

I have a small image gallery, with two classes declared in CSS:

imagem: selected image, with border

imagem-activa: all the others, without border

How can i use JavaScript to add/remove the classes when the user clicks one image? I already know how to do it in jQuery, but want to learn also pure JS.

HTML

            Exercício 4

CSS

.imagem{border:5px solid #000;opacity:0.5;cursor: pointer;}
.imagem-activa{border:5px solid #ff0066;opacity:1;}

JS

This part i can't make it work. Can someone help me?

    var imagens = document.getElementsByClassName("imagem");
    var imagemActual = 0;
    for(var i = 0; i < imagens.length; i++) {
      imagens[i].addEventListener("click", function() {
          imagens[imagemActual].classList.remove("imagem-activa");
          this.classList.add("imagem-activa");
          imagemActual = i;
      });
    }

This is my working jQuery solution

    $(".imagem").click(function() {
      $(".imagem").removeClass("imagem-activa");
      $(this).addClass("imagem-activa");
    });

Body:
So, what is happening here is that anytime any of your click handlers is invoked, your variable imageActual gets set to the current value of i which will always be 4 because this is the final value of i after the for loop. For the first click, you might not run into any errors and you might get the expected result. But as soon as any of your event listeners has run, the value of imagemActual will be 4 and that will cause an error on any future invocation of your event listeners because imagens[4] will be undefined.

There are a few ways to solve this.

1) bind

You can bind the (temporary) value of i inside the loop to the event listener function:

var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
  imagens[i].addEventListener("click", function(index) {
      imagens[imagemActual].classList.remove("imagem-activa");
      this.classList.add("imagem-activa");
      imagemActual = index;
  }.bind(imagens[i], i));
}

.imagem {
  width: 20px;
  height: 20px;
  background-color: blue;
}

.imagem.imagem-activa {
  background-color: red;
}

<div class="exercicio">
    <h2 class="titulo">
        Exercício 4
    </h2>
    <img src="" class="imagem imagem-activa" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
</div>

2) let

If you can use ES6, you can use let which will make sure that your counting variable is a unique instance for every value that is applied:

const imagens = document.getElementsByClassName("imagem");
let imagemActual = 0;
for(let i = 0; i < imagens.length; i++) {
  imagens[i].addEventListener("click", function() {
      imagens[imagemActual].classList.remove("imagem-activa");
      this.classList.add("imagem-activa");
      imagemActual = i;
  });
}

.imagem {
  width: 20px;
  height: 20px;
  background-color: blue;
}

.imagem.imagem-activa {
  background-color: red;
}

<div class="exercicio">
    <h2 class="titulo">
        Exercício 4
    </h2>
    <img src="" class="imagem imagem-activa" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
    <img src="" class="imagem" />
</div>


问:
How to get long-link from dynamic link when opening app for the first time?
When I click on a dynamic link I will be redirected to the appstore and from there I download the app. What I really need is the long link of the dynamic link because I got data in it which I need to extract.

This method will be opened when I start the app for the first time:

```<code>-(Bool)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDICtionarry<NSString *, id>options).
</code>```

答:
Clarification of terms here:
deep link -> this is what you will put inside dynamic link;
long dynamic link -> dynamic link that has your deep link and bunch of parameters related to dynamic link behavior;
short dynamic link - the same as long but has short representation;

To store more data you need to add your data as parameters to deep link. For example instead of deep link https://example.com you use https://example.com?promotionID=abc&openViewName=startingViewOptionB&loadImageOnPromo=imageSmall

Let me know if have questions.

Body:
When I click on a dynamic link I will be redirected to the appstore and from there I download the app. What I really need is the long link of the dynamic link because I got data in it which I need to extract.

This method will be opened when I start the app for the first time:

-(Bool)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDICtionarry<NSString *, id>options).


问:
SQL Joins vs Single Table : Performance Difference?
I am trying to stick to the practice of keeping the database normalized, but that leads to the need to run multiple join queries. Is there a performance degradation if many queries use joins vs having a call to a single table that might contain redundant data?</p>

答:
With the proper indexes set up, your joins can perform very quickly. Use SQL Profiler to determine what indexes need to be created or altered to optimize performance of your common queries. Be sure to have a maintenance plan set up for your database to run once a week (or every day for tables that change a lot) that updates your statistics and indexes.

Normalization is normally preferred over keeping data in multiple locations. There are scenarios where insert/update does not need to occur quickly and select need to occur very quickly in which case you could be better off without normalization. Even so, premature optimization is not recommended so go with a normalized structure first.

OwnerDisplayName: zsharp

LastEditorDisplayName: mwigdahl

OwnerDisplayName: David Thomas Garcia


问:
How to launch an .exe file by clicking a JButton in GUI?
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

```<code>JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file
</code>```

Thanks in advance

答:
I think that you would use Runtime.exec() or a ProcessBuilder similar to how you'd call an exe program if you weren't calling it from a GUI.  Some things to take care about are that you'd likely want to call the Runtime.exec() on a background thread off of the Swing main thread, the EDT, such as provided by a SwingWorker object.  Otherwise your GUI could freeze while the exe program takes over the Swing thread.  Also you'll also want to head all of the warnings about calling Runtime.exec() shown in this great article,
When Runtime.exec() won't, possibly one of the best articles written on the subject --highly recommended!

Question: What do you mean by this statement as it isn't clear to me?:

Note: The program.exe file is created from a java main program.

Body:
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file

Thanks in advance


问:
installing OpenCV on mac osx 10.10.5
I would like to use OpenCV on python and I am using the command lines on the terminal:

To get homebrew ...

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

I believe this works ok.

Then I try to install the dependency gtk+
brew install gtk+

This seems to be ok.

The problem occurs when I install opencv
brew install opencv

I get the return error.... and I just noticed that it is for python2 ... (that could be the issue), but if it is not it seems to be that I have an old mac OS ... is there a way around this?

```<code>1 error generated.
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

Do not report this issue to Homebrew/brew or Homebrew/core!

Error: You are using macOS 10.10.
We (and Apple) do not provide support for this old version.
You may encounter build failures or other breakages.
Please create pull-requests instead of filing issues.
</code>```

答:
If you just need the base module. </p>

```<code>pip install opencv-python
</code>```

Title: installing OpenCV on mac osx 10.10.5

Body:
I would like to use OpenCV on python and I am using the command lines on the terminal:

To get homebrew ...

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I believe this works ok.

Then I try to install the dependency gtk+
brew install gtk+

This seems to be ok.

The problem occurs when I install opencv
brew install opencv

I get the return error.... and I just noticed that it is for python2 ... (that could be the issue), but if it is not it seems to be that I have an old mac OS ... is there a way around this?

1 error generated.
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

Do not report this issue to Homebrew/brew or Homebrew/core!

Error: You are using macOS 10.10.
We (and Apple) do not provide support for this old version.
You may encounter build failures or other breakages.
Please create pull-requests instead of filing issues.

Body:
If you just need the base module.

pip install opencv-python


问:
Spring Data JPA - How can I fetch data from a Date column using only month and day?
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

```<code>1935-12-08 00:00:00
</code>```

If I want to do this in a db level it works fine:

```<code>SELECT * FROM my_database.event where event_date LIKE '%-12-08%';
</code>```

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

```<code>List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);
</code>```

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

答:
Use nativeQuery to emulate the query in the Database.

```<code>@Query(value = "SELECT * FROM events WHERE event_date Like %?1%", nativeQuery = true)
List<Match> findByMatchMonthAndMatchDay(@Param ("eventDate") String eventDate);
</code>```

The DB takes care of the conversion between Date/String for the LIKE clause.

Passing the param as "-month-day" (e.g.: -12-08) will return a collection of events with that string in the date field.

Body:
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

1935-12-08 00:00:00

If I want to do this in a db level it works fine:

SELECT * FROM my_database.event where event_date LIKE '%-12-08%';

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

Body:
Use nativeQuery to emulate the query in the Database.

@Query(value = "SELECT * FROM events WHERE event_date Like %?1%", nativeQuery = true)
List<Match> findByMatchMonthAndMatchDay(@Param ("eventDate") String eventDate);

The DB takes care of the conversion between Date/String for the LIKE clause.

Passing the param as "-month-day" (e.g.: -12-08) will return a collection of events with that string in the date field.


问:
Scala apply filter based on a flag
To apply a filter only when a flag is set to true, My current solution looks like this:

```<code>val list = List(5,17,25,80)
val checkAge = false
val ageCheckedList = list.filter(i => i>18)
</code>```

The idea is that if checkAge is set to true, filter should be applied, but if checkAge is false, do not perform the filtering.

What's a concise way of expressing this? The best I've come up with is this:

```<code>ageCheckedList = list.filterNot(i => checkAge && i <= 18)
</code>```

which is very confusing to read to say the least.

答:
I think what you have is perfectly fine. You can invert the logic and that makes it a little more readable perhaps.

```<code>list.filter(i => !checkAge || i <= 18)
</code>```

This basically says either we aren't checking age or the age is in the range.

Title: Scala apply filter based on a flag

Body:
To apply a filter only when a flag is set to true, My current solution looks like this:

val list = List(5,17,25,80)
val checkAge = false
val ageCheckedList = list.filter(i => i>18)

The idea is that if checkAge is set to true, filter should be applied, but if checkAge is false, do not perform the filtering.

What's a concise way of expressing this? The best I've come up with is this:

ageCheckedList = list.filterNot(i => checkAge && i <= 18)

which is very confusing to read to say the least.

Body:
I think what you have is perfectly fine. You can invert the logic and that makes it a little more readable perhaps.

list.filter(i => !checkAge || i <= 18)

This basically says either we aren't checking age or the age is in the range.


问:
MVC Html.ActionLink doesn't work after upgrade from .net 3.5 to 4.0
Well as the title says, I have a project with a bunch of Html.ActionLink

```<code><%= Html.ActionLink("Reason for booking", "BookingReason")%>
</code>```

I have upgraded the project to .net 4.0 and they no longer render a link to the action.  Its just a blank  of course causing the page to reload.

The Html.ActionLink tags are in a user control (ascx) in the Shared folder of an Area.

I tried downgrading again to .net 3.5 and it works - weird.  any ideas?

Thx

答:
Be sure to mark your optional params with UrlParameter.Optional

```<code>            routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
</code>```

That was the problem for us (symptoms as yours).

-- Edited
It wasn't the only problem.
When migrating to MVC 3 you can get next problem,
suppose you had such route(id and page were optional)

```<code>            routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}/{page}", // URL with parameters
            new { controller = "Home", action = "Index", id = "", page = "" } // Parameter defaults
        );
</code>```

now you have to split it to 2 different routes:

```<code>        routes.MapRoute(
            "Paged",                                                     // Route name
            "{controller}/{action}/{id}/{page}",
            new { controller = "Home", action = "Index", page = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default",                                                     // Route name
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional}//, page = UrlParameter.Optional }  // Parameter defaults
        );
</code>```

Body:
Well as the title says, I have a project with a bunch of Html.ActionLink

<%= Html.ActionLink("Reason for booking", "BookingReason")%>

I have upgraded the project to .net 4.0 and they no longer render a link to the action.  Its just a blank  of course causing the page to reload.

The Html.ActionLink tags are in a user control (ascx) in the Shared folder of an Area.

I tried downgrading again to .net 3.5 and it works - weird.  any ideas?

Thx

Body:
Be sure to mark your optional params with UrlParameter.Optional

            routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

That was the problem for us (symptoms as yours).

-- Edited
It wasn't the only problem.
When migrating to MVC 3 you can get next problem,
suppose you had such route(id and page were optional)

            routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}/{page}", // URL with parameters
            new { controller = "Home", action = "Index", id = "", page = "" } // Parameter defaults
        );

now you have to split it to 2 different routes:

        routes.MapRoute(
            "Paged",                                                     // Route name
            "{controller}/{action}/{id}/{page}",
            new { controller = "Home", action = "Index", page = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default",                                                     // Route name
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional}//, page = UrlParameter.Optional }  // Parameter defaults
        );


问:
How to add selective nodes in the log file
I am trying to perform a testing on a trained model.  I have restored the checkpoint in the session. The model has a lot of operations but I am only testing part of it.

I would like to see the op network that I am testing in the tensorboard, but currently, it's all entangled with all other operations that I do not want.

Is there any way to store the tf.summary for the selective operations that you are performing in the session?

答: Instead of merging all summaries by merged_summary = tf.summary.merge_all(), you can merge the ops that you wanted like merged_summary_group1 = tf.summary.merge([op1, op2, ...]). After that, replacing all merged_summary in sess.run with merged_summary_group1.