问:
Wildfly MySQL datasource: service jboss.jdbc-driver.mysql (missing) dependents
I'm using Wildfly 10. At first I tried to create datasource via CLI.

A command deploy mysql-connector-java-6.0.4.jar was executed well.
/subsystem=datasources:installed-drivers-list shows that driver was installed

```<code>{
    "driver-name" => "mysql-connector-java-6.0.4.jar",
    "deployment-name" => "mysql-connector-java-6.0.4.jar",
    "driver-module-name" => undefined,
    "module-slot" => undefined,
    "driver-datasource-class-name" => undefined,
    "driver-xa-datasource-class-name" => undefined,
    "driver-class-name" => "com.mysql.cj.jdbc.Driver",
    "driver-major-version" => 6,
    "driver-minor-version" => 0,
    "jdbc-compliant" => false
}
</code>```

But data source was not created with command

```<code>data-source add --name=zktest-datasource
--jndi-name=java:/jdbc/zktest-database --driver-name=mysql-connector-java-6.0.4.jar --connection-url=jdbc:mysql://localhost:3306/zktest --user-name=root --password=111
</code>```

Connection test

```<code>/subsystem=datasources/data-source=zktest-datasource:test-connection-in-pool
was failed.
</code>```

Now I trying to create datasource using standalone.xml

My modules.xml

```<code><module xmlns="urn:jboss:module:1.1" name="com.mysql.jdbc">
  <resources>
    <resource-root path="mysql-connector-java-6.0.4.jar">
  </resource-root>
  </resources>
  <dependencies>
    <module name="javax.api"></module>
    <module name="javax.transaction.api"></module>
  </dependencies>
</module>
</code>```

modules.xml placed into the JBOSS_HOME/modules/system/layers/base/com/mysql/jdbc

'Datasources' section in JBOSS_HOME/standalone/configuration/standalone.xml

```<code><datasources>
        <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
            <driver>h2</driver>
            <security>
                <user-name>sa</user-name>
                <password>sa</password>
            </security>
        </datasource>
        <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:mysql://localhost:3306/zktest</connection-url>
            <driver>mysql</driver>
            <security>
                <user-name>root</user-name>
                <password>111</password>
            </security>
        </datasource>
        <drivers>
            <driver name="h2" module="com.h2database.h2">
                <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
            </driver>
            <driver name="mysql" module="com.mysql.jdbc">
                <xa-datasource-class>com.mysql.cj.jdbc.Driver</xa-datasource-class>
            </driver>
        </drivers>
    </datasources>
</code>```

Now while deploing I see such message

WFLYCTL0184:    New missing/unsatisfied dependencies:
        service jboss.jdbc-driver.mysql (missing) dependents: [service jboss.driver-demander.java:jboss/datasources/MySqlDS, service
  org.wildfly.data-source.MySqlDS]

And while test connection in Wildfly control panel:

{
      "outcome" => "failed",
      "failure-description" => "WFLYJCA0040: failed to invoke operation: WFLYJCA0042: failed to match pool. Check JndiName:
  java:jboss/datasources/MySqlDS",
      "rolled-back" => true }

答:
The main problem with the jar that you are using in kmodule.xml.

Please use latest jar from Mysql site.

Body:
I'm using Wildfly 10. At first I tried to create datasource via CLI.

A command deploy mysql-connector-java-6.0.4.jar was executed well.
/subsystem=datasources:installed-drivers-list shows that driver was installed

{
    "driver-name" => "mysql-connector-java-6.0.4.jar",
    "deployment-name" => "mysql-connector-java-6.0.4.jar",
    "driver-module-name" => undefined,
    "module-slot" => undefined,
    "driver-datasource-class-name" => undefined,
    "driver-xa-datasource-class-name" => undefined,
    "driver-class-name" => "com.mysql.cj.jdbc.Driver",
    "driver-major-version" => 6,
    "driver-minor-version" => 0,
    "jdbc-compliant" => false
}

But data source was not created with command

data-source add --name=zktest-datasource
--jndi-name=java:/jdbc/zktest-database --driver-name=mysql-connector-java-6.0.4.jar --connection-url=jdbc:mysql://localhost:3306/zktest --user-name=root --password=111

Connection test

/subsystem=datasources/data-source=zktest-datasource:test-connection-in-pool
was failed.

Now I trying to create datasource using standalone.xml

My modules.xml

<module xmlns="urn:jboss:module:1.1" name="com.mysql.jdbc">
  <resources>
    <resource-root path="mysql-connector-java-6.0.4.jar">
  </resource-root>
  </resources>
  <dependencies>
    <module name="javax.api"></module>
    <module name="javax.transaction.api"></module>
  </dependencies>
</module>

modules.xml placed into the JBOSS_HOME/modules/system/layers/base/com/mysql/jdbc

'Datasources' section in JBOSS_HOME/standalone/configuration/standalone.xml

<datasources>
        <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
            <driver>h2</driver>
            <security>
                <user-name>sa</user-name>
                <password>sa</password>
            </security>
        </datasource>
        <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS" enabled="true" use-java-context="true">
            <connection-url>jdbc:mysql://localhost:3306/zktest</connection-url>
            <driver>mysql</driver>
            <security>
                <user-name>root</user-name>
                <password>111</password>
            </security>
        </datasource>
        <drivers>
            <driver name="h2" module="com.h2database.h2">
                <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
            </driver>
            <driver name="mysql" module="com.mysql.jdbc">
                <xa-datasource-class>com.mysql.cj.jdbc.Driver</xa-datasource-class>
            </driver>
        </drivers>
    </datasources>

Now while deploing I see such message

WFLYCTL0184:    New missing/unsatisfied dependencies:
        service jboss.jdbc-driver.mysql (missing) dependents: [service jboss.driver-demander.java:jboss/datasources/MySqlDS, service
  org.wildfly.data-source.MySqlDS]

And while test connection in Wildfly control panel:

{
      "outcome" => "failed",
      "failure-description" => "WFLYJCA0040: failed to invoke operation: WFLYJCA0042: failed to match pool. Check JndiName:
  java:jboss/datasources/MySqlDS",
      "rolled-back" => true }


来源: stackexchange

问:
DB2 i5 no schemas with JDBC
I've got a stored procedure which I need to debug, and seeing how iNavigator is not that good in that regard, I got IBM Data Studio.

In order to be able to debug said procedure, I need to connect using the IBM Driver for JDBC and SQLJ. I took the name of the database from iNavigator, put everything in, hit test connection and I got the OK.

Now, if I open the connection and go in my database, I can see no schemas at all. If I try to perform any kind of operation (even a select) I get this error:

```<code>DB2 SQL Error: SQLCODE=-805, SQLSTATE=51002, SQLERRMC=NULLID.SYSSH200;00;S659e870          , DRIVER=4.18.60
</code>```

Weird thing is, it works perfectly if I use the AS/400 driver, but I just can't have that for debugging. I've scoured the web and I can't find the problem so far.

Thank you in advance!

答:
try to put inot your url connexion

```<code>jdbc:db2://SERVER400NAME:446/databasename:retrieveMessagesFromServerOnGetMessage=true;
</code>```

in tab optionnal add this:

```<code>Libraries=YOURLIB1,YOURLIB2
</code>```

ContentLicense: CC BY-SA 3.0

Title: DB2 i5 no schemas with JDBC

Body:
I've got a stored procedure which I need to debug, and seeing how iNavigator is not that good in that regard, I got IBM Data Studio.

In order to be able to debug said procedure, I need to connect using the IBM Driver for JDBC and SQLJ. I took the name of the database from iNavigator, put everything in, hit test connection and I got the OK.

Now, if I open the connection and go in my database, I can see no schemas at all. If I try to perform any kind of operation (even a select) I get this error:

DB2 SQL Error: SQLCODE=-805, SQLSTATE=51002, SQLERRMC=NULLID.SYSSH200;00;S659e870          , DRIVER=4.18.60

Weird thing is, it works perfectly if I use the AS/400 driver, but I just can't have that for debugging. I've scoured the web and I can't find the problem so far.

Thank you in advance!

Body:
try to put inot your url connexion

jdbc:db2://SERVER400NAME:446/databasename:retrieveMessagesFromServerOnGetMessage=true;

in tab optionnal add this:

Libraries=YOURLIB1,YOURLIB2


问:
Delegated event doesn't work for elements after sort
I have this HTML element:

```<code><div class="row preview-pictogram">
  <div class="column3 col-xs-3" data-index="3">
    <span class="index">Spalte <span>3</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column1 col-xs-4" data-index="1">
    <span class="index">Spalte <span>1</span></span>
    <span class="dec p-2">-</span>
    <span class="width">4</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column4 col-xs-3" data-index="4">
    <span class="index">Spalte <span>4</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
  <div class="column2 col-xs-3" data-index="2">
    <span class="index">Spalte <span>2</span></span>
    <span class="dec p-2">-</span>
    <span class="width">3</span>
    <span class="inc p-2">+</span>
  </div>
</div>
</code>```

The is a (delegated) event that listens on the click event of the .dec and .inc classes:

```<code>$(".dec, .inc").on("click", this.overlay, function () {
  _this.updateWidth(this);
});
</code>```

