问:
Python OSError No space left on device
Im writing a lot of files to a folder, no subdirectories, however after 2.8 million files this error shows up:

```<code>with open(bottleneck_path, 'w') as save_file:
OSError: [Errno 28] No space left on device: '/home/user/path/redacted'
</code>```

I've checked the length of the filename which is only 149 characters long. The file size is supposed to be around 18K.

My operating system is Linux.

df -i:

```<code>Filesystem                               Inodes   IUsed    IFree IUse% Mounted on
udev                                    4106923     544  4106379    1% /dev
tmpfs                                   4113022     836  4112186    1% /run
/dev/sda2                              28401664 9008557 19393107   32% /
tmpfs                                   4113022      40  4112982    1% /dev/shm
tmpfs                                   4113022       5  4113017    1% /run/lock
tmpfs                                   4113022      16  4113006    1% /sys/fs/cgroup
/dev/sda1                                     0       0        0     - /boot/efi
</code>```

df -T

```<code>Filesystem                             Type      1K-blocks       Used  Available Use% Mounted on
udev                                   devtmpfs   16427692          0   16427692   0% /dev
tmpfs                                  tmpfs       3290420      22136    3268284   1% /run
/dev/sda2                              ext4      447088512  355325584   69029056  84% /
tmpfs                                  tmpfs      16452088      82448   16369640   1% /dev/shm
tmpfs                                  tmpfs          5120          4       5116   1% /run/lock
tmpfs                                  tmpfs      16452088          0   16452088   0% /sys/fs/cgroup
/dev/sda1                              vfat         523248       3684     519564   1% /boot/efi
</code>```

du -sh .

```<code>56G
</code>```

ls | wc -l

```<code>2892084
</code>```

From my understanding ext4 should be able to handle this just fine.

EDIT:

tune2fs -l /dev/sda2

```<code>tune2fs 1.42.13 (17-May-2015)
Filesystem volume name:   <none>
Last mounted on:          /
Filesystem UUID:          cd620466-1f88-400b-acf5-457a9c9544cf
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              28401664
Block count:              113587456
Reserved block count:     5679372
Free blocks:              82864623
Free inodes:              25755495
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      996
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   512
Flex block group size:    16
Filesystem created:       Wed Mar  1 15:14:22 2017
Last mount time:          Mon Mar 27 13:20:00 2017
Last write time:          Mon Mar 27 13:20:00 2017
Mount count:              35
Maximum mount count:      -1
Last checked:             Wed Mar  1 15:14:22 2017
Check interval:           0 (<none>)
Lifetime writes:          1813 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:           256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
First orphan inode:       1312056
Default directory hash:   half_md4
Directory Hash Seed:      e186507d-32b5-49c0-8ce1-09bf2a75d816
Journal backup:           inode blocks
</code>```

Using

```<code>touch /home/user/path/redacted/somefile_1
</code>```

throws an error but the same filename structure with a different name works fine. eg:

```<code>touch /home/user/path/redacted/somefile_2
</code>```

答: Its due to hash collision. Disabling dir_index resolved the issue.</p>

Title: Python OSError No space left on device

Body:
Im writing a lot of files to a folder, no subdirectories, however after 2.8 million files this error shows up:

with open(bottleneck_path, 'w') as save_file:
OSError: [Errno 28] No space left on device: '/home/user/path/redacted'

I've checked the length of the filename which is only 149 characters long. The file size is supposed to be around 18K.

My operating system is Linux.

df -i:

Filesystem                               Inodes   IUsed    IFree IUse% Mounted on
udev                                    4106923     544  4106379    1% /dev
tmpfs                                   4113022     836  4112186    1% /run
/dev/sda2                              28401664 9008557 19393107   32% /
tmpfs                                   4113022      40  4112982    1% /dev/shm
tmpfs                                   4113022       5  4113017    1% /run/lock
tmpfs                                   4113022      16  4113006    1% /sys/fs/cgroup
/dev/sda1                                     0       0        0     - /boot/efi

df -T

Filesystem                             Type      1K-blocks       Used  Available Use% Mounted on
udev                                   devtmpfs   16427692          0   16427692   0% /dev
tmpfs                                  tmpfs       3290420      22136    3268284   1% /run
/dev/sda2                              ext4      447088512  355325584   69029056  84% /
tmpfs                                  tmpfs      16452088      82448   16369640   1% /dev/shm
tmpfs                                  tmpfs          5120          4       5116   1% /run/lock
tmpfs                                  tmpfs      16452088          0   16452088   0% /sys/fs/cgroup
/dev/sda1                              vfat         523248       3684     519564   1% /boot/efi

du -sh .

56G

ls | wc -l

2892084

From my understanding ext4 should be able to handle this just fine.

EDIT:

tune2fs -l /dev/sda2

tune2fs 1.42.13 (17-May-2015)
Filesystem volume name:   <none>
Last mounted on:          /
Filesystem UUID:          cd620466-1f88-400b-acf5-457a9c9544cf
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              28401664
Block count:              113587456
Reserved block count:     5679372
Free blocks:              82864623
Free inodes:              25755495
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      996
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   512
Flex block group size:    16
Filesystem created:       Wed Mar  1 15:14:22 2017
Last mount time:          Mon Mar 27 13:20:00 2017
Last write time:          Mon Mar 27 13:20:00 2017
Mount count:              35
Maximum mount count:      -1
Last checked:             Wed Mar  1 15:14:22 2017
Check interval:           0 (<none>)
Lifetime writes:          1813 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:           256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
First orphan inode:       1312056
Default directory hash:   half_md4
Directory Hash Seed:      e186507d-32b5-49c0-8ce1-09bf2a75d816
Journal backup:           inode blocks

Using

touch /home/user/path/redacted/somefile_1

throws an error but the same filename structure with a different name works fine. eg:

touch /home/user/path/redacted/somefile_2


来源: stackexchange

问:
Starting and Stopping dedicated AWS instances using Java
I am looking to start and stop my Amazon instances through Java. I have dedicated instances and do not create new instances on the fly for my needs.

I have read the AWS Java SDK documentation for starting and stopping the instances but I could only find RunInstancesRequest class which is used to launch a new instance.

Currently, I use the AWS CLI to start and stop the instances.

I am working on creating an Android/iOS app which can be used to start, stop and request status of my AWS instances

答:
Try these API references

AWS Java SDK: StartInstancesRequest and StopInstancesRequest

AWS Android SDK: StartInstancesRequest and StopInstancesRequest

AWS iOS SDK: StartInstancesRequest and StopInstancesRequest

ContentLicense: CC BY-SA 3.0


问:
Finding the right argument for addActionListener
I'm trying to make a button that toggles the state of the button (changes color and text) when pressed. But I can't get the addActionListener to work and I can't find the ToggleState method from my main class. I am new to java and would appreciate your help.

I get the errors
 - “The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments”
- "ActionListener cannot be resolved to a type"

```<code>package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class coolgrafik extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel label;

public coolgrafik(){

    //super(title);
    setSize(400,60);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setBackground(Color.GRAY);
    label = new JLabel("test");
    panel.add(label);

    MyButton button = new MyButton(Color.green, Color.red, "RUN","STOP");
    panel.add(button);
    button.addActionListener(this);

    add(panel);
}

public static void main(String[] args){
    new coolgrafik().setVisible(true);
    //toggleState(Color.green, Color.red, "RUN","STOP");
}

public void actionPerformed(ActionEvent e) {
    toggleState(Color.green, Color.red, "RUN","STOP");
}
}
</code>```

and this is the button class

```<code>package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class MyButton extends JButton{

private static final long serialVersionUID = 1L;

public MyButton(Color c1, Color c2, String s1, String s2){

    setText(s1);
    setForeground(c1);
    setBackground(c1);
    setOpaque(true);

}

public void toggleState(Color c1, Color c2, String s1, String s2){

    setText(s2);
    setForeground(c2);
    setBackground(c2);
    setOpaque(true);

}
</code>```

}

答:
To complete @Japu_D_Cret 's comment :

You either need to make your toggleState method static to call it like you do in your actionPerformed method, or to use your button to call it :

```<code>button.toggleState(Color.green, Color.red, "RUN","STOP");
</code>```

as it is a method defined in your MyButton class and not in your coolgrafik class.

Body:
I'm trying to make a button that toggles the state of the button (changes color and text) when pressed. But I can't get the addActionListener to work and I can't find the ToggleState method from my main class. I am new to java and would appreciate your help.

I get the errors
 - “The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments”
- "ActionListener cannot be resolved to a type"

package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class coolgrafik extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel label;

public coolgrafik(){

    //super(title);
    setSize(400,60);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setBackground(Color.GRAY);
    label = new JLabel("test");
    panel.add(label);

    MyButton button = new MyButton(Color.green, Color.red, "RUN","STOP");
    panel.add(button);
    button.addActionListener(this);

    add(panel);
}

public static void main(String[] args){
    new coolgrafik().setVisible(true);
    //toggleState(Color.green, Color.red, "RUN","STOP");
}

public void actionPerformed(ActionEvent e) {
    toggleState(Color.green, Color.red, "RUN","STOP");
}
}

and this is the button class

package Grafiktest;

import javax.swing.*;
import java.awt.*;

