问:
PHPSESSID security issues?
I've been curious for a while now about the security issues surrounding the PHP session name: PHPSESSID.

I've noticed that some websites rename their session ID cookie, while others just leave it as the default.

Is there any security advantage in using a different name? or is it merely useful for being able to track multiple sessions per user?

答:
It is sometimes to change the default sessionID if you are uber-worried about session hijacking though the chances of someone successfully hijacking a session are pretty well slim if you take the most rudimentary steps in sanitizing your data, turn off register globals and only accept the specific POST or GET variables cast correctly from your forms...

you can read about Session Fixation here (which is what the changing of the standard sessionId is usually used to combat)..

Title: PHPSESSID security issues?


来源: stackexchange

问:
string query in a function in kdb
```<code>func:{[query] value query};
</code>```

query is part of my function. I have add some like delete xxx, yyyy from (value query) and some manipulation. I am not sure why when I don't use value "query", the function doesn't work. It said it cannot find the table. So I have to use value query in the function and query is a parameter. I need to pass "select from tab" to the function.

My questions is: how do I send if the filter is a string too?

```<code>func["select from tab where a="abc""] <<< this does not work
</code>```

How can I make string inside a string work?

Also, not sure why if I do

```<code>func["select from tab where date = max date"]  it did not work due to length error
but func["100#select from tab where date = max date"] it works ?
</code>```

The whole function is

```<code>getTable:{[query]loadHDB[];.Q.view date where date < .z.D-30;tab:(delete xxxx,yyyyy,sub,ID,subID,tID,subTID,text,gID from((value query)));remove[];update {";"sv @[s;where (s:";"vs x) like "cId=*";:;enlist""]}each eData from (update {";"sv @[s;where (s:";"vs x) like "AId=*";:;enlist""]}each eData from tab)};

remove:{[]delete tab from `.};
loadHDB:{[]value "\\l /hdb};
</code>```

答:
You can escape the quotes using backslash  http://code.kx.com/wiki/Reference/BackSlash#escape

```<code>func["select from tab where a like \"abc\""]
</code>```

Edit:

If tab is a HDB table then this length error could point to a column length issue (which 100# is avoiding). What does the following return?

```<code>q)checkPartition:{[dt] a!{c!{count get x} each ` sv' x,/:c:({x where not x like "*#"} key[x])except `.d}each a:(` sv' d,/:key[d:hsym `$string dt])};
q)check:checkPartition last date
q)(where{1<count distinct value x}each check)#check
</code>```

ContentLicense: CC BY-SA 4.0

Title: string query in a function in kdb

Body:
func:{[query] value query};

query is part of my function. I have add some like delete xxx, yyyy from (value query) and some manipulation. I am not sure why when I don't use value "query", the function doesn't work. It said it cannot find the table. So I have to use value query in the function and query is a parameter. I need to pass "select from tab" to the function.

My questions is: how do I send if the filter is a string too?

func["select from tab where a="abc""] <<< this does not work

How can I make string inside a string work?

Also, not sure why if I do

func["select from tab where date = max date"]  it did not work due to length error
but func["100#select from tab where date = max date"] it works ?

The whole function is

getTable:{[query]loadHDB[];.Q.view date where date < .z.D-30;tab:(delete xxxx,yyyyy,sub,ID,subID,tID,subTID,text,gID from((value query)));remove[];update {";"sv @[s;where (s:";"vs x) like "cId=*";:;enlist""]}each eData from (update {";"sv @[s;where (s:";"vs x) like "AId=*";:;enlist""]}each eData from tab)};

remove:{[]delete tab from `.};
loadHDB:{[]value "\\l /hdb};

Body:
You can escape the quotes using backslash  http://code.kx.com/wiki/Reference/BackSlash#escape

func["select from tab where a like \"abc\""]

Edit:

If tab is a HDB table then this length error could point to a column length issue (which 100# is avoiding). What does the following return?

q)checkPartition:{[dt] a!{c!{count get x} each ` sv' x,/:c:({x where not x like "*#"} key[x])except `.d}each a:(` sv' d,/:key[d:hsym `$string dt])};
q)check:checkPartition last date
q)(where{1<count distinct value x}each check)#check

ContentLicense: CC BY-SA 3.0


问:
PyQt Threading: GUI interaction Crashes Program
I am designing a program to edit DICOMs. Specifically, I am having issues appropriately interacting with my PyQt UI.