This works fine. But at one point I'm sorting the columns by its class name with this code:

```<code>ColumnConfigurator.prototype.sortColumns = function (columns) {
  var items = $("div", columns).get();
  items.sort(sort_by_class);
  $(columns).html(items);
};

var sort_by_class = function(a, b) {
  return $(a).attr("class").localeCompare($(b).attr("class"));
};
</code>```

After that happened that delegated event from above doesn't work anymore. I wonder why that happens. I thought the point of delegated events is that they work also for new elements. this.overlay is an element that contains the HTML above and it doesn't change at all.

答:
.on() should be used on the parent.
In your case if this.overlay is a jQuery element that contains the posted HTML then</p>

```<code>this.overlay.on("click", ".dec, .inc", function () {
  _this.updateWidth(this);
});
</code>```

Body:
I have this HTML element:

    Spalte 3
    -
    3
    +

    Spalte 1
    -
    4
    +

    Spalte 4
    -
    3
    +

    Spalte 2
    -
    3
    +

The is a (delegated) event that listens on the click event of the .dec and .inc classes:

$(".dec, .inc").on("click", this.overlay, function () {
  _this.updateWidth(this);
});

This works fine. But at one point I'm sorting the columns by its class name with this code:

ColumnConfigurator.prototype.sortColumns = function (columns) {
  var items = $("div", columns).get();
  items.sort(sort_by_class);
  $(columns).html(items);
};

var sort_by_class = function(a, b) {
  return $(a).attr("class").localeCompare($(b).attr("class"));
};

After that happened that delegated event from above doesn't work anymore. I wonder why that happens. I thought the point of delegated events is that they work also for new elements. this.overlay is an element that contains the HTML above and it doesn't change at all.

Body:
.on() should be used on the parent.
In your case if this.overlay is a jQuery element that contains the posted HTML then

this.overlay.on("click", ".dec, .inc", function () {
  _this.updateWidth(this);
});


问:
Having issues with python nested dictionaries
I am having a few newbie issues with python where, despite all the suggestions I've seen online, I can't access the value in a listed dictionary I'm trying to access.

This is the data the API returns:

```<code>OrderedDict([(u'totalSize', 1), (u'done', True), (u'records', [OrderedDict([(u'attributes', OrderedDict([(u'type', u'Contact'), (u'url', u'/services/data/v29.0/sobjects/Contact/00346000004eV89AAE')])), (u'Name', u'This is my name')])])])
</code>```

This is my most recent attempt:

```<code>dict['records']['Name']

    print(dict['records']['Name'])
TypeError: list indices must be integers, not str
</code>```

Any help would be greatly appreciated

答:
You just need to remove the brackets around the nested OrderedDict, so

```<code>OrderedDict([..., (u'records', OrderedDict([...]))])
</code>```

instead of

```<code>OrderedDict([..., (u'records', [OrderedDict([...])])])
</code>```

This is because OrderedDict expects its argument to be a list of key-value pairs. In your code, the value for the key 'records' is a list containing a single dictionary. You want it to just be a dictionary.

EDIT: Since you can't change the data that's being used to construct the dictionary there are a couple of workarounds.

Workaround #1

Put up with a more annoying calling scheme:

```<code>d['records'][0]['Name']
</code>```

This is the simpler workaround but of course it is ugly and harder to understand.

Workaround #2

Wrap the OrderedDict in a new class that customizes the item access syntax.

```<code>class MyOrderedDict(OrderedDict):
    def __getitem__(self, key):
        ret = super().__getitem__(key)
        if isinstance(ret, list):
            if ret and isinstance(ret[0], OrderedDict):
                return ret[0]
        return ret
</code>```

This makes it so that if the return value of call like d['records'] is a list whose first element is an OrderedDict, then the OrderedDict will be returned instead of the list, so that you can just chain the item accesses. You would write it like this:

```<code>d = MyOrderedDict(api_data)
d['records']['Name'] # 'This is my name'
</code>```

Body:
I am having a few newbie issues with python where, despite all the suggestions I've seen online, I can't access the value in a listed dictionary I'm trying to access.

This is the data the API returns:

OrderedDict([(u'totalSize', 1), (u'done', True), (u'records', [OrderedDict([(u'attributes', OrderedDict([(u'type', u'Contact'), (u'url', u'/services/data/v29.0/sobjects/Contact/00346000004eV89AAE')])), (u'Name', u'This is my name')])])])

This is my most recent attempt:

dict['records']['Name']

    print(dict['records']['Name'])
TypeError: list indices must be integers, not str

Any help would be greatly appreciated

Body:
You just need to remove the brackets around the nested OrderedDict, so

OrderedDict([..., (u'records', OrderedDict([...]))])

instead of

OrderedDict([..., (u'records', [OrderedDict([...])])])

This is because OrderedDict expects its argument to be a list of key-value pairs. In your code, the value for the key 'records' is a list containing a single dictionary. You want it to just be a dictionary.

EDIT: Since you can't change the data that's being used to construct the dictionary there are a couple of workarounds.

Workaround #1

Put up with a more annoying calling scheme:

d['records'][0]['Name']

This is the simpler workaround but of course it is ugly and harder to understand.

Workaround #2

Wrap the OrderedDict in a new class that customizes the item access syntax.

class MyOrderedDict(OrderedDict):
    def __getitem__(self, key):
        ret = super().__getitem__(key)
        if isinstance(ret, list):
            if ret and isinstance(ret[0], OrderedDict):
                return ret[0]
        return ret

This makes it so that if the return value of call like d['records'] is a list whose first element is an OrderedDict, then the OrderedDict will be returned instead of the list, so that you can just chain the item accesses. You would write it like this:

d = MyOrderedDict(api_data)
d['records']['Name'] # 'This is my name'


问:
Check and uncheck checkbox and read its state
How can I read the state of my checkbox and set it's state to be visible ? I'm trying something like this, but it always returns true:</p>

```<code> $('.show-check').live('click', function(e) {
    e.preventDefault();

    var checked = ($(this).is(':checked'));
    if(checked == true){
       $(this).attr('checked', true);
    }
    else{
        $(this).attr('checked', false);
    }
 });

    <li>
        <img src="" class="show-image"/>
        <span class="show-title"></span>
        <input type="checkbox" class="show-check" />
    </li>
</code>```

答:
It works this way:

```<code> $('.show-check').live('click', function() {

var checked = ($(this).is(':checked'));

if(checked){
   $(this).attr('checked', true);
}
else{
    $(this).attr('checked', false);
}
</code>```

});

I think you couldn't check the checkbox because the default action is prevented, which is to check/uncheck the box

Here's my thought:

the checkbox is initially unchecked;

when you click the checkbox, the click event is fired, and the var checked is set to true;

since it's set to true, the if(checked) block will always be executed;

but you may wonder why the checkbox is not checked on the UI. I think it's because you set e.preventDefault() which tells the checkbox not to be affected by the default behaviour of click event, which is to check it;

the next time you check it again, same thing will happen.

ContentLicense: CC BY-SA 2.5

Body:
How can I read the state of my checkbox and set it's state to be visible ? I'm trying something like this, but it always returns true:

 $('.show-check').live('click', function(e) {
    e.preventDefault();

    var checked = ($(this).is(':checked'));
    if(checked == true){
       $(this).attr('checked', true);
    }
    else{
        $(this).attr('checked', false);
    }
 });

        <input type="checkbox" class="show-check" />

Body:
It works this way:

 $('.show-check').live('click', function() {

var checked = ($(this).is(':checked'));

if(checked){
   $(this).attr('checked', true);
}
else{
    $(this).attr('checked', false);
}

});

I think you couldn't check the checkbox because the default action is prevented, which is to check/uncheck the box

Here's my thought:

the checkbox is initially unchecked;

when you click the checkbox, the click event is fired, and the var checked is set to true;

since it's set to true, the if(checked) block will always be executed;

but you may wonder why the checkbox is not checked on the UI. I think it's because you set e.preventDefault() which tells the checkbox not to be affected by the default behaviour of click event, which is to check it;

the next time you check it again, same thing will happen.


问:
RangetoHTML no longer working
When I run the macro I get

Compile Error: Wrong number of arguements or invalid property assignment

the Function RangetoHTML(rng As Range) is highlighted yellow and format in the TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm" line is highlighted gray

```<code>Sub GenerateEmail()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    MsgBox "This will generate an email, please check Outlook"

    Set rng = Sheets("ERC NPA").Range("B2:H23").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = Range("G13") & " : Payment Request"
        .HTMLBody = "Please find below payment request form" & RangetoHTML(rng)
        .display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub
</code>```

```<code>Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
</code>```

答:
```<code>Sub testFunction()
'   Try testing the function like this to pinpoint the problem
'   It works fine for me on Excel 2013
'   Cool function, btw
Dim rng As Range
Dim someString As String

    Set rng = Sheets("ERC NPA").Range("B2:H23").SpecialCells(xlCellTypeVisible)
    someString = RangetoHTML(rng)
    Debug.Print someString

Set rng = Nothing
End Sub
</code>```

Title: RangetoHTML no longer working

