问:
Its possible to show JDatePickerImpl on right side of button instated of down in java?
I am using JDatePickerImpl and want to show right or left side of button
instated of bottom please help me out
Code :

```<code>UtilDateModel model = null;
Properties property = null;
JDatePanelImpl datePanel = null;

try{

    model = new UtilDateModel();
    model.setSelected(true);
    property = new Properties();
    property.put("text.today", "Today");
    property.put("text.month", "Month");
    property.put("text.year", "Year");
    datePanel = new JDatePanelImpl(model,property);

    f_ObjDateLabelFormatter = new DateLabelFormatter();
    m_fromDateChooser = new
    JDatePickerImpl(datePanel,f_ObjDateLabelFormatter);

    m_fromDateChooser.setBounds(102, 18, 161, 36);
    m_fromDateChooser.getComponent(1).setEnabled(false);
    fromAndto_DChooser_Panel.add(m_fromDateChooser);
    java.util.Date m_DtFromDate  = (Date)
    m_fromDateChooser.getModel().getValue();

    fromCalendar = Calendar.getInstance();
    fromCalendar.setTime(m_DtFromDate);
    m_DtFromDate = null;
    fromDatePickerClicked();
 }
</code>```

Thanks

答:
In JDatePickerImpl update this method

```<code>/**
 * Called internally to popup the dates.
 */
private void showPopup() {
    if (popup == null){
        PopupFactory fac = new PopupFactory();
        Point xy = getLocationOnScreen();
        datePanel.setVisible(true);

        int width = button.getWidth();
        int height = formattedTextField.getHeight();

        popup = fac.getPopup(this, datePanel, (int) (xy.getX() - width), (int) (xy.getY() - height + this.getHeight()));
        popup.show();
    }
}
</code>```

Added width and height to show it to the left of the button hiding the formattedTextField.

Body:
I am using JDatePickerImpl and want to show right or left side of button
instated of bottom please help me out
Code :

UtilDateModel model = null;
Properties property = null;
JDatePanelImpl datePanel = null;

try{

    model = new UtilDateModel();
    model.setSelected(true);
    property = new Properties();
    property.put("text.today", "Today");
    property.put("text.month", "Month");
    property.put("text.year", "Year");
    datePanel = new JDatePanelImpl(model,property);

    f_ObjDateLabelFormatter = new DateLabelFormatter();
    m_fromDateChooser = new
    JDatePickerImpl(datePanel,f_ObjDateLabelFormatter);

    m_fromDateChooser.setBounds(102, 18, 161, 36);
    m_fromDateChooser.getComponent(1).setEnabled(false);
    fromAndto_DChooser_Panel.add(m_fromDateChooser);
    java.util.Date m_DtFromDate  = (Date)
    m_fromDateChooser.getModel().getValue();

    fromCalendar = Calendar.getInstance();
    fromCalendar.setTime(m_DtFromDate);
    m_DtFromDate = null;
    fromDatePickerClicked();
 }

Thanks

Body:
In JDatePickerImpl update this method

/**
 * Called internally to popup the dates.
 */
private void showPopup() {
    if (popup == null){
        PopupFactory fac = new PopupFactory();
        Point xy = getLocationOnScreen();
        datePanel.setVisible(true);

        int width = button.getWidth();
        int height = formattedTextField.getHeight();

        popup = fac.getPopup(this, datePanel, (int) (xy.getX() - width), (int) (xy.getY() - height + this.getHeight()));
        popup.show();
    }
}

Added width and height to show it to the left of the button hiding the formattedTextField.


来源: stackexchange

问:
Dynamically controlling sprite blit order with pygame
I'm currently writing a Tower Defence game. Everything works fine but there's a visual issue that's bugging me.

Basically, a sprite that has a lower rect.y and should be higher on the map to pass behind a slower mob with a higher rect.y, can be blitted after (and therefore in front of) the foreground sprite.

I could fix it, but not while keeping the random spread-out spawn points that I like.

Could anybody suggest anything to help? I omitted irrelevant code, so there's not much to sift through.

```<code>class Pokemon(pygame.sprite.Sprite):
    def __init__(self, name, health, speed, attack, typeOf, typeOf2, level, order):
        pygame.sprite.Sprite.__init__(self)
        self.order = order
        self.image = pygame.image.load('C:/Users/#/#/#/pygames/tower_defense/Distributable/images/POKEMON/%sright.png'%(name))

        self.rect = self.image.get_rect()
        # X/Y axis locations
        self.rect.centerx = 0-self.rect.width - self.order*100
        self.rect.centery = random.randint(500, 540)
</code>```

Then the creation block -

```<code>for e in range(numberOfEnemies):
    poke = random.randint(1, 2)
    if poke == 1:
        level = random.randint(2, 5)
        Pidgey = Pokemon('Pidgey', 15, 2, 5, 'Normal', 'Flying', level, e)
        enemies.append(Pidgey)
        enemy_sprites.add(Pidgey)
    else:
        level = random.randint(2, 4)
        Rattata = Pokemon('Rattata', 13, 3, 5, 'Normal', None, level, e)
        enemies.append(Rattata)
        enemy_sprites.add(Rattata)
    enemyNumber += 1
</code>```

答:
If you need to control the layers of the sprites, you can use a LayeredUpdates sprite group. The sprites need a self._layer attribute or you can pass the layer when you add the sprite to the group, e.g.:

```<code>layered_group.add(sprite, layer=desired_layer)
</code>```

When a sprite is moved, you can call the change_layer method of the sprite group:

```<code>layered_group.change_layer(sprite, sprite.rect.bottom)
</code>```

However, if you have to update the layers of all sprites each frame, it would be more efficient to sort the sprites by their rect.bottom position, iterate over the list and blit them:

```<code>blit = screen.blit  # Local variable to improve the performance.
for sprite in sorted(all_sprites, key=lambda spr: spr.rect.bottom):
    blit(sprite.image, sprite.rect)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently writing a Tower Defence game. Everything works fine but there's a visual issue that's bugging me.

Basically, a sprite that has a lower rect.y and should be higher on the map to pass behind a slower mob with a higher rect.y, can be blitted after (and therefore in front of) the foreground sprite.

I could fix it, but not while keeping the random spread-out spawn points that I like.

Could anybody suggest anything to help? I omitted irrelevant code, so there's not much to sift through.

class Pokemon(pygame.sprite.Sprite):
    def __init__(self, name, health, speed, attack, typeOf, typeOf2, level, order):
        pygame.sprite.Sprite.__init__(self)
        self.order = order
        self.image = pygame.image.load('C:/Users/#/#/#/pygames/tower_defense/Distributable/images/POKEMON/%sright.png'%(name))

        self.rect = self.image.get_rect()
        # X/Y axis locations
        self.rect.centerx = 0-self.rect.width - self.order*100
        self.rect.centery = random.randint(500, 540)

Then the creation block -

for e in range(numberOfEnemies):
    poke = random.randint(1, 2)
    if poke == 1:
        level = random.randint(2, 5)
        Pidgey = Pokemon('Pidgey', 15, 2, 5, 'Normal', 'Flying', level, e)
        enemies.append(Pidgey)
        enemy_sprites.add(Pidgey)
    else:
        level = random.randint(2, 4)
        Rattata = Pokemon('Rattata', 13, 3, 5, 'Normal', None, level, e)
        enemies.append(Rattata)
        enemy_sprites.add(Rattata)
    enemyNumber += 1

Body:
If you need to control the layers of the sprites, you can use a LayeredUpdates sprite group. The sprites need a self._layer attribute or you can pass the layer when you add the sprite to the group, e.g.:

layered_group.add(sprite, layer=desired_layer)

When a sprite is moved, you can call the change_layer method of the sprite group:

layered_group.change_layer(sprite, sprite.rect.bottom)

However, if you have to update the layers of all sprites each frame, it would be more efficient to sort the sprites by their rect.bottom position, iterate over the list and blit them:

blit = screen.blit  # Local variable to improve the performance.
for sprite in sorted(all_sprites, key=lambda spr: spr.rect.bottom):
    blit(sprite.image, sprite.rect)


问:
Angular 2/4 preloader for all routes available in the application
I have created a preloader service for an angular application, that displays the preloader below the top navigation. I need to show the preloader while navigating from one route to another and for all routes available within the application. As of now I have implemented preloader service within all the routes in my application. But with this approach I'll have to write the same code repeatedly for all the routes. I feel there must be a way to avoid this but I'm unable to find the exact solution.</p>

答:
Provide the service on bootstrapped Angular Module, so that the service is globally accessible (Dependency Injection will provide on every component the same instance) and will exist for full lifetime of the Application (Singelton), then subscribe to 'route.events' (is an Observable) to get notified via different events (NavigationStart, NavigationEnd etc.) when the route change.

When you need to read router configuration use 'router.config' (is an Array).

Add service as argument on your component constructor and get what you need to display.


问:
What's a cool way to StopPlay(); a <object id="myflashvideo"> with JavaScript?
I heard that I can control Flash via Javascript.. but I really need some advice about the possibilitys of it. I have a  Flash Video Movie .flv, I dont know if this makes a difference, which contains a navigation .swf.

HTML

```<code><div class="video">
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" style="position:absolute;z-index:0;"width="809" height="459" id="FLVPlayer">
              <param name="movie" value="FLVPlayer_Progressive.swf" />
              <param name="quality" value="high" />
              <param name="wmode" value="transparent" />
              <param name="scale" value="noscale" />
              <param name="salign" value="lt" />
              <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
              <param name="swfversion" value="8,0,0,0" />
              <!-- Dieses param-Tag fordert Benutzer von Flash Player 6.0 r65 und höher auf, die aktuelle Version von Flash Player herunterzuladen. Wenn Sie nicht wünschen, dass die Benutzer diese Aufforderung sehen, löschen Sie dieses Tag. -->
              <param name="expressinstall" value="scripts/expressInstall.swf" />
              <!-- Das nächste Objekt-Tag ist für Nicht-IE-Browser vorgesehen. Blenden Sie es daher mit IECC in IE aus. -->
              <!--[if !IE]>-->
              <object id="FLVPLayer" type="application/x-shockwave-flash" data="FLVPlayer_Progressive.swf" width="809" height="459">
                <!--<![endif]-->
                <param name="quality" value="high" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="salign" value="lt" />
                <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
                <param name="swfversion" value="8,0,0,0" />
                <param name="expressinstall" value="scripts/expressInstall.swf" />
                <!-- Im Browser wird für Benutzer von Flash Player 6.0 und älteren Versionen der folgende alternative Inhalt angezeigt. -->
                <div>
                  <h4>Für den Inhalt dieser Seite ist eine neuere Version von Adobe Flash Player erforderlich.</h4>
                  <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Adobe Flash Player herunterladen" /></a></p>
                </div>
                <!--[if !IE]>-->
              </object>
              <!--<![endif]-->
            </object>
          </div>