I want to be able to click on a "pause" and on a "stop" button to either pause or stop my editing function. My editing function takes a significant amount of time to process / loop through. Depending on the number of files that it is editing, it can take anywhere from 30 seconds to over an hour. Because of this, I decided to throw my editing function into its own thread using the native threading capabilities of Qt. I was able to get the thread working ie: from my MainWindow class I can click a button that initializes my editing class (class edit(QThread), however interacting with the GUI still crashes the program and I'm not sure why! Below I have added a sample of the general code structure / set up that I am using.

```<code>class anonymizeThread(QThread):
    def __init__(self):
        QThread.__init__(self)

    def __del__(self):
        self.wait()

    #def sendAnon(self, progress_val):
     #   self.completed = 0
      #  return self.completed

    def run(self):
            # while self.completed < 100:
            #     self.completed += 0.00001
            #     self.emit(QtCore.SIGNAL('PROGRESS'), self.completed)
            # ANONYMIZE FUNCTION!
            i = 0
            #flag = self.stop_flag
            while i < 10000000: # and self.stop_flag is not 1:
                print(i)
                i+=1
            print('i didnt enter the loop')

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # connect the buttons
        self.worker = anonymizeThread()
        self.anonbtn.clicked.connect(self.anonymize)
        self.open_directory.clicked.connect(self.open_dir)
        self.pause.clicked.connect(self.paused)
        self.stopbtn.clicked.connect(self.stopped)

        # block button signals to start
        self.pause.blockSignals(True)
        self.stopbtn.blockSignals(True)

        self.dir_name = None
        self.pause_flag = None
        self.stop_flag = None
        self.anon_flag = None

        # This is how we quit from the main menu "File" option
        extractAction = self.actionQuit_Ctrl_Q
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip('Leave The App')
        extractAction.triggered.connect(self.close_application)

    def updateProgressBar(self,val):
        self.progressBar.setValue(val)
    def close_application(self):
        choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            sys.exit()
        else:
            pass

    def anonymize(self):
        self.pause.blockSignals(False)
        self.stopbtn.blockSignals(False)
        self.worker.start()
        # check if directory chosen
        # self.progressBar.setMaximum(len(dcm)
        # start our anon thread!

    def paused(self):
        #only if running
        if self.pause_flag is 0:
            self.pause_flag = 1
            self.pause.setText('Start')
        elif self.pause_flag is 1:
            self.pause_flag = 0
            self.pause.setText('Pause')
        else:
            pass

    def stopped(self): # need a self.stop() for anonThread

        choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
                              QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.stop_flag = 1
            #self.stopbtn.blockSignals(True)
            #self.paused.blockSignals(True)
        else:
            pass

    def open_dir(self):
        self.dir_name = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        if len(self.dir_name) is not 0:
            self.anon_flag = 0

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

答:
It is advisable not to access the flags directly, it is better to do it through the functions to make use of it transparently, for this the same class should verify the tasks.

Also it is good to give a small delay so that the application can deal with the graphic part, another possible improvement is to avoid usat sys.exit, you could call the close method that closes the window.

In the following code I have implemented the stop and pause methods.

```<code>class anonymizeThread(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.onRunning = True
        self.onStop = False

    def __del__(self):
        self.wait()

    def stop(self):
        self.onStop = True

    def pause(self):
        if self.isRunning():
            self.onRunning = not self.onRunning

    def run(self):
            i = 0
            #flag = self.stop_flag
            while i < 10000000:
                if self.onRunning: # and self.stop_flag is not 1:
                    print(i)
                    i+=1

                if self.onStop:
                    break
                QThread.msleep(10)
            print('i didnt enter the loop')

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # connect the buttons
        self.worker = anonymizeThread()
        self.anonbtn.clicked.connect(self.anonymize)
        self.pause.clicked.connect(self.paused)
        self.stopbtn.clicked.connect(self.stopped)

        # block button signals to start
        self.pause.blockSignals(True)
        self.stopbtn.blockSignals(True)

    def close_application(self):
        choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.close()

    def anonymize(self):
        self.pause.blockSignals(False)
        self.stopbtn.blockSignals(False)
        self.worker.start()

    def paused(self):
        self.worker.pause()

    def stopped(self): # need a self.stop() for anonThread

        choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
                              QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.worker.stop()
</code>```

Body:
I am designing a program to edit DICOMs. Specifically, I am having issues appropriately interacting with my PyQt UI.

I want to be able to click on a "pause" and on a "stop" button to either pause or stop my editing function. My editing function takes a significant amount of time to process / loop through. Depending on the number of files that it is editing, it can take anywhere from 30 seconds to over an hour. Because of this, I decided to throw my editing function into its own thread using the native threading capabilities of Qt. I was able to get the thread working ie: from my MainWindow class I can click a button that initializes my editing class (class edit(QThread), however interacting with the GUI still crashes the program and I'm not sure why! Below I have added a sample of the general code structure / set up that I am using.

class anonymizeThread(QThread):
    def __init__(self):
        QThread.__init__(self)

    def __del__(self):
        self.wait()

    #def sendAnon(self, progress_val):
     #   self.completed = 0
      #  return self.completed

    def run(self):
            # while self.completed < 100:
            #     self.completed += 0.00001
            #     self.emit(QtCore.SIGNAL('PROGRESS'), self.completed)
            # ANONYMIZE FUNCTION!
            i = 0
            #flag = self.stop_flag
            while i < 10000000: # and self.stop_flag is not 1:
                print(i)
                i+=1
            print('i didnt enter the loop')

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # connect the buttons
        self.worker = anonymizeThread()
        self.anonbtn.clicked.connect(self.anonymize)
        self.open_directory.clicked.connect(self.open_dir)
        self.pause.clicked.connect(self.paused)
        self.stopbtn.clicked.connect(self.stopped)

        # block button signals to start
        self.pause.blockSignals(True)
        self.stopbtn.blockSignals(True)

        self.dir_name = None
        self.pause_flag = None
        self.stop_flag = None
        self.anon_flag = None

        # This is how we quit from the main menu "File" option
        extractAction = self.actionQuit_Ctrl_Q
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip('Leave The App')
        extractAction.triggered.connect(self.close_application)

    def updateProgressBar(self,val):
        self.progressBar.setValue(val)
    def close_application(self):
        choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            sys.exit()
        else:
            pass

    def anonymize(self):
        self.pause.blockSignals(False)
        self.stopbtn.blockSignals(False)
        self.worker.start()
        # check if directory chosen
        # self.progressBar.setMaximum(len(dcm)
        # start our anon thread!

    def paused(self):
        #only if running
        if self.pause_flag is 0:
            self.pause_flag = 1
            self.pause.setText('Start')
        elif self.pause_flag is 1:
            self.pause_flag = 0
            self.pause.setText('Pause')
        else:
            pass

    def stopped(self): # need a self.stop() for anonThread

        choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
                              QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.stop_flag = 1
            #self.stopbtn.blockSignals(True)
            #self.paused.blockSignals(True)
        else:
            pass

    def open_dir(self):
        self.dir_name = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        if len(self.dir_name) is not 0:
            self.anon_flag = 0

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Body:
It is advisable not to access the flags directly, it is better to do it through the functions to make use of it transparently, for this the same class should verify the tasks.

Also it is good to give a small delay so that the application can deal with the graphic part, another possible improvement is to avoid usat sys.exit, you could call the close method that closes the window.

In the following code I have implemented the stop and pause methods.

class anonymizeThread(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.onRunning = True
        self.onStop = False

    def __del__(self):
        self.wait()

    def stop(self):
        self.onStop = True

    def pause(self):
        if self.isRunning():
            self.onRunning = not self.onRunning

    def run(self):
            i = 0
            #flag = self.stop_flag
            while i < 10000000:
                if self.onRunning: # and self.stop_flag is not 1:
                    print(i)
                    i+=1

                if self.onStop:
                    break
                QThread.msleep(10)
            print('i didnt enter the loop')

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # connect the buttons
        self.worker = anonymizeThread()
        self.anonbtn.clicked.connect(self.anonymize)
        self.pause.clicked.connect(self.paused)
        self.stopbtn.clicked.connect(self.stopped)

        # block button signals to start
        self.pause.blockSignals(True)
        self.stopbtn.blockSignals(True)

    def close_application(self):
        choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.close()

    def anonymize(self):
        self.pause.blockSignals(False)
        self.stopbtn.blockSignals(False)
        self.worker.start()

    def paused(self):
        self.worker.pause()

    def stopped(self): # need a self.stop() for anonThread

        choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
                              QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.worker.stop()


问:
CSS Transitions with multiple delays
So I am using CSS transitions to have multiple blocks come together and form a new image (a house in this case). Thing is, I am using delay on each of the blocks so they start coming in at different times. That is all working fine.

Now, what I would like to have happen is when I click a different button those blocks need to be sent back to their original positions and in reverse order of which they appeared.

```<code>.house-container {
  position: relative;
  overflow: hidden;
}
.house-block {
  letter-spacing: 1px;
  position: relative;
  text-align: center;
  color: #fff
}
.roof {
  position: absolute;
  top: -228px;
  transition: top .5s ease 2.5s
}
.roof.moved {
  top: 0
}
.peak {
  position: absolute;
  top: -145px;
  right: 76px;
  transition: top .5s ease 2.0s
}
.peak.moved {
  top: 47px
}
.peak:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-left {
  position: absolute;
  left: -165px;
  top: 194px;
  transition: left .5s ease 1.2s;
}
.top-left.moved {
  left: 103px
}
.top-left:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-center {
  position: absolute;
  left: 257px;
  top: -170px;
  transition: top .5s ease 1.6s
}
.top-center.moved {
  top: 194px;
  left: 257px
}
.top-center:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-right {
  position: absolute;
  left: 640px;
  top: 194px;
  transition: left .5s ease 0.9s
}
.top-right.moved {
  top: 194px;
  left: 442px
}
.top-right:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.bottom-left {
  position: absolute;
  left: -165px;
  top: 392px;
  transition: left .5s ease 0.3s
}
.bottom-left.moved {
  left: 103px;
  top: 392px
}
.bottom-left:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.bottom-right {
  position: absolute;
  left: 660px;
  top: 467px;
  transition: left .5s ease 0.1s
}
.bottom-right.moved {
  top: 467px;
  left: 257px
}
.bottom-right:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.middle-center {
  position: absolute;
  left: 257px;
  top: -120px;
  transition: top .5s ease 0.6s
}
.middle-center.moved {
  top: 355px;
  left: 257px
}
.middle-center:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.house-block .energy-mngt {
  position: absolute;
  width: 464px;
  top: 20%
}
.house-block .water-conver {
  position: absolute;
  width: 150px;
  top: 20%
}
.house-block .solar {
  position: absolute;
  width: 181px;
  top: 20%
}
.house-block .leed-certfd {
  position: absolute;
  width: 123px;
  top: 30%
}
.house-block .multimedia {
  position: absolute;
  width: 181px;
  top: 30%
}
.house-block .security {
  position: absolute;
  width: 150px;
  top: 25%
}
.house-block .auto-cont-integri {
  position: absolute;
  width: 308px;
  top: 10%
}
.house-block h4 {
  display: block;
  font-weight: 700;
  margin-bottom: 0
}
.house-block .solar h4, .house-block .multimedia h4, .house-block .auto-cont-integri h4 {
  display: inline-block;
  margin-top: 20px
}
</code>```

As you can see above, the .roof is the last element to appear (2.5 second delay) and the .bottom-right block is the first (.1s delay). I want these same delays to happen in the reverse order when being hidden (removing the .moved class from the elements).

Is this even possible?

Thanks

答:
Sure it's possible, just add the forward delay to your "visible" state and the backwards delay to your normal state. Or if you have a "hidden" state the other way arround:

```<code>.my-element.-isVisible {
  ...
  transition-delay: 1s;
}

.my-element {
  ...
  transition-delay: 2.5s;
}
</code>```

This will add a 1s delay when the elements becomes "visible" and a 2.5s delay if it becomes "hidden" again.

Title: CSS Transitions with multiple delays

Body:
So I am using CSS transitions to have multiple blocks come together and form a new image (a house in this case). Thing is, I am using delay on each of the blocks so they start coming in at different times. That is all working fine.

Now, what I would like to have happen is when I click a different button those blocks need to be sent back to their original positions and in reverse order of which they appeared.

.house-container {
  position: relative;
  overflow: hidden;
}
.house-block {
  letter-spacing: 1px;
  position: relative;
  text-align: center;
  color: #fff
}
.roof {
  position: absolute;
  top: -228px;
  transition: top .5s ease 2.5s
}
.roof.moved {
  top: 0
}
.peak {
  position: absolute;
  top: -145px;
  right: 76px;
  transition: top .5s ease 2.0s
}
.peak.moved {
  top: 47px
}
.peak:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-left {
  position: absolute;
  left: -165px;
  top: 194px;
  transition: left .5s ease 1.2s;
}
.top-left.moved {
  left: 103px
}
.top-left:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-center {
  position: absolute;
  left: 257px;
  top: -170px;
  transition: top .5s ease 1.6s
}
.top-center.moved {
  top: 194px;
  left: 257px
}
.top-center:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.top-right {
  position: absolute;
  left: 640px;
  top: 194px;
  transition: left .5s ease 0.9s
}
.top-right.moved {
  top: 194px;
  left: 442px
}
.top-right:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.bottom-left {
  position: absolute;
  left: -165px;
  top: 392px;
  transition: left .5s ease 0.3s
}
.bottom-left.moved {
  left: 103px;
  top: 392px
}
.bottom-left:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.bottom-right {
  position: absolute;
  left: 660px;
  top: 467px;
  transition: left .5s ease 0.1s
}
.bottom-right.moved {
  top: 467px;
  left: 257px
}
.bottom-right:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.middle-center {
  position: absolute;
  left: 257px;
  top: -120px;
  transition: top .5s ease 0.6s
}
.middle-center.moved {
  top: 355px;
  left: 257px
}
.middle-center:hover {
  transform: scale(1.2, 1.2);
  z-index: 99
}
.house-block .energy-mngt {
  position: absolute;
  width: 464px;
  top: 20%
}
.house-block .water-conver {
  position: absolute;
  width: 150px;
  top: 20%
}
.house-block .solar {
  position: absolute;
  width: 181px;
  top: 20%
}
.house-block .leed-certfd {
  position: absolute;
  width: 123px;
  top: 30%
}
.house-block .multimedia {
  position: absolute;
  width: 181px;
  top: 30%
}
.house-block .security {
  position: absolute;
  width: 150px;
  top: 25%
}
.house-block .auto-cont-integri {
  position: absolute;
  width: 308px;
  top: 10%
}
.house-block h4 {
  display: block;
  font-weight: 700;
  margin-bottom: 0
}
.house-block .solar h4, .house-block .multimedia h4, .house-block .auto-cont-integri h4 {
  display: inline-block;
  margin-top: 20px
}

As you can see above, the .roof is the last element to appear (2.5 second delay) and the .bottom-right block is the first (.1s delay). I want these same delays to happen in the reverse order when being hidden (removing the .moved class from the elements).

Is this even possible?

Thanks

Body:
Sure it's possible, just add the forward delay to your "visible" state and the backwards delay to your normal state. Or if you have a "hidden" state the other way arround:

.my-element.-isVisible {
  ...
  transition-delay: 1s;
}

.my-element {
  ...
  transition-delay: 2.5s;
}

This will add a 1s delay when the elements becomes "visible" and a 2.5s delay if it becomes "hidden" again.


问:
DatePicker in xaml.vb
I am completely new to XAML.vb. when I want to calculate the age in .cs, I used to enter the following code:

```<code>private void dateTimePicker1_valueChanged (object sender, EventArgs e)
{
DateTime from = dateTimePicker1.Value;
DateTime  to = dateTimePicker1.Now;
TimeSpan Tspan = to-from;
double days = Tspan.TotalDays;
textbox1.Text = (days/365)ToString("0");
}
</code>```

The following code is from XAML.VB. All the functions that I used in cs before are not present.

```<code>Private Sub dob_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

{

DateTime from = dob.Value;  // it doesn't exist. I found dob.GetValue but its not helping.

}
</code>```

Same was with "TimeSpan" and all the other built-in functions from Microsoft they have changed it so much and much is not available on the internet. It would be great if someone has any idea about it.
Thanks

答:
Timespan is available in vb too... check on this

https://msdn.microsoft.com/en-us/library/bk8a3558(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Follwoing is the same code in vb ....

```<code>Private Sub dateTimePicker1_valueChanged(sender As Object, e As EventArgs)
    Dim from As DateTime = dateTimePicker1.Value
    Dim [to] As DateTime = dateTimePicker1.Now
    Dim Tspan As TimeSpan = [to] - from
    Dim days As Double = Tspan.TotalDays
    textbox1.Text = (days / 365).ToString("0")
End Sub
</code>```

Title: DatePicker in xaml.vb

Body:
I am completely new to XAML.vb. when I want to calculate the age in .cs, I used to enter the following code:

private void dateTimePicker1_valueChanged (object sender, EventArgs e)
{
DateTime from = dateTimePicker1.Value;
DateTime  to = dateTimePicker1.Now;
TimeSpan Tspan = to-from;
double days = Tspan.TotalDays;
textbox1.Text = (days/365)ToString("0");
}

The following code is from XAML.VB. All the functions that I used in cs before are not present.

Private Sub dob_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

{

DateTime from = dob.Value;  // it doesn't exist. I found dob.GetValue but its not helping.

}

Same was with "TimeSpan" and all the other built-in functions from Microsoft they have changed it so much and much is not available on the internet. It would be great if someone has any idea about it.
Thanks

Body:
Timespan is available in vb too... check on this

https://msdn.microsoft.com/en-us/library/bk8a3558(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Follwoing is the same code in vb ....

Private Sub dateTimePicker1_valueChanged(sender As Object, e As EventArgs)
    Dim from As DateTime = dateTimePicker1.Value
    Dim [to] As DateTime = dateTimePicker1.Now
    Dim Tspan As TimeSpan = [to] - from
    Dim days As Double = Tspan.TotalDays
    textbox1.Text = (days / 365).ToString("0")
End Sub


问:
Is it possible to use published instant apps(BuzzFeed, Wish, etc) on the emulator?
I've run a hello world instant app on an emulator following this Google's tutorial.

Everything worked well, I got the dialog asking for permission to enable instant apps and clicked 'I'm in'. After that, I could also see that instant apps were enabled in Settings > Google > Instant Apps.

But when I open my browser, run a search and click on links from websites that already have published instant apps, such as BuzzFeed, NY Times Crossword and Wish, they just open the regular web page.

I found out those apps watching Google IO 16 and 17 presentations about instant apps. I even tried the link https://www.buzzfeed.com/tasty, featured on this keynote, to no avail.

I suspect that's due to the fact that the current supported emulator doesn't come with Play Store built-in.

I'm also in a country(Brazil) where Instant apps are not supported yet according to this list. But I'm not sure if that impacts on the emulator.

Does anyone know if those are indeed the reasons why I can't check out instant apps already published on Play Store?

答:
There are possibly two reasons. I recommend following the guide here to set up your emulator. Once you've confirmed that instant apps is enabled successfully via adb shell pm list packages | grep "com.google.android.instantapps.supervisor" and it is enabled in Settings->Google->Instant Apps, then try sending the link as an email to the emulator.

I've found that clicking links within the browser will often times keep you in the browser. But opening the link from Gmail always works for me. I've just checked that it works with Vimeo not too long ago - https://vimeo.com/190063150.


问:
Extract integer from a list
I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it.
I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string.
So I want that the answer should be [2,3,4,1,2,3,-1]

What is the best way to do so in terms of complexity as well as less code.

Thanks...

ContentLicense: CC BY-SA 2.5

Title: Extract integer from a list

Body:
And another list comprehension.

>>> l = ['-1', '1,2,3', '2']
>>> [ int(x) for s in l for x in s.split(',')]
[-1, 1, 2, 3, 2]


问:
Git cannot merge due to untracked working tree

This is printed when trying to merge.

答:
If you want to keep the local copy, then you should git add and git commit it before you merge.

```<code>git add .gitignore
git commit -m 'Adding gitignore file'
</code>```

If you want to replace the local copy, just delete the file.

Body: This is printed when trying to merge.

Body:
If you want to keep the local copy, then you should git add and git commit it before you merge.

git add .gitignore
git commit -m 'Adding gitignore file'

If you want to replace the local copy, just delete the file.


问:
Lasagne LSTM regression produces zerros as output
Inspired by Andrej Karpathy's blog i wanted to make my own version of a recurrent neural network that selects the next word instead of character.
Because of the number of different words in a text is so many, i used word2vec to represent the words as vectors (where similar words are closer in the vector-space). The NN should now train to learn the new vector from the pattern of old ones.

-one important note is that where Karpathy used a classifier, i am trying a regression method (squared loss cost).

My problem is that my neural network predicts the output [0,0,0....,0] no matter how much training. so my guess is that there is a problem in my method of training or prediction (the average error drops a little during training, so some training must be done)

below is my entire code if anyone wants to run it (it uses the brown corpus so requires installation of nltk to work as is).

This is my "Hello World" project in Lasagne, so any pointers if i do something stupid is appreciated.
Thanks in advance :)

```<code>from gensim.models import Word2Vec
import gensim
import sys
from datetime import timedelta
import matplotlib.pyplot as plt
from nltk.corpus import brown
import theano.tensor as T
import theano
import time
import numpy as np
from lasagne import layers
import lasagne
from lasagne.updates import nesterov_momentum
from sklearn.preprocessing import MinMaxScaler
from sklearn.manifold import TSNE

def modelExcept(input, model, size):
    try:
        out = model[input]
        return out
    except Exception:
        out = np.zeros((size))
        print 'exception ' + str(input)
        return out

def plot_TSNE(model,nr_words=None):
    tsne = TSNE(n_components=2)
    if nr_words == None:
        X_tsne = tsne.fit_transform(model[model.wv.vocab][:])
    else:
        X_tsne = tsne.fit_transform(model[model.wv.vocab][0:nr_words])

    X_names =  [key for key in model.wv.vocab]
    plt.figure()
    ax = plt.subplot(111)
    for i in range(X_tsne.shape[0]):
        plt.text(X_tsne[i, 0], X_tsne[i, 1], str(X_names[i]),
                    #color=plt.cm.Set1(y[i] / 10.),
                    fontdict={'weight': 'bold', 'size': 9})

    plt.xticks([]), plt.yticks([])
    plt.draw()
    #plt.scatter(X_tsne[:, 0], X_tsne[:, 1])
    #plt.show()

def getBatch(words_as_vecs , wordSize,totalwords, windowSize, BATCHSIZE):

    BatchIndexes = np.random.randint(0,totalwords-windowSize, size=BATCHSIZE)
    input = np.empty((BATCHSIZE,windowSize,wordSize),dtype=np.float32)
    target = np.empty((BATCHSIZE,wordSize),dtype=np.float32)
    for i in range(BATCHSIZE):
        k = BatchIndexes[i]
        input[i,:,:] = words_as_vecs[k:k+windowSize,:]
        target[i,:] = words_as_vecs[k+windowSize,:]

    return input, target

wordSize = 30
windowSize = 5
BATCHSIZE = 128
LEARNING_RATE = .1
Nr_EPOCHS = 100
NR_Predictions = 15

model_raw = Word2Vec(brown.sents(),workers=4,window=10,iter=15,size=wordSize, min_count=10)
#plot_TSNE(model_raw,None)
model = model_raw.wv #trim model after training to save RAM
del model_raw

words_filtered = filter(lambda x: x in model.vocab, brown.words())#filter away words that are not in vocabulary
words_as_vecs = np.asarray([modelExcept(word, model,wordSize) for word in words_filtered],dtype = np.float32) #create all vector representations beforehand to save time!!
scaler = MinMaxScaler(feature_range=(0,1))
words_as_vecs = scaler.fit_transform(words_as_vecs)

print 'creating neural net...'

Num_units_per_layer = 512
GRAD_CLIP = 100
l_in = lasagne.layers.InputLayer(shape=(None,None,wordSize))
l_LSTM1 = lasagne.layers.LSTMLayer(l_in,Num_units_per_layer,grad_clipping=GRAD_CLIP,nonlinearity=lasagne.nonlinearities.rectify)
l_drop1 = lasagne.layers.DropoutLayer(l_LSTM1,p=0.5)
l_LSTM2 = lasagne.layers.LSTMLayer(l_drop1,Num_units_per_layer,grad_clipping=GRAD_CLIP,nonlinearity=lasagne.nonlinearities.rectify, only_return_final=True)
l_drop2 = lasagne.layers.DropoutLayer(l_LSTM2,p=0.5)
l_shp = lasagne.layers.ReshapeLayer(l_drop2,(-1,Num_units_per_layer))
l_out = lasagne.layers.DenseLayer(l_shp,num_units=wordSize,W=lasagne.init.Normal(), nonlinearity=lasagne.nonlinearities.rectify)

target_vals = T.imatrix('target values')
net_out = lasagne.layers.get_output(l_out)
net_out_predict = lasagne.layers.get_output(l_out,deterministic = True)

#use squared error because the problem is now a regession problem
cost = T.sum(lasagne.objectives.squared_error(net_out,target_vals))

all_params = lasagne.layers.get_all_params(l_out, trainable = True)
updates = lasagne.updates.adagrad(cost, all_params, LEARNING_RATE)

net_train = theano.function([l_in.input_var, target_vals], cost, updates=updates, allow_input_downcast=True)
compute_cost = theano.function([l_in.input_var, target_vals], cost, allow_input_downcast=True)
net_predict = theano.function([l_in.input_var],net_out_predict,allow_input_downcast=True)

print 'creating testphrase...'
testphrase_vectors = np.empty((1,5,wordSize),dtype=np.float32)
testphrase_vectors[0,:,:] = words_as_vecs[1:6,:]
testphrase_words = words_filtered[0:6]
#testphrase_words = brown.words()[0:6]

print 'training...'
avg_cost = 0
totalwords = len(words_filtered)
#totalwords = len(brown.words())
print_freq = totalwords/BATCHSIZE #print example every epoch

nrItterations = Nr_EPOCHS*totalwords/BATCHSIZE

for i in range(nrItterations):
    inTrain, target = getBatch(words_as_vecs, wordSize, totalwords, windowSize, BATCHSIZE)
    avg_cost += net_train(inTrain,target)

    #generate text sample
    if (i%print_freq == 0) and (i != 0):
        print 'prediction of train'

        print 'average cost is {0}' .format(avg_cost/(BATCHSIZE*print_freq))
        avg_cost = 0
        generated_example = ' '.join(testphrase_words)
        testphrase_vectors_copy = testphrase_vectors
        for k in range(NR_Predictions):
            prediction = np.asarray(net_predict(testphrase_vectors_copy))
            prediction_unscaled = scaler.inverse_transform(prediction.reshape(1,-1)).reshape(-1)
            current_word = model.most_similar(positive=[prediction_unscaled], topn=1)

            generated_example = ' '.join((generated_example, current_word[0][0]))

            #insert new word in testphrase (and delete first)
            testphrase_vectors_copy[0,0:-1,:] = testphrase_vectors_copy[0,1:,:]
            testphrase_vectors_copy[0,-1,:] = model[current_word[0][0]]
            #print testphrase_vectors_copy
        print 'example nr. {}' .format(i/print_freq + 1)
        print generated_example
        print '\n \n'
</code>```

答:
I finally found the error.

The problem was this line:

target_vals = T.imatrix('target values')

which should be:

target_vals = T.fmatrix('target values')

since i'm aiming after floats and not integers.

Body:
Inspired by Andrej Karpathy's blog i wanted to make my own version of a recurrent neural network that selects the next word instead of character.
Because of the number of different words in a text is so many, i used word2vec to represent the words as vectors (where similar words are closer in the vector-space). The NN should now train to learn the new vector from the pattern of old ones.

-one important note is that where Karpathy used a classifier, i am trying a regression method (squared loss cost).

My problem is that my neural network predicts the output [0,0,0....,0] no matter how much training. so my guess is that there is a problem in my method of training or prediction (the average error drops a little during training, so some training must be done)

below is my entire code if anyone wants to run it (it uses the brown corpus so requires installation of nltk to work as is).

This is my "Hello World" project in Lasagne, so any pointers if i do something stupid is appreciated.
Thanks in advance :)

from gensim.models import Word2Vec
import gensim
import sys
from datetime import timedelta
import matplotlib.pyplot as plt
from nltk.corpus import brown
import theano.tensor as T
import theano
import time
import numpy as np
from lasagne import layers
import lasagne
from lasagne.updates import nesterov_momentum
from sklearn.preprocessing import MinMaxScaler
from sklearn.manifold import TSNE

def modelExcept(input, model, size):
    try:
        out = model[input]
        return out
    except Exception:
        out = np.zeros((size))
        print 'exception ' + str(input)
        return out

def plot_TSNE(model,nr_words=None):
    tsne = TSNE(n_components=2)
    if nr_words == None:
        X_tsne = tsne.fit_transform(model[model.wv.vocab][:])
    else:
        X_tsne = tsne.fit_transform(model[model.wv.vocab][0:nr_words])

    X_names =  [key for key in model.wv.vocab]
    plt.figure()
    ax = plt.subplot(111)
    for i in range(X_tsne.shape[0]):
        plt.text(X_tsne[i, 0], X_tsne[i, 1], str(X_names[i]),
                    #color=plt.cm.Set1(y[i] / 10.),
                    fontdict={'weight': 'bold', 'size': 9})

    plt.xticks([]), plt.yticks([])
    plt.draw()
    #plt.scatter(X_tsne[:, 0], X_tsne[:, 1])
    #plt.show()

def getBatch(words_as_vecs , wordSize,totalwords, windowSize, BATCHSIZE):

    BatchIndexes = np.random.randint(0,totalwords-windowSize, size=BATCHSIZE)
    input = np.empty((BATCHSIZE,windowSize,wordSize),dtype=np.float32)
    target = np.empty((BATCHSIZE,wordSize),dtype=np.float32)
    for i in range(BATCHSIZE):
        k = BatchIndexes[i]
        input[i,:,:] = words_as_vecs[k:k+windowSize,:]
        target[i,:] = words_as_vecs[k+windowSize,:]

    return input, target

wordSize = 30
windowSize = 5
BATCHSIZE = 128
LEARNING_RATE = .1
Nr_EPOCHS = 100
NR_Predictions = 15

model_raw = Word2Vec(brown.sents(),workers=4,window=10,iter=15,size=wordSize, min_count=10)
#plot_TSNE(model_raw,None)
model = model_raw.wv #trim model after training to save RAM
del model_raw

words_filtered = filter(lambda x: x in model.vocab, brown.words())#filter away words that are not in vocabulary
words_as_vecs = np.asarray([modelExcept(word, model,wordSize) for word in words_filtered],dtype = np.float32) #create all vector representations beforehand to save time!!
scaler = MinMaxScaler(feature_range=(0,1))
words_as_vecs = scaler.fit_transform(words_as_vecs)

print 'creating neural net...'

Num_units_per_layer = 512
GRAD_CLIP = 100
l_in = lasagne.layers.InputLayer(shape=(None,None,wordSize))
l_LSTM1 = lasagne.layers.LSTMLayer(l_in,Num_units_per_layer,grad_clipping=GRAD_CLIP,nonlinearity=lasagne.nonlinearities.rectify)
l_drop1 = lasagne.layers.DropoutLayer(l_LSTM1,p=0.5)
l_LSTM2 = lasagne.layers.LSTMLayer(l_drop1,Num_units_per_layer,grad_clipping=GRAD_CLIP,nonlinearity=lasagne.nonlinearities.rectify, only_return_final=True)
l_drop2 = lasagne.layers.DropoutLayer(l_LSTM2,p=0.5)
l_shp = lasagne.layers.ReshapeLayer(l_drop2,(-1,Num_units_per_layer))
l_out = lasagne.layers.DenseLayer(l_shp,num_units=wordSize,W=lasagne.init.Normal(), nonlinearity=lasagne.nonlinearities.rectify)

target_vals = T.imatrix('target values')
net_out = lasagne.layers.get_output(l_out)
net_out_predict = lasagne.layers.get_output(l_out,deterministic = True)

#use squared error because the problem is now a regession problem
cost = T.sum(lasagne.objectives.squared_error(net_out,target_vals))

all_params = lasagne.layers.get_all_params(l_out, trainable = True)
updates = lasagne.updates.adagrad(cost, all_params, LEARNING_RATE)

net_train = theano.function([l_in.input_var, target_vals], cost, updates=updates, allow_input_downcast=True)
compute_cost = theano.function([l_in.input_var, target_vals], cost, allow_input_downcast=True)
net_predict = theano.function([l_in.input_var],net_out_predict,allow_input_downcast=True)

print 'creating testphrase...'
testphrase_vectors = np.empty((1,5,wordSize),dtype=np.float32)
testphrase_vectors[0,:,:] = words_as_vecs[1:6,:]
testphrase_words = words_filtered[0:6]
#testphrase_words = brown.words()[0:6]

print 'training...'
avg_cost = 0
totalwords = len(words_filtered)
#totalwords = len(brown.words())
print_freq = totalwords/BATCHSIZE #print example every epoch

nrItterations = Nr_EPOCHS*totalwords/BATCHSIZE

for i in range(nrItterations):
    inTrain, target = getBatch(words_as_vecs, wordSize, totalwords, windowSize, BATCHSIZE)
    avg_cost += net_train(inTrain,target)

    #generate text sample
    if (i%print_freq == 0) and (i != 0):
        print 'prediction of train'

        print 'average cost is {0}' .format(avg_cost/(BATCHSIZE*print_freq))
        avg_cost = 0
        generated_example = ' '.join(testphrase_words)
        testphrase_vectors_copy = testphrase_vectors
        for k in range(NR_Predictions):
            prediction = np.asarray(net_predict(testphrase_vectors_copy))
            prediction_unscaled = scaler.inverse_transform(prediction.reshape(1,-1)).reshape(-1)
            current_word = model.most_similar(positive=[prediction_unscaled], topn=1)

            generated_example = ' '.join((generated_example, current_word[0][0]))

            #insert new word in testphrase (and delete first)
            testphrase_vectors_copy[0,0:-1,:] = testphrase_vectors_copy[0,1:,:]
            testphrase_vectors_copy[0,-1,:] = model[current_word[0][0]]
            #print testphrase_vectors_copy
        print 'example nr. {}' .format(i/print_freq + 1)
        print generated_example
        print '\n \n'


问:
What's the easiest way to load single band Landsat 8 rasters from AWS and combine them into a single multiband RDD?
I'm using geotrellis to load geotiff rasters from Landsat 8 that are sitting on S3. However, they are stored on a per-band basis. I can use S3GeoTiff class to load individual bands, e.g.:

```<code>val options = S3GeoTiffRDD.Options(getS3Client = () => S3Client.ANONYMOUS)

val rddBlue = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B2.TIF", options)
val rddGreen = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B3.TIF", options)
val rddRed = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B4.TIF", options)
</code>```

But how do I go about combining them to generate an RGB raster, e.g.

```<code>val rddRGB = ??? // something like combineRDDs(rddRed, rddGreen, rddBlue)
</code>```

答:
From the RDDs of single files with no maxTileSize option set, you'll end up with RDDs of full images (one element). I'd recommend setting the maxTileSize option.

There's an overload that allows you to place extra information into the key. This is how I'd approach this problem generically.

Here is some code that does what you are looking for, which utilizes those options:

import geotrellis.raster._
import geotrellis.spark._
import geotrellis.spark.io.s3._
import geotrellis.vector._

import org.apache.spark.SparkContext
import org.apache.spark.rdd._

import java.net.URI
import scala.math.BigDecimal.RoundingMode

implicit val sc: SparkContext =
  geotrellis.spark.util.SparkUtils.createLocalSparkContext("local[*]", "landsat-example")

try {

  val options =
    S3GeoTiffRDD.Options(
      getS3Client = () => S3Client.ANONYMOUS,
      maxTileSize = Some(512),
      numPartitions = Some(100)
    )

  type LandsatKey = (ProjectedExtent, URI, Int)

  // For each RDD, we're going to include more information in the key, including:
  // - the ProjectedExtent
  // - the URI
  // - the future band value
  def uriToKey(bandIndex: Int): (URI, ProjectedExtent) => LandsatKey =
    { (uri, pe) =>
      (pe, uri, bandIndex)
    }

  // Read an RDD of source tiles for each of the bands.

  val redSourceTiles =
    S3GeoTiffRDD[ProjectedExtent, LandsatKey, Tile](
      "landsat-pds",
      "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B2.TIF",
      uriToKey(0),
      options
    )

  val greenSourceTiles =
    S3GeoTiffRDD[ProjectedExtent, LandsatKey, Tile](
      "landsat-pds",
      "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B3.TIF",
      uriToKey(1),
      options
    )

  val blueSourceTiles =
    S3GeoTiffRDD[ProjectedExtent, LandsatKey, Tile](
      "landsat-pds",
      "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B4.TIF",
      uriToKey(2),
      options
    )

  // Union these together, rearrange the elements so that we'll be able to group by key,
  // group them by key, and the rearrange again to produce multiband tiles.
  val sourceTiles: RDD[(ProjectedExtent, MultibandTile)] = {
    sc.union(redSourceTiles, greenSourceTiles, blueSourceTiles)
      .map { case ((pe, uri, bandIndex), tile) =>
        // Get the center of the tile, which we will join on
        val (x, y) = (pe.extent.center.x, pe.extent.center.y)

        // Round the center coordinates in case there's any floating point errors
        val center =
          (
            BigDecimal(x).setScale(5, RoundingMode.HALF_UP).doubleValue(),
            BigDecimal(y).setScale(5, RoundingMode.HALF_UP).doubleValue()
          )

        // Get the scene ID from the path
        val sceneId = uri.getPath.split('/').reverse.drop(1).head

        val newKey = (sceneId, center)
        val newValue = (pe, bandIndex, tile)
        (newKey, newValue)
      }
      .groupByKey()
      .map { case (oldKey, groupedValues) =>
        val projectedExtent = groupedValues.head._1
        val bands = Array.ofDim[Tile](groupedValues.size)
        for((_, bandIndex, tile) <- groupedValues) {
          bands(bandIndex) = tile
        }

        (projectedExtent, MultibandTile(bands))
      }
  }

  // From here, you could ingest the multiband layer.
  // But for a simple test, we will rescale the bands and write them out to a single GeoTiff
  import geotrellis.spark.tiling.FloatingLayoutScheme
  import geotrellis.raster.io.geotiff.GeoTiff

  val (_, metadata) = sourceTiles.collectMetadata[SpatialKey](FloatingLayoutScheme(512))
  val tiles = sourceTiles.tileToLayout[SpatialKey](metadata)
  val raster =
    ContextRDD(tiles, metadata)
      .withContext { rdd =>
        rdd.mapValues { tile =>
          // Magic numbers! These were created by fiddling around with
          // numbers until some example landsat images looked good enough
          // to put on a map for some other project.
          val (min, max) = (4000, 15176)
          def clamp(z: Int) = {
            if(isData(z)) { if(z > max) { max } else if(z < min) { min } else { z } }
            else { z }
          }
          val red = tile.band(0).map(clamp _).delayedConversion(ByteCellType).normalize(min, max, 0, 255)
          val green = tile.band(1).map(clamp _).delayedConversion(ByteCellType).normalize(min, max, 0, 255)
          val blue = tile.band(2).map(clamp _).delayedConversion(ByteCellType).normalize(min, max, 0, 255)

          MultibandTile(red, green, blue)
        }
      }
      .stitch

  GeoTiff(raster, metadata.crs).write("/tmp/landsat-test.tif")
} finally {
  sc.stop()
}
```

Body:
I'm using geotrellis to load geotiff rasters from Landsat 8 that are sitting on S3. However, they are stored on a per-band basis. I can use S3GeoTiff class to load individual bands, e.g.:

val options = S3GeoTiffRDD.Options(getS3Client = () => S3Client.ANONYMOUS)

val rddBlue = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B2.TIF", options)
val rddGreen = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B3.TIF", options)
val rddRed = S3GeoTiffRDD.spatial("landsat-pds", "L8/139/045/LC81390452014295LGN00/LC81390452014295LGN00_B4.TIF", options)

But how do I go about combining them to generate an RGB raster, e.g.

val rddRGB = ??? // something like combineRDDs(rddRed, rddGreen, rddBlue)


问:
Android Studio: Webview and Sessions Basics
I have a webview that is working perfectly as follows:

```<code>    wv = (WebView) findViewById(R.id.wv);
    //Enable JavaScript
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setFocusable(true);
    wv.setFocusableInTouchMode(true);
    //Set Render Priority To High
    wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setDatabaseEnabled(true);
    wv.getSettings().setAppCacheEnabled(true);
    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    //Load Url
    wv.loadUrl("https://str8red.com/");
</code>```

I then have the following code which runs when a button is clicked:

```<code>    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.GET,"https://str8red.com/loggedincheck",

                    new Response.Listener<String>(){
                        @Override
                        public void onResponse(String response) {
                            textView.setText(response);
                            requestQueue.stop();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    textView.setText("Something went wrong");
                    error.printStackTrace();
                    requestQueue.stop();
                }
            });
            requestQueue.add(stringRequest);
        }
    });
</code>```

The address simply returns a string of "True" or "False" depending if the user is logged into the webview.  The good news is that it is returning a string but it is always returning False, even when I have logged in to my site using the webview. I know the address https://str8red.com/loggedincheck works as expected as it works both in a web browser and also in the iOS app.

I am assuming that when the button is clicked it is not using the the same webview and therefore has no idea if the user is logged in or not.

I have looked online for a solution but have come unstuck.  Any help would be appreciated.

If you need any additional information please do not hesitate to ask.

答:
Indeed it will be always return false, because there is no relation between your Volly code and your webView code, so the right way based on this answer, you have to use evaluateJavascript instead of volley, by passing your javaScript function you can know user case.

```<code>wv.evaluateJavascript("(function() { return 'this'; })();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s); // Prints: "this"

        //check for user case based on javaScriptFunction
    }
});
</code>```

Body:
I have a webview that is working perfectly as follows:

    wv = (WebView) findViewById(R.id.wv);
    //Enable JavaScript
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setFocusable(true);
    wv.setFocusableInTouchMode(true);
    //Set Render Priority To High
    wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setDatabaseEnabled(true);
    wv.getSettings().setAppCacheEnabled(true);
    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    //Load Url
    wv.loadUrl("https://str8red.com/");

I then have the following code which runs when a button is clicked:

    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.GET,"https://str8red.com/loggedincheck",

                    new Response.Listener<String>(){
                        @Override
                        public void onResponse(String response) {
                            textView.setText(response);
                            requestQueue.stop();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    textView.setText("Something went wrong");
                    error.printStackTrace();
                    requestQueue.stop();
                }
            });
            requestQueue.add(stringRequest);
        }
    });