Body:
When I run the macro I get

Compile Error: Wrong number of arguements or invalid property assignment

the Function RangetoHTML(rng As Range) is highlighted yellow and format in the TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm" line is highlighted gray

Sub GenerateEmail()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    MsgBox "This will generate an email, please check Outlook"

    Set rng = Sheets("ERC NPA").Range("B2:H23").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = Range("G13") & " : Payment Request"
        .HTMLBody = "Please find below payment request form" & RangetoHTML(rng)
        .display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function


问:
Python error : index out of bounds
I was curious about image processing with python, so I found this great library imageio,
I tried to manipulate the pixels of a picture and save them in a new file,
but i had some problems with the loops
this is what the code looks like
enter image description here
and this the error that i Got !
IndexError: index 3507 is out of bounds for axis 0 with size 3507
the code :</p>

```<code> # -*- coding: iso-8859-1 -*-
    import imageio
    import numpy as np
    im = imageio.imread("JAFFRE009a.png")
    taille=im.shape  #taille is a tuple (Width,Height)
    print taille  # (4961,3507)
    matrice_pixels=open("matrice.txt",'w')
    for i in range(taille[1]):
        line=""
        for j in range(taille[0]):
            line+=repr(im[i][j])
        matrice_pixels.write(line+'\n')
    matrice_pixels.close()
</code>```

答: Because your image doesn't have squarred shape, reshape it before you go through your loop</p>

Title: Python error : index out of bounds

Body:
I was curious about image processing with python, so I found this great library imageio,
I tried to manipulate the pixels of a picture and save them in a new file,
but i had some problems with the loops
this is what the code looks like
enter image description here
and this the error that i Got !
IndexError: index 3507 is out of bounds for axis 0 with size 3507
the code :

 # -*- coding: iso-8859-1 -*-
    import imageio
    import numpy as np
    im = imageio.imread("JAFFRE009a.png")
    taille=im.shape  #taille is a tuple (Width,Height)
    print taille  # (4961,3507)
    matrice_pixels=open("matrice.txt",'w')
    for i in range(taille[1]):
        line=""
        for j in range(taille[0]):
            line+=repr(im[i][j])
        matrice_pixels.write(line+'\n')
    matrice_pixels.close()


问:
on the Y/N I would like a lowercase y to be able to respond exactly how an uppercase Y would
When it asks the user if they would like to "run the coin toss simulation(Y/N)" I want the user to be able to input a lowercase y as well as an uppercase Y and having them both do the same thing. What is happening when I put a lowercase y is that it gives me the goodbye message as if the user inputted N

the areas that deal with this are on lines 7-9 and 32-34 any help is greatly appreciated, thanks all

```<code>import random
def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return
</code>```

main()

答:
Use the .lower() method:

```<code>if yn.lower() != 'y'
</code>```

You could also use .upper():

```<code>if yn.upper() != 'Y'
</code>```

However, programmers are lazy and like to avoid hitting the Shift key as much as possible, hence the ongoing popularity of .lower().

Body:
When it asks the user if they would like to "run the coin toss simulation(Y/N)" I want the user to be able to input a lowercase y as well as an uppercase Y and having them both do the same thing. What is happening when I put a lowercase y is that it gives me the goodbye message as if the user inputted N

the areas that deal with this are on lines 7-9 and 32-34 any help is greatly appreciated, thanks all

import random
def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return

main()

Body:
Use the .lower() method:

if yn.lower() != 'y'

You could also use .upper():

if yn.upper() != 'Y'

However, programmers are lazy and like to avoid hitting the Shift key as much as possible, hence the ongoing popularity of .lower().


问:
How to execute different @Before in JUnit
Currently If I write @Before method, it will be executed for each of tests present in the JUnit. However i want the following.

I need to have multiple @Before methods and only needed should be executed for each test.

```<code>Example:
 @Before
  setUpBeforeForTest1AndTest3()

 @Before
 setUpBeforeForTest2AndTest4()
</code>```

For test1 and test2, setUpBeforeForTest1AndTest3() should be executed and for other tests setUpBeforeForTest2AndTest4 should be executed.

How i can acheive this?

答:
You can use Junit

@Rule TestName

Then in your

@Before, depending on the test method name, do something differently.

Body:
Currently If I write @Before method, it will be executed for each of tests present in the JUnit. However i want the following.

I need to have multiple @Before methods and only needed should be executed for each test.

Example:
 @Before
  setUpBeforeForTest1AndTest3()

 @Before
 setUpBeforeForTest2AndTest4()

For test1 and test2, setUpBeforeForTest1AndTest3() should be executed and for other tests setUpBeforeForTest2AndTest4 should be executed.

How i can acheive this?


问:
Sort an ArrayList base on multiple attributes
I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?

答:
Implement a custom Comparator, then use Collections.sort(List, Comparator). It will probably look something like this:

```<code>public class FooComparator implements Comparator<Foo> {
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
}

Collections.sort(foos, new FooComparator());
</code>```

Body:
Implement a custom Comparator, then use Collections.sort(List, Comparator). It will probably look something like this:

public class FooComparator implements Comparator<Foo> {
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
}

Collections.sort(foos, new FooComparator());


问:
What data file to use for easily importing into an iOS app with Swift?
I'm creating an app which generates a random question from a list  (currently stored as a Numbers doc). Once that question is answered by the user, the unique question ID, the question itself and their answer is stored in core data.

When the user requests a new question one will be generated randomly from the original document and it will then be cross referenced with core data to find out if the user has previous answered that question.

I haven't included the code of my app at the moment as I'm not really looking for specific coding help. As someone who is new to the world of code I'm just looking for a nudge in the right direction for me to go and do more studying.

JSON looks like a possible, but the more I read about that the more it seems that it is about an app communicating with a website. I don't really want the questions to be accessed by just anyone, so putting them on my website might not work? Could I do it with a file local in the app? maybe a CSV?

I'm anticipating the file may become quite big as I add more questions - so I'm not sure if that changes things?

Thanks so much in advance, and apologies if this isn't quite the right way to ask questions on here.

答:
I'm just looking for a nudge in the right direction for me to go and
  do more studying.

There are many options to solve your problem. Each option depends on your skill, time and if the solution is even necessary for the app you want to make. In the end it's you who decides on which solution solves your problem. There are a few options:

creating your own backend

have a local file in your app

or use a third party service like Firebase.

Each option has its own benefits. Just to list a few:

Local file:

You could have a local file in nearly any format (XML, JSON, .plist) etc. The downside is that your app isn't dynamic - you have to manually keep adding text to this file and update your app trough the App Store for your users to see these changes. If you're going with this approach, I'd recommend using a .plist or a JSON file which is saved in your project. How to implement this correctly is beyond the scope of the question, but there are plenty tutorials out there to help you getting started.

You could put your data in a .plist file. This is nothing more than a dictionary with key-value data (same principle as JSON where each key has a value). An example:

question1 is the key, of type String, containing the value "How are you today". It's easy to read from this .plist since it's the same principle as JSON.

Also, JSON is just a format, it's used often to communicate with websites, but it's not limited to sites only.

Custom backend

This means that you make a backend on which your app can communicate with. You'd have to host your backend, write logic / code on your backend and so on. This can be very time consuming, especially if your app isn't that big/demanding. I wouldn't recommend this unless you have the experience, time, patience and need for this solution.

Third party

This can be a nice solution. Using a third party service like Firebase means that you have your data online. The Firebase library has been well tested and has great documentation to get you started. It's secure, fast, simple but .. it does take a little bit of time to learn how it works - but the end result is that you have a dynamic app where you can add, delete, edit questions and so on. This data can be protected if you wish - which means only authenticated users can access this data (Nobody else will be spying on your data :))

I don't really want the questions to be accessed by just anyone, so
  putting them on my website might not work?

Read custom backend and Third Party.

Could I do it with a file local in the app?

Yes. Read Local file.

maybe a CSV?

That's possible but I wouldn't recommend it, but that's a personal opinion. I find it outdated and it's more difficult to work with than JSON.

I'm anticipating the file may become quite big as I add more questions
  - so I'm not sure if that changes things?

What is a big file? Nowadays reading a "big" JSON file is probably nothing more than a few MB at most. Your phone reads this in no time. This won't be an issue for your phone or app.


问:
JQuery call function and multiple params from string
If I have a function:

```<code>function myfunc(param1, param2, param3) {
  // ...
}
</code>```

and I have a string:

```<code>var myCall = "myfunc(1, 'abc', 'true')"
</code>```

Is there a way to make the function call using the string and include the params?  I don't know the number of parameters in advance.
I have tried

```<code>var func = myCall.substr(0, myCall.indexOf('('));
var args = myCall.substring(myCall.indexOf('(')+1, myCall.length-1);
window[func](args.split(','));
</code>```

but that just calls the function with an array to the first parameter.  How do I split the arguments and pass them in with an unknown number of parameters?

答:
You can do this using the Function constructor:

function myfunc(param1, param2, param3) {
    console.log(param1, param2, param3);
}