public class MyButton extends JButton{

private static final long serialVersionUID = 1L;

public MyButton(Color c1, Color c2, String s1, String s2){

    setText(s1);
    setForeground(c1);
    setBackground(c1);
    setOpaque(true);

}

public void toggleState(Color c1, Color c2, String s1, String s2){

    setText(s2);
    setForeground(c2);
    setBackground(c2);
    setOpaque(true);

}

}

Body:
To complete @Japu_D_Cret 's comment :

You either need to make your toggleState method static to call it like you do in your actionPerformed method, or to use your button to call it :

button.toggleState(Color.green, Color.red, "RUN","STOP");

as it is a method defined in your MyButton class and not in your coolgrafik class.


问:
Get the client's computer name
I am getting the client's (website user's) IP address. Now I'd like to go one step further by knowing the user's computer name. So far, my research has not turned up anything to aid me in retrieving this information.

Is it possible to use the user's IP address, or some other means, to get my visitor's computer name using PHP?

答:
This is all that you could get using just PHP (you may try these butIi dont think this is what you actually needed):</p>

```<code>gethostname()
gethostbyname(gethostname())
$_SERVER['HTTP_HOST']
$_SERVER['SERVER_SIGNATURE']
$_SERVER['SERVER_NAME']
$_SERVER['SERVER_ADDR']
$_SERVER['SERVER_PORT']
$_SERVER['REMOTE_ADDR']
gethostbyaddr($_SERVER['REMOTE_ADDR'])
php_uname()
</code>```

Title: Get the client's computer name

Body:
This is all that you could get using just PHP (you may try these butIi dont think this is what you actually needed):

gethostname()
gethostbyname(gethostname())
$_SERVER['HTTP_HOST']
$_SERVER['SERVER_SIGNATURE']
$_SERVER['SERVER_NAME']
$_SERVER['SERVER_ADDR']
$_SERVER['SERVER_PORT']
$_SERVER['REMOTE_ADDR']
gethostbyaddr($_SERVER['REMOTE_ADDR'])
php_uname()


答:
"The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments” - "ActionListener cannot be resolved to a type"

you didn't import the class ActionListener, since it's not in java.awt.* but in java.awt.event.ActionListener - for reference https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html

But I still can't use my toggleState method from the actionperformer. How come?

well in your void actionPerformed(ActionEvent) you try to call a method called void toggleState(Color,Color,String,String) - but it is not declared in the same class nor is it statically imported.

You obviously want to call the toggleState method on your object button of class MyButton, to do that you have to call the method on that object like button.toggeState(...)
This will also not directly work, since your object button is only known in your constructor and you have to add an object attribute to your coolgrafik class, like you did with the panels - then it should work just fine

here are code fragments that you need to change in your coolgrafik class

attributes:

```<code>private JPanel panel;
private JLabel label;
private MyButton button;
</code>```

in your coolgrafik constructor

```<code>//...
this.button = new MyButton(Color.green, Color.red, "RUN","STOP");
this.panel.add(this.button);
this.button.addActionListener(this);
//...
</code>```

and your actionPerformed Method

```<code>public void actionPerformed(ActionEvent e) {
    button.toggleState(Color.green, Color.red, "RUN","STOP");
}
</code>```

Title: Finding the right argument for addActionListener

Body:
"The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments” - "ActionListener cannot be resolved to a type"

you didn't import the class ActionListener, since it's not in java.awt.* but in java.awt.event.ActionListener - for reference https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html

But I still can't use my toggleState method from the actionperformer. How come?

well in your void actionPerformed(ActionEvent) you try to call a method called void toggleState(Color,Color,String,String) - but it is not declared in the same class nor is it statically imported.

You obviously want to call the toggleState method on your object button of class MyButton, to do that you have to call the method on that object like button.toggeState(...)
This will also not directly work, since your object button is only known in your constructor and you have to add an object attribute to your coolgrafik class, like you did with the panels - then it should work just fine

here are code fragments that you need to change in your coolgrafik class

attributes:

private JPanel panel;
private JLabel label;
private MyButton button;

in your coolgrafik constructor

//...
this.button = new MyButton(Color.green, Color.red, "RUN","STOP");
this.panel.add(this.button);
this.button.addActionListener(this);
//...

and your actionPerformed Method

public void actionPerformed(ActionEvent e) {
    button.toggleState(Color.green, Color.red, "RUN","STOP");
}


问:
Using response from one API call to do another API Call
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

```<code>var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}
</code>```

And in my view it would look something like this:

```<code><div ng-repeat = "song in songlist">
    <div>{{ song.rank }}</div>
    <div>
        <img ng-src=" {{ spotifyImg[$index] }}"/>
    </div>
</div>
</code>```

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

答:
create separate function and put the content of for loop inside that function and call that function inside the loop

```<code>$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if (spotifyID[i] !== null) {
            sampleFunc(i);
        }
    }
}

function sampleFunc(i) {
    musicService.getSpotify(spotifyID[i]).then(function(data) {
        $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
    });
}
</code>```

I think reason you get only last index of an array is when you are calling promise inside loop, loop does't wait until the promise returns. it just keep executing.At the time promise returns loop is executed and it;s getting last index of the array.  That's why you need to separately call the promise from for loop

Body:
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}

And in my view it would look something like this:

{{ song.rank }}

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

Body:
create separate function and put the content of for loop inside that function and call that function inside the loop

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if (spotifyID[i] !== null) {
            sampleFunc(i);
        }
    }
}

function sampleFunc(i) {
    musicService.getSpotify(spotifyID[i]).then(function(data) {
        $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
    });
}

I think reason you get only last index of an array is when you are calling promise inside loop, loop does't wait until the promise returns. it just keep executing.At the time promise returns loop is executed and it;s getting last index of the array.  That's why you need to separately call the promise from for loop


问:
Getting Unknown Command error on IF-THEN-ELSE
I have the following query that I am using in Oracle 11g

```<code>IF EXISTS (SELECT * FROM EMPLOYEE_MASTER WHERE EMPID='ABCD32643')
THEN
update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1' where EMPID='ABCD32643' ;
ELSE
insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE) values('A62352','JOHN DOE','1') ;
END IF;
</code>```

On running the statement I get the following output:

```<code>Error starting at line : 4 in command -
ELSE
Error report -
Unknown Command

1 row inserted.

Error starting at line : 6 in command -
END IF
Error report -
Unknown Command
</code>```

The values get inserted with error when I run it directly. But when I try to execute this query through my application I get an oracle exception because of the error generated :

```<code>ORA-00900: invalid SQL statement
</code>```

And hence the values are not inserted.

I am relatively new to Oracle. Please advise on what's wrong with the above query so that I could run this query error free.

答:
"what's wrong with the above query "

What's wrong with the query is that it is not a query (SQL). It should be a program snippet (PL/SQL) but it isn't written as PL/SQL block, framed by BEGIN and END; keywords.

But turning it into an anonymous PL/SQL block won't help. Oracle PL/SQL does not support IF EXISTS (select ... syntax.

Fortunately Oracle SQL does support MERGE statement which does the same thing as your code, with less typing.

```<code>merge into EMPLOYEE_MASTER em
using ( select 'A62352' as empid,
               'JOHN DOE' as empname,
               '1' as emptype
         from dual ) q
on (q.empid = em.empid)
when not matched then
    insert (EMPID,EMPNAME,EMPTYPE)
           values (q.empid, q.empname, q.emptype)
when matched then
    update
    set em.empname = q.empname, em.emptype = q.emptype
/
</code>```

Except that you're trying to update empid as well. That's not supported in MERGE. Why would you want to change the primary key?

"Does this query need me to add values to all columns in the table?  "

The INSERT can have all the columns in the table. The UPDATE cannot change the columns used in the ON clause (usually the primary key) because that's a limitation of the way MERGE works. I think it's the same  key preservation mechanism we see when updating views. Find out more.

Body:
I have the following query that I am using in Oracle 11g

IF EXISTS (SELECT * FROM EMPLOYEE_MASTER WHERE EMPID='ABCD32643')
THEN
update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1' where EMPID='ABCD32643' ;
ELSE
insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE) values('A62352','JOHN DOE','1') ;
END IF;

On running the statement I get the following output:

Error starting at line : 4 in command -
ELSE
Error report -
Unknown Command

1 row inserted.

Error starting at line : 6 in command -
END IF
Error report -
Unknown Command

The values get inserted with error when I run it directly. But when I try to execute this query through my application I get an oracle exception because of the error generated :

ORA-00900: invalid SQL statement

And hence the values are not inserted.

I am relatively new to Oracle. Please advise on what's wrong with the above query so that I could run this query error free.

Body:
"what's wrong with the above query "

What's wrong with the query is that it is not a query (SQL). It should be a program snippet (PL/SQL) but it isn't written as PL/SQL block, framed by BEGIN and END; keywords.

But turning it into an anonymous PL/SQL block won't help. Oracle PL/SQL does not support IF EXISTS (select ... syntax.

Fortunately Oracle SQL does support MERGE statement which does the same thing as your code, with less typing.

merge into EMPLOYEE_MASTER em
using ( select 'A62352' as empid,
               'JOHN DOE' as empname,
               '1' as emptype
         from dual ) q
on (q.empid = em.empid)
when not matched then
    insert (EMPID,EMPNAME,EMPTYPE)
           values (q.empid, q.empname, q.emptype)
when matched then
    update
    set em.empname = q.empname, em.emptype = q.emptype
/

Except that you're trying to update empid as well. That's not supported in MERGE. Why would you want to change the primary key?