The address simply returns a string of "True" or "False" depending if the user is logged into the webview.  The good news is that it is returning a string but it is always returning False, even when I have logged in to my site using the webview. I know the address https://str8red.com/loggedincheck works as expected as it works both in a web browser and also in the iOS app.

I am assuming that when the button is clicked it is not using the the same webview and therefore has no idea if the user is logged in or not.

I have looked online for a solution but have come unstuck.  Any help would be appreciated.

If you need any additional information please do not hesitate to ask.

Body:
Indeed it will be always return false, because there is no relation between your Volly code and your webView code, so the right way based on this answer, you have to use evaluateJavascript instead of volley, by passing your javaScript function you can know user case.

wv.evaluateJavascript("(function() { return 'this'; })();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("LogName", s); // Prints: "this"

        //check for user case based on javaScriptFunction
    }
});


问:
c remove new line char help
Im fairly new to c sorry if this is a stupid question!

i have this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;
</code>```

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;
</code>```

there was no effect!

答:
to get rid of the newline, before your malloc, do :

```<code>question[strlen(question)-1] = 0;
</code>```

an alternative (suggested in the comments below) would be to do the following instead:

```<code>question[strcspn(question, "\n")] = '\0';
</code>```

change the malloc line to:

```<code>char *memq = malloc(strlen(question)+1);
</code>```