var myCall = "myfunc(1, 'abc', 'true')";
// here the 'myfunc' string indicates the name of a parameter that will
// be passed into the function that new Function is creating.
// i.e., we are going to pass in the myfunc function
// when we actually call myCaller
var myCaller = new Function('myfunc', myCall);

myCaller(myfunc);```

Body:
If I have a function:

function myfunc(param1, param2, param3) {
  // ...
}

and I have a string:

var myCall = "myfunc(1, 'abc', 'true')"

Is there a way to make the function call using the string and include the params?  I don't know the number of parameters in advance.
I have tried

var func = myCall.substr(0, myCall.indexOf('('));
var args = myCall.substring(myCall.indexOf('(')+1, myCall.length-1);
window[func](args.split(','));

but that just calls the function with an array to the first parameter.  How do I split the arguments and pass them in with an unknown number of parameters?


问:
onClick() display formatted time, Reactive, Vue.js and Firebase DB
Long time browser, first time questioner.

So for an in and out board I need employees to click the "out button" and with a Vue.js v-on:click() next to it I want to to display "Out at 3:55pm".

Here is the button -

<button class="btn btn-smaller btn-out" v-show="user.in" v-on:click="updateOut(user)">out</button>

Which in turn updates the usersRef timeOut status in the Firebase DB like this -

```<code>updateOut: function (user) {usersRef.child(user['.key']).child('in').set(false)
         usersRef.child(user['.key']).child('timeOut').set(Date())
    },
</code>```

Which updates this with the actual date stamp -

```<code>{{ user.timeOut }}
</code>```

The problem I am getting is that I can not format this inside the updateOut function to simply show "out at 3:55pm". I can only get it to show "Wed Mar 29 2017 10:55:02 GMT-0600 (MDT)"

Srinivas - I can't get this to work. I tried this -

```<code>methods: {
    addUser: function () {
      if (this.newUserName) {
        usersRef.push({
          name: this.newUserName,
          in: false,
          returnTime: ''

        })
        this.newUserName = ''
      },
    },
    getTime: function(user) {
      const outTime = new Date(this.user.timeOut)
      const hours = outTime.getHours()
      let minutes = outTime.getMinutes()
      if (minutes < 10) minutes = "0" + minutes // prepend 0
      return (hours + ":" + minutes)
    },
    updateReturnTime: function (user, newText) {
        usersRef.child(user['.key']).child('returnTime').set(newText)
    },
    updateIn: function (user) {
        usersRef.child(user['.key']).child('in').set(true)
        usersRef.child(user['.key']).child('timeOut').set('')
    },
    updateOut: function (user) {
         usersRef.child(user['.key']).child('in').set(false)
         usersRef.child(user['.key']).child('timeOut').set(Date.now())
    },
</code>```

答:
You can create a method to convert date into required format.

```<code>methods: {
 getTime() {
  const outTime = new Date(this.user.timeOut)
  const hours = outTime.getHours()
  let minutes = outTime.getMinutes()
  if (minutes < 10) minutes = "0" + minutes // prepend 0
  return (hours + ":" + minutes)
 }
}
</code>```

If you are using this method in multiple places, you can create a filter.

```<code>Vue.filter('getTime', function(date) {
    const outTime = new Date(date)
    const hours = outTime.getHours()
    let minutes = outTime.getMinutes()
    if (minutes < 10) minutes = "0" + minutes // prepend 0
    return (hours + ":" + minutes)
})

You can use it template like this.

{{ user.timeOut | getTime }}
</code>```

Body:
Long time browser, first time questioner.

So for an in and out board I need employees to click the "out button" and with a Vue.js v-on:click() next to it I want to to display "Out at 3:55pm".

Here is the button -

<button class="btn btn-smaller btn-out" v-show="user.in" v-on:click="updateOut(user)">out</button>

Which in turn updates the usersRef timeOut status in the Firebase DB like this -

updateOut: function (user) {usersRef.child(user['.key']).child('in').set(false)
         usersRef.child(user['.key']).child('timeOut').set(Date())
    },

Which updates this with the actual date stamp -

{{ user.timeOut }}

The problem I am getting is that I can not format this inside the updateOut function to simply show "out at 3:55pm". I can only get it to show "Wed Mar 29 2017 10:55:02 GMT-0600 (MDT)"

Srinivas - I can't get this to work. I tried this -

methods: {
    addUser: function () {
      if (this.newUserName) {
        usersRef.push({
          name: this.newUserName,
          in: false,
          returnTime: ''

        })
        this.newUserName = ''
      },
    },
    getTime: function(user) {
      const outTime = new Date(this.user.timeOut)
      const hours = outTime.getHours()
      let minutes = outTime.getMinutes()
      if (minutes < 10) minutes = "0" + minutes // prepend 0
      return (hours + ":" + minutes)
    },
    updateReturnTime: function (user, newText) {
        usersRef.child(user['.key']).child('returnTime').set(newText)
    },
    updateIn: function (user) {
        usersRef.child(user['.key']).child('in').set(true)
        usersRef.child(user['.key']).child('timeOut').set('')
    },
    updateOut: function (user) {
         usersRef.child(user['.key']).child('in').set(false)
         usersRef.child(user['.key']).child('timeOut').set(Date.now())
    },

Body:
You can create a method to convert date into required format.

methods: {
 getTime() {
  const outTime = new Date(this.user.timeOut)
  const hours = outTime.getHours()
  let minutes = outTime.getMinutes()
  if (minutes < 10) minutes = "0" + minutes // prepend 0
  return (hours + ":" + minutes)
 }
}

If you are using this method in multiple places, you can create a filter.

Vue.filter('getTime', function(date) {
    const outTime = new Date(date)
    const hours = outTime.getHours()
    let minutes = outTime.getMinutes()
    if (minutes < 10) minutes = "0" + minutes // prepend 0
    return (hours + ":" + minutes)
})

You can use it template like this.

{{ user.timeOut | getTime }}


问:
ng-click is not firing
adding the following 'hyperlink' to html like:

```<code><a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>
</code>```

and then use this code to trigger click event like

```<code> $scope.ClickMe = function () { alert("clicked"); }
</code>```

works fine, but this did not work when  'hyperlink' generated dynamically like

```<code> $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");
</code>```

Could anyone explain why did that happen?

答: Angular processes the bindings on load.  Since the element is generated dynamically, you will have to bind it dynamically as well.</p>

Title: ng-click is not firing

Body:
adding the following 'hyperlink' to html like:

Click

and then use this code to trigger click event like

 $scope.ClickMe = function () { alert("clicked"); }

works fine, but this did not work when  'hyperlink' generated dynamically like

 $('Click').insertAfter("#dashboard_link");

Could anyone explain why did that happen?


问:
Left outer join runtime error with LINQ
I'm trying to write a left outer join query with Linq on 2 tables, but getting NULL reference exception during runtime, when there are null values in the right table.

For all MatchID values as on tbl_Match table tbl_UserBets table does not have values for all. Hence when NULL value comes up, I'm getting run time exception

PFB my LINQ query,

```<code>string userID = "dfa3c0e7-2aa3-42ee-a7d3-803db902dc56";
var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam1 == userID).FirstOrDefault(b => b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam2 == userID).FirstOrDefault(b => b.MatchID == m.MatchID)
            });

            foreach (var item in res2)
            {
                Console.WriteLine(item.MatchID + " " + item.Team1 + " vs " + item.Team2 + " " + item.UserForTeam1 == null ? " NA " : item.UserForTeam1.UserForTeam1);
            }
</code>```

SQL Table design for tbl_Match table:

```<code>Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);
</code>```

SQL Table design for tbl_UserBets table:

```<code>Create Table tbl_UserBets(
UserBetSlNo int primary key identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
MatchID int Foreign key references tbl_Match(MatchID),
UserForTeam1 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForTeam2 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForNoBets nvarchar(128) Foreign key references AspNetUsers(Id)
);
</code>```

With the below query in SQL i'm able to get the results properly, Need to do the same with LINQ.

```<code>select DISTINCT(tbl_Match.MatchID),tbl_Match.Team1,tbl_Match.Team2,tbl_Match.StartTime,tbl_Match.MatchBetAmount,tbl_UserBets.UserForTeam1,tbl_UserBets.UserForTeam2,tbl_UserBets.UserForNoBets from tbl_Match left outer join tbl_UserBets on tbl_Match.MatchID = tbl_UserBets.MatchID and (tbl_UserBets.UserForTeam1 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56' or tbl_UserBets.UserForTeam2 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56')
</code>```

Please let me know, what changes i should be doing to fix the issue. Thanks.

答:
try merging the where condition with the first or default

i'm guessing the problem is when the where returns null the first or default will cause the exception as stated by msdn doc

```<code>var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam1 == userID && b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam2 == userID && b.MatchID == m.MatchID)
            });