</code>```

Pseudo Javascript (btw I use JQuery on the website.. maybe we can short code with that, but not required)

```<code>GetDocumentObjectID("FLVPlayer").StopPlay();
</code>```

Is there a cool, easy way to get this done? I prioritize IE 8,7.. but it is okay if it worked in all other browsers too.

答:
i'm no flash expert, but i think that if you want to interact with the swf via javascript, you should have methods built in the swf.

ex :  if your flash movie has a method "stop" that stops the movie, you could call the same method from javascript and have the same results :

document.getElementById('FLVPlayer').stop();

I don't know about cool, but this certainly should be easy.

ContentLicense: CC BY-SA 2.5

Body:
I heard that I can control Flash via Javascript.. but I really need some advice about the possibilitys of it. I have a  Flash Video Movie .flv, I dont know if this makes a difference, which contains a navigation .swf.

HTML

            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" style="position:absolute;z-index:0;"width="809" height="459" id="FLVPlayer">
              <param name="movie" value="FLVPlayer_Progressive.swf" />
              <param name="quality" value="high" />
              <param name="wmode" value="transparent" />
              <param name="scale" value="noscale" />
              <param name="salign" value="lt" />
              <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
              <param name="swfversion" value="8,0,0,0" />

              <param name="expressinstall" value="scripts/expressInstall.swf" />

              <object id="FLVPLayer" type="application/x-shockwave-flash" data="FLVPlayer_Progressive.swf" width="809" height="459">

                <param name="quality" value="high" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="salign" value="lt" />
                <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
                <param name="swfversion" value="8,0,0,0" />
                <param name="expressinstall" value="scripts/expressInstall.swf" />

Für den Inhalt dieser Seite ist eine neuere Version von Adobe Flash Player erforderlich.

              </object>

            </object>

Pseudo Javascript (btw I use JQuery on the website.. maybe we can short code with that, but not required)

GetDocumentObjectID("FLVPlayer").StopPlay();

Is there a cool, easy way to get this done? I prioritize IE 8,7.. but it is okay if it worked in all other browsers too.


问:
Having a trouble with "database is locked" error
I've been searching since 2 days ago to fix this error pop up when i tried to show database values on jComboBox(variable named "nama_supplier"). After the value appeared on that jComboBox, i want to catch the other columns in database where the "nama_supplier" data was chosen, the code is:

```<code>private void pilih_supplier(){
    java.sql.Connection koneksi = new DBKoneksi().konek();

    try {
                String sqlSupplier = "SELECT * FROM tabel_supplier ORDER BY nama_supplier asc";
                PreparedStatement stmt = koneksi.prepareStatement(sqlSupplier);
                ResultSet rqs=stmt.executeQuery();
                while (rqs.next()) {
                    String pat = rqs.getString("nama_supplier");
                    nama_supplier.addItem(pat);
                    }
                    String select_supplier = (String) nama_supplier.getSelectedItem();

                   String sqlSelectSupplier = "SELECT * FROM tabel_supplier where nama_supplier = '"+select_supplier+"'";
                   PreparedStatement stmt1 = koneksi.prepareStatement(sqlSupplier);
                   ResultSet res=stmt1.executeQuery();
                   while (res.next()) {
                    String add1 = res.getString("kode_barang");
                    kode_barang.setText(add1);
                    String add2 = res.getString("nama_barang");
                    nama_barang.setText(add2);
                    String add3 = res.getString("harga");
                    harga.setText(add3);
                    }
                //rqs.close();
                //res.close();
                //stmt1.close();
                //koneksi.close();
        }

        catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

rqs.close();
res.close();
stmt1.close();
koneksi.close();   //these 4 codes should remove the error, but it doesn't work
</code>```

Also, i've tried to use that 4 codes in finally{} method after try{} but it didn't worked either

Any suggest will accepted

答:
Found this solution , still using 2 connection but i'm separating them in 2 classes, this is the fix code. All credits to this man http://rahmadfaisal.blogspot.co.id/2015/03/tutorial-menampilkan-isi-database.html</p>

```<code>public void tampil()
{
    try {
    java.sql.Connection koneksi = new DBKoneksi().konek();
    Statement stt = koneksi.createStatement();
    String sql = "select nama_supplier, kode_barang, nama_barang, harga from tabel_supplier where nama_supplier='"+nama_select_supplier.getSelectedItem()+"'";
    ResultSet res = stt.executeQuery(sql);

    while(res.next()){
        Object[] ob = new Object[3];
        ob[0]=  res.getString(2);
        ob[1]= res.getString(3);
        ob[2]= res.getString(4);

        kode_barang.setText((String) ob[0]);
        nama_barang.setText((String) ob[1]);
        harga.setText((String) ob[2]);
    }
    res.close(); stt.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public void tampil_combo()
{
    try {
    java.sql.Connection koneksi = new DBKoneksi().konek();
    Statement stt = koneksi.createStatement();
    String sql = "select nama_supplier from tabel_supplier order by nama_supplier asc";
    ResultSet res = stt.executeQuery(sql);

    while(res.next()){
        Object[] ob = new Object[3];
        ob[0] = res.getString(1);

        nama_select_supplier.addItem((String) ob[0]);
    }
    res.close(); stt.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
</code>```

Body:
I've been searching since 2 days ago to fix this error pop up when i tried to show database values on jComboBox(variable named "nama_supplier"). After the value appeared on that jComboBox, i want to catch the other columns in database where the "nama_supplier" data was chosen, the code is:

private void pilih_supplier(){
    java.sql.Connection koneksi = new DBKoneksi().konek();

    try {
                String sqlSupplier = "SELECT * FROM tabel_supplier ORDER BY nama_supplier asc";
                PreparedStatement stmt = koneksi.prepareStatement(sqlSupplier);
                ResultSet rqs=stmt.executeQuery();
                while (rqs.next()) {
                    String pat = rqs.getString("nama_supplier");
                    nama_supplier.addItem(pat);
                    }
                    String select_supplier = (String) nama_supplier.getSelectedItem();

                   String sqlSelectSupplier = "SELECT * FROM tabel_supplier where nama_supplier = '"+select_supplier+"'";
                   PreparedStatement stmt1 = koneksi.prepareStatement(sqlSupplier);
                   ResultSet res=stmt1.executeQuery();
                   while (res.next()) {
                    String add1 = res.getString("kode_barang");
                    kode_barang.setText(add1);
                    String add2 = res.getString("nama_barang");
                    nama_barang.setText(add2);
                    String add3 = res.getString("harga");
                    harga.setText(add3);
                    }
                //rqs.close();
                //res.close();
                //stmt1.close();
                //koneksi.close();
        }

        catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

rqs.close();
res.close();
stmt1.close();
koneksi.close();   //these 4 codes should remove the error, but it doesn't work

Also, i've tried to use that 4 codes in finally{} method after try{} but it didn't worked either

Any suggest will accepted

Body:
Found this solution , still using 2 connection but i'm separating them in 2 classes, this is the fix code. All credits to this man http://rahmadfaisal.blogspot.co.id/2015/03/tutorial-menampilkan-isi-database.html

public void tampil()
{
    try {
    java.sql.Connection koneksi = new DBKoneksi().konek();
    Statement stt = koneksi.createStatement();
    String sql = "select nama_supplier, kode_barang, nama_barang, harga from tabel_supplier where nama_supplier='"+nama_select_supplier.getSelectedItem()+"'";
    ResultSet res = stt.executeQuery(sql);

    while(res.next()){
        Object[] ob = new Object[3];
        ob[0]=  res.getString(2);
        ob[1]= res.getString(3);
        ob[2]= res.getString(4);

        kode_barang.setText((String) ob[0]);
        nama_barang.setText((String) ob[1]);
        harga.setText((String) ob[2]);
    }
    res.close(); stt.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public void tampil_combo()
{
    try {
    java.sql.Connection koneksi = new DBKoneksi().konek();
    Statement stt = koneksi.createStatement();
    String sql = "select nama_supplier from tabel_supplier order by nama_supplier asc";
    ResultSet res = stt.executeQuery(sql);

    while(res.next()){
        Object[] ob = new Object[3];
        ob[0] = res.getString(1);

        nama_select_supplier.addItem((String) ob[0]);
    }
    res.close(); stt.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}


问:
Parsing irregular JSON fields in Python
Consider this json format:

```<code>{
"HostSystem(\"host-527\")": {},
"HostSystem(\"host-487\")": {},
"HostSystem(\"host-482\")": {
    "hardware.cpuInfo.numCpuThreads": 2,
    "name": "192.168.1.1",
    "config.network.consoleVnic": [],
    "capability.perVmSwapFiles": true,
    "capability.maxRunningVMs": 0,
    "config.dateTimeInfo.timeZone.name": "UTC",
}
</code>```

I'd like to parse out 'name'  and 'hardware.cpuInfo.numCpuThreads' from each 'HostSystem' but I'm failing to read the key properly and it doesn't appear that I can use a wildcard.

This is my starter code to test out reading 'HostSystem *' and its failing miserably.

```<code>import json

with open("blob.json") as json_data:
    data = json.load(json_data)
    print data['HostSystem *']
</code>```

Thanks for your suggestions.

答:
Is your json data copied properly? If so, you're failing parsing json data because it's not valid format.

Check whether your json format is in a correct format in Online Json Editor (http://www.jsoneditoronline.org/). Your should delete comma at the end of "config.dateTimeInfo.timeZone.name": "UTC", and add } after it.

Title: Parsing irregular JSON fields in Python

Body:
Consider this json format:

{
"HostSystem(\"host-527\")": {},
"HostSystem(\"host-487\")": {},
"HostSystem(\"host-482\")": {
    "hardware.cpuInfo.numCpuThreads": 2,
    "name": "192.168.1.1",
    "config.network.consoleVnic": [],
    "capability.perVmSwapFiles": true,
    "capability.maxRunningVMs": 0,
    "config.dateTimeInfo.timeZone.name": "UTC",
}

I'd like to parse out 'name'  and 'hardware.cpuInfo.numCpuThreads' from each 'HostSystem' but I'm failing to read the key properly and it doesn't appear that I can use a wildcard.

This is my starter code to test out reading 'HostSystem *' and its failing miserably.

import json

with open("blob.json") as json_data:
    data = json.load(json_data)
    print data['HostSystem *']

Thanks for your suggestions.


问:
How do I PIVOT on an XML column?
Is it possible, using SQL Server 2014 Standard Edition, to PIVOT on the value of an XML column name?  Ultimately I'd like to take this:

```<code><table>
  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" /><----THIS IS THE COLUMN ON WHICH I WOULD LIKE TO PIVOT
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />
</table>
</code>```

....and create these results:

```<code>DefaultKey  DESC    ec_amount   ec_exrate   ec_total    ItemNo      UOM
1           DACS    5000        1           5000        PVT-C30     EA
2           DACS    1500        5           7500        PVT-C30     EA
</code>```

I've searched the Stack Overflow site and of everything I came across, these two posts came close, but they don't quite get me there:

SQL Pivot using an XML column

How do I Pivot on an XML column's attributes in T-SQL

My apologies if this has already been addressed and I simply gave up too soon.

答:
No need for pivoting... Try this</p>

```<code>DECLARE @xml XML=N'<table>
  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" />
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />
</table>';

SELECT r.value(N'(columns/column[@name="DefaultKey"]/@value)[1]',N'int') AS DefaultKey
      ,r.value(N'(columns/column[@name="DESC"]/@value)[1]',N'nvarchar(max)') AS [DESC]
      ,r.value(N'(columns/column[@name="ec_amount"]/@value)[1]',N'decimal(10,4)') AS ec_amount
      --similar with your other elements
FROM @xml.nodes(N'/table/rows/row') AS A(r)
</code>```

Title: How do I PIVOT on an XML column?

Body:
Is it possible, using SQL Server 2014 Standard Edition, to PIVOT on the value of an XML column name?  Ultimately I'd like to take this:

  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" /><----THIS IS THE COLUMN ON WHICH I WOULD LIKE TO PIVOT
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />

....and create these results:

DefaultKey  DESC    ec_amount   ec_exrate   ec_total    ItemNo      UOM
1           DACS    5000        1           5000        PVT-C30     EA
2           DACS    1500        5           7500        PVT-C30     EA

I've searched the Stack Overflow site and of everything I came across, these two posts came close, but they don't quite get me there:

SQL Pivot using an XML column

How do I Pivot on an XML column's attributes in T-SQL

My apologies if this has already been addressed and I simply gave up too soon.

Body:
No need for pivoting... Try this

DECLARE @xml XML=N'<table>
  <id>{3d2699c4-3159-4e8b-b48c-c2c4c9b5bd77}</id>
  <rows>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="5000" type="System.Decimal" />
        <column name="ec_exrate" value="1" type="System.Decimal" />
        <column name="ec_total" value="5000.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="1" type="System.Int32" />
      </columns>
    </row>
    <row>
      <columns>
        <column name="DESC" value="DACS" type="System.String" />
        <column name="ec_amount" value="1500" type="System.Decimal" />
        <column name="ec_exrate" value="5" type="System.Decimal" />
        <column name="ec_total" value="7500.00" type="System.Decimal" />
        <column name="ItemNo" value="PVT-C30" type="System.String" />
        <column name="UOM" value="EA" type="System.String" />
        <column name="DefaultKey" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>DefaultKey</key>
  <total>12500.00</total>
  <data />
  <parameters />
</table>';

SELECT r.value(N'(columns/column[@name="DefaultKey"]/@value)[1]',N'int') AS DefaultKey
      ,r.value(N'(columns/column[@name="DESC"]/@value)[1]',N'nvarchar(max)') AS [DESC]
      ,r.value(N'(columns/column[@name="ec_amount"]/@value)[1]',N'decimal(10,4)') AS ec_amount
      --similar with your other elements
FROM @xml.nodes(N'/table/rows/row') AS A(r)


问:
Android Gradle 3.0 how to exclude multi groups
As we know, in Gradle previous 3.0 version, we can exclude multi groups and modules by following code:

```<code>compile('com.lean.util:jiabujia:2.5.0') {
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
        exclude group: 'com.android.support', module: 'appcompat-v7'
}
</code>```

but in Gradle 3.0 how can I achieve the same thing?

答:
As of gradle 3.0 you have to do this now:

```<code> android.testVariants.all { variant ->
variant.getCompileConfiguration().exclude group: 'com.squareup.okhttp3', module: 'okhttp'
variant.getRuntimeConfiguration().exclude group: 'com.squareup.okhttp3', module:  'okhttp'
variant.getCompileConfiguration().exclude group:'com.android.support' , module: 'appcompat-v7'
variant.getRuntimeConfiguration().exclude group:'com.android.support' , module:  'appcompat-v7'
}
</code>```

Please check this: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

Body:
As we know, in Gradle previous 3.0 version, we can exclude multi groups and modules by following code:

compile('com.lean.util:jiabujia:2.5.0') {
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
        exclude group: 'com.android.support', module: 'appcompat-v7'
}

but in Gradle 3.0 how can I achieve the same thing?

Body:
As of gradle 3.0 you have to do this now:

 android.testVariants.all { variant ->
variant.getCompileConfiguration().exclude group: 'com.squareup.okhttp3', module: 'okhttp'
variant.getRuntimeConfiguration().exclude group: 'com.squareup.okhttp3', module:  'okhttp'
variant.getCompileConfiguration().exclude group:'com.android.support' , module: 'appcompat-v7'
variant.getRuntimeConfiguration().exclude group:'com.android.support' , module:  'appcompat-v7'
}

Please check this: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html


问:
Setting downloads directory for chrome driver suddenly stopped working after upgrade
After I've upgraded my project to use latest java selenium webdriver 3.7.1 and latest chrome driver 2.33 I noticed that my tests dealing with Excel export started to fail.

After debugging I see that for some reasons downloads directory is not being set to custom location and instead the default one is used. Nothing shows up in logs or whatsoever.

Any help appreciated.

Setting downloads directory is like usual:

```<code>    val prefs = Map(
      "profile.default_content_settings.popups" -> Integer.valueOf(0),
      "download.default_directory" -> downloadsDir,
      "credentials_enable_service" ->  false,
      "profile.password_manager_enabled" -> false
    )
    val chromeOptions:ChromeOptions = new ChromeOptions()
    chromeOptions.setExperimentalOption("prefs", prefs)
    val d = new ChromeDriver(chromeOptions)
</code>```

答:
I use WebDriver 3.7.1 and Chromedriver 2.33 and of course Chrome v.62 (try check Your Version of Chrome), and I can download files.

I'm using folder

```<code>public static String javaIoTmpDir = System.getProperty("java.io.tmpdir")+"/autotest/";
</code>```

and I create/clean it with script in TestNG annotation: @BeforeSuite

```<code>File theDir = new File(javaIoTmpDir);
    // if the directory does not exist, create it
    if (!theDir.exists()) {
        System.out.println("creating directory: " + theDir.getName());
        boolean result = false;
        try{
            theDir.mkdir();
            result = true;
        }
        catch(SecurityException se){
            se.printStackTrace();
        }
        if(result) {
            System.out.println(javaIoTmpDir+" created");
        }
    }
        FileUtils.cleanDirectory(new File(javaIoTmpDir));
    }
</code>```

Body:
After I've upgraded my project to use latest java selenium webdriver 3.7.1 and latest chrome driver 2.33 I noticed that my tests dealing with Excel export started to fail.

After debugging I see that for some reasons downloads directory is not being set to custom location and instead the default one is used. Nothing shows up in logs or whatsoever.

Any help appreciated.

Setting downloads directory is like usual:

    val prefs = Map(
      "profile.default_content_settings.popups" -> Integer.valueOf(0),
      "download.default_directory" -> downloadsDir,
      "credentials_enable_service" ->  false,
      "profile.password_manager_enabled" -> false
    )
    val chromeOptions:ChromeOptions = new ChromeOptions()
    chromeOptions.setExperimentalOption("prefs", prefs)
    val d = new ChromeDriver(chromeOptions)

Body:
I use WebDriver 3.7.1 and Chromedriver 2.33 and of course Chrome v.62 (try check Your Version of Chrome), and I can download files.

I'm using folder

public static String javaIoTmpDir = System.getProperty("java.io.tmpdir")+"/autotest/";

and I create/clean it with script in TestNG annotation: @BeforeSuite

File theDir = new File(javaIoTmpDir);
    // if the directory does not exist, create it
    if (!theDir.exists()) {
        System.out.println("creating directory: " + theDir.getName());
        boolean result = false;
        try{
            theDir.mkdir();
            result = true;
        }
        catch(SecurityException se){
            se.printStackTrace();
        }
        if(result) {
            System.out.println(javaIoTmpDir+" created");
        }
    }
        FileUtils.cleanDirectory(new File(javaIoTmpDir));
    }


问:
VR Ready definition
What does a VR Ready computer mean technically?

Does an industry standard exist that specifies a VR Ready computer has to be able to render X number of triangles twice (left and right eye) at a frame rate F at a resolution R, where X, F and R are defined some industry standard?

答:
Oculus has quite strict guidelines on what are the minimal requirements. It will not work or at least will constantly nag you if your machine isn't up to spec.

Vive has minimum specs, but they're not so orthodox in enforcing them as Oculus is.

OSVR has no such thing as far as I know - and it works almost everywhere.

That said, the stereoscopic display and rotation measurement actually isn't that costly in terms of computing power¹, the specs above are arbitrary and provided as a baseline for content makers. For example VR video can work on really old machines, provided that middleware (Oculus drivers mostly) doesn't forbid you to.

¹ positional tracking is moderately expensive in case of camera based trackers like Oculus or OSVR. Still, it mostly eats up USB bandwidth and not that much of the CPU. Vive has no such issue.

Title: VR Ready definition


问:
how do I get my bootstrap form to be showed horizontally?
my question is about forms in bootstrap.

I had to convert from bootstrap v3 to v4. Now my form keeps showing vertically. What do I need to do to get it horizontally?

screenshot of what it looked like in bootstrap 3

my code:

```<code><div class="col-4">
    <form method="post" action="index_s.php?action=add&id=<?php echo $row["product_id"]; ?>">
        <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:15px; padding:20px;" align="center">
            <img src="<?php echo $row["product_image"]; ?>" class="img-fluid" /><br />
            <h4 class="text-info"><?php echo $row["product_name"]; ?></h4>
            <h4 class="text-danger">€ <?php echo $row["product_price"]; ?></h4>
            <input type="text" name="quantity" class="form-conrol" value="1" />
            <input type="hidden" name="hidden_name" value="<?php echo $row["product_name"]; ?>" />
            <input type="hidden" name="hidden_price" value="<?php echo $row["product_price"]; ?>" />
            <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />
        </div>
    </form>
</div>
</code>```

if anyone could help me, that would be fantastic!
thanks for considering my request

答:
I have used bootstrap 4 and slightly modified your markup to produce a very similar result to your screenshot. I also removed PHP blocks for the purpose of the snippet.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

      <form method="post" action="">

Product name

€ 0.00

          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />

      </form>

      <form method="post" action="">

Product name

€ 0.00

          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />

      </form>

      <form method="post" action="">

Product name

€ 0.00

          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />

      </form>

```

Body:
my question is about forms in bootstrap.

I had to convert from bootstrap v3 to v4. Now my form keeps showing vertically. What do I need to do to get it horizontally?

screenshot of what it looked like in bootstrap 3

my code:

    <form method="post" action="index_s.php?action=add&id=<?php echo $row["product_id"]; ?>">

            <img src="<?php echo $row["product_image"]; ?>" class="img-fluid" />

<?php echo $row["product_name"]; ?>

€ <?php echo $row["product_price"]; ?>

            <input type="text" name="quantity" class="form-conrol" value="1" />
            <input type="hidden" name="hidden_name" value="<?php echo $row["product_name"]; ?>" />
            <input type="hidden" name="hidden_price" value="<?php echo $row["product_price"]; ?>" />
            <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />

    </form>

if anyone could help me, that would be fantastic!
thanks for considering my request

Body:
I have used bootstrap 4 and slightly modified your markup to produce a very similar result to your screenshot. I also removed PHP blocks for the purpose of the snippet.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-4">
      <form method="post" action="">
        <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:15px; padding:20px;" align="center">
          <img src="http://placehold.it/200x300" class="img-fluid" />
          <h4 class="text-info">Product name</h4>
          <h4 class="text-danger">€ 0.00</h4>
          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />
        </div>
      </form>
    </div>

    <div class="col-4">
      <form method="post" action="">
        <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:15px; padding:20px;" align="center">
          <img src="http://placehold.it/200x300" class="img-fluid" />
          <h4 class="text-info">Product name</h4>
          <h4 class="text-danger">€ 0.00</h4>
          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />
        </div>
      </form>
    </div>

    <div class="col-4">
      <form method="post" action="">
        <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:15px; padding:20px;" align="center">
          <img src="http://placehold.it/200x300" class="img-fluid" />
          <h4 class="text-info">Product name</h4>
          <h4 class="text-danger">€ 0.00</h4>
          <input type="text" name="quantity" class="form-conrol" value="1" />
          <input type="hidden" name="hidden_name" value="Name" />
          <input type="hidden" name="hidden_price" value="Price" />
          <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="In winkelwagen" />
        </div>
      </form>
    </div>
  </div>
</div>


问:
Mongodb lookup not working with deep id
I am working with MomgoDb to get results for the following code (in the context of a get request):

```<code>db.uiRepo.aggregate([
            {$match:{ "module.id": req.params.mid } },
            {"$lookup":
                {
                    from: "privileges",
                    localField: "_id",
                    foreignField: "ui._id",
                    as: "actions"
                }
            }
        ], {}, function(err, views) {
            if (err) res.json({});
            res.json(views);
        })
</code>```

Now, the problem is the $lookup part because when I remove it, the match function works just fine.

What am i doing wrong? Thanks

答:
Found it:

Lookup operation is not supported on the version I was using. Upgrading to 3.4 fixed this

Title: Mongodb lookup not working with deep id

Body:
I am working with MomgoDb to get results for the following code (in the context of a get request):

db.uiRepo.aggregate([
            {$match:{ "module.id": req.params.mid } },
            {"$lookup":
                {
                    from: "privileges",
                    localField: "_id",
                    foreignField: "ui._id",
                    as: "actions"
                }
            }
        ], {}, function(err, views) {
            if (err) res.json({});
            res.json(views);
        })

Now, the problem is the $lookup part because when I remove it, the match function works just fine.

What am i doing wrong? Thanks


问:
angular editable control multi language component or directive
What is the best way to create a control to define the value of a field in several languages.
Should I use the directives or components.
I would like that when I am logged in as admin, when clicking on a field, all the languages are displayed with the possibility to modify the values.

thank you in advance

答:
Hi you don't need to create a component or anything for it.

One of the ways you do translations in angular is using ngx-translate

Usage is very simple:

Have a look at this


问:
pass variable on item click from one page to another in ionic2
I'm working with ionic2 and I have a static list of items (ion-item).

When I click on an item I need to pass a variable (wcyear in this case) to a second page.
The problem is that if I print to console the variable I passed (wcyear) I get undefined.

Note: If I replace wcyear with a constant string in home.ts (i.e. year:"helloworld") then I see "helloworld" printed in my console.

This makes me think I have an error in my home.html but I can't see it.

home.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 2 app
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
  <ion-item let wcyear="2014" (click)="goToYear(wcyear)">
    <ion-avatar item-left>
      <img src="img/2014.png">
    </ion-avatar>
    <h2>2014</h2>
    <h3>some text</h3>
  </ion-item>
  <ion-item let wcyear="2010" (click)="goToYear(wcyear)">
    <ion-avatar item-left>
      <img src="img/2010.png">
    </ion-avatar>
    <h2>2010</h2>
    <h3>some text</h3>
  </ion-item>
  <ion-item let wcyear="2006" (click)="goToYear(wcyear)">
    <ion-avatar item-left>
      <img src="img/2006.png">
    </ion-avatar>
    <h2>2006</h2>
    <h3>some text</h3>
  </ion-item>
  <ion-item let wcyear="2002" (click)="goToYear(wcyear)">
    <ion-avatar item-left>
      <img src="img/2002.png">
    </ion-avatar>
    <h2>2002</h2>
    <h3>some text</h3>
  </ion-item>
</ion-list>
</code>```

home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {YearDashboardPage} from '../year-dashboard/year-dashboard';

@Component({
  templateUrl: 'build/pages/home/home.html'
})

export class HomePage {
  constructor(public navCtrl: NavController) {
    this.navCtrl = navCtrl;
  }

  goToYear(wcyear){
    this.navCtrl.push(YearDashboardPage, {
      year: wcyear,
    });
  }

}
</code>```

year-dashboard.ts

```<code>import { Component } from '@angular/core';
import { NavController, NavParams} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/year-dashboard/year-dashboard.html',
})
export class YearDashboardPage {

  selectedYear
  constructor(private navCtrl: NavController, private navParams: NavParams) {
     console.log(navParams.get('year'));  // I get undefined
  }

}
</code>```

答:
Instead of      </p>

```<code>console.log(navParams.get('year'));
</code>```

<p>use    </p>

```<code>console.log(this.navParams.get('year'));..
</code>```

Body:
I'm working with ionic2 and I have a static list of items (ion-item).

When I click on an item I need to pass a variable (wcyear in this case) to a second page.
The problem is that if I print to console the variable I passed (wcyear) I get undefined.

Note: If I replace wcyear with a constant string in home.ts (i.e. year:"helloworld") then I see "helloworld" printed in my console.

This makes me think I have an error in my home.html but I can't see it.

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 2 app
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
<ion-list>
  <ion-item let wcyear="2014" (click)="goToYear(wcyear)">
    <ion-avatar item-left>

    </ion-avatar>

2014

some text

  </ion-item>
  <ion-item let wcyear="2010" (click)="goToYear(wcyear)">
    <ion-avatar item-left>

    </ion-avatar>

2010

some text

  </ion-item>
  <ion-item let wcyear="2006" (click)="goToYear(wcyear)">
    <ion-avatar item-left>

    </ion-avatar>

2006

some text

  </ion-item>
  <ion-item let wcyear="2002" (click)="goToYear(wcyear)">
    <ion-avatar item-left>

    </ion-avatar>

2002

some text

  </ion-item>
</ion-list>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {YearDashboardPage} from '../year-dashboard/year-dashboard';

@Component({
  templateUrl: 'build/pages/home/home.html'
})

export class HomePage {
  constructor(public navCtrl: NavController) {
    this.navCtrl = navCtrl;
  }

  goToYear(wcyear){
    this.navCtrl.push(YearDashboardPage, {
      year: wcyear,
    });
  }

}

year-dashboard.ts

import { Component } from '@angular/core';
import { NavController, NavParams} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/year-dashboard/year-dashboard.html',
})
export class YearDashboardPage {

  selectedYear
  constructor(private navCtrl: NavController, private navParams: NavParams) {
     console.log(navParams.get('year'));  // I get undefined
  }

}

Body:
Instead of

console.log(navParams.get('year'));

use

console.log(this.navParams.get('year'));..


问:
How to stop labels from moving up when navigation bar disappears?
The layout in Xcode:

Output, in an iPhone 5s simulator once the navigation bar is removed:

Initially, at the start of this view, the navigation bar is required, but when I hit the record button, the navigation bar is to disappear, which it does. However, in doing so, it moves the timer labels up with it. How do I stop autolayout from moving the labels up?

Thanks.

答:
You have to set top layout guide to 64

Select viewController on which you are using it and make sure "Under top Bars" is ticked as in Picture below


问:
Filling 2D Array with DIV-Container and display it
i want to program a 4x4 Game and need to create 2D Array to store Div-Containers within. My current Code is this:

```<code>$(function(){
var columns = 6;
var rows = 6;
var f = [];
var $square = $('<div class="squares"></div>');

for (var i = 0; i < columns; i++) {
    f[i] = [];
    for (var j = 0; j < rows; j++) {
        f[i][j] = $square;
    }
}
console.log(f);
    $('.board').appendTo(f);
});
</code>```

In the Console i see the Array is created correct. But i cant display it. It only shows something like:

```<code>[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
</code>```

What is the correct Method to show the generated DIV's corretly?

答:
Are you trying to append those .squaress into .board?

If so, I think you'll need append. Not appendTo. Also, you cannot append an array to an element via jQuery. Try $():

var columns = 6;
var rows = 6;

var $columns = $();

for (var i = 0; i < columns; i++) {
    var $row = $();
    for (var j = 0; j < rows; j++) {
        $row = $row.add('
' + i + ',' + j + '
');
    }
    $columns = $columns.add($row);
}

$('.board').append($columns);
```

Working demo: https://jsfiddle.net/shuding/1bd5bvz5/

Body:
i want to program a 4x4 Game and need to create 2D Array to store Div-Containers within. My current Code is this:

$(function(){
var columns = 6;
var rows = 6;
var f = [];
var $square = $('

');

for (var i = 0; i < columns; i++) {
    f[i] = [];
    for (var j = 0; j < rows; j++) {
        f[i][j] = $square;
    }
}
console.log(f);
    $('.board').appendTo(f);
});

In the Console i see the Array is created correct. But i cant display it. It only shows something like:

[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object
Object],[object Object][object Object],[object Object],[object Object],
[object Object],[object Object],[object Object][object Object],[object
Object],[object Object],[object Object],[object Object],[object Object]

What is the correct Method to show the generated DIV's corretly?

Body:
Are you trying to append those .squaress into .board?

If so, I think you'll need append. Not appendTo. Also, you cannot append an array to an element via jQuery. Try $():

var columns = 6;
var rows = 6;

var $columns = $();

for (var i = 0; i < columns; i++) {
    var $row = $();
    for (var j = 0; j < rows; j++) {
        $row = $row.add('<div class="squares">' + i + ',' + j + '</div>');
    }
    $columns = $columns.add($row);
}

$('.board').append($columns);

Working demo: https://jsfiddle.net/shuding/1bd5bvz5/


问:
Laravel 5.2 add one more condition to login in standard Auth controller
I'm trying to add one condition to laravel standard auth. I have found a lot of forums with this question. Most of them make change in vendor folder, what I don't want to do. I also found a way of adding credentials(Request $request) function in AuthController.php, but I have no luck. It looks like this:

```<code>protected function credentials(Request $request)
{
    return array_merge($request->only($this->username(), 'password'),
        ['Type' => 1]);

}
</code>```

Does anyone solve this issue or can advice me what to do? Thanks

答:
Below is the function your can use in AuthController to override the login function:

```<code>public function login(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            array(
                'user_name' => 'required',
                'password' => 'required',
            ),
            array(
            )
        );

        if($validator->fails()){
            return redirect()->back()->withInput()->withErrors($validator->errors(),'invalid_credentials');
        }

        if (!\Auth::validate(['user_name' => $request->user_name, 'password' => $request->password])) {

            return redirect()->back()->withInput($request->only('user_name'))->withErrors([
                'user_name' => 'Incorrect Username or Password',
            ],'invalid_credentials');
        }

        $credentials  = array('user_name' => $request->user_name, 'password' => $request->password);

        if (\Auth::attempt($credentials, true)){

            /* Check your user type condition */
            if(\Auth::User()->type == '1'){
                return redirect()->intended($this->redirectPath());
            }
            else{
                \Auth::logout();
                return redirect()->back()->withInput($request->only('user_name'))->withErrors([
                    'user_name' => 'Your type validation message',
                ],'invalid_credentials');
            }
        }

        return redirect()->back()->withInput($request->only('user_name'))->withErrors([
            'user_name' => 'Incorrect email address or password',
        ],'invalid_credentials');
    }
</code>```

Hope this helps you.. :)

Body:
I'm trying to add one condition to laravel standard auth. I have found a lot of forums with this question. Most of them make change in vendor folder, what I don't want to do. I also found a way of adding credentials(Request $request) function in AuthController.php, but I have no luck. It looks like this:

protected function credentials(Request $request)
{
    return array_merge($request->only($this->username(), 'password'),
        ['Type' => 1]);

}

Does anyone solve this issue or can advice me what to do? Thanks

Body:
Below is the function your can use in AuthController to override the login function:

public function login(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            array(
                'user_name' => 'required',
                'password' => 'required',
            ),
            array(
            )
        );

        if($validator->fails()){
            return redirect()->back()->withInput()->withErrors($validator->errors(),'invalid_credentials');
        }

        if (!\Auth::validate(['user_name' => $request->user_name, 'password' => $request->password])) {

            return redirect()->back()->withInput($request->only('user_name'))->withErrors([
                'user_name' => 'Incorrect Username or Password',
            ],'invalid_credentials');
        }

        $credentials  = array('user_name' => $request->user_name, 'password' => $request->password);

        if (\Auth::attempt($credentials, true)){

            /* Check your user type condition */
            if(\Auth::User()->type == '1'){
                return redirect()->intended($this->redirectPath());
            }
            else{
                \Auth::logout();
                return redirect()->back()->withInput($request->only('user_name'))->withErrors([
                    'user_name' => 'Your type validation message',
                ],'invalid_credentials');
            }
        }

        return redirect()->back()->withInput($request->only('user_name'))->withErrors([
            'user_name' => 'Incorrect email address or password',
        ],'invalid_credentials');
    }

Hope this helps you.. :)


问:
Batch file to delete folder if it contains specific file
I'm trying to create batch file that will do the following:

It will scan through all subfolders in specific directory for
specific file.

If it finds file within subfolder, all contents of
this subfolder and subfolder itself will be deleted.

For example the file I'm looking for is "test.txt" and main folder is "C:\Test" with following structure:

```<code>\A
\B with test.txt
\C
\C\C0
\C\C1
\C\C2 with test.txt
\D
\D\D0
\D\D1 with test.txt
\D\D1\D10
\D\D1\D11
</code>```

Each folder has some other random files in it.

In this example script should delete following folders and all their contents:

```<code>C:\Test\B
C:\Test\C\C2
C:\Test\D\D1
</code>```

I tried several different scripts, but with no success. Batch file is placed directly in "C:\Test\"

First script I checked is:

```<code>for /R %%f in (test.txt) do @IF EXIST %%f @echo "%%f"
</code>```

It properly listed only path to folders with text.txt inside. Because it worked, I tried following one to delete only files for test:

```<code>for /R %%f in (test.txt) do @IF EXIST %%f del /q /s /f "*.*"
</code>```

It deleted all files in main folder and all subfolders where batch file is, along with batch file itself.

I tried to edit then several other scripts to match my conditions, but results were obvious. Last thing I was able to create is:

```<code>for /R %%p in (test.txt) do @IF EXIST %%p (rd "%%p" /s || del "*.*" /s/f)
</code>```

I ommited here "/q" parameter to be able to see what it wants to delete. It finds properly first "text.txt" file. If "y" is chosen to delete this file, script returns error that this is not proper folder. Then it starts to delete files from main folder and all subfolders with batch file being first victim (it asks each time if I want to delete files in specific subfolder). Subfolders are not deleted, only their contents.

I'm out of ideas.

答:
When the problem seems too difficult to solve, split it into two.

1) List the directory tree into a temporary text file, one per line:

```<code>dir /ad /b /s %1 >%TEMP%\Temporary.txt
</code>```

2) Iterate listed directories and do what you need with each of them:

```<code>for /f %%g in (%TEMP%\Temporary.txt) do if exist %%g\test.txt rd /s /q %%g
</code>```

Body:
I'm trying to create batch file that will do the following:

It will scan through all subfolders in specific directory for
specific file.

If it finds file within subfolder, all contents of
this subfolder and subfolder itself will be deleted.

For example the file I'm looking for is "test.txt" and main folder is "C:\Test" with following structure:

\A
\B with test.txt
\C
\C\C0
\C\C1
\C\C2 with test.txt
\D
\D\D0
\D\D1 with test.txt
\D\D1\D10
\D\D1\D11

Each folder has some other random files in it.

In this example script should delete following folders and all their contents:

C:\Test\B
C:\Test\C\C2
C:\Test\D\D1

I tried several different scripts, but with no success. Batch file is placed directly in "C:\Test\"

First script I checked is:

for /R %%f in (test.txt) do @IF EXIST %%f @echo "%%f"

It properly listed only path to folders with text.txt inside. Because it worked, I tried following one to delete only files for test:

for /R %%f in (test.txt) do @IF EXIST %%f del /q /s /f "*.*"

It deleted all files in main folder and all subfolders where batch file is, along with batch file itself.

I tried to edit then several other scripts to match my conditions, but results were obvious. Last thing I was able to create is:

for /R %%p in (test.txt) do @IF EXIST %%p (rd "%%p" /s || del "*.*" /s/f)

I ommited here "/q" parameter to be able to see what it wants to delete. It finds properly first "text.txt" file. If "y" is chosen to delete this file, script returns error that this is not proper folder. Then it starts to delete files from main folder and all subfolders with batch file being first victim (it asks each time if I want to delete files in specific subfolder). Subfolders are not deleted, only their contents.

I'm out of ideas.

Body:
When the problem seems too difficult to solve, split it into two.

1) List the directory tree into a temporary text file, one per line:

dir /ad /b /s %1 >%TEMP%\Temporary.txt

2) Iterate listed directories and do what you need with each of them:

for /f %%g in (%TEMP%\Temporary.txt) do if exist %%g\test.txt rd /s /q %%g


问:
How to Hide Bottom button when keyboard is open in kotlin?
I am having an EditText and a Button in my layout.

my button is parentbottom aligned. So whenever i try to type something in edittext button comes over it.

So to hide button i tried it as:
`

```<code>fun hideButton(editText: EditText, button: Button) {

    editText.viewTreeObserver.addOnGlobalLayoutListener {
        val r = Rect()
        editText.getWindowVisibleDisplayFrame(r)
        val screenHeight = editText.rootView.height
        val keypadHeight = screenHeight - r.bottom
        if (keypadHeight > screenHeight * 0.15) {
            // keyboard is open
            button.visibility = View.GONE
        } else {
            // keyboard is closed
            button.visibility = View.VISIBLE

        }
    }
}
</code>```

and called this function as:

```<code>    edText?.setOnClickListener { hideButton(edName!!, btnSave!!) }
</code>```

but still no success in hiding.

答:
Try using this :

```<code>  editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if(b){
             //Hide button here
            }else{
             //Show button here
            }
        }
    });
</code>```

Hope this helps.

Edit : Kotlin version-

```<code>editText.onFocusChangeListener = View.OnFocusChangeListener { view, b ->
        if (b) {
         //Hide Button
        } else {
         //Show Button
        }
    }
</code>```

Body:
I am having an EditText and a Button in my layout.

my button is parentbottom aligned. So whenever i try to type something in edittext button comes over it.

So to hide button i tried it as:
`

fun hideButton(editText: EditText, button: Button) {

    editText.viewTreeObserver.addOnGlobalLayoutListener {
        val r = Rect()
        editText.getWindowVisibleDisplayFrame(r)
        val screenHeight = editText.rootView.height
        val keypadHeight = screenHeight - r.bottom
        if (keypadHeight > screenHeight * 0.15) {
            // keyboard is open
            button.visibility = View.GONE
        } else {
            // keyboard is closed
            button.visibility = View.VISIBLE

        }
    }
}

and called this function as:

    edText?.setOnClickListener { hideButton(edName!!, btnSave!!) }

but still no success in hiding.

Body:
Try using this :

  editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if(b){
             //Hide button here
            }else{
             //Show button here
            }
        }
    });

Hope this helps.

Edit : Kotlin version-

editText.onFocusChangeListener = View.OnFocusChangeListener { view, b ->
        if (b) {
         //Hide Button
        } else {
         //Show Button
        }
    }


问:
Handle Screen Orientation?
When the page loads, first it loads in LANDSCAPE_MODE and then after a few seconds the orientation changes to PORTRAIT_MODE the value </p>

```<code>protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate();

    setContentView(R.layout.layout);

    if(orientation.equals("true"))
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
</code>```

答:
By default whatever the devices is in the current orientation is it will opens the activity in that mode.There is no specific way to handle this

As your changing the orientation programmatically in the activity which will be execute only after activity onCreate() method

So you will always face a glitch every time.I have face similar kind of orientation issue here
Splash Screen Image for landscape and Portrait using Theme

Title: Handle Screen Orientation?

Body:
When the page loads, first it loads in LANDSCAPE_MODE and then after a few seconds the orientation changes to PORTRAIT_MODE the value

protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate();

    setContentView(R.layout.layout);

    if(orientation.equals("true"))
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}


问:
<Error>: Couldn't read values in CFPrefsPlistSource
I'm facing some problems with iOS 11. We use App Groups to share some information between some of our apps, but some clients after updated their iPhone to iOS 11+ the apps stoped accessing the information in the App Groups. It always worked.

I'm getting following error:

Couldn't read values in CFPrefsPlistSource<0x1c010b5b0> (Domain: group.com.****, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd

Anyone has any idea of what can be causing this? Some clients after delete all apps and install again resolved the problem, but some said that it didn't resolved (I don't know if they really deleted all of our apps).

There is some way to recycle or clean the App Groups?

答:
From watch OS 2 we are not able to access app groups so if you want to get any info from keychain e.g login info or some thing, you can use watch connectivity framework. When I tried to access some information from userdefault which worked fine in watchOS1 it shows me the same error after upgrading watchOS . For how work with watch connectivity please see this link. Here everything is explained.

https://kristina.io/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/

ContentLicense: CC BY-SA 4.0


问:
Fs2 how to fold then append to a Stream
I want to append to a Stream

But next stream relies on previous Stream's folding result

Here is how I did, but the Stream s is evaluated twice

scasite link

```<code>import fs2._

def ints(start: Int) = Stream.iterate(start) { i =>
  println(i)
  i + 1
}.take(10)

val s = ints(0)

def foldAppend(init: Int)(f: (Int, Int) => Int)(next: Int => Stream[Pure, Int]) = {
  s ++ s.fold(init)(f).flatMap(next)
}

val res = foldAppend(0)((s, i) => s + 1)(ints)
println(res.toList)
</code>```

How can I implement the foldAppend method that evalute s only once.

答:
Brian's answer is wrong, s is actually lazy so the entire stream is evaluated twice. The variable binding to s is strict, but Stream in fs2 is a lazy stream, that is only evaluated once you run it.

Your main issue is that Pure is not a monad for implementing side effect safely, like IO. You shouldn't println in pure. An example that works is:

```<code>import cats.effect.IO
import fs2._

def ints(start: Int) = Stream.iterate(start) { i => println(i)
  i + 1
}.take(10)

val s = ints(0)

def foldAppend(init: Int)(f: (Int, Int) => Int)(next: Int => Stream[IO, Int]) = {

  val result = s.covary[IO].runLog
  Stream.eval(result).covary[IO].flatMap {
    s =>
      Stream.emits(s) ++ Stream.emits(s).fold(init)(f).flatMap(next)
  }
}
val res = foldAppend(0)((s, i) => s + 1)(ints)
println(res.runLast.unsafeRunSync())
</code>```

This will evaluate the stream once

Title: Fs2 how to fold then append to a Stream

Body:
I want to append to a Stream

But next stream relies on previous Stream's folding result

Here is how I did, but the Stream s is evaluated twice

scasite link

import fs2._

def ints(start: Int) = Stream.iterate(start) { i =>
  println(i)
  i + 1
}.take(10)

val s = ints(0)

def foldAppend(init: Int)(f: (Int, Int) => Int)(next: Int => Stream[Pure, Int]) = {
  s ++ s.fold(init)(f).flatMap(next)
}

val res = foldAppend(0)((s, i) => s + 1)(ints)
println(res.toList)

How can I implement the foldAppend method that evalute s only once.

Body:
Brian's answer is wrong, s is actually lazy so the entire stream is evaluated twice. The variable binding to s is strict, but Stream in fs2 is a lazy stream, that is only evaluated once you run it.

Your main issue is that Pure is not a monad for implementing side effect safely, like IO. You shouldn't println in pure. An example that works is:

import cats.effect.IO
import fs2._

def ints(start: Int) = Stream.iterate(start) { i => println(i)
  i + 1
}.take(10)

val s = ints(0)

def foldAppend(init: Int)(f: (Int, Int) => Int)(next: Int => Stream[IO, Int]) = {

  val result = s.covary[IO].runLog
  Stream.eval(result).covary[IO].flatMap {
    s =>
      Stream.emits(s) ++ Stream.emits(s).fold(init)(f).flatMap(next)
  }
}
val res = foldAppend(0)((s, i) => s + 1)(ints)
println(res.runLast.unsafeRunSync())

This will evaluate the stream once


问:
Can't change native base tabs' height
Tab is working correctly. But I can't change the underline and the height of <Tabs> like the image below

I'm using Native-Base to handle tabs. But I can't think of any way to change its default height.

```<code><Tabs initialPage={0}
  tabBarUnderlineStyle={styles.tabBarUnderlineStyle}
  style={{height:40}}
>
  <Tab
    heading="Following"
    tabStyle={styles.tabStyle}
    activeTabStyle={styles.activeTabStyle}
    activeTextStyle={styles.activeTextStyle}
    textStyle={styles.textStyle}
  >
    <FeedScreen navigation={this.props.navigation}/>
  </Tab>
</code>```

Should I use another navigation? native-base is terrible to customize.. :(

UPDATE as request, I'm sharing my style

```<code>  tabStyle : {
    // backgroundColor: theme.colors.navbar,
    backgroundColor: 'white',
    justifyContent: 'center',
    width: 120,
    height: 40,
  },
  activeTabStyle: {
    backgroundColor: 'white',
    height: 40,
  },
  textStyle: {
    // color: 'white',
    color: "#968D8A"
  },
  activeTextStyle: {
    // color: 'white',
    color: theme.colors.navbar
  },
  tabBarUnderlineStyle: {
    backgroundColor: theme.colors.navbar,
    height: 2
  }
</code>```

答:
Use tabContainerStyle prop of <Tabs/> to adjust the height. Same way use tabBarUnderlineStyle prop to style the tab indicator.

```<code><Tabs
      tabContainerStyle={{ height: 60 }}
      tabBarUnderlineStyle={{
        backgroundColor: "black",
        height: 5,
      }}
    />
</code>```

Title: Can't change native base tabs' height

Body:
Tab is working correctly. But I can't change the underline and the height of <Tabs> like the image below

I'm using Native-Base to handle tabs. But I can't think of any way to change its default height.

<Tabs initialPage={0}
  tabBarUnderlineStyle={styles.tabBarUnderlineStyle}
  style={{height:40}}
>
  <Tab
    heading="Following"
    tabStyle={styles.tabStyle}
    activeTabStyle={styles.activeTabStyle}
    activeTextStyle={styles.activeTextStyle}
    textStyle={styles.textStyle}
  >
    <FeedScreen navigation={this.props.navigation}/>
  </Tab>

Should I use another navigation? native-base is terrible to customize.. :(

UPDATE as request, I'm sharing my style

  tabStyle : {
    // backgroundColor: theme.colors.navbar,
    backgroundColor: 'white',
    justifyContent: 'center',
    width: 120,
    height: 40,
  },
  activeTabStyle: {
    backgroundColor: 'white',
    height: 40,
  },
  textStyle: {
    // color: 'white',
    color: "#968D8A"
  },
  activeTextStyle: {
    // color: 'white',
    color: theme.colors.navbar
  },
  tabBarUnderlineStyle: {
    backgroundColor: theme.colors.navbar,
    height: 2
  }

Body:
Use tabContainerStyle prop of <Tabs/> to adjust the height. Same way use tabBarUnderlineStyle prop to style the tab indicator.

<Tabs
      tabContainerStyle={{ height: 60 }}
      tabBarUnderlineStyle={{
        backgroundColor: "black",
        height: 5,
      }}
    />


问:
Developing CLDC or J2ME applications under Mac OSX?
I have noticed that Oracle now has released a Java Platform Micro Edition SDK for OSX. It works, it can compile the provided examples and the included phone emulator works too. But how do I compile my own J2ME project from Ant or Eclipse?

There are a lot of related jars but they are all inside the ".app" in the /Applications directory. Eclipse does not like it when I put a toolchain path to inside the ".app".

答: If you want to use ANT I have simply copied over the required jars from the Windows SDK and just used the pre verifier and javac from the osx 3.0 sdk, works well!</p>


问:
Chart.js dataset label issue
The dataset label in my chart.js bar chart does not show correct values. I am trying different chart configurations but nothing seems to work.
Here is my JS Fiddle. What I want to achieve is that the bar chart should show values like 'HIGH : 30' or 'MED: 25' but right now the tooltip is showing only the first label (HIGH: 30, HIGH: 25, HIGH: 56) on all the 3 bars. This is strange. Need some assistance.

Some more details about what I tried so far:
If I use arroChartConfig1 it gives tooltip title as HIGH for all graphs and label as HIGH: 30 (red bar), HIGH: 25 (yellow bar), HIGH: 56 (blue bar).

If I use arroChartConfig2 it gives correct title and labels but shows only one  legend with label HIGH,MED,LOW.

If I use arroChartConfig3 distinct labels in legend but bar tooltip title and labels have values same as in arroChartConfig1.

Thanks in advance.

```<code>var oMyBarChart;
var ctx = document.getElementById("canvas").getContext("2d");
function GetSelectedChartType(sSelectedOption){
 return sSelectedOption.options[sSelectedOption.selectedIndex].value;
}
arroLevels = ["HIGH","MED","LOW"];
arroLevelsCount = [30,25,56];
arroLevelColors =
['rgba(230,0,0,1)','rgba(255,255,79,1)','rgba(150,198,250,1)'];
arroDataset=[];
sChartType = GetSelectedChartType(document.getElementById('chartSelector'));
arroLevels.map(function(sValue,iIndex){
  let oData = [arroLevelsCount[iIndex]];
  let sColorData = arroLevelColors[iIndex];
  arroDataset.push({
      label: sValue,
      data: oData,
      backgroundColor: sColorData,
      pointStyle: 'triangle',
  });
 });
barChartData = {
    labels: arroLevels,
    datasets: arroDataset,
}

arroChartConfig1 = {
    type: sChartType,
    data: barChartData,
    options: {
        responsive: true,
        legend: {
          position: 'right',
          generateLabels: function(data){
            return data.text;
          }
        },
        title: {
          display: true,
          text: 'My Bar Chart'
        },
        tooltips: {
          callbacks:{
           label: function(ttitem,data){
              return ttitem.xLabel+": "+ttitem.yLabel
           }
         }
       }
     }
    }
arroChartConfig2 = {
      type: sChartType,
      data: {
       datasets: [{
          label: arroLevels,
          data: arroLevelsCount,
          backgroundColor: arroLevelColors,
          pointStyle: 'triangle',
        }],
        labels: arroLevels
      },
      options: {
        responsive: true,
        legend: {
          position: 'right',
          generateLabels: function(data){
            return data.text;
          }
        },
         title: {
           display: true,
           text: 'My Bar Chart'
         },
         tooltips: {
           callbacks:{
             label: function(ttitem,data){
               return ttitem.xLabel+": "+ttitem.yLabel
             }
           }
         }
       }
   }
arroChartConfig3 = {
      type: sChartType,
      data: {
        datasets: [{
          label: "HIGH",
          data: ["30"],
          backgroundColor: 'rgba(230,0,0,1)',
          pointStyle: 'triangle',
        },
        {
          label: "MED",
          data: ["25"],
          backgroundColor: 'rgba(255,255,79,1)',
          pointStyle: 'triangle',
        },
         {
          label: "LOW",
          data: ["56"],
          backgroundColor: 'rgba(150,198,250,1)',
          pointStyle: 'triangle',
        }],
        labels: ["HIGH","MED","LOW"]
      },
      options: {
        responsive: true,
        legend: {
          position: 'right',
         generateLabels: function(data){
           return data.text;
          }
        },
         title: {
           display: true,
          text: 'My Bar Chart'
         },
         tooltips: {
           callbacks:{
             title: function(ttitem,data){
                 return '';
             },
             label: function(ttitem,data){
               return ttitem.xLabel+": "+ttitem.yLabel;
             }
           }
         }
       }
   }
    //oMyBarChart = new Chart(ctx,arroChartConfig1);
    //oMyBarChart = new Chart(ctx,arroChartConfig2);
    oMyBarChart = new Chart(ctx,arroChartConfig3);
</code>```

答:
It might be easier to achieve what you'd like if you would consider every element in your arroLevelsCount array as a standalone dataset. So the simplest config would look like this (and here's a JSFiddle of that):

```<code>arroChartConfig = {
  type: sChartType,
  data: {
    datasets: [{
      label: arroLevels[0],
      data: [arroLevelsCount[0] ],
      backgroundColor: arroLevelColors[0],
      pointStyle: 'triangle',
    },
    {
      label: arroLevels[1],
      data: [ arroLevelsCount[1] ],
      backgroundColor: arroLevelColors[1],
      pointStyle: 'triangle',
    },
    {
      label: arroLevels[2],
      data: [ arroLevelsCount[2] ],
      backgroundColor: arroLevelColors[2],
      pointStyle: 'triangle',
    }],
    labels: arroLevels
  },
  options: {
    tooltips: {
      callbacks: {
        title: function(chart, data) {
          return data.labels[chart[0].datasetIndex];
        }
      }
    }
  }
 }
</code>```

But if you'd like to stick to your approach there are a few things to consider. The generateLabels option has to be inside of the labels option and the function passes the entire config as a parameter so you can't just return data.text, instead you have to iterate over the labels. The function generateLabels requires an array legend item as return.

Considering all points above the legend option could look like this:

```<code>legend: {
  position: 'right',
  labels: {
    generateLabels: function(chart) {
        return chart.data.labels.map(function(label, i) {
            return {
                text: label,
                fillStyle: chart.data.datasets[0].backgroundColor[i]
            };
        });
    }
  }
}
</code>```

Here is your updated JSFiddle.

Edit:
To display the correct tooltip label color for your approach you should add the labelColor callback aswell and return the color depending on the hovered dataset.

```<code>labelColor: function(ttitem, data) {
          return {
            borderColor: arroLevelColors[ttitem.index],
            backgroundColor: arroLevelColors[ttitem.index]
          };
</code>```

This is the second JSFiddle updated with the labelColor callback.

Title: Chart.js dataset label issue

Body:
The dataset label in my chart.js bar chart does not show correct values. I am trying different chart configurations but nothing seems to work.
Here is my JS Fiddle. What I want to achieve is that the bar chart should show values like 'HIGH : 30' or 'MED: 25' but right now the tooltip is showing only the first label (HIGH: 30, HIGH: 25, HIGH: 56) on all the 3 bars. This is strange. Need some assistance.

Some more details about what I tried so far:
If I use arroChartConfig1 it gives tooltip title as HIGH for all graphs and label as HIGH: 30 (red bar), HIGH: 25 (yellow bar), HIGH: 56 (blue bar).

If I use arroChartConfig2 it gives correct title and labels but shows only one  legend with label HIGH,MED,LOW.

If I use arroChartConfig3 distinct labels in legend but bar tooltip title and labels have values same as in arroChartConfig1.

Thanks in advance.

var oMyBarChart;
var ctx = document.getElementById("canvas").getContext("2d");
function GetSelectedChartType(sSelectedOption){
 return sSelectedOption.options[sSelectedOption.selectedIndex].value;
}
arroLevels = ["HIGH","MED","LOW"];
arroLevelsCount = [30,25,56];
arroLevelColors =
['rgba(230,0,0,1)','rgba(255,255,79,1)','rgba(150,198,250,1)'];
arroDataset=[];
sChartType = GetSelectedChartType(document.getElementById('chartSelector'));
arroLevels.map(function(sValue,iIndex){
  let oData = [arroLevelsCount[iIndex]];
  let sColorData = arroLevelColors[iIndex];
  arroDataset.push({
      label: sValue,
      data: oData,
      backgroundColor: sColorData,
      pointStyle: 'triangle',
  });
 });
barChartData = {
    labels: arroLevels,
    datasets: arroDataset,
}

arroChartConfig1 = {
    type: sChartType,
    data: barChartData,
    options: {
        responsive: true,
        legend: {
          position: 'right',
          generateLabels: function(data){
            return data.text;
          }
        },
        title: {
          display: true,
          text: 'My Bar Chart'
        },
        tooltips: {
          callbacks:{
           label: function(ttitem,data){
              return ttitem.xLabel+": "+ttitem.yLabel
           }
         }
       }
     }
    }
arroChartConfig2 = {
      type: sChartType,
      data: {
       datasets: [{
          label: arroLevels,
          data: arroLevelsCount,
          backgroundColor: arroLevelColors,
          pointStyle: 'triangle',
        }],
        labels: arroLevels
      },
      options: {
        responsive: true,
        legend: {
          position: 'right',
          generateLabels: function(data){
            return data.text;
          }
        },
         title: {
           display: true,
           text: 'My Bar Chart'
         },
         tooltips: {
           callbacks:{
             label: function(ttitem,data){
               return ttitem.xLabel+": "+ttitem.yLabel
             }
           }
         }
       }
   }
arroChartConfig3 = {
      type: sChartType,
      data: {
        datasets: [{
          label: "HIGH",
          data: ["30"],
          backgroundColor: 'rgba(230,0,0,1)',
          pointStyle: 'triangle',
        },
        {
          label: "MED",
          data: ["25"],
          backgroundColor: 'rgba(255,255,79,1)',
          pointStyle: 'triangle',
        },
         {
          label: "LOW",
          data: ["56"],
          backgroundColor: 'rgba(150,198,250,1)',
          pointStyle: 'triangle',
        }],
        labels: ["HIGH","MED","LOW"]
      },
      options: {
        responsive: true,
        legend: {
          position: 'right',
         generateLabels: function(data){
           return data.text;
          }
        },
         title: {
           display: true,
          text: 'My Bar Chart'
         },
         tooltips: {
           callbacks:{
             title: function(ttitem,data){
                 return '';
             },
             label: function(ttitem,data){
               return ttitem.xLabel+": "+ttitem.yLabel;
             }
           }
         }
       }
   }
    //oMyBarChart = new Chart(ctx,arroChartConfig1);
    //oMyBarChart = new Chart(ctx,arroChartConfig2);
    oMyBarChart = new Chart(ctx,arroChartConfig3);

Body:
It might be easier to achieve what you'd like if you would consider every element in your arroLevelsCount array as a standalone dataset. So the simplest config would look like this (and here's a JSFiddle of that):

arroChartConfig = {
  type: sChartType,
  data: {
    datasets: [{
      label: arroLevels[0],
      data: [arroLevelsCount[0] ],
      backgroundColor: arroLevelColors[0],
      pointStyle: 'triangle',
    },
    {
      label: arroLevels[1],
      data: [ arroLevelsCount[1] ],
      backgroundColor: arroLevelColors[1],
      pointStyle: 'triangle',
    },
    {
      label: arroLevels[2],
      data: [ arroLevelsCount[2] ],
      backgroundColor: arroLevelColors[2],
      pointStyle: 'triangle',
    }],
    labels: arroLevels
  },
  options: {
    tooltips: {
      callbacks: {
        title: function(chart, data) {
          return data.labels[chart[0].datasetIndex];
        }
      }
    }
  }
 }

But if you'd like to stick to your approach there are a few things to consider. The generateLabels option has to be inside of the labels option and the function passes the entire config as a parameter so you can't just return data.text, instead you have to iterate over the labels. The function generateLabels requires an array legend item as return.

Considering all points above the legend option could look like this:

legend: {
  position: 'right',
  labels: {
    generateLabels: function(chart) {
        return chart.data.labels.map(function(label, i) {
            return {
                text: label,
                fillStyle: chart.data.datasets[0].backgroundColor[i]
            };
        });
    }
  }
}

Here is your updated JSFiddle.

Edit:
To display the correct tooltip label color for your approach you should add the labelColor callback aswell and return the color depending on the hovered dataset.

labelColor: function(ttitem, data) {
          return {
            borderColor: arroLevelColors[ttitem.index],
            backgroundColor: arroLevelColors[ttitem.index]
          };

This is the second JSFiddle updated with the labelColor callback.


问:
How to type in new responsive design mode
In the new Firefox responsive design mode I cannot seem to type anything in a text field. When I try typing Firefox starts searching instead. When I go back to the old responsive design mode it works fine.</p>

答: Disable "Search for text when you start typing" in settings -> general -> browsing.</p>


问:
How do I make a rewrite rule in php?
Hey guys I'm new to mod_rewrite and just now learning how to use it. I have a question. This piece of code doesn't seem to work.

```<code>RewriteEngine On
RewriteRule ^([a-z]+)$ /users.php?username=$1 [L]
</code>```

I'm trying to redirect ppl that write something like www.domain.com/username to www.domain.com/users.php?username=username. Could you please help?

答:
Not precisely an answer because @lweller is basically right. Try turning on the rewrite log and examining the output.

```<code>RewriteLog "/usr/local/var/apache/logs/rewrite.log"
RewriteLogLevel 3
</code>```

You may need to increase the log level to get the information you need.

Title: How do I make a rewrite rule in php?

Body:
Hey guys I'm new to mod_rewrite and just now learning how to use it. I have a question. This piece of code doesn't seem to work.

RewriteEngine On
RewriteRule ^([a-z]+)$ /users.php?username=$1 [L]

I'm trying to redirect ppl that write something like www.domain.com/username to www.domain.com/users.php?username=username. Could you please help?

Body:
Not precisely an answer because @lweller is basically right. Try turning on the rewrite log and examining the output.

RewriteLog "/usr/local/var/apache/logs/rewrite.log"
RewriteLogLevel 3

You may need to increase the log level to get the information you need.


问:
Wordpress won't update edits
Problem is - I'm logged in as admin, working on a website, let's say I have doctors on my website, and they are in categories. I deleted one doctor, cause he left work in that clinic. I deleted his page, where was info. I go to visit website, everything seems good doctor gone. Than my friend says why you didn't delete that doctor, I said I deleted and checked. So the thing is than I logged in as admin I can see my edits, then I log out I see doctor that doesn't even exist(i deleted it even from trash.) HOW TO FIX THIS?

UPDATE: Ok, i figure it out, that problem is only with doctors page, let's say contact page is updating normal...

SOLUTION: My URL was broken, I don't know why and how, but I created new page, reupload info, and it worked.

答:
Have you actually deleted the page, and not just left it in 'Bin' or 'Trash'?

If you're logged in as Admin, I believe deleted, and draft pages still show as normal so you can preview them.

Try logging out of /wp-admin/ and see if you can still access the page. If it says 'Page not found', then your page is still in Wordpress and hasn't been deleted.

Title: Wordpress won't update edits


问:
cors angular/node +express issue
I know there are a bunch of stuff about how to enable CORS in node/express and have tried implementing those, but with no luck.

My request in angular:

```<code>function getPhotos(location) {
      var url = 'https://api.instagram.com/v1/media/search?lat=' + location.lat + '&lng=' + location.lng + '&access_token=' + ig_access_token;
      $http({
        method: 'GET',
        url: url
      }).then(function (response) {
        console.log("here are the photos: ", response);
      }, function(err) {
        console.log("whoops, there is an error: ", err);
    });
</code>```

and my server setup in node/express:

```<code> app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(methodOverride('X-HTTP-Method-Override'));

 app.use(function(req, res, next) {
 res.setHeader('Access-Control-Allow-Origin', '*');
 res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

app.use(express.static(__dirname + '/public'));

app.listen(port);`
</code>```

but I still keep getting this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Any ideas?

答:
Try doing this in your angular code

$http({
    method: 'GET',
    url: url,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
    }
  })```

Title: cors angular/node +express issue

Body:
I know there are a bunch of stuff about how to enable CORS in node/express and have tried implementing those, but with no luck.

My request in angular:

function getPhotos(location) {
      var url = 'https://api.instagram.com/v1/media/search?lat=' + location.lat + '&lng=' + location.lng + '&access_token=' + ig_access_token;
      $http({
        method: 'GET',
        url: url
      }).then(function (response) {
        console.log("here are the photos: ", response);
      }, function(err) {
        console.log("whoops, there is an error: ", err);
    });

and my server setup in node/express:

 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(methodOverride('X-HTTP-Method-Override'));

 app.use(function(req, res, next) {
 res.setHeader('Access-Control-Allow-Origin', '*');
 res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

app.use(express.static(__dirname + '/public'));

app.listen(port);`

but I still keep getting this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Any ideas?


问:
Numpy argsort - what is it doing?
Why is numpy giving this result:

```<code>x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()

>[2 3 1 0]
</code>```

when I'd expect it to do this:

[3 2 0 1]

Clearly my understanding of the function is lacking.

答:
Just want to directly contrast the OP's original understanding against the actual implementation with code.

numpy.argsort is defined such that for 1D arrays:

```<code>x[x.argsort()] == numpy.sort(x) # this will be an array of True's
</code>```

The OP originally thought that it was defined such that for 1D arrays:

```<code>x == numpy.sort(x)[x.argsort()] # this will not be True
</code>```

Note: This code doesn't work in the general case (only works for 1D), this answer is purely for illustration purposes.

Title: Numpy argsort - what is it doing?

Body:
Why is numpy giving this result:

x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()

>[2 3 1 0]

when I'd expect it to do this:

[3 2 0 1]

Clearly my understanding of the function is lacking.

Body:
Just want to directly contrast the OP's original understanding against the actual implementation with code.

numpy.argsort is defined such that for 1D arrays:

x[x.argsort()] == numpy.sort(x) # this will be an array of True's

The OP originally thought that it was defined such that for 1D arrays:

x == numpy.sort(x)[x.argsort()] # this will not be True

Note: This code doesn't work in the general case (only works for 1D), this answer is purely for illustration purposes.