change the assignation line:

```<code>memq = question;
</code>```

to:

```<code>strcpy (memq, question);
</code>```

Title: c remove new line char help

Body:
Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!

Body:
to get rid of the newline, before your malloc, do :

question[strlen(question)-1] = 0;

an alternative (suggested in the comments below) would be to do the following instead:

question[strcspn(question, "\n")] = '\0';

change the malloc line to:

char *memq = malloc(strlen(question)+1);

change the assignation line:

memq = question;

to:

strcpy (memq, question);


问:
How to do initial styling of labels and UILabels/UIImageViews in a sub view which is loaded via an XIB in a UITableViewCell
I have a UITableViewCell which has a subview (inside its content view) which contains labels, and an image view and other properties I need to set.

This subview is set from an XIB as it is used elsewhere in the app. I am loading it into the cell with

```<code>private func setup() {
    let nib = UINib.init(nibName: "AuthorHeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}
</code>```

Then, when the cell is loaded I am setting some default values in awakeFromNib(). When I have a breakpoint there, I can see that the headerView: AuthorHeaderView has been loaded into memory and is set up correctly, but it's labels and imageView haven't been, they are nil, and thus it crashes when trying to style these views.

How to do initial styling of labels and image views and everything in a sub view which is loaded via an XIB?

答:
OK, so I found  the solution out. The problem was that I hadn't added init(coder aDecoder: NSCoder)