</code>```

Title: Left outer join runtime error with LINQ

Body:
I'm trying to write a left outer join query with Linq on 2 tables, but getting NULL reference exception during runtime, when there are null values in the right table.

For all MatchID values as on tbl_Match table tbl_UserBets table does not have values for all. Hence when NULL value comes up, I'm getting run time exception

PFB my LINQ query,

string userID = "dfa3c0e7-2aa3-42ee-a7d3-803db902dc56";
var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam1 == userID).FirstOrDefault(b => b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam2 == userID).FirstOrDefault(b => b.MatchID == m.MatchID)
            });

            foreach (var item in res2)
            {
                Console.WriteLine(item.MatchID + " " + item.Team1 + " vs " + item.Team2 + " " + item.UserForTeam1 == null ? " NA " : item.UserForTeam1.UserForTeam1);
            }

SQL Table design for tbl_Match table:

Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);

SQL Table design for tbl_UserBets table:

Create Table tbl_UserBets(
UserBetSlNo int primary key identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
MatchID int Foreign key references tbl_Match(MatchID),
UserForTeam1 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForTeam2 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForNoBets nvarchar(128) Foreign key references AspNetUsers(Id)
);

With the below query in SQL i'm able to get the results properly, Need to do the same with LINQ.

select DISTINCT(tbl_Match.MatchID),tbl_Match.Team1,tbl_Match.Team2,tbl_Match.StartTime,tbl_Match.MatchBetAmount,tbl_UserBets.UserForTeam1,tbl_UserBets.UserForTeam2,tbl_UserBets.UserForNoBets from tbl_Match left outer join tbl_UserBets on tbl_Match.MatchID = tbl_UserBets.MatchID and (tbl_UserBets.UserForTeam1 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56' or tbl_UserBets.UserForTeam2 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56')

Please let me know, what changes i should be doing to fix the issue. Thanks.

Body:
try merging the where condition with the first or default

i'm guessing the problem is when the where returns null the first or default will cause the exception as stated by msdn doc

var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam1 == userID && b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam2 == userID && b.MatchID == m.MatchID)
            });


问:
validation for php

Possible Duplicate:

  Is there a php library for email address validation?

How can I create a validation for email address?

答:
use filter</p>

```<code><?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>
</code>```

Title: validation for php

Body:
use filter

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>


问:
Break into multiple rows based on date range of a single row
I have a table which captures appointments, some are single day appointments and some are multi day appointments, so the data looks like

```<code>AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-03
11              2017-06-01  2017-06-01
</code>```

I want to split the multi day appointment as single days, so the result I am trying to achieve is like

```<code>AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01
</code>```

So I have split the appointment id 10 into multiple rows. I checked a few other questions like
here but those are to split just based on a single start date and end date and not based on table data

答:
You can use a Calendar or dates table for this sort of thing.

For only 152kb in memory, you can have 30 years of dates in a table with this:

```<code>/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
  on dbo.Dates([Date]);
</code>```

Without taking the actual step of creating a table, you can use it inside a common table expression with just this:

```<code>declare @fromdate date = '20161229';
declare @thrudate date = '20170103';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;
</code>```

Use either like so:

```<code>select
    t.AppointmentId
  , StartDate = d.date
  , EndDate = d.date
from dates d
  inner join appointments t
    on d.date >= t.StartDate
   and d.date <= t.EndDate
</code>```

rextester demo: http://rextester.com/TNWQ64342

returns:

```<code>+---------------+------------+------------+
| AppointmentId | StartDate  |  EndDate   |
+---------------+------------+------------+
|             9 | 2017-04-12 | 2017-04-12 |
|            10 | 2017-05-01 | 2017-05-01 |
|            10 | 2017-05-02 | 2017-05-02 |
|            10 | 2017-05-03 | 2017-05-03 |
|            11 | 2017-06-01 | 2017-06-01 |
+---------------+------------+------------+
</code>```

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand

tsql Function to Determine Holidays in sql Server - Aaron Bertrand

F_table_date - Michael Valentine Jones

Body:
I have a table which captures appointments, some are single day appointments and some are multi day appointments, so the data looks like

AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-03
11              2017-06-01  2017-06-01

I want to split the multi day appointment as single days, so the result I am trying to achieve is like

AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01

So I have split the appointment id 10 into multiple rows. I checked a few other questions like
here but those are to split just based on a single start date and end date and not based on table data

Body:
You can use a Calendar or dates table for this sort of thing.

For only 152kb in memory, you can have 30 years of dates in a table with this:

/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
  on dbo.Dates([Date]);

Without taking the actual step of creating a table, you can use it inside a common table expression with just this:

declare @fromdate date = '20161229';
declare @thrudate date = '20170103';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;

Use either like so:

select
    t.AppointmentId
  , StartDate = d.date
  , EndDate = d.date
from dates d
  inner join appointments t
    on d.date >= t.StartDate
   and d.date <= t.EndDate

rextester demo: http://rextester.com/TNWQ64342

returns:

+---------------+------------+------------+
| AppointmentId | StartDate  |  EndDate   |
+---------------+------------+------------+
|             9 | 2017-04-12 | 2017-04-12 |
|            10 | 2017-05-01 | 2017-05-01 |
|            10 | 2017-05-02 | 2017-05-02 |
|            10 | 2017-05-03 | 2017-05-03 |
|            11 | 2017-06-01 | 2017-06-01 |
+---------------+------------+------------+

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand

tsql Function to Determine Holidays in sql Server - Aaron Bertrand

F_table_date - Michael Valentine Jones


问:
How to cancel timeout inside of Javascript Promise?
I'm toying with promises in JavaScript and tried to promisify setTimeout function:

```<code>function timeout(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('timeout done');
    }, ms);
  });
}

var myPromise=timeout(3000);

myPromise.then(function(result) {
  console.log(result); // timeout done
})
</code>```

Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. timeout returns Promise object hence I loose access to value that setTimeout returns and cannot cancel timeout via clearTimeout. What woud be the best way to do it?

BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview

答:
The above to answers by @Benjamin and @PSL work, but what if you need the cancelable timeout to be used by an outside source while being canceled internally?

For example, the interaction might look somewhat like this:

```<code>// externally usage of timeout
async function() {
  await timeout() // timeout promise
}

// internal handling of timeout
timeout.cancel()
</code>```

I needed this kind of implementation myself, so here's what I came up with:

```<code>/**
 * Cancelable Timer hack.
 *
 *  @notes
 *    - Super() does not have `this` context so we have to create the timer
 *      via a factory function and use closures for the cancelation data.
 *    - Methods outside the consctutor do not persist with the extended
 *      promise object so we have to declare them via `this`.
 *  @constructor Timer
 */
function createTimer(duration) {
  let timerId, endTimer
  class Timer extends Promise {
    constructor(duration) {
      // Promise Construction
      super(resolve => {
        endTimer = resolve
        timerId = setTimeout(endTimer, duration)
      })
      // Timer Cancelation
      this.isCanceled = false
      this.cancel = function() {
        endTimer()
        clearTimeout(timerId)
        this.isCanceled = true
      }
    }
  }
  return new Timer(duration)
}
</code>```

Now you can use the timer like this:

```<code>let timeout = createTimer(100)
</code>```

And have the promise canceled somewhere else:

```<code> if (typeof promise !== 'undefined' && typeof promise.cancel === 'function') {
  timeout.cancel()
}
</code>```

Body:
I'm toying with promises in JavaScript and tried to promisify setTimeout function:

function timeout(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('timeout done');
    }, ms);
  });
}

var myPromise=timeout(3000);

myPromise.then(function(result) {
  console.log(result); // timeout done
})

Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. timeout returns Promise object hence I loose access to value that setTimeout returns and cannot cancel timeout via clearTimeout. What woud be the best way to do it?

BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview

Body:
The above to answers by @Benjamin and @PSL work, but what if you need the cancelable timeout to be used by an outside source while being canceled internally?

For example, the interaction might look somewhat like this:

// externally usage of timeout
async function() {
  await timeout() // timeout promise
}

// internal handling of timeout
timeout.cancel()

I needed this kind of implementation myself, so here's what I came up with:

/**
 * Cancelable Timer hack.
 *
 *  @notes
 *    - Super() does not have `this` context so we have to create the timer
 *      via a factory function and use closures for the cancelation data.
 *    - Methods outside the consctutor do not persist with the extended
 *      promise object so we have to declare them via `this`.
 *  @constructor Timer
 */
function createTimer(duration) {
  let timerId, endTimer
  class Timer extends Promise {
    constructor(duration) {
      // Promise Construction
      super(resolve => {
        endTimer = resolve
        timerId = setTimeout(endTimer, duration)
      })
      // Timer Cancelation
      this.isCanceled = false
      this.cancel = function() {
        endTimer()
        clearTimeout(timerId)
        this.isCanceled = true
      }
    }
  }
  return new Timer(duration)
}

Now you can use the timer like this:

let timeout = createTimer(100)

And have the promise canceled somewhere else:

 if (typeof promise !== 'undefined' && typeof promise.cancel === 'function') {
  timeout.cancel()
}


问:
Google BigQuery create simple count table
I want to user Google Bigquery to store number of searches for certain keyword in my site. I create table structure like this:

```<code>| date       | keyword | number_of_searches |
| 2017-03-29 | pizza   | 1                  |
</code>```

I want to increment number_of_searches value if combination of date and keyword already exists.

答:
So you wanted a solution to store number of searches for certain keyword.

Using BigQuery technology you need to change some approach.

Let's discuss traditional steps:

- use a SELECT to find out if there is a row for today

- if not, then INSERT one with default

- when exists, use an UPDATE statement to increment counter

With BigQuery where the main change is that it's append only and it's not suitable to do UPDATE statements, you need to change how you analyse data and simplify the collection. Instead of doing 3 steps like above you would do one:

- insert a new row for each search

This way you will end up with multiple rows, and you can aggregate to find out the value and can run a query to find out how many searches you had for your queries, it would be something like this:

```<code>SELECT
   myday as date,
   keyword,
   count(1) as number_of_search