"Does this query need me to add values to all columns in the table?  "

The INSERT can have all the columns in the table. The UPDATE cannot change the columns used in the ON clause (usually the primary key) because that's a limitation of the way MERGE works. I think it's the same  key preservation mechanism we see when updating views. Find out more.


问:
More than 2 columns in a CONCAT function
In SQL Server 2012 I want to concat 5 columns into 1 but in the query it works but when I put in in a view it gives me an error like

Msg 174, Level 15, State 1, Line 3

  The CONCAT function requires 2 argument(s).

What's the problem so I can fix it because concat is a good function for concatenate more than 1 column because if its null they make it empty..

CODE:

```<code>SELECT
   'Aan ' + A.Name AS 'Naam',
   { fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.',
   ISNULL(ISNULL(A.Address1_Line2, A.Address1_Line1),
   C.Address1_Line2) AS 'Adres',
   ISNULL(A.Address1_PostalCode + ' ' + A.Address1_City, A.Address2_PostalCode + ' ' + A.Address2_City) AS 'Woonplaats',
   'heer' + ' ' + ISNULL(C.MiddleName + ' ', N'') + ISNULL(C.LastName, N'') AS 'Aanhef'
FROM
    dbo.Account AS A
FULL OUTER JOIN
    dbo.Contact AS C ON A.Name = C.AccountIdName
WHERE
    (C.Salutation = 'Dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1)
    AND (ISNULL(C.StatusCode, 1) = 1) OR (C.Salutation = 'dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1) AND (ISNULL(C.StatusCode, 1) = 1)
</code>```

答:
I had the same problem and all the other answers did not work for me and i did not want to use the one from Andrei.

I managed to create the view using a create view statement.

```<code>CREATE VIEW ViewName AS
SELECT
   'Aan ' + A.Name AS 'Naam',
   { fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.',
   ISNULL(ISNULL(A.Address1_Line2, A.Address1_Line1),
   C.Address1_Line2) AS 'Adres',
   ISNULL(A.Address1_PostalCode + ' ' + A.Address1_City,     A.Address2_PostalCode + ' ' + A.Address2_City) AS 'Woonplaats',
   'heer' + ' ' + ISNULL(C.MiddleName + ' ', N'') + ISNULL(C.LastName, N'') AS 'Aanhef'
FROM dbo.Account AS A
FULL OUTER JOIN
    dbo.Contact AS C ON A.Name = C.AccountIdName
WHERE
    (C.Salutation = 'Dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1)
    AND (ISNULL(C.StatusCode, 1) = 1) OR (C.Salutation = 'dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1) AND (ISNULL(C.StatusCode, 1) = 1)
</code>```

Body:
In SQL Server 2012 I want to concat 5 columns into 1 but in the query it works but when I put in in a view it gives me an error like

Msg 174, Level 15, State 1, Line 3

  The CONCAT function requires 2 argument(s).

What's the problem so I can fix it because concat is a good function for concatenate more than 1 column because if its null they make it empty..

CODE:

SELECT
   'Aan ' + A.Name AS 'Naam',
   { fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.',
   ISNULL(ISNULL(A.Address1_Line2, A.Address1_Line1),
   C.Address1_Line2) AS 'Adres',
   ISNULL(A.Address1_PostalCode + ' ' + A.Address1_City, A.Address2_PostalCode + ' ' + A.Address2_City) AS 'Woonplaats',
   'heer' + ' ' + ISNULL(C.MiddleName + ' ', N'') + ISNULL(C.LastName, N'') AS 'Aanhef'
FROM
    dbo.Account AS A
FULL OUTER JOIN
    dbo.Contact AS C ON A.Name = C.AccountIdName
WHERE
    (C.Salutation = 'Dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1)
    AND (ISNULL(C.StatusCode, 1) = 1) OR (C.Salutation = 'dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1) AND (ISNULL(C.StatusCode, 1) = 1)

Body:
I had the same problem and all the other answers did not work for me and i did not want to use the one from Andrei.

I managed to create the view using a create view statement.

CREATE VIEW ViewName AS
SELECT
   'Aan ' + A.Name AS 'Naam',
   { fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.',
   ISNULL(ISNULL(A.Address1_Line2, A.Address1_Line1),
   C.Address1_Line2) AS 'Adres',
   ISNULL(A.Address1_PostalCode + ' ' + A.Address1_City,     A.Address2_PostalCode + ' ' + A.Address2_City) AS 'Woonplaats',
   'heer' + ' ' + ISNULL(C.MiddleName + ' ', N'') + ISNULL(C.LastName, N'') AS 'Aanhef'
FROM dbo.Account AS A
FULL OUTER JOIN
    dbo.Contact AS C ON A.Name = C.AccountIdName
WHERE
    (C.Salutation = 'Dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1)
    AND (ISNULL(C.StatusCode, 1) = 1) OR (C.Salutation = 'dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1) AND (ISNULL(C.StatusCode, 1) = 1)


问:
.NET/C# Drizzle database client
I am planning to use Drizzle in my next C# Mono app.  Since there is no C# client available for Drizzle, I thought I would have a stab at writing my own by converting the Java client, and then making it work with DBLinq.

Having seen the Java client, I realise that it's a longer job that I had anticipated, and I don't have the time.  Besides the Java client is not all that mature yet.

Since there is an official Drizzle C client library (libdrizzle), writing a C# wrapper might be the best solution.  Are there any tools available that can assist in generating the code for this?

答: Additionally, Drizzle speaks the MySQL protocol, so most MySQL clients should work just fine.</p>

Title: .NET/C# Drizzle database client

ContentLicense: CC BY-SA 2.5


问:
Apply css style to all components in Angular 2 app
I have very basic, and reusable css rules, such as:

```<code>.ng-invalid {
    border-left: 5px solid #a94442;
}

.ng-valid {
    border-left: 5px solid #42A948;
}
</code>```

I'd like to re-use these for all of my components. If I place this in my root AppComponent, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent.

I must be missing something very obvious here.

答:
In my opinion you should agree to a particular strategy in this regards across your whole team.

E.g. you could set encapsulation: ViewEncapsulation.None just like @sreeramu mentioned in his reply. But only for app (root) component.

You should take advantage of CSS encapsulation as much as you can so turning it off for several components is kinda smelly. But applying it only to one component might work fine.

Body:
I have very basic, and reusable css rules, such as:

.ng-invalid {
    border-left: 5px solid #a94442;
}

.ng-valid {
    border-left: 5px solid #42A948;
}

I'd like to re-use these for all of my components. If I place this in my root AppComponent, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent.

I must be missing something very obvious here.


问:
Run docker build in ubuntu:16.04 docker
I want to build a docker image in docker container.

So, I tried to create a docker-installed ubuntu docker image following https://docs.docker.com/engine/installation/linux/ubuntu/, but failed.

```<code>FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN apt-key fingerprint 0EBFCD88

RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

RUN apt-get update && \
    apt-get install -y docker-ce
</code>```

When I run docker images or other commands on the docker image created by above Dockerfile, the error happens.

```<code>Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

Is there any way to solve this problem? Thanks.

答:
AWS CodeBuild doesn't "[..] allow customers to bring in their own Docker-in-Docker images [..]" yet.

We currently only support Docker-in-Docker (dind) with the official CodeBuild images

Source (Jan 12, 2017):

Title: Run docker build in ubuntu:16.04 docker

Body:
I want to build a docker image in docker container.

So, I tried to create a docker-installed ubuntu docker image following https://docs.docker.com/engine/installation/linux/ubuntu/, but failed.

FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN apt-key fingerprint 0EBFCD88

RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

RUN apt-get update && \
    apt-get install -y docker-ce

When I run docker images or other commands on the docker image created by above Dockerfile, the error happens.

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Is there any way to solve this problem? Thanks.


问:
Unable to make function call in template argument
The following program compiles fine.

```<code>#include <bitset>
#include <cmath>

int main()
{
    const int r = std::sqrt(100);
    std::bitset<r> n;
}
</code>```

```<code>$ g++ -Wall -Wextra -pedantic -std=c++11 foo.cpp
$
</code>```

But the following program fails to compile.

```<code>#include <bitset>
#include <cmath>

int main()
{
    std::bitset<std::sqrt(100)> n;
}
</code>```

```<code>$ g++ -Wall -Wextra -pedantic -std=c++11 bar.cpp
bar.cpp: In function ‘int main()’:
bar.cpp:6:31: error: conversion from ‘__gnu_cxx::__enable_if<true, double>::__type {aka double}’ to ‘long unsigned int’ not considered for non-type template argument
     std::bitset<std::sqrt(100)> n;
                               ^
bar.cpp:6:31: error: could not convert template argument ‘std::sqrt<int>(100)’ to ‘long unsigned int’
bar.cpp:6:34: error: invalid type in declaration before ‘;’ token
     std::bitset<std::sqrt(100)> n;
                                  ^
bar.cpp:6:33: warning: unused variable ‘n’ [-Wunused-variable]
     std::bitset<std::sqrt(100)> n;
                                 ^
</code>```

According to me, both C++ programs are equivalent. Why is it that then the second one does not compile whereas the first one does?

Update

Some of the answers are saying that std::sqrt() is generally not declared as constexpr but on gcc has extended it by declaring it constexpr. But it still does not answer my question.

If std::sqrt() is not declared as constexpr, then both programs should fail to compile.

If std::sqrt() is declared as constexpr in gcc, then both programs should compile successfully.

Why is it that only the first program compiles but the second one fails?

答:
The first program might compile for you, but it is not portable because the std::sqrt function is not specified by the standard to be constexpr. It appears that GCC has decided to make it constexpr:

```<code>template<typename _Tp>
  inline _GLIBCXX_CONSTEXPR
  typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
                                  double>::__type
  sqrt(_Tp __x)
  { return __builtin_sqrt(__x); }
</code>```

But another standard library implementation might not have a constexpr std::sqrt function so your first program would not compile there.

Let us instead simplify the code, and modify it a bit so that the relevant concepts are involved exactly:

```<code>constexpr std::size_t r = 10.0;
std::bitset<r> b1;      // OK
std::bitset<10.0> b2;   // ill-formed
</code>```

It really looks as though the declarations of b1 and b2 should be treated the same way, but the rules for implicit conversions of template arguments are more strict than the rules for implicit conversions elsewhere.

According to the standard, when the type of a template argument (here, double) differs from the type of the template parameter it is being passed to (here, std::size_t), only a restricted set of conversion is allowed, namely "conversions permitted in a converted constant expression" ([temp.arg.nontype]/5). According to [expr.const]/3, a converted constant expression can involve only the following conversions:

user-defined conversions

lvalue-to-rvalue conversions

integral promotions

integral conversions other than narrowing conversions

A floating-integral conversion is not allowed in this context, even though it is allowed in the initialization of r.

Body:
The following program compiles fine.

#include <bitset>
#include <cmath>

int main()
{
    const int r = std::sqrt(100);
    std::bitset<r> n;
}

$ g++ -Wall -Wextra -pedantic -std=c++11 foo.cpp
$

But the following program fails to compile.

#include <bitset>
#include <cmath>

int main()
{
    std::bitset<std::sqrt(100)> n;
}

$ g++ -Wall -Wextra -pedantic -std=c++11 bar.cpp
bar.cpp: In function ‘int main()’:
bar.cpp:6:31: error: conversion from ‘__gnu_cxx::__enable_if<true, double>::__type {aka double}’ to ‘long unsigned int’ not considered for non-type template argument
     std::bitset<std::sqrt(100)> n;
                               ^
bar.cpp:6:31: error: could not convert template argument ‘std::sqrt<int>(100)’ to ‘long unsigned int’
bar.cpp:6:34: error: invalid type in declaration before ‘;’ token
     std::bitset<std::sqrt(100)> n;
                                  ^
bar.cpp:6:33: warning: unused variable ‘n’ [-Wunused-variable]
     std::bitset<std::sqrt(100)> n;
                                 ^

According to me, both C++ programs are equivalent. Why is it that then the second one does not compile whereas the first one does?

Update

Some of the answers are saying that std::sqrt() is generally not declared as constexpr but on gcc has extended it by declaring it constexpr. But it still does not answer my question.

If std::sqrt() is not declared as constexpr, then both programs should fail to compile.

If std::sqrt() is declared as constexpr in gcc, then both programs should compile successfully.

Why is it that only the first program compiles but the second one fails?

Body:
The first program might compile for you, but it is not portable because the std::sqrt function is not specified by the standard to be constexpr. It appears that GCC has decided to make it constexpr:

template<typename _Tp>
  inline _GLIBCXX_CONSTEXPR
  typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
                                  double>::__type
  sqrt(_Tp __x)
  { return __builtin_sqrt(__x); }

But another standard library implementation might not have a constexpr std::sqrt function so your first program would not compile there.

Let us instead simplify the code, and modify it a bit so that the relevant concepts are involved exactly:

constexpr std::size_t r = 10.0;
std::bitset<r> b1;      // OK
std::bitset<10.0> b2;   // ill-formed

It really looks as though the declarations of b1 and b2 should be treated the same way, but the rules for implicit conversions of template arguments are more strict than the rules for implicit conversions elsewhere.

According to the standard, when the type of a template argument (here, double) differs from the type of the template parameter it is being passed to (here, std::size_t), only a restricted set of conversion is allowed, namely "conversions permitted in a converted constant expression" ([temp.arg.nontype]/5). According to [expr.const]/3, a converted constant expression can involve only the following conversions:

user-defined conversions

lvalue-to-rvalue conversions

integral promotions

integral conversions other than narrowing conversions

A floating-integral conversion is not allowed in this context, even though it is allowed in the initialization of r.


问:
In VSTS, how do I add an email notification task to the build and release definitions?
I am new to VSTS Continuous Integration and configuring one of my first sets of build and release definitions.

Is there a task I can add that will allow me to notify certain team members of events such as a build failed, or a release is ready?

答:
For build fail notification, you can set on https://account.visualstudio.com/_notifications -> new -> select Build for category -> select A build fails for template -> next -> select other email for Deliver to -> add the email address and separate with semicolon (;) for multiple email addresses -> you can filter for a specific team project -> finish.

For release success notification, there is no present setting for this. You can create your extension for release success email notification. More detail, you can refer sending email notification.


问:
How to specify rel property for a css file in a libraries.yml file?
So I'd like to specify a custom rel property for a css (well, less) file in my libraries.yml file in Drupal 8.

Would something like that possible?

```<code>base:
  version: VERSION
    css:
      theme:
        css/styles.less: { rel: stylesheet/less }
</code>```

The resulting HTML would be:

```<code><link rel="stylesheet/less" href="css/styles.less" media="all" />
</code>```

Thank you!

答:
I'm not shure but you can try this :

```<code>   base:
      version: VERSION
        css:
          theme:
            css/styles.less:
               attributes:
                  rel: stylesheet/less
</code>```

seen on : https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#attributes

EDIT

Or try

```<code> base:
      version: VERSION
        css:
          theme:
            css/styles.less: { rel: stylesheet/less }
</code>```

or :

```<code>base:
 version: VERSION
    css:
      theme:
        css/styles.less:
            attributes : { rel : stylesheet/less }
</code>```

Body:
So I'd like to specify a custom rel property for a css (well, less) file in my libraries.yml file in Drupal 8.

Would something like that possible?

base:
  version: VERSION
    css:
      theme:
        css/styles.less: { rel: stylesheet/less }

The resulting HTML would be:

<link rel="stylesheet/less" href="css/styles.less" media="all" />

Thank you!

Body:
I'm not shure but you can try this :

   base:
      version: VERSION
        css:
          theme:
            css/styles.less:
               attributes:
                  rel: stylesheet/less

seen on : https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#attributes

EDIT

Or try

 base:
      version: VERSION
        css:
          theme:
            css/styles.less: { rel: stylesheet/less }

or :

base:
 version: VERSION
    css:
      theme:
        css/styles.less:
            attributes : { rel : stylesheet/less }


问:
Swift does not support multiple inheritance, How could be achieved?
The following code:

```<code>class City {
    var cityId : String?
    var cityName : String?
}

class Town {
    var townid : String?
    var townName : String?

}

class Address : City , Town {

    var house : String?
    var street: String?

}
</code>```

Generates a compile-time error:

Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'

How can I solve his kind of problem? What approach to follow?

答:
Remark: If you are unsure that inheritance the is right choice for your case, I suggest to check Sulthan's answer.

However, As you mentioned, Swift does not support multiple inheritance. What you should do instead is to let Address class adopts protocols; You can also add Protocol Extensions:

You can extend an existing type to adopt and conform to a new
  protocol, even if you do not have access to the source code for the
  existing type. Extensions can add new properties, methods, and
  subscripts to an existing type, and are therefore able to add any
  requirements that a protocol may demand.

means that you can implement default values/behaviors to a protocol methods/properties.

Referring to your example, it should be similar to:

```<code>protocol City { }

extension City {
    var cityId: String {
        return "Default City ID"
    }

    var cityName: String {
        return "Default City Name"
    }

    // adding method:
    func doSomething() {
        print("Do Something!!")
    }
}

protocol Town { }

extension Town {
    var townid: String {
        return "Default Town ID"
    }

    var townName: String {
        return "Default Town Name"
    }
}

class Address:City, Town {}
</code>```

Output:

```<code>let address = Address()

print(address.cityId) // Defaut City ID
print(address.cityName) // Defaut City Name
print(address.townid) // Default Town ID
print(address.townName) // Default Town Name

address.doSomething() // Do Something!!
</code>```

Also, if you want to add some additional job to a method (similar to super.doSomething()), you do it like this:

```<code>class Address:City, Town {
    func doSomething() {
        (self as City).doSomething()
        print("Addtional Job!!")
    }
}
</code>```

Output:

```<code>let address2 = Address()
address2.doSomething()
// Do Something!!
// Addtional Job!!
</code>```

Take it Further:

For more information, check Protocols and Extensions Documentations.

Also, you might want to watch Protocol-Oriented Programming in Swift Apple Session.

Body:
The following code:

class City {
    var cityId : String?
    var cityName : String?
}

class Town {
    var townid : String?
    var townName : String?

}

class Address : City , Town {

    var house : String?
    var street: String?

}

Generates a compile-time error:

Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'

How can I solve his kind of problem? What approach to follow?

Body:
Remark: If you are unsure that inheritance the is right choice for your case, I suggest to check Sulthan's answer.

However, As you mentioned, Swift does not support multiple inheritance. What you should do instead is to let Address class adopts protocols; You can also add Protocol Extensions:

You can extend an existing type to adopt and conform to a new
  protocol, even if you do not have access to the source code for the
  existing type. Extensions can add new properties, methods, and
  subscripts to an existing type, and are therefore able to add any
  requirements that a protocol may demand.

means that you can implement default values/behaviors to a protocol methods/properties.

Referring to your example, it should be similar to:

protocol City { }

extension City {
    var cityId: String {
        return "Default City ID"
    }

    var cityName: String {
        return "Default City Name"
    }

    // adding method:
    func doSomething() {
        print("Do Something!!")
    }
}

protocol Town { }

extension Town {
    var townid: String {
        return "Default Town ID"
    }

    var townName: String {
        return "Default Town Name"
    }
}

class Address:City, Town {}

Output:

let address = Address()

print(address.cityId) // Defaut City ID
print(address.cityName) // Defaut City Name
print(address.townid) // Default Town ID
print(address.townName) // Default Town Name

address.doSomething() // Do Something!!

Also, if you want to add some additional job to a method (similar to super.doSomething()), you do it like this:

class Address:City, Town {
    func doSomething() {
        (self as City).doSomething()
        print("Addtional Job!!")
    }
}

Output:

let address2 = Address()
address2.doSomething()
// Do Something!!
// Addtional Job!!

Take it Further:

For more information, check Protocols and Extensions Documentations.

Also, you might want to watch Protocol-Oriented Programming in Swift Apple Session.


问:
webpack dev server proxy post requests to local .json file
I have a new project in hand, so I don't have any server-side support, they are not ready yet.

I want to mock my http requests with local json files.

I have two requests on-going:

/entity/get  method is 'GET'

/entity/create  method is 'POST'

And I have two local json files

mock/entity/get.json

mock/entity/create.json

In my config file:

config/index.js:

proxyTable: {

```<code>'/entity':{

    target: 'http://localhost:8080/mock/',

    pathRewrite(path) {

        return url.parse(path).pathname + '.json';

    }

}
</code>```

}

build/dev-server.js

app.use('/mock', express.static('mock'));

Results:

/entity/get, I get what I want.

/entity/create, 404

My question:

Why cannot I get create.json responsed by the express server?

In webpack1.0  I had same question, but I handled the question by turning all post request to get request, the side effect is, I lost all request params during the post-to-get transition. I can live with it but in webpack 2.0 I even don't kown how to config like that.

答:
Question 2 soloved:

config/index.js:

```<code>proxyTable: {

'/entity':{

    target: 'http://localhost:8080/mock/',

    pathRewrite(path, option) {

        option.method = 'GET';

        return url.parse(path).pathname + '.json';

    }

}
</code>```

Body:
I have a new project in hand, so I don't have any server-side support, they are not ready yet.

I want to mock my http requests with local json files.

I have two requests on-going:

/entity/get  method is 'GET'

/entity/create  method is 'POST'

And I have two local json files

mock/entity/get.json

mock/entity/create.json

In my config file:

config/index.js:

proxyTable: {

'/entity':{

    target: 'http://localhost:8080/mock/',

    pathRewrite(path) {

        return url.parse(path).pathname + '.json';

    }

}

}

build/dev-server.js

app.use('/mock', express.static('mock'));

Results:

/entity/get, I get what I want.

/entity/create, 404

My question:

Why cannot I get create.json responsed by the express server?

In webpack1.0  I had same question, but I handled the question by turning all post request to get request, the side effect is, I lost all request params during the post-to-get transition. I can live with it but in webpack 2.0 I even don't kown how to config like that.

Body:
Question 2 soloved:

config/index.js:

proxyTable: {

'/entity':{

    target: 'http://localhost:8080/mock/',

    pathRewrite(path, option) {

        option.method = 'GET';

        return url.parse(path).pathname + '.json';

    }

}


问:
Casting a ListBox.SelectedObjectCollection to a ListBox.ObjectCollection?
Is it possible to cast a ListBox.SelectedObjectCollection to a ListBox.ObjectCollection in C#? If so, how would I go about it?</p>

答:
This is my answer I used to convert Checked list box to list box</p>

```<code>CheckedListBox.CheckedItemCollection s= checkedListBox1.CheckedItems;

        List<object> ns = new List<object>();

        foreach (object ob in s)
        {
            ns.Add(ob);
        }

        listBox1.Items.AddRange(ns.ToArray());
</code>```

Body:
This is my answer I used to convert Checked list box to list box

CheckedListBox.CheckedItemCollection s= checkedListBox1.CheckedItems;

        List<object> ns = new List<object>();

        foreach (object ob in s)
        {
            ns.Add(ob);
        }

        listBox1.Items.AddRange(ns.ToArray());


问:
Sorting two arrays (values,keys), then sorting the keys
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

```<code>int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);
</code>```

Then the arrays would look like this:

```<code>values = {10,10,20,20,30};
keys = {4,1,2,3,5};
</code>```

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

```<code>keys = {1,4,2,3,5};
</code>```

Notice the 1 and 4 values are switched and the order of the value array has not changed.

答: Array.Sort(values,keys) will use the default Comparer to sort the values and keys.  You would need to write a custom Comparer to do what you're describing, and pass your Comparer in to the Array.Sort method.</p>

Body:
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);

Then the arrays would look like this:

values = {10,10,20,20,30};
keys = {4,1,2,3,5};

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

keys = {1,4,2,3,5};

Notice the 1 and 4 values are switched and the order of the value array has not changed.


问:
Linked List: How to Sort Doubly Linked List?
This is the code for my doubly linked list. It works fine. I need help with sorting the data elements of this linked list.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;//global variable

int GetNewNode(int x)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=x;
newNode->prev=NULL;
newNode->next=NULL;
return newNode;
}

int InsertAtHead(int x)
{
struct Node* newNode =GetNewNode(x);
if(head==NULL)//list empty
{
    head=newNode;
    return;
}
head->prev=newNode;
newNode->next=head;
head=newNode;
}

void print()
{
struct Node* temp=head;//start printing from head
printf("Forward: ");
while(temp!=NULL)
{
    printf("%d ",temp->data);
    temp=temp->next;
}
    printf("\n");
}

   int main()
   {
   head=NULL;// initially taking it as null
   InsertAtHead(2);print();
   InsertAtHead(5);print();
   InsertAtHead(3);print();
   InsertAtHead(9);print();

   return 0;
   }
</code>```

I want to sort the Data elements here.
I tried this:

```<code>void sort()
{
struct Node* temp=head;
int numTemp;
while(temp!=NULL)
{
    if(temp->prev > temp->next)
    {
        numTemp=temp->next;
        temp->next= temp->prev;
        temp->prev=numTemp;
    }
}
}
</code>```

But this compares the address, not the data of the linked list, How do i compare data and sort them accordingly ?

答:
head,next and prec in your Node struct are pointers and thus, they will just point to the respective node, in the same way as temp(in sort() function)is the pointer to the node you are currently accessing.

For accessing the data of node pointed by temp, you will do temp->data. Similarly, if you want to access the data of the next node(having address temp->next), you will do temp->next->data.

It seems, there is a problem with iterating through the linked list too.
To iterate forward in the linked list, you have to make temp point to the next node.

```<code>while(temp!=NULL)
{
    ...
    temp=temp->next;
}
</code>```

This is how you can iterate through the list.

Body:
This is the code for my doubly linked list. It works fine. I need help with sorting the data elements of this linked list.

#include <stdio.h>
#include <stdlib.h>

struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;//global variable

int GetNewNode(int x)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=x;
newNode->prev=NULL;
newNode->next=NULL;
return newNode;
}

int InsertAtHead(int x)
{
struct Node* newNode =GetNewNode(x);
if(head==NULL)//list empty
{
    head=newNode;
    return;
}
head->prev=newNode;
newNode->next=head;
head=newNode;
}

void print()
{
struct Node* temp=head;//start printing from head
printf("Forward: ");
while(temp!=NULL)
{
    printf("%d ",temp->data);
    temp=temp->next;
}
    printf("\n");
}

   int main()
   {
   head=NULL;// initially taking it as null
   InsertAtHead(2);print();
   InsertAtHead(5);print();
   InsertAtHead(3);print();
   InsertAtHead(9);print();

   return 0;
   }

I want to sort the Data elements here.
I tried this:

void sort()
{
struct Node* temp=head;
int numTemp;
while(temp!=NULL)
{
    if(temp->prev > temp->next)
    {
        numTemp=temp->next;
        temp->next= temp->prev;
        temp->prev=numTemp;
    }
}
}

But this compares the address, not the data of the linked list, How do i compare data and sort them accordingly ?

Body:
head,next and prec in your Node struct are pointers and thus, they will just point to the respective node, in the same way as temp(in sort() function)is the pointer to the node you are currently accessing.

For accessing the data of node pointed by temp, you will do temp->data. Similarly, if you want to access the data of the next node(having address temp->next), you will do temp->next->data.

It seems, there is a problem with iterating through the linked list too.
To iterate forward in the linked list, you have to make temp point to the next node.

while(temp!=NULL)
{
    ...
    temp=temp->next;
}

This is how you can iterate through the list.


问:
Assingning Refrences in Java
```<code>class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}
</code>```

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?

答:
a, b and c are variables of type A, which means they can hold references to objects of class A or any sub-class of A, which includes the classes B and C.

When you write

```<code>b = c;
</code>```

you are not assigning an an object of class C to a variable of class B (which wouldn't pass compilation), you are assigning a reference to an object of class C (held by the c variable) to a variable of class A.

Title: Assingning Refrences in Java

Body:
class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?

Body:
a, b and c are variables of type A, which means they can hold references to objects of class A or any sub-class of A, which includes the classes B and C.

When you write

b = c;

you are not assigning an an object of class C to a variable of class B (which wouldn't pass compilation), you are assigning a reference to an object of class C (held by the c variable) to a variable of class A.


问:
Avoiding complex if statements
I have the following function

```<code>const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}
</code>```

is there a better way to express this? How would such a code be written in functional programming style

答:
You can use ternary operator. Something like this:

```<code>return type? ( a&&b ? val : ( a?  toPercent(val) : undefined )) : toPx(val);
</code>```

const toPercent=(val)=>{
  return 'toPercent';
}
const toPx=(val)=>{
  return 'toPx';
}
const getVal = (type, a, b, val) => {
    return type? (a && b? val :( a ?  toPercent(val) : undefined)) : toPx(val);
}
console.log(getVal('type',0,0,100));
console.log(getVal('type',1,0,100));
console.log(getVal('type',1,2,100));```

Title: Avoiding complex if statements

Body:
I have the following function

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

is there a better way to express this? How would such a code be written in functional programming style

Body:
You can use ternary operator. Something like this:

return type? ( a&&b ? val : ( a?  toPercent(val) : undefined )) : toPx(val);

const toPercent=(val)=>{
  return 'toPercent';
}
const toPx=(val)=>{
  return 'toPx';
}
const getVal = (type, a, b, val) => {
    return type? (a && b? val :( a ?  toPercent(val) : undefined)) : toPx(val);
}
console.log(getVal('type',0,0,100));
console.log(getVal('type',1,0,100));
console.log(getVal('type',1,2,100));


问:
Why does C# not allow generic properties?
I was wondering why I can not have generic property in non-generic class the way I can have generic methods. I.e.:

```<code>public interface TestClass
{
   IEnumerable<T> GetAllBy<T>(); //this works

   IEnumerable<T> All<T> { get; } //this does not work
}
</code>```

I read @Jon Skeet's answer, but it's just a statement, which most probably is somewhere in the specifications.

My question is why actually it is that way? Was kind of problems were avoided with this limitation?

答:
I made somthing like that.
It type checks at run time.</p>

```<code>public class DataPackage
{
    private dynamic _list;

    public List<T> GetList<T>()
    {
        return (List<T>)_list;
    }

    public void SetList<T>(List<T> list)
    {
        _list = list;
    }

    public string Name { get; set; }
}
</code>```

Body:
I was wondering why I can not have generic property in non-generic class the way I can have generic methods. I.e.:

public interface TestClass
{
   IEnumerable<T> GetAllBy<T>(); //this works

   IEnumerable<T> All<T> { get; } //this does not work
}

I read @Jon Skeet's answer, but it's just a statement, which most probably is somewhere in the specifications.

My question is why actually it is that way? Was kind of problems were avoided with this limitation?

Body:
I made somthing like that.
It type checks at run time.

public class DataPackage
{
    private dynamic _list;

    public List<T> GetList<T>()
    {
        return (List<T>)_list;
    }

    public void SetList<T>(List<T> list)
    {
        _list = list;
    }

    public string Name { get; set; }
}


问:
Is there a perfect solution that can display swf files with Qt 5.7 in ubuntu 16.04?
My project need I achieve this function.

And I'd crawled lots of methods online , unfortunately , they all doesn't work.

I ever used the QAxWidget widget , that works ,but only in Windows OS.

Now I'm in Ubuntu 16.04. So How can I display a flash file in my Qt program ? My Qt version is 5.7 .

I have tried (But it also doesn't work) :

```<code>QWebEngineView view;
QWebEngineSettings *websetting = view.settings();
websetting->setAttribute(QWebEngineSettings::PluginsEnabled, true);
view.load( QUrl(QStringLiteral("/Users/yrd241/Desktop/ic_phiz_action.swf") ));
</code>```

答: Did you try using QWebEngineView with QWebEngineSettings::PluginsEnabled enabled? According to docs you can enable "Pepper Plugin API" which supports Flash player. This feature was introduced in Qt 5.6

Body:
My project need I achieve this function.

And I'd crawled lots of methods online , unfortunately , they all doesn't work.

I ever used the QAxWidget widget , that works ,but only in Windows OS.

Now I'm in Ubuntu 16.04. So How can I display a flash file in my Qt program ? My Qt version is 5.7 .

I have tried (But it also doesn't work) :

QWebEngineView view;
QWebEngineSettings *websetting = view.settings();
websetting->setAttribute(QWebEngineSettings::PluginsEnabled, true);
view.load( QUrl(QStringLiteral("/Users/yrd241/Desktop/ic_phiz_action.swf") ));


问:
Robotlegs AS3-Signals Dispatch signal from ItemRenderer
I have a mediated view with a DataGroup with a custom ItemRenderer. I want when I click a button in the ItemRenderer to dispatch a signal and handle it in my mediator? How can I do that?

Thanks in advance

答: In your item renderer dispatch an event that bubbles, then on your DataGroup add a listener for that event (in your mediator).</p>


Title: Running count for each 2 rows

Body:
I am trying to calculate running count for each 2 rows like below,

CREATE TABLE sales
(
     EmpId INT,
     Yr INT,
     Sales DECIMAL(8,2)
)

INSERT INTO sales (EmpId, Yr, Sales)
VALUES (1, 2005, 12000), (1, 2006, 18000), (1, 2007, 25000),
       (1, 2008, 25000), (1, 2009, 25000),
       (2, 2005, 15000), (2, 2006, 6000), (2, 2007, 6000)

SELECT
    EmpId, Yr, sales,
    SUM(Sales) OVER (PARTITION BY empid ORDER BY empid ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS TotalSales2
FROM
    sales

Output:

EmpId   Yr      sales   TotalSales2
-----------------------------------
  1     2005    12000      12000
  1     2006    18000      30000
  1     2007    25000      55000
  1     2008    25000      68000
  1     2009    25000      75000
  2     2005    15000      15000
  2     2006     6000      21000
  2     2007     6000      27000

But expected output:

EmpId   Yr     Sales    TotalSales2
-----------------------------------
  1     2005    12000   12000
  1     2006    18000   30000
  1     2007    25000   25000
  1     2008    25000   50000
  1     2009    25000   25000
  2     2005    15000   15000
  2     2006     6000   21000
  2     2007     6000    6000

What am I doing wrong in this query?

Note: SQL Servre version is 2012.

Body:
Although answer is already accepted, consider below query also. This will give the required output :

DECLARE @sales TABLE(EmpId INT, Yr INT, Sales DECIMAL(8,2))

INSERT INTO @sales ( EmpId, Yr, Sales )
VALUES  (1, 2005, 12000),
      (1, 2006, 18000),
      (1, 2007, 25000),
      (1, 2008, 25000),
      (1, 2009, 25000),
      (2, 2005, 15000),
      (2, 2006, 6000),
      (2, 2007, 6000)
;WITH SAMPLE_DATA
AS
(
SELECT ROW_NUMBER()over(partition by empid order by (select 100))SNO,* FROM     @Sales
)
SELECT EmpId,Yr,Sales
    ,CASE WHEN (SNO%2=0)
     THEN SALES+
    (
        SELECT Sales FROM SAMPLE_DATA T2 WHERE T2.EmpId=T1.EmpId AND     T2.SNO=T1.SNO-1
    )
    ELSE Sales END
TotalSales2
FROM SAMPLE_DATA T1

OUTPUT

--------------------------------------
--EmpId Yr  Sales   TotalSales2
--------------------------------------
1   2005    12000.00    12000.00
1   2006    18000.00    30000.00
1   2007    25000.00    25000.00
1   2008    25000.00    50000.00
1   2009    25000.00    25000.00
2   2005    15000.00    15000.00
2   2006    6000.00     21000.00
2   2007    6000.00     6000.00
--------------------------------------


问:
Using Click event and Dragend event
I am wanting to have to event on my pins. one that when the user clicks on a pin a click method is called. A second method would be dragend for when the user drags the pin.

I currently have the following event handlers:

```<code>Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
Microsoft.Maps.Events.addHandler(pin, "dragend", endDragHandler);
</code>```

the problem is that when the user only clicks on the pin, the endDragHandler gets called first and then calls the click method.

Any Suggestions on how to fix this?

Thanks

答:
Although the question has already been answered, I found a solution at this CodeProject link, similar to what @johnston suggested above:

Basically on click event of pushpin, the new and old latitude/longitude is being compared in 3 decimal values. If it matches its assumed its a click event, otherwise its a drag event.
I am though amazed as to why Bing team hasn't looked itself into this weird issue, that took me hours to sort out. Bing API should itself address this issue.

Title: Using Click event and Dragend event

Body:
I am wanting to have to event on my pins. one that when the user clicks on a pin a click method is called. A second method would be dragend for when the user drags the pin.

I currently have the following event handlers:

Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
Microsoft.Maps.Events.addHandler(pin, "dragend", endDragHandler);

the problem is that when the user only clicks on the pin, the endDragHandler gets called first and then calls the click method.

Any Suggestions on how to fix this?

Thanks


问:
Replace string from returned string
I have a function which returning HTML form. Before the particular form appended to the HTML, I have to make a string replacement. I have tried to make the replacement however, it returning form without performing replace.

Here's the code sample:

```<code><?php
class test{
    function testing()
    {
        ?>
        <input type="hidden" value="<?php echo 'TEST_TAG' ?>">
        <?php
    }
}
add_action('wp_footer', str_replace('TEST_TAG', wp_create_nonce('submit_of_form_lead'), (new test)->testing()));
?>
</code>```

答:
You are not returning your form code with php but outputing it right away

The ?> is the php closing tag where you effectively say everything i write after this is not php anymore. Also the php echo outputs right away and does not return the string "TEST_TAG". What you can do to solve it is:

```<code><?php
class test{
    function testing()
    {
        return '<input type="hidden" value="TEST_TAG">';
    }
}
add_action('wp_footer', str_replace('TEST_TAG', wp_create_nonce('submit_of_form_lead'), (new test)->testing()));
?>
</code>```

However this honestly would be a strange way to handle that what would be better is add a parameter to the function call and give this to where you call the form.

```<code><?php
class test{
    function testing($value)
    {
        return "<input type='hidden' value='$value'>";
    }
}
add_action('wp_footer', (new test)->testing(wp_create_nonce('submit_of_form_lead')));
?>
</code>```

This should give the same result without having to replace the placeholder.

Title: Replace string from returned string

Body:
I have a function which returning HTML form. Before the particular form appended to the HTML, I have to make a string replacement. I have tried to make the replacement however, it returning form without performing replace.

Here's the code sample:

<?php
class test{
    function testing()
    {
        ?>
        <input type="hidden" value="<?php echo 'TEST_TAG' ?>">
        <?php
    }
}
add_action('wp_footer', str_replace('TEST_TAG', wp_create_nonce('submit_of_form_lead'), (new test)->testing()));
?>

Body:
You are not returning your form code with php but outputing it right away

The ?> is the php closing tag where you effectively say everything i write after this is not php anymore. Also the php echo outputs right away and does not return the string "TEST_TAG". What you can do to solve it is:

<?php
class test{
    function testing()
    {
        return '<input type="hidden" value="TEST_TAG">';
    }
}
add_action('wp_footer', str_replace('TEST_TAG', wp_create_nonce('submit_of_form_lead'), (new test)->testing()));
?>

However this honestly would be a strange way to handle that what would be better is add a parameter to the function call and give this to where you call the form.

<?php
class test{
    function testing($value)
    {
        return "<input type='hidden' value='$value'>";
    }
}
add_action('wp_footer', (new test)->testing(wp_create_nonce('submit_of_form_lead')));
?>

This should give the same result without having to replace the placeholder.


问:
Can I give my facebook messenger chat bot the exclusivity of answering users?
I connected a Facebook messenger bot to a page with several admins. I am not yet very familiar with the facebook messenger platform but it looks like when a user messages our page. Admins see the incoming message and can respond to it. Can I deactivate this ? I want my bot and only my bot to handle incoming message, I don't want admins of the page to be able to interfere in the user experience. I was thinking it should be easy to do but I cannot find how to do that. To recap : I would like my chat bot to have the exclusivity of chatting with users from my facebook page, do you know how to do this ?
Thank you very much</p>

答: Well, according to this Facebook help article, the roles available to your page admins are listed there. Use it as your guide.</p>


问:
Content block overlay fade in/out on click
I'm stumped on a problem with overlay fading in and out to cover a block generated by some JS code.

Below is the link to the work. If you click on any of the continents, a bunch of blocks with the country flags will be generated. You'll also see the gray bar that says "some content". Ideally, I want that bar to be hidden, until I click on one of the flags. At which point, the overlay would slide in over the flag. Then when I click elsewhere outside the block, the overlay would slide out and disappear.

CodePen link.

I tried to set:

```<code>&__block-overlay {
  ....
  opacity: 0;
  ....
}
</code>```

and

```<code>&__block-overlay:active {
  opacity: 0.7;
}
</code>```

But it didn't work.

Any suggestions would be greatly appreciated!!

答:
There's two issues to solve here. The first is the hiding of the 'Some Content' bars. You can achieve that by setting overflow: hidden on their parent, so that they are only visible when over the flag:

```<code>&__block {
  display: inline-block;
  width: 25%;
  margin: 0.5%;
  height: 150px;
  text-align: center;
  position: relative;
  cursor: pointer;
  border-radius: 5px;
  overflow: hidden; /* add this */
</code>```

Then, to toggle the content visibility on successive clicks, use toggleClass() instead of addClass():

```<code>blockClicked(e) {
  const $block = $(e.target.closest('.js-block'));
  $('.details-open').removeClass('details-open');
  $block.toggleClass('details-open');
},
</code>```

Updated CodePen

Body:
I'm stumped on a problem with overlay fading in and out to cover a block generated by some JS code.

Below is the link to the work. If you click on any of the continents, a bunch of blocks with the country flags will be generated. You'll also see the gray bar that says "some content". Ideally, I want that bar to be hidden, until I click on one of the flags. At which point, the overlay would slide in over the flag. Then when I click elsewhere outside the block, the overlay would slide out and disappear.

CodePen link.

I tried to set:

&__block-overlay {
  ....
  opacity: 0;
  ....
}

and

&__block-overlay:active {
  opacity: 0.7;
}

But it didn't work.

Any suggestions would be greatly appreciated!!

Body:
There's two issues to solve here. The first is the hiding of the 'Some Content' bars. You can achieve that by setting overflow: hidden on their parent, so that they are only visible when over the flag:

&__block {
  display: inline-block;
  width: 25%;
  margin: 0.5%;
  height: 150px;
  text-align: center;
  position: relative;
  cursor: pointer;
  border-radius: 5px;
  overflow: hidden; /* add this */

Then, to toggle the content visibility on successive clicks, use toggleClass() instead of addClass():

blockClicked(e) {
  const $block = $(e.target.closest('.js-block'));
  $('.details-open').removeClass('details-open');
  $block.toggleClass('details-open');
},

Updated CodePen


问:
Bootstrap drop down cutting off
I am trying to add a dropdown setting menu to my comments section in a project that I've been working on.

The dropdown menu seems to cut itself off and I am not sure why is that the case.

I tried overflow:visible and z-index:999. but none of them seem to work.

This is a basic comment block that I am trying to include a dropdown in

This is the basic code that I am trying to Implement

```<code><div class="media">
    <a class="pull-left" href="/user/{{shared_scribble.scribble.user.username}}/"><img class="media-object" src="/img.png/"></a>
    <div class="dropdown pull-right">
        <a class="btn dropdown-toggle" data-toggle="dropdown" href="#" style="font-size:10px;padding: 4px 8px;">
            <b data-icon=""></b> <b class="caret"></b>
        </a>
        <ul class="dropdown-menu">
            <li><a href="#"><i class="icon-pencil"></i> Edit</a></li>
            <li><a href="#"><i class="icon-trash"></i> Delete</a></li>
            <li><a href="#"><i class="icon-ban-circle"></i> Ban</a></li>
            <li class="divider"></li>
            <li><a href="#"><i class="i"></i> Make admin</a></li>
        </ul>
    </div>
    <div class="media-body">
        <h4 class="media-heading"><a class="username" href="/user/hi/">Test User</h4>
        <p>
            Main body of the comment
        </p>
    </div>
</div>
</code>```

And this is how my dropdown menu is turning out to be

media CSS

```<code>.media,
.media-body {
  overflow: hidden;
  *overflow: visible;
  zoom: 1;
}
.media,
.media .media {
  margin-top: 15px;
}
.media:first-child {
  margin-top: 0;
}
.media-object {
  display: block;
}
.media-heading {
  margin: 0 0 5px;
}
.media .pull-left {
  margin-right: 10px;
}
.media .pull-right {
  margin-left: 10px;
}
.media-list {
  margin-left: 0;
  list-style: none;
}
</code>```

答:
Get this quite often on projects I inherit; tends to be a case of one of the parent elements having

```<code>overflow:hidden
</code>```

Once I remove this it seems to work as expected (as long as your design doesn't rely on this property).

Title: Bootstrap drop down cutting off

Body:
I am trying to add a dropdown setting menu to my comments section in a project that I've been working on.

The dropdown menu seems to cut itself off and I am not sure why is that the case.

I tried overflow:visible and z-index:999. but none of them seem to work.

This is a basic comment block that I am trying to include a dropdown in

This is the basic code that I am trying to Implement

 Edit

 Delete

 Ban

 Make admin

Test User

            Main body of the comment

And this is how my dropdown menu is turning out to be

media CSS

.media,
.media-body {
  overflow: hidden;
  *overflow: visible;
  zoom: 1;
}
.media,
.media .media {
  margin-top: 15px;
}
.media:first-child {
  margin-top: 0;
}
.media-object {
  display: block;
}
.media-heading {
  margin: 0 0 5px;
}
.media .pull-left {
  margin-right: 10px;
}
.media .pull-right {
  margin-left: 10px;
}
.media-list {
  margin-left: 0;
  list-style: none;
}

Body:
Get this quite often on projects I inherit; tends to be a case of one of the parent elements having

overflow:hidden

Once I remove this it seems to work as expected (as long as your design doesn't rely on this property).

ContentLicense: CC BY-SA 4.0


问:
Using response from one API call to do another API Call
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

```<code>var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}
</code>```

And in my view it would look something like this:

```<code><div ng-repeat = "song in songlist">
    <div>{{ song.rank }}</div>
    <div>
        <img ng-src=" {{ spotifyImg[$index] }}"/>
    </div>
</div>
</code>```

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

答:
The problem is that getSpotify is run asynchronous, when the responses to these calls come in, i is probably set to spotifyID.length - 1 which means that all callback functions set the $scope.spotifyImg[spotifyID.length - 1] element.

Try this:

$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            $scope.getImage(data[i].spotify_id, i);
        }
});

$scope.getImage = function(id, index) {
  musicService.getSpotify(id).then(function(data){
      $scope.spotifyImg[index] = data.album.images[0].url;
  });
}```

Body:
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}

And in my view it would look something like this:

{{ song.rank }}

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?


问:
Why to use where clause even when Having can be used for the same purpose?
It is known that Having clause works same as where clause but where clause only works with present table columns and not aggregate columns.

Can we always use Having and is there some specific functionality which where is preferable than having, like performance issues?

答:
The only instance I have ever seen where (no pun intended) WHERE and HAVING could possibly be used interchangably is with the MySQL database, and for certain situations.

In a MySQL query which does not have a GROUP BY clause, HAVING would appear to do the same thing which WHERE does.  Consider the following query:

```<code>SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
WHERE some_computed_column = 10    -- WRONG!
</code>```

In the above query, we tried to use a computed column alias in the WHERE clause, but did not get away with it.  The reason for this is that MySQL cannot guarantee that the alias will be available at the time the WHERE clause is evaluated.  This would appear to leave us with only the following option:

```<code>SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
WHERE (a + b + c) / (d + e) = 10    -- correct, but ugly
</code>```

The above query is correct, will run, but is ugly and possibly verbose, because we had to repeat the logic of the computed column again.  However, it is possible to use the HAVING clause as an alternative, as the alias will be available at that point in the query.  Hence, we could write the following:

```<code>SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
HAVING some_computed_column = 10    -- allowed, and not ugly
</code>```

But keep in mind that not every database will accept the above query.  If you want a database independent way of avoiding the verbosity, you could wrap the original query in a subquery, and then query that, e.g.:

```<code>SELECT t.some_computed_column
FROM
(
    SELECT (a + b + c) / (d + e) AS some_computed_column
    FROM yourTable
) t
WHERE t.some_computed_column = 10
</code>```

Body:
The only instance I have ever seen where (no pun intended) WHERE and HAVING could possibly be used interchangably is with the MySQL database, and for certain situations.

In a MySQL query which does not have a GROUP BY clause, HAVING would appear to do the same thing which WHERE does.  Consider the following query:

SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
WHERE some_computed_column = 10    -- WRONG!

In the above query, we tried to use a computed column alias in the WHERE clause, but did not get away with it.  The reason for this is that MySQL cannot guarantee that the alias will be available at the time the WHERE clause is evaluated.  This would appear to leave us with only the following option:

SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
WHERE (a + b + c) / (d + e) = 10    -- correct, but ugly

The above query is correct, will run, but is ugly and possibly verbose, because we had to repeat the logic of the computed column again.  However, it is possible to use the HAVING clause as an alternative, as the alias will be available at that point in the query.  Hence, we could write the following:

SELECT (a + b + c) / (d + e) AS some_computed_column
FROM yourTable
HAVING some_computed_column = 10    -- allowed, and not ugly

But keep in mind that not every database will accept the above query.  If you want a database independent way of avoiding the verbosity, you could wrap the original query in a subquery, and then query that, e.g.:

SELECT t.some_computed_column
FROM
(
    SELECT (a + b + c) / (d + e) AS some_computed_column
    FROM yourTable
) t
WHERE t.some_computed_column = 10


问:
How do I get my list in as a tooltip
In the code below, I would like the return from GetChainDetails to go where i have "I WANT MY LIST HERE" in GetChains method.  Not sure how to accomplish or what other way to do this.</p>

```<code>public static IEnumerable GetChains(int actGroupid, int dispid)
    {
        EEDBEntities db = new EEDBEntities();
        var query = from c in db.Chains
                    where c.Activity_Basis.activity_group_id == actGroupid && c.Activity_Basis.discipline_id == dispid
                    select new
                    {
                        ChainID = c.ChainID,
                        ChainDesc =  @"<span data-toggle=""tooltip"" title =""" + I WANT MY LIST HERE + @""">" + c.ChainID + "</span>"
                    };
        return query.ToList();
    }

    public string GetChainDetails(string chainID)
    {
        string sStep = null;
        var chainDetailList = from c in db.Chains_Detail
                              where c.chainID == chainID
                              orderby c.Order
                              select new
                              {
                                  Order = c.Order,
                                  Step = c.Step
                              };
        foreach (var oItem in chainDetailList.ToList())
        {
            sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
        }
        return sStep;
    }
</code>```

答:
Your method public string GetChainDetails(string chainID) is not static. Perhaps this is the reason you are getting error. Make it static and try and run the code.

```<code>public static string GetChainDetails(string chainID)
</code>```

Also you can follow this approach :

```<code>class X
    {
        public int Property1;
        public int Property2;

        public string ChainID;
        public string MyListToolTipText;
    }

    class Y
    {
        public string ChainID;
        public string ChainDesc;
    }
</code>```

And your main code

```<code>class Program
    {
    static void Main()
    {
        var myResult = GetChains(1, 1);
        foreach (var result in myResult)
        {
            result.ChainDesc = GetChainDetails(result.ChainID);
        }
        //you can use either foreach or linq
        //var m = myResult.Select(result => result = new Y { ChainID = result.ChainID, ChainDesc = GetChainDetails(result.ChainDesc) });
    }

    public static IEnumerable<Y> GetChains(int actGroupid, int dispid)
    {
        var Chains = new List<X>();
        var query = from c in Chains
                    where c.Property1 == actGroupid && c.Property2 == dispid
                    select new Y
                    {
                        ChainID = c.ChainID,
                        ChainDesc =  @"<span data-toggle=""tooltip"" title =""" + c.MyListToolTipText + @""">" + c.ChainID + "</span>"
                    };
        return query.ToList<Y>();
    }

    public static string GetChainDetails(string chainID)
    {
        string sStep = null;
        var chainDetailList = from c in db.Chains_Detail
                              where c.chainID == chainID
                              orderby c.Order
                              select new
                              {
                                  Order = c.Order,
                                  Step = c.Step
                              };
        foreach (var oItem in chainDetailList.ToList())
        {
            sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
        }
        return sStep;
    }
}
</code>```

Hence after calling GetChains, I am modifying each member property.

Title: How do I get my list in as a tooltip

Body:
In the code below, I would like the return from GetChainDetails to go where i have "I WANT MY LIST HERE" in GetChains method.  Not sure how to accomplish or what other way to do this.

public static IEnumerable GetChains(int actGroupid, int dispid)
    {
        EEDBEntities db = new EEDBEntities();
        var query = from c in db.Chains
                    where c.Activity_Basis.activity_group_id == actGroupid && c.Activity_Basis.discipline_id == dispid
                    select new
                    {
                        ChainID = c.ChainID,
                        ChainDesc =  @"" + c.ChainID + ""
                    };
        return query.ToList();
    }

    public string GetChainDetails(string chainID)
    {
        string sStep = null;
        var chainDetailList = from c in db.Chains_Detail
                              where c.chainID == chainID
                              orderby c.Order
                              select new
                              {
                                  Order = c.Order,
                                  Step = c.Step
                              };
        foreach (var oItem in chainDetailList.ToList())
        {
            sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
        }
        return sStep;
    }

Body:
Your method public string GetChainDetails(string chainID) is not static. Perhaps this is the reason you are getting error. Make it static and try and run the code.

public static string GetChainDetails(string chainID)

Also you can follow this approach :

class X
    {
        public int Property1;
        public int Property2;

        public string ChainID;
        public string MyListToolTipText;
    }

    class Y
    {
        public string ChainID;
        public string ChainDesc;
    }

And your main code

class Program
    {
    static void Main()
    {
        var myResult = GetChains(1, 1);
        foreach (var result in myResult)
        {
            result.ChainDesc = GetChainDetails(result.ChainID);
        }
        //you can use either foreach or linq
        //var m = myResult.Select(result => result = new Y { ChainID = result.ChainID, ChainDesc = GetChainDetails(result.ChainDesc) });
    }

    public static IEnumerable<Y> GetChains(int actGroupid, int dispid)
    {
        var Chains = new List<X>();
        var query = from c in Chains
                    where c.Property1 == actGroupid && c.Property2 == dispid
                    select new Y
                    {
                        ChainID = c.ChainID,
                        ChainDesc =  @"<span data-toggle=""tooltip"" title =""" + c.MyListToolTipText + @""">" + c.ChainID + "</span>"
                    };
        return query.ToList<Y>();
    }

    public static string GetChainDetails(string chainID)
    {
        string sStep = null;
        var chainDetailList = from c in db.Chains_Detail
                              where c.chainID == chainID
                              orderby c.Order
                              select new
                              {
                                  Order = c.Order,
                                  Step = c.Step
                              };
        foreach (var oItem in chainDetailList.ToList())
        {
            sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
        }
        return sStep;
    }
}

Hence after calling GetChains, I am modifying each member property.