I have a setup method that was being called from awakeFromNib, but I also needed to call it from initWithCoder.

Example:

```<code>override func awakeFromNib() {
    super.awakeFromNib()

    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    setup()
}

private func setup() {
    let nib = UINib.init(nibName: "HeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}
</code>```

Anyway, now it works perfectly. Hope this helps someone else at some stage :-)

Body:
I have a UITableViewCell which has a subview (inside its content view) which contains labels, and an image view and other properties I need to set.

This subview is set from an XIB as it is used elsewhere in the app. I am loading it into the cell with

private func setup() {
    let nib = UINib.init(nibName: "AuthorHeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

Then, when the cell is loaded I am setting some default values in awakeFromNib(). When I have a breakpoint there, I can see that the headerView: AuthorHeaderView has been loaded into memory and is set up correctly, but it's labels and imageView haven't been, they are nil, and thus it crashes when trying to style these views.

How to do initial styling of labels and image views and everything in a sub view which is loaded via an XIB?

Body:
OK, so I found  the solution out. The problem was that I hadn't added init(coder aDecoder: NSCoder)

I have a setup method that was being called from awakeFromNib, but I also needed to call it from initWithCoder.

Example:

override func awakeFromNib() {
    super.awakeFromNib()

    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    setup()
}

private func setup() {
    let nib = UINib.init(nibName: "HeaderView", bundle: nil)
    if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {

        view.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(view)

        view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        view.topAnchor.constraint(equalTo: topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

Anyway, now it works perfectly. Hope this helps someone else at some stage :-)


问:
How to replace a button and re position it dynamically?
I have a text box and a add button next to it, when I click on add button I am able to add a text box and delete button next to it. Now I want the add button on the first row to be changed to delete and the add button should be re-positioned below two rows, when the second row delete button  is clicked (the second row is deleted )the add button should go back to the first row and replace delete button. It should look like following.

How do I achieve this?

答:
If you create a Composite as a container of sorts, you can add and remove from it allowing everything outside to remain in the correct order. By reserving the space, the delete button is always below the contents of the container.

I have a text box and a add button next to it, when I click on add button I am able to add a text box and delete button next to it

For example, if we have a small Shell with an add Button as you mentioned, and an empty space to add the Text widgets to:

```<code>final Composite baseComposite = new Composite(shell, SWT.BORDER);
baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
baseComposite.setLayout(new GridLayout());

final Composite rowsContainerComposite = new Composite(baseComposite, SWT.BORDER);
rowsContainerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
rowsContainerComposite.setLayout(new GridLayout());

final Button addButton = new Button(baseComposite, SWT.PUSH);
addButton.setText("Add");
</code>```

(For now the empty space is grabbing all available space, but you can change that as needed)

When adding rows, you can add to the rowsContainerComposite:

```<code>addButton.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(final SelectionEvent e) {
        new Row(rowsContainerComposite);
        rowsContainerComposite.layout();
    }
});
</code>```

A sample Row class:

```<code>public class Row {

    final Composite baseComposite;

    public Row(final Composite parent) {
        baseComposite = new Composite(parent, SWT.BORDER);
        baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        baseComposite.setLayout(new GridLayout(2, false));

        final Text text = new Text(baseComposite, SWT.BORDER);
        text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        final Button deleteButton = new Button(baseComposite, SWT.PUSH);
        deleteButton.setText("Delete");
        deleteButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent e) {
                baseComposite.dispose();
                parent.layout();
            }

        });
    }

}
</code>```

when the second row delete button is clicked (the second row is deleted )the add button should go back to the first row

Then when deleted, rows will shift back appropriately:

the add button should be re-positioned below two rows

The idea is that by using the "container" composite, you're reserving that space to add and remove the rows from. The delete button will always be below the rows as they are added and removed.

Full example:

```<code>public class AddDeleteButtonTest {

    private static class Row {

        final Composite baseComposite;

        public Row(final Composite parent) {
            baseComposite = new Composite(parent, SWT.BORDER);
            baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
            baseComposite.setLayout(new GridLayout(2, false));

            final Text text = new Text(baseComposite, SWT.BORDER);
            text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

            final Button deleteButton = new Button(baseComposite, SWT.PUSH);
            deleteButton.setText("Delete");
            deleteButton.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(final SelectionEvent e) {
                    baseComposite.dispose();
                    parent.layout();
                }

            });
        }

    }

    private final Display display;
    private final Shell shell;

    public AddDeleteButtonTest() {
        display = new Display();
        shell = new Shell(display);
        shell.setLayout(new FillLayout());

        final Composite baseComposite = new Composite(shell, SWT.BORDER);
        baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        baseComposite.setLayout(new GridLayout());

        final Composite rowsContainerComposite = new Composite(baseComposite, SWT.BORDER);
        rowsContainerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        rowsContainerComposite.setLayout(new GridLayout());

        final Button addButton = new Button(baseComposite, SWT.PUSH);
        addButton.setText("Add");
        addButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent e) {
                new Row(rowsContainerComposite);
                rowsContainerComposite.layout();
            }

        });
    }

    public void run() {
        shell.setSize(200, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    public static void main(final String... args) {
        new AddDeleteButtonTest().run();
    }

}
</code>```

Body:
If you create a Composite as a container of sorts, you can add and remove from it allowing everything outside to remain in the correct order. By reserving the space, the delete button is always below the contents of the container.

I have a text box and a add button next to it, when I click on add button I am able to add a text box and delete button next to it

For example, if we have a small Shell with an add Button as you mentioned, and an empty space to add the Text widgets to:

final Composite baseComposite = new Composite(shell, SWT.BORDER);
baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
baseComposite.setLayout(new GridLayout());

final Composite rowsContainerComposite = new Composite(baseComposite, SWT.BORDER);
rowsContainerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
rowsContainerComposite.setLayout(new GridLayout());

final Button addButton = new Button(baseComposite, SWT.PUSH);
addButton.setText("Add");

(For now the empty space is grabbing all available space, but you can change that as needed)

When adding rows, you can add to the rowsContainerComposite:

addButton.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(final SelectionEvent e) {
        new Row(rowsContainerComposite);
        rowsContainerComposite.layout();
    }
});

A sample Row class:

public class Row {

    final Composite baseComposite;

    public Row(final Composite parent) {
        baseComposite = new Composite(parent, SWT.BORDER);
        baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        baseComposite.setLayout(new GridLayout(2, false));

        final Text text = new Text(baseComposite, SWT.BORDER);
        text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        final Button deleteButton = new Button(baseComposite, SWT.PUSH);
        deleteButton.setText("Delete");
        deleteButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent e) {
                baseComposite.dispose();
                parent.layout();
            }

        });
    }

}