FROM table
group by 1,2
</code>```

Body:
I want to user Google Bigquery to store number of searches for certain keyword in my site. I create table structure like this:

| date       | keyword | number_of_searches |
| 2017-03-29 | pizza   | 1                  |

I want to increment number_of_searches value if combination of date and keyword already exists.

Body:
So you wanted a solution to store number of searches for certain keyword.

Using BigQuery technology you need to change some approach.

Let's discuss traditional steps:

- use a SELECT to find out if there is a row for today

- if not, then INSERT one with default

- when exists, use an UPDATE statement to increment counter

With BigQuery where the main change is that it's append only and it's not suitable to do UPDATE statements, you need to change how you analyse data and simplify the collection. Instead of doing 3 steps like above you would do one:

- insert a new row for each search

This way you will end up with multiple rows, and you can aggregate to find out the value and can run a query to find out how many searches you had for your queries, it would be something like this:

SELECT
   myday as date,
   keyword,
   count(1) as number_of_search
FROM table
group by 1,2


问:
How to stop loop with delay to continue another
I am trying to make two things happen at once, but only one of them is allowed. If something is already occuring, I need to be able to stop that completely and let the other one take over. Here is my example:

https://jsfiddle.net/mortenmoulder/5eceLvgu/

```<code>function log(text, interval, amount) {
    (function myLoop(i) {
        timer = setTimeout(function() {
            console.log(text);
            if (--i) myLoop(i);
        }, interval)
    })(amount);
}

$("#first").on("click", () => log("first", 500, 10));
$("#second").on("click", () => log("second", 500, 10));
</code>```

Click on the first button, it will console.log("first") 10 times with a 500ms delay. When you click on the second button, it should cancel the first one and start console.log("second") without being interrupted (unless you click on the first button).

How can I do that? I need to delay the loop and I need to have one function to do this (so not a lot of if-statements with each button, as there are many buttons).

答:
You need to store the timer id and clear it if you call log:

```<code>var logTimer;

function log(text, interval, amount) {
  clearTimeout(logTimer);
  (function myLoop(i) {
    logTimer = setTimeout(function() {
      console.log(text);
      if (--i) myLoop(i);
    }, interval)
  })(amount);
}
</code>```

Body:
I am trying to make two things happen at once, but only one of them is allowed. If something is already occuring, I need to be able to stop that completely and let the other one take over. Here is my example:

https://jsfiddle.net/mortenmoulder/5eceLvgu/

function log(text, interval, amount) {
    (function myLoop(i) {
        timer = setTimeout(function() {
            console.log(text);
            if (--i) myLoop(i);
        }, interval)
    })(amount);
}

$("#first").on("click", () => log("first", 500, 10));
$("#second").on("click", () => log("second", 500, 10));

Click on the first button, it will console.log("first") 10 times with a 500ms delay. When you click on the second button, it should cancel the first one and start console.log("second") without being interrupted (unless you click on the first button).

How can I do that? I need to delay the loop and I need to have one function to do this (so not a lot of if-statements with each button, as there are many buttons).

Body:
You need to store the timer id and clear it if you call log:

var logTimer;

function log(text, interval, amount) {
  clearTimeout(logTimer);
  (function myLoop(i) {
    logTimer = setTimeout(function() {
      console.log(text);
      if (--i) myLoop(i);
    }, interval)
  })(amount);
}


问:
SSO IdentityServer3 Authentication and MVC
I have an MVC 4.5 project which will have multiple domains, for example:

HTTPS:// domain1 .com (secured with SSL)

HTTP:// domain2 .com

HTTP:// domain3 .com

Only the secure domain (https://domain1.com) will be used to authorize users. After signing in, Users should be authenticated across all the other domains.

What I did to achieve this:
I have installed identity server and made it work perfectly. But I still wonder if it is possible to achieve the following scenario:

The user logs in in (domain1.com) with ASP Identity.

A cookie is created for the user and he is authenticated now in the authorizations server (domain1.com).

Now, when this user comes from domain2.com (the client app), he gets redirected to identityServer3's authorize endpoint, instead of being automatically authenticated.

Is there a way I can authorize the user directly if he had already logged in with ASP Identity?

Really appreciate your help.

Iyad

答: You can setup your domain 2 and 3 as implicit JavaScript client , see this sample, but it doesn't sign users in automatically when they navigate to the sites after they've signed in on domain 1, you have to implement something your own to achieve that, hope this might help you</p>


问:
Is there an open source C visual debugger for windows?
Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?

Thanks.

答: Look at CodeLite IDE. I could attach to gdb debbager and provide GUI for it.</p>

OwnerDisplayName: linkedlist

LastEditorDisplayName: splattne

OwnerDisplayName: Malx


问:
Intellij file tab missing (but not module!)
I cloned a repo from github only to find that the intellij project window is missing!

But! I have a not missing a project module (like other people on are)!

答:
It looks like your problem is just that you're not showing the project tab!

To show the project tab:

Press the  icon in the bottom left of the screen

On the left side of your window, a bar should appear, press the:

 If it's not already pressed.

(optional) You may need to change to "Project view", on the top part of the project window there should be a little drop down, select "Project"

That should do it!  I hope this helps :)


问:
How to change volume/alter AudioClip
I've seen methods to change Clip volume, however, I am using an AudioClip (code below). Is there a good way to change the volume of the clip? Or would I have to instead use a Clip?</p>

```<code>    private static AudioClip getcharend() {
    File file = new File("charend.wav");
    AudioClip clip;
    try {
        clip = JApplet.newAudioClip(file.toURL());
        clip.play();
    } catch (Exception e) {
        e.getMessage();
        return null;
    }

    return clip;
}
</code>```

答:
According to the documentation here

The relative volume level at which the clip is played. Valid range is
  0.0 (muted) to 1.0 (full volume). Values are clamped to this range internally so values outside this range will have no additional
  effect. Volume is controlled by attenuation, so values below 1.0 will
  reduce the sound level accordingly.

Since the clip object is being returned. you can just use it to set volume. For example calling your Method above in my code

```<code>AudioClip audioClip = getcharend();
audioClip.setVolume(0.9);
</code>```

Title: How to change volume/alter AudioClip

Body:
I've seen methods to change Clip volume, however, I am using an AudioClip (code below). Is there a good way to change the volume of the clip? Or would I have to instead use a Clip?

    private static AudioClip getcharend() {
    File file = new File("charend.wav");
    AudioClip clip;
    try {
        clip = JApplet.newAudioClip(file.toURL());
        clip.play();
    } catch (Exception e) {
        e.getMessage();
        return null;
    }

    return clip;
}

Body:
According to the documentation here

The relative volume level at which the clip is played. Valid range is
  0.0 (muted) to 1.0 (full volume). Values are clamped to this range internally so values outside this range will have no additional
  effect. Volume is controlled by attenuation, so values below 1.0 will
  reduce the sound level accordingly.

Since the clip object is being returned. you can just use it to set volume. For example calling your Method above in my code

AudioClip audioClip = getcharend();
audioClip.setVolume(0.9);


答:
If you are in a controller: You're going to want to use the $compile service.

```<code>var el =  $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");

$compile(el)($scope);
</code>```

don't forget to inject $compile into your controller.

However as pointed out in the comments, there are better alternatives than using jquery to manipulate the dom.

Title: ng-click is not firing

Body:
If you are in a controller: You're going to want to use the $compile service.

var el =  $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");

$compile(el)($scope);

don't forget to inject $compile into your controller.

However as pointed out in the comments, there are better alternatives than using jquery to manipulate the dom.


问:
JAX-RS Jersey - Web service resources cooperation
I am implementing a restful web service using Jersey (Jax-rs).

I have two resources:

/news : returns a list of news

/countries: returns a list of countries

And I want to implement something to allow me to get the news of a certain country.

Something like : /countries/{countryId}/news

How, and where I should implement it?

News Resource Code:

```<code>@Path("/news")
public class NewsResource {

    NewsService newsService = new NewsService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<News> getNews(){
            return newsService.getNews();
    }

}
</code>```

Countries Resource Code:

```<code>@Path("/countries")
public class CountriesResource {

    CountriesService countriesService = new CountriesService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<Countries> getCountries(){
            return countriesService.getCountries();
    }

}
</code>```

I can do it by adding the following method to the Countries class.

```<code>@Path("/{countryId}/news")
    @Produces(MediaType.APPLICATION_JSON)
    public List<News> getCountryNews(@PathParam("countryId") int countryId){
        return countryService.getCountryNews(countryId);
    }
</code>```

But, this way, my Countries resource is returning news, which I don't find logical!

答:
Here comes the solution:

News Resource Code:

```<code>@Path("/news")
public class NewsResource {

    NewsService newsService = new NewsService();

    @GET
    public List<News> getNews(@PathParam("countryId") int countryId){
        if(countryId==null){
            return newsService.getNews();
        }else{
            return newsService.getCountryNews(countryId);
        }
    }

}
</code>```

Countries Resource Code:

```<code>@Path("/countries")
public class CountriesResource {

    CountriesService countriesService = new CountriesService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<Countries> getCountries(){
            return countriesService.getCountries();
    }

    @Path("/{countryId}/news")
    public NewsResource getCountryNews(){
        return new CountryResource();
    }

}
</code>```

When calling /news since countryId is null, we get all news.

When calling countries/{countryId}/news, we call the news resource from the countries resource, and since countryId contains the id of the country for which we want to get the news, we call the getCountryNews(countryId) method.

Body:
I am implementing a restful web service using Jersey (Jax-rs).

I have two resources:

/news : returns a list of news

/countries: returns a list of countries

And I want to implement something to allow me to get the news of a certain country.

Something like : /countries/{countryId}/news

How, and where I should implement it?

News Resource Code:

@Path("/news")
public class NewsResource {

    NewsService newsService = new NewsService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<News> getNews(){
            return newsService.getNews();
    }

}

Countries Resource Code:

@Path("/countries")
public class CountriesResource {

    CountriesService countriesService = new CountriesService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<Countries> getCountries(){
            return countriesService.getCountries();
    }

}

I can do it by adding the following method to the Countries class.

@Path("/{countryId}/news")
    @Produces(MediaType.APPLICATION_JSON)
    public List<News> getCountryNews(@PathParam("countryId") int countryId){
        return countryService.getCountryNews(countryId);
    }

But, this way, my Countries resource is returning news, which I don't find logical!

Body:
Here comes the solution:

News Resource Code:

@Path("/news")
public class NewsResource {

    NewsService newsService = new NewsService();

    @GET
    public List<News> getNews(@PathParam("countryId") int countryId){
        if(countryId==null){
            return newsService.getNews();
        }else{
            return newsService.getCountryNews(countryId);
        }
    }

}

Countries Resource Code:

@Path("/countries")
public class CountriesResource {

    CountriesService countriesService = new CountriesService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<Countries> getCountries(){
            return countriesService.getCountries();
    }

    @Path("/{countryId}/news")
    public NewsResource getCountryNews(){
        return new CountryResource();
    }

}

When calling /news since countryId is null, we get all news.

When calling countries/{countryId}/news, we call the news resource from the countries resource, and since countryId contains the id of the country for which we want to get the news, we call the getCountryNews(countryId) method.


问:
Controlling system volume using trackbar in Inno Setup
How can we control system volume using trackbar in Inno Setup?

With bass.dll or mediaplayer.dll we play music, but how to control system volume with trackbar to manage volume level?

And can forward and rewind option is available with those library?

答:
There's no trackbar control in Inno Setup.

But you can draw your own interactive volume bar using TBitmapImage:

function GetCursorPos(var lpPoint: TPoint): BOOL;
  external 'GetCursorPos@user32.dll stdcall';
function ScreenToClient(hWnd: HWND; var lpPoint: TPoint): BOOL;
  external 'ScreenToClient@user32.dll stdcall';

procedure DrawVolume(Image: TBitmapImage; Volume: Integer);
var
  Canvas: TCanvas;
  Width: Integer;
begin
  Canvas := Image.Bitmap.Canvas;

  Canvas.Pen.Style := psClear;

  Width := Image.Bitmap.Width * Volume / 100

  Canvas.Brush.Color := clHighlight;
  Canvas.Rectangle(1, 1, Width, Image.Bitmap.Height);

  Canvas.Brush.Color := clBtnFace;
  Canvas.Rectangle(Width - 1, 1, Image.Bitmap.Width, Image.Bitmap.Height);

  Canvas.Pen.Style := psSolid;
  Canvas.Pen.Mode := pmCopy;
  Canvas.Pen.Color := clBlack;
  Canvas.Brush.Style := bsClear;
  Canvas.Rectangle(1, 1, Image.Bitmap.Width, Image.Bitmap.Height);
end;

procedure VolumeBarImageClick(Sender: TObject);
var
  P: TPoint;
  Image: TBitmapImage;
  Volume: Integer;
begin
  { Calculate where in the bar did user click to }
  GetCursorPos(P);
  Image := TBitmapImage(Sender);
  ScreenToClient(Image.Parent.Handle, P);
  Volume := ((P.X - Image.Left) * 100 / Image.Width) + 1;

  { Update volume bar }
  DrawVolume(Image, Volume);

  { Replace this with your code that sets the volume }
  MsgBox(Format('Setting volume to %d%%', [Volume]), mbInformation, MB_OK);
end;

procedure InitializeWizard();
var
  VolumeBarImage: TBitmapImage;
begin
  VolumeBarImage := TBitmapImage.Create(WizardForm);
  VolumeBarImage.Parent := WizardForm;
  VolumeBarImage.Left := ScaleX(10);
  VolumeBarImage.Top := WizardForm.ClientHeight - ScaleY(34);
  VolumeBarImage.Width := ScaleX(200);
  VolumeBarImage.Height := ScaleY(20);
  VolumeBarImage.BackColor := clWhite;
  VolumeBarImage.Bitmap.Width := VolumeBarImage.Width;
  VolumeBarImage.Bitmap.Height := VolumeBarImage.Height;
  VolumeBarImage.OnClick := @VolumeBarImageClick;

  { Replace with setting to actual initial volume }
  DrawVolume(VolumeBarImage, 100);
end;
```

The code is mostly from:

How do I change the color of my progress bar in Inno Setup?

Inno Setup: OnHover event

Body:
There's no trackbar control in Inno Setup.

But you can draw your own interactive volume bar using TBitmapImage:

function GetCursorPos(var lpPoint: TPoint): BOOL;
  external 'GetCursorPos@user32.dll stdcall';
function ScreenToClient(hWnd: HWND; var lpPoint: TPoint): BOOL;
  external 'ScreenToClient@user32.dll stdcall';

procedure DrawVolume(Image: TBitmapImage; Volume: Integer);
var
  Canvas: TCanvas;
  Width: Integer;
begin
  Canvas := Image.Bitmap.Canvas;

  Canvas.Pen.Style := psClear;

  Width := Image.Bitmap.Width * Volume / 100

  Canvas.Brush.Color := clHighlight;
  Canvas.Rectangle(1, 1, Width, Image.Bitmap.Height);

  Canvas.Brush.Color := clBtnFace;
  Canvas.Rectangle(Width - 1, 1, Image.Bitmap.Width, Image.Bitmap.Height);

  Canvas.Pen.Style := psSolid;
  Canvas.Pen.Mode := pmCopy;
  Canvas.Pen.Color := clBlack;
  Canvas.Brush.Style := bsClear;
  Canvas.Rectangle(1, 1, Image.Bitmap.Width, Image.Bitmap.Height);
end;

procedure VolumeBarImageClick(Sender: TObject);
var
  P: TPoint;
  Image: TBitmapImage;
  Volume: Integer;
begin
  { Calculate where in the bar did user click to }
  GetCursorPos(P);
  Image := TBitmapImage(Sender);
  ScreenToClient(Image.Parent.Handle, P);
  Volume := ((P.X - Image.Left) * 100 / Image.Width) + 1;

  { Update volume bar }
  DrawVolume(Image, Volume);

  { Replace this with your code that sets the volume }
  MsgBox(Format('Setting volume to %d%%', [Volume]), mbInformation, MB_OK);
end;

procedure InitializeWizard();
var
  VolumeBarImage: TBitmapImage;
begin
  VolumeBarImage := TBitmapImage.Create(WizardForm);
  VolumeBarImage.Parent := WizardForm;
  VolumeBarImage.Left := ScaleX(10);
  VolumeBarImage.Top := WizardForm.ClientHeight - ScaleY(34);
  VolumeBarImage.Width := ScaleX(200);
  VolumeBarImage.Height := ScaleY(20);
  VolumeBarImage.BackColor := clWhite;
  VolumeBarImage.Bitmap.Width := VolumeBarImage.Width;
  VolumeBarImage.Bitmap.Height := VolumeBarImage.Height;
  VolumeBarImage.OnClick := @VolumeBarImageClick;

  { Replace with setting to actual initial volume }
  DrawVolume(VolumeBarImage, 100);
end;

The code is mostly from:

How do I change the color of my progress bar in Inno Setup?

Inno Setup: OnHover event


问:
ReactJS TypeError: Cannot read property 'setState'
I am new at ReactJS, and I encounter some problems.

I also learned about the ES6 syntax, and it said the following codes are the same meaning.

1.

```<code>YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
});
</code>```

2.

```<code>YTSearch({key: API_KEY, term: 'nba'}, (videos) => {
  this.setState({ videos });
});
</code>```

However, the first way threw this error

```<code>TypeError: Cannot read property 'setState' of undefined
</code>```

答:
```<code>YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
});
</code>```

Throws an error because here this inside the callback doesn't refer to the context of React Component rather the context of the function itself and hence setState is undefined here.