when the second row delete button is clicked (the second row is deleted )the add button should go back to the first row

Then when deleted, rows will shift back appropriately:

the add button should be re-positioned below two rows

The idea is that by using the "container" composite, you're reserving that space to add and remove the rows from. The delete button will always be below the rows as they are added and removed.

Full example:

public class AddDeleteButtonTest {

    private static class Row {

        final Composite baseComposite;

        public Row(final Composite parent) {
            baseComposite = new Composite(parent, SWT.BORDER);
            baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
            baseComposite.setLayout(new GridLayout(2, false));

            final Text text = new Text(baseComposite, SWT.BORDER);
            text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

            final Button deleteButton = new Button(baseComposite, SWT.PUSH);
            deleteButton.setText("Delete");
            deleteButton.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(final SelectionEvent e) {
                    baseComposite.dispose();
                    parent.layout();
                }

            });
        }

    }

    private final Display display;
    private final Shell shell;

    public AddDeleteButtonTest() {
        display = new Display();
        shell = new Shell(display);
        shell.setLayout(new FillLayout());

        final Composite baseComposite = new Composite(shell, SWT.BORDER);
        baseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        baseComposite.setLayout(new GridLayout());

        final Composite rowsContainerComposite = new Composite(baseComposite, SWT.BORDER);
        rowsContainerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        rowsContainerComposite.setLayout(new GridLayout());

        final Button addButton = new Button(baseComposite, SWT.PUSH);
        addButton.setText("Add");
        addButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent e) {
                new Row(rowsContainerComposite);
                rowsContainerComposite.layout();
            }

        });
    }

    public void run() {
        shell.setSize(200, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    public static void main(final String... args) {
        new AddDeleteButtonTest().run();
    }

}


问:
Not able to merge records in Oracle database using merge statement
```<code>SELECT * FROM DIM_TRANS_TYPE WHERE TRANSACTION_TYPE='ILAU';
</code>```

All I want to accomplish here is change ILAU to IFAU and Instant Loan Authorization Request to Instant Finance Authorization Request in the above-mentioned record.

Table Schema:

```<code>Name                  Null     Type
--------------------- -------- ------------------
TRANSACTION_TYPE      NOT NULL VARCHAR2(4 CHAR)   --> PRIMARY KEY
TRANSACTION_TYPE_DESC          VARCHAR2(256 CHAR)
</code>```

WORKS !!!

```<code>MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);
</code>```

DOES NOT WORK !!! (Error shown below)

```<code>MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE = 'IFAU',
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);
</code>```

Error:

```<code>Error at Command Line : 5 Column : 9
Error report -
SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."TRANSACTION_TYPE"
38104. 00000 -  "Columns referenced in the ON Clause cannot be updated: %s"
*Cause:    LHS of UPDATE SET contains the columns referenced in the ON Clause
*Action:
</code>```

答:
Perhaps I am missing something....   It seems you are looking to identify all the rows where transaction_type = 'ILAU' (regardless of transaction_type_desc), and for those rows to update transaction_type to 'IFAU' and transaction_type_desc to 'Instant Finance Authorization Request'. Right?

If so, why do you need anything other than a trivial UPDATE statement?

```<code>update  dim_trans_type
  set   transaction_type      = 'IFAU',
        transaction_type_desc = 'Instant Finance Authorization Request'
  where transaction_type      = 'ILAU'
;
</code>```

In your attempts there is also a when not matched clause - inserting a row if none of the existing rows have transaction_type = 'ILAU'. How is that related to your requirement? You said All I want to accomplish here is change [.....] - no mention of inserting anything. Is the problem statement, in plain English, incomplete? Or are you inserting things that don't need to be inserted?

Body:
SELECT * FROM DIM_TRANS_TYPE WHERE TRANSACTION_TYPE='ILAU';

All I want to accomplish here is change ILAU to IFAU and Instant Loan Authorization Request to Instant Finance Authorization Request in the above-mentioned record.

Table Schema:

Name                  Null     Type
--------------------- -------- ------------------
TRANSACTION_TYPE      NOT NULL VARCHAR2(4 CHAR)   --> PRIMARY KEY
TRANSACTION_TYPE_DESC          VARCHAR2(256 CHAR)

WORKS !!!

MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);

DOES NOT WORK !!! (Error shown below)

MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE = 'IFAU',
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);

Error:

Error at Command Line : 5 Column : 9
Error report -
SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."TRANSACTION_TYPE"
38104. 00000 -  "Columns referenced in the ON Clause cannot be updated: %s"
*Cause:    LHS of UPDATE SET contains the columns referenced in the ON Clause
*Action:

Body:
Perhaps I am missing something....   It seems you are looking to identify all the rows where transaction_type = 'ILAU' (regardless of transaction_type_desc), and for those rows to update transaction_type to 'IFAU' and transaction_type_desc to 'Instant Finance Authorization Request'. Right?

If so, why do you need anything other than a trivial UPDATE statement?

update  dim_trans_type
  set   transaction_type      = 'IFAU',
        transaction_type_desc = 'Instant Finance Authorization Request'
  where transaction_type      = 'ILAU'
;

In your attempts there is also a when not matched clause - inserting a row if none of the existing rows have transaction_type = 'ILAU'. How is that related to your requirement? You said All I want to accomplish here is change [.....] - no mention of inserting anything. Is the problem statement, in plain English, incomplete? Or are you inserting things that don't need to be inserted?


问:
How can I set a font-family instead of font when using Batik's SVGGraphics2D?
I currently have the following code using Batik's SVGGraphics2D:

```<code>...
final SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgGeneratorContext, false);
svgGraphics2D.setSVGCanvasSize(new Dimension(width, height));
svgGraphics2D.setFont(font);
...
</code>```

As a result, if font is an available Font on the system on which the code is executed, the correct attribute is added to the resulting SVG file.

However, if the font is missing (for instance "Verdana" on a linux box) a default font is used (font-family:'Dialog' is added).

Thus, instead of specifying a font, I would like to pass a font-family in order to have font-family="DejaVu Sans,Verdana,Geneva,sans-serif" in the resulting SVG. How can I achieve this knowing that, if I'm not wrong, the API only accepts Font parameters ?

I hope that there's a easier way than using a xslt to transform the xml output.

Thank you in advance.

答:
If you have a (licensed) font file, say as resource, you might do:

```<code>    InputStream is = SomeClass.getResourceAsStream("/fonts/DejaVu Sans.ttf");
    Font font = Font.createFont(Font.TRUETYPE_FONT, is);
    GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(font);
</code>```

This is a general way to deliver an application with its own font.

Then in the SVG you can embed the exact font for stand-alone svg files.

I wonder that it is not possible to do:

```<code>font-family="'DejaVu Sans',Verdana,Geneva,sans-serif"
</code>```

as that would be the CSS way.

Body:
I currently have the following code using Batik's SVGGraphics2D:

...
final SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgGeneratorContext, false);
svgGraphics2D.setSVGCanvasSize(new Dimension(width, height));
svgGraphics2D.setFont(font);
...

As a result, if font is an available Font on the system on which the code is executed, the correct attribute is added to the resulting SVG file.

However, if the font is missing (for instance "Verdana" on a linux box) a default font is used (font-family:'Dialog' is added).

Thus, instead of specifying a font, I would like to pass a font-family in order to have font-family="DejaVu Sans,Verdana,Geneva,sans-serif" in the resulting SVG. How can I achieve this knowing that, if I'm not wrong, the API only accepts Font parameters ?

I hope that there's a easier way than using a xslt to transform the xml output.

Thank you in advance.

Body:
If you have a (licensed) font file, say as resource, you might do:

    InputStream is = SomeClass.getResourceAsStream("/fonts/DejaVu Sans.ttf");
    Font font = Font.createFont(Font.TRUETYPE_FONT, is);
    GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(font);

This is a general way to deliver an application with its own font.

Then in the SVG you can embed the exact font for stand-alone svg files.

I wonder that it is not possible to do:

font-family="'DejaVu Sans',Verdana,Geneva,sans-serif"

as that would be the CSS way.


问:
Collection of Great Applications and Programs using Macros
I am very very interested in Macros and just beginning to understand its true power. Please help me collect some great usage of macro systems.

So far I have these constructs:

Pattern Matching:

Andrew Wright and Bruce Duba. Pattern
  matching for Scheme, 1995

Relations in the spirit of Prolog:

Dorai Sitaram. Programming in schelog.
  http://www.ccs.neu.edu/home/dorai/schelog/schelog.html

Daniel P. Friedman, William E. Byrd,
  and Oleg Kiselyov. The Reasoned
  Schemer. The MIT Press, July 2005

Matthias Felleisen. Transliterating
  Prolog into Scheme. Technical Report
  182, Indiana University, 1985.

Extensible Looping Constructs:

Sebastian Egner. Eager comprehensions
  in Scheme: The design of SRFI-42. In
  Workshop on Scheme and Functional
  Programming, pages13–26, September
  2005.

Olin Shivers. The anatomy of a loop: a
  story of scope and control. In
  International Conference on Functional
  Programming, pages 2–14, 2005.

Class Systems:

PLT. PLT MzLib: Libraries manual.
  Technical Report PLT-TR2006-4-v352,
  PLT Scheme Inc., 2006.
  http://www.plt-scheme.org/techreports/

Eli Barzilay. Swindle.
  http://www.barzilay.org/Swindle.

Component Systems:

Ryan Culpepper, Scott Owens, and
  Matthew Flatt. Syntactic abstraction
  in component interfaces. In
  International Conference on Generative
  Programming and Component Engineering,
  pages 373–388, 2005

Software Contract Checking

Matthew Flatt and Matthias Felleisen.
  Units: Cool modules for HOT languages
  In ACM SIGPLAN Conference on
  Programming Language Design and
  Implementation, pages 236–248, 1998

Oscar Waddell and R. Kent Dybvig.
  Extending the scope of syntactic
  abstraction.In Symposium on Principles
  of Programming Languages, pages
  203–215, 199

Parser Generators

Scott Owens, Matthew Flatt, Olin
  Shivers, and Benjamin McMullan. Lexer
  and parser generators in Scheme. In
  Workshop on Scheme and Functional
  Programming, pages 41–52, September
  2004.

Tools for Engineering Semantics:

Matthias Felleisen, Robert Bruce
  Findler, and Matthew Flatt. Semantics
  Engineering with PLT Redex. MIT Press,
  August 2009.

Speciﬁcations of Compiler Transformations:

Dipanwita Sarkar, Oscar Waddell, and R. Kent Dybvig. A nanopass
  framework for compiler education.
  Journal of Functional
  Programming,15(5):653–667, September
  2005. Educational Pearl.

Novel Forms of Execution

Servlets with serializable
  continuations Greg Pettyjohn, John
  Clements, Joe Marshall, Shriram
  Krishnamurthi, and Matthias Felleisen.
  Continuations from generalized stack
  inspection. In International
  Conference on Functional Programming,
  pages216–227, 2005.

Theorem-Proving System

Sebastian Egner. Eager comprehensions in Scheme: The design
  of  SRFI-42.
  In Workshop on Scheme and Functional Programming, pages 13–26,
  September 2005.

Extensions of the Base Language with Types

Sam Tobin-Hochstadt and Matthias
  Felleisen.The design and
  implementation of typed scheme. In
  Symposium on Principles of Programming
  Languages, pages 395–406, 2008.

Laziness

Eli Barzilay and John Clements.
  Laziness without all the hard
  work:combining lazy and strict
  languages for teaching. In Functional
  and declarative programming in
  education, pages 9–13, 2005.

Functional Reactivity

Gregory H. Cooper and Shriram
  Krishnamurthi. Embedding dynamic
  dataﬂow in a call-by-value language.
  In European Symposium on Programming,
  2006

Reference:

Collected from Ryan Culpepper's Dissertation

答:
Check one of my favorites implementations of a REST API: the Slack api client, that isn't written in Scheme but it is in Racket. </p>

<p>octotep/racket-slack-api
</p>

Body:
Check one of my favorites implementations of a REST API: the Slack api client, that isn't written in Scheme but it is in Racket.

octotep/racket-slack-api