In the second example

```<code>YTSearch({key: API_KEY, term: 'nba'}, (videos) => {
  this.setState({ videos });
});
</code>```

You are making use of arrow function to bind the function to the context of the react component. Another way to do the same would be to use bind(this)

```<code>YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
}.bind(this));
</code>```

Body:
I am new at ReactJS, and I encounter some problems.

I also learned about the ES6 syntax, and it said the following codes are the same meaning.

1.

YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
});

2.

YTSearch({key: API_KEY, term: 'nba'}, (videos) => {
  this.setState({ videos });
});

However, the first way threw this error

TypeError: Cannot read property 'setState' of undefined

Body:
YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
});

Throws an error because here this inside the callback doesn't refer to the context of React Component rather the context of the function itself and hence setState is undefined here.

In the second example

YTSearch({key: API_KEY, term: 'nba'}, (videos) => {
  this.setState({ videos });
});

You are making use of arrow function to bind the function to the context of the react component. Another way to do the same would be to use bind(this)

YTSearch({key: API_KEY, term: 'nba'}, function(videos) {
  this.setState({ videos });
}.bind(this));


问:
Will ROW_NUMBER() always order the outer result?
I'm using a CTE to rank book authors based on their sales rank. I understand that ROW_NUMBER() can take in an ORDER BY to determine the returned row number based on it.

My query looks like this:

```<code>WITH cte (idWork, author, rn)
AS
(
    SELECT
        idWork,
        authorName,
        ROW_NUMBER() OVER (PARTITION BY idWork ORDER BY authorSalesRank)
    FROM dbo.Works_Authors_Works
    INNER JOIN Authors ON Authors.idAuthor = Works_Authors_Works.idAuthor
)
SELECT TOP 100 * FROM cte
</code>```

I noticed that the the results look like this, which is as expected:

```<code>+---------+----------------+------+
| idWork  | author         | rn   |
+---------+----------------+------+
| 1       | test1          | 1    |
| 1       | test2          | 2    |
| 1       | test3          | 3    |
| 2       | beep1          | 1    |
| 2       | beep2          | 2    |
| 3       | nobody         | 1    |
+---------+----------------+------+
</code>```

I have two questions with this CTE:

Will the results always be sorted on the ROW_NUMBER field rn? Like how the results are grouped on idWork then sorted on rn? For example, when idWork is 1, the rows are sorted on rn from 1, 2, then 3. Is this a coincidence or will it always be like this?

If I do a SELECT TOP 1 * FROM cte WHERE idWork = 1, will it always return the row where rn = 1?

In the execution plan, it has an input Sort on idWork, authorSalesRank. Do these imply that the outer result is sorted on this too?

答:
You should explicitly order it.

```<code>WITH cte (idWork, author, rn) AS (
    SELECT
        idWork,
        authorName,
        ROW_NUMBER() OVER (PARTITION BY idWork ORDER BY authorSalesRank) AS rn
    FROM dbo.Works_Authors_Works
    INNER JOIN Authors ON Authors.idAuthor = Works_Authors_Works.idAuthor
)
SELECT TOP 100 *
FROM cte
order by idWork, rn
</code>```

SQL (all databases) do not guarantee order if no order is specified, even if it seems like it "always works", you should not rely on that anecdotal evidence.

Body:
I'm using a CTE to rank book authors based on their sales rank. I understand that ROW_NUMBER() can take in an ORDER BY to determine the returned row number based on it.

My query looks like this:

WITH cte (idWork, author, rn)
AS
(
    SELECT
        idWork,
        authorName,
        ROW_NUMBER() OVER (PARTITION BY idWork ORDER BY authorSalesRank)
    FROM dbo.Works_Authors_Works
    INNER JOIN Authors ON Authors.idAuthor = Works_Authors_Works.idAuthor
)
SELECT TOP 100 * FROM cte

I noticed that the the results look like this, which is as expected:

+---------+----------------+------+
| idWork  | author         | rn   |
+---------+----------------+------+
| 1       | test1          | 1    |
| 1       | test2          | 2    |
| 1       | test3          | 3    |
| 2       | beep1          | 1    |
| 2       | beep2          | 2    |
| 3       | nobody         | 1    |
+---------+----------------+------+

I have two questions with this CTE:

Will the results always be sorted on the ROW_NUMBER field rn? Like how the results are grouped on idWork then sorted on rn? For example, when idWork is 1, the rows are sorted on rn from 1, 2, then 3. Is this a coincidence or will it always be like this?

If I do a SELECT TOP 1 * FROM cte WHERE idWork = 1, will it always return the row where rn = 1?

In the execution plan, it has an input Sort on idWork, authorSalesRank. Do these imply that the outer result is sorted on this too?

Body:
You should explicitly order it.

WITH cte (idWork, author, rn) AS (
    SELECT
        idWork,
        authorName,
        ROW_NUMBER() OVER (PARTITION BY idWork ORDER BY authorSalesRank) AS rn
    FROM dbo.Works_Authors_Works
    INNER JOIN Authors ON Authors.idAuthor = Works_Authors_Works.idAuthor
)
SELECT TOP 100 *
FROM cte
order by idWork, rn

SQL (all databases) do not guarantee order if no order is specified, even if it seems like it "always works", you should not rely on that anecdotal evidence.


答:
You are already storing the timer, so you can clear its timeout.

https://jsfiddle.net/5eceLvgu/1/

```<code>var timer;
function log(...)
    clearTimeout(timer);
    (function myLoop(i) {
</code>```

Title: How to stop loop with delay to continue another

Body:
You are already storing the timer, so you can clear its timeout.

https://jsfiddle.net/5eceLvgu/1/

var timer;
function log(...)
    clearTimeout(timer);
    (function myLoop(i) {


问:
Sort an ArrayList base on multiple attributes
I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?

答: If the class of the object implements Comparable, then all you need to do is properly code the compareTo method to first compare dates, and then if dates are equal, compare values, and then return the appropriate int result based on the findings.</p>


问:
how to implement an onclick listener for a list view that links to a new fragment
So I have a listview that works, but I want to implement an onclick listener for this listview. I want the onclick listener to link to a new fragment so that another page is opened when I click on some index in the list. I have done some testing and have determined that the onclick listener as a whole does not work.

This is what I have so far:

```<code>package ca.queensu.engsoc.events;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class eventList extends Activity implements AdapterView.OnItemClickListener
{
public static final String KEY_NAME = "NAME_KEY";
ListView events;
String[] e;
mockData myBadData = new mockData();
@Override

protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();

    e = myBadData.getData();

    super.onCreate(savedInstanceState);

    setContentView(R.layout.event_list);

    events=(ListView) findViewById(R.id.dayList);

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);

    events.setAdapter(adapter);

    events.setOnItemClickListener(this);
}

@Override

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    //TextView temp=(TextView) view;

    View temp=view;

    //final Toast toast = Toast.makeText(this, temp.getText() + "" + i, Toast.LENGTH_SHORT.show());

    temp.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Bundle bundle = new Bundle();

            bundle.putString(KEY_NAME,myBadData.getOneData(i));

            Fragment fr = new event_description();

            fr.setArguments(bundle);

            FragmentManager fm = getFragmentManager();

            FragmentTransaction fragmentTransaction = fm.beginTransaction();

            int contId = v.getId();

            fragmentTransaction.replace(contId, fr);

            fragmentTransaction.commit();

            Intent i=new Intent(eventList.this, fr.getClass());

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

}

What am I doing wrong?

答:
Actually as far as I understand you don't need to set any additional click listeners.
onItemClick() method should do the stuff.
final int i this is position of clicked view if you need one.</p>

Body:
So I have a listview that works, but I want to implement an onclick listener for this listview. I want the onclick listener to link to a new fragment so that another page is opened when I click on some index in the list. I have done some testing and have determined that the onclick listener as a whole does not work.

This is what I have so far:

package ca.queensu.engsoc.events;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class eventList extends Activity implements AdapterView.OnItemClickListener
{
public static final String KEY_NAME = "NAME_KEY";
ListView events;
String[] e;
mockData myBadData = new mockData();
@Override

protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();

    e = myBadData.getData();

    super.onCreate(savedInstanceState);

    setContentView(R.layout.event_list);

    events=(ListView) findViewById(R.id.dayList);

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);

    events.setAdapter(adapter);

    events.setOnItemClickListener(this);
}

@Override

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    //TextView temp=(TextView) view;

    View temp=view;

    //final Toast toast = Toast.makeText(this, temp.getText() + "" + i, Toast.LENGTH_SHORT.show());

    temp.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Bundle bundle = new Bundle();

            bundle.putString(KEY_NAME,myBadData.getOneData(i));

            Fragment fr = new event_description();

            fr.setArguments(bundle);

            FragmentManager fm = getFragmentManager();

            FragmentTransaction fragmentTransaction = fm.beginTransaction();

            int contId = v.getId();

            fragmentTransaction.replace(contId, fr);

            fragmentTransaction.commit();

            Intent i=new Intent(eventList.this, fr.getClass());

        }
    });
}

}

What am I doing wrong?