问:
Laravel 5.4 delete table row and rows from related table
When i delete a row from a groups table, i want the function to also delete all relation mapping from table group_user. For example, if i delete group with id 4, all rows in group_user table with group_id 4 are deleted as well. Tables below:

 Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('phone');
            $table->boolean('approved')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
 Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('course_id');
            $table->timestamp('start_date')->nullable();
            $table->timestamp('end_date')->nullable();
            $table->timestamps();
        });
  Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('group_id');
            $table->timestamps();
        });```
</div>
</div>
</p>

<p>Currently using this function in group controller, but it only deletes from groups table:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>function deleteGroup($id){
  $group = Group::find($id);
  $group->delete();
  return redirect()->back();
 }</code>```

答:
If your table storage engine type is innodb you can try in your migrations to set correct relationships and all will be done in the database layer.</p>

```<code>Schema::create('group_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('group_id');
        $table->timestamps();

        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
    });
</code>```

Body:
When i delete a row from a groups table, i want the function to also delete all relation mapping from table group_user. For example, if i delete group with id 4, all rows in group_user table with group_id 4 are deleted as well. Tables below:

 Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('phone');
            $table->boolean('approved')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
 Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('course_id');
            $table->timestamp('start_date')->nullable();
            $table->timestamp('end_date')->nullable();
            $table->timestamps();
        });
  Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('group_id');
            $table->timestamps();
        });

Currently using this function in group controller, but it only deletes from groups table:

function deleteGroup($id){
  $group = Group::find($id);
  $group->delete();
  return redirect()->back();
 }

Body:
If your table storage engine type is innodb you can try in your migrations to set correct relationships and all will be done in the database layer.

Schema::create('group_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('group_id');
        $table->timestamps();

        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
    });


问:
Multi html formatting in Snackbar
Im trying to add multiple html foreground formattings of a snackbar text programmatically.

In my strings.xml:

```<code><string name="html_test">The html entries %1$s and %2$s are looking different.</string>
</code>```

How i try to format them:

```<code>  public static Spanned getString(Context p_Context, int p_iResID, int p_iColor, String... p_Items) {
    int l_iColor = ContextCompat.getColor(p_Context, p_iColor);
    String l_HexColor = Integer.toHexString(l_iColor);

    String l_Before = "<font color=" + l_HexColor + ">";
    String l_After = "</font>";

    Object[] l_Items = new String[p_Items.length];
    for(int i = 0; i < p_Items.length; i++) {
      l_Items[i] = l_Before + p_Items[i] + l_After;
    }

    return Html.fromHtml(p_Context.getString(p_iResID, l_Items));
  }
</code>```

How i call the function:

```<code>getString(getContext(), R.string.html_test, R.color.blue, "Test1", "Test2");
</code>```

Then i create a snackbar and pass the html formated text.

```<code>Snackbar l_SnackBar = Snackbar.make(p_Root, p_Text, p_iSnackBarLenght);
l_SnackBar.getView().setBackgroundColor(p_iBGColor);
return l_SnackBar;
</code>```

The problem is that there is no html formatting of the two entries i passed into getString().

I don't want to use ![CDATA... because i read that there are some problems with the formatting.

答:
I didn't found a solution to format the foreground parameters of getString() with html. Now im doing it with SpannableString which works for me. My code looks like this now:

```<code>  public static SpannableString getString(Context p_Context, int p_iResID, int p_iColor, Object... p_Items) {
    String l_Feedback = p_Context.getString(p_iResID, p_Items);
    SpannableString l_SpannableFeedback = new SpannableString(l_Feedback);
    int l_iItemColor = ContextCompat.getColor(p_Context, p_iColor);

    for(Object l_Object : p_Items) {
      String l_Item = (String) l_Object;
      int l_iStartIndex = l_Feedback.indexOf(l_Item);
      int l_iEndIndex = l_iStartIndex + l_Item.length();

      l_SpannableFeedback.setSpan(new ForegroundColorSpan(l_iItemColor), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      l_SpannableFeedback.setSpan(new StyleSpan(Typeface.BOLD), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return l_SpannableFeedback;
  }
</code>```

Title: Multi html formatting in Snackbar

Body:
Im trying to add multiple html foreground formattings of a snackbar text programmatically.

In my strings.xml:

<string name="html_test">The html entries %1$s and %2$s are looking different.</string>

How i try to format them:

  public static Spanned getString(Context p_Context, int p_iResID, int p_iColor, String... p_Items) {
    int l_iColor = ContextCompat.getColor(p_Context, p_iColor);
    String l_HexColor = Integer.toHexString(l_iColor);

    String l_Before = "";
    String l_After = "";

    Object[] l_Items = new String[p_Items.length];
    for(int i = 0; i < p_Items.length; i++) {
      l_Items[i] = l_Before + p_Items[i] + l_After;
    }

    return Html.fromHtml(p_Context.getString(p_iResID, l_Items));
  }

How i call the function:

getString(getContext(), R.string.html_test, R.color.blue, "Test1", "Test2");

Then i create a snackbar and pass the html formated text.

Snackbar l_SnackBar = Snackbar.make(p_Root, p_Text, p_iSnackBarLenght);
l_SnackBar.getView().setBackgroundColor(p_iBGColor);
return l_SnackBar;

The problem is that there is no html formatting of the two entries i passed into getString().

I don't want to use ![CDATA... because i read that there are some problems with the formatting.

Body:
I didn't found a solution to format the foreground parameters of getString() with html. Now im doing it with SpannableString which works for me. My code looks like this now:

  public static SpannableString getString(Context p_Context, int p_iResID, int p_iColor, Object... p_Items) {
    String l_Feedback = p_Context.getString(p_iResID, p_Items);
    SpannableString l_SpannableFeedback = new SpannableString(l_Feedback);
    int l_iItemColor = ContextCompat.getColor(p_Context, p_iColor);

    for(Object l_Object : p_Items) {
      String l_Item = (String) l_Object;
      int l_iStartIndex = l_Feedback.indexOf(l_Item);
      int l_iEndIndex = l_iStartIndex + l_Item.length();

      l_SpannableFeedback.setSpan(new ForegroundColorSpan(l_iItemColor), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      l_SpannableFeedback.setSpan(new StyleSpan(Typeface.BOLD), l_iStartIndex, l_iEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return l_SpannableFeedback;
  }


问:
Sending variables from two different HTML sources to a single PHP script using HTML/PHP/JScript only
I have a situation in which a page is built off two different sources with HTML by combining with each other in a containter third page. Each section also has a variable they pass through a form using POST to a single PHP file. These variables change in every execution (When they form a page together).

For example:

```<code><!--Start of HTML 3 -->
<html>
<!-- Start of HTML 1 -->
<body>

<a href='process.php' id='php1' name='php1' onclick='document.getElementById("infoForm").submit()'> A link to php file that receives a hidden form's value</a>

<form id='infoForm' action='process.php' method='POST'>
  <input name ="var1" id="var1" value="changing1" hidden />
</form>
<p>Stuff here</p>
<!-- End of HTML 1 -->

<!-- Start of HTML 2 -->
<p>Some more stuff here</p>
<form id='infoForm2' action='process.php' method='POST'>
  <input name ="var2" id="var2" value="changing2" hidden />
</form>

</body>
<!-- End of HTML 2 -->
</html>
<!-- End of HTML 3 -->
</code>```

A few more details:

The forms are independent of each other, joining them would be difficult since they are created using previous processes that work with other variables.

Code can be added inside HTML 1 and 2, but not 3.

This one will only be able to send var1 to process.php (which can invoke it with $_POST). How could I submit both variables to a single PHP file, using a single link, using basic technologies (e.g. Excluding JQuery, AJAX, etc)? Is there a better way than using forms/POST without using the URI?

EDIT: The method I used was @glenn ferns first point: use the form attribute to attach the second one to the first form in the html makeup:

```<code><!-- Start of HTML 2 -->
<p>Some more stuff here</p>

<input form="infoForm" name ="var2" id="var2" value="changing2" hidden />

</body>
<!-- End of HTML 2 -->
</code>```

答:
As per your comments, you need to submit the forms and catch the variables together. This is not applicable with two forms as they will submit two different requests. And as HTTP is a stateless protocol, every request will be handled away from the other. You can use sessions to store one value from the first request and use it within the handling of the second request.

Another solution could be using JavaScript to send your variables with an Ajax request. (I don't see any valid use case to not use JavaScript)

Body:
I have a situation in which a page is built off two different sources with HTML by combining with each other in a containter third page. Each section also has a variable they pass through a form using POST to a single PHP file. These variables change in every execution (When they form a page together).

For example:

 A link to php file that receives a hidden form's value

<form id='infoForm' action='process.php' method='POST'>
  <input name ="var1" id="var1" value="changing1" hidden />
</form>

Stuff here

Some more stuff here

<form id='infoForm2' action='process.php' method='POST'>
  <input name ="var2" id="var2" value="changing2" hidden />
</form>

A few more details:

The forms are independent of each other, joining them would be difficult since they are created using previous processes that work with other variables.

Code can be added inside HTML 1 and 2, but not 3.

This one will only be able to send var1 to process.php (which can invoke it with $_POST). How could I submit both variables to a single PHP file, using a single link, using basic technologies (e.g. Excluding JQuery, AJAX, etc)? Is there a better way than using forms/POST without using the URI?

EDIT: The method I used was @glenn ferns first point: use the form attribute to attach the second one to the first form in the html makeup:

Some more stuff here

<input form="infoForm" name ="var2" id="var2" value="changing2" hidden />


问:
Should bcrypted passwords be stored as byte array or as string and why?
I read on some SO answer (which I can't seem to find again) that bcrypted passwords must be stored as byte array in the database. I'm storing them as string. Is there any advantage I gain by storing them as byte array or maybe it's more secure that way?</p>

答: An encoding doesn't change the security of the system. Use whatever is easier and compatible with your database. As always the encoding that you choose and the database API must be appropriate for arbitrary binary data, most character encodings such as UTF-8 and ASCII are not.</p>