问:
Unable to update time in datePicker on button click in tableview swift
I am trying to display a date picker and update its time on button click.

I have a table view which shows business hours as shown in the below figure 1.

Figure 1

On clicking the timings cell or the time button inside the cell, I am expanding the cell to show date picker, I am unable to update the time in the date picker to the time on the time button.

For example when 9:00 AM is clicked, I would like to show 9:00 AM in the date picker as shown in below figure 2 or when 5:00 PM is clicked I would like to show 5:00 PM in date picker.

Also when the user changes the time in the date picker, I would like to update its corresponding time button in the tableview cell.

Figure 2

Below is the code, see code below comment //Updating the date picker

Since I am trying to update the date picker time inside a closure, it doesn't seem to work. Can someone please advice how I can fix this ?

```<code>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.setEditing(true, animated: true)      // This displays the delete button infront of the cell
        tableView.allowsSelectionDuringEditing = true   // Allows the table view cells to be selected during editing mode

        if indexPath.section == 0 {

            let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell

            // Configure the cell...
            cell.selectionStyle             = UITableViewCellSelectionStyle.none; // Ensuring that there is no background for the selected cell
            cell.datePicker.datePickerMode  = .time         // Setting start and time
            cell.datePicker.minuteInterval = 5
            cell.datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)

            let startTime   = timesArray[indexPath.row]["startTime"]
            cell.startTime.setTitle(startTime as! String?, for: .normal)
            cell.startTime.setTitleColor(UIColor.black, for: .normal)

            let endTime     = timesArray[indexPath.row]["endTime"]

            cell.endTime.setTitle(endTime as! String?, for: .normal)
            cell.endTime.setTitleColor(UIColor.black, for: .normal)

            // Closure
            cell.startTimeTapped = { (button  : UIButton) -> Void in

                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

            }

            // Closure
            cell.endTimeTapped = { (button) -> Void in
                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: endTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath{
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)
                    self.selectedCellIndexPath = nil
                }else{
                    self.selectedCellIndexPath = indexPath
                }
            }
            return cell
      }
}
</code>```

DailyTimesTableViewCell code:

```<code>import UIKit

class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {
    typealias  buttonTappedBlock = (_ button:UIButton) -> Void
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!

    @IBAction func startTimeClicked(_ sender: subclassedUIButton) {
        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
    }

    @IBAction func endTimeClicked(_ sender: UIButton) {
        if endTimeTapped != nil{
            endTimeTapped(sender as UIButton)
        }
    }
}
</code>```

答:
The answer for this part of the question:

I am unable to update the time in the date picker to the time on the
  time button

is the below code:

the issue was with this line of code tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) and by adding tableView.beginUpdates(), tableView.beginUpdates() and returning the cell helped.

In the function cellForRow At updated to the below code

```<code>cell.startTimeTapped = { (button) -> DailyTimesTableViewCell in
                self.tableView.beginUpdates()
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

                tableView.endUpdates()

                return cell

            }
</code>```

In the class DailyTimesTableViewCell, updated to the below code

```<code>class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {

typealias  buttonTappedBlock = (_ button:UIButton) -> DailyTimesTableViewCell
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!
    @IBAction func startTimeClicked(_ sender: UIButton) {

        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
   }

}
</code>```

Body:
I am trying to display a date picker and update its time on button click.

I have a table view which shows business hours as shown in the below figure 1.

Figure 1

On clicking the timings cell or the time button inside the cell, I am expanding the cell to show date picker, I am unable to update the time in the date picker to the time on the time button.

For example when 9:00 AM is clicked, I would like to show 9:00 AM in the date picker as shown in below figure 2 or when 5:00 PM is clicked I would like to show 5:00 PM in date picker.

Also when the user changes the time in the date picker, I would like to update its corresponding time button in the tableview cell.

Figure 2

Below is the code, see code below comment //Updating the date picker

Since I am trying to update the date picker time inside a closure, it doesn't seem to work. Can someone please advice how I can fix this ?

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.setEditing(true, animated: true)      // This displays the delete button infront of the cell
        tableView.allowsSelectionDuringEditing = true   // Allows the table view cells to be selected during editing mode

        if indexPath.section == 0 {

            let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell

            // Configure the cell...
            cell.selectionStyle             = UITableViewCellSelectionStyle.none; // Ensuring that there is no background for the selected cell
            cell.datePicker.datePickerMode  = .time         // Setting start and time
            cell.datePicker.minuteInterval = 5
            cell.datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)

            let startTime   = timesArray[indexPath.row]["startTime"]
            cell.startTime.setTitle(startTime as! String?, for: .normal)
            cell.startTime.setTitleColor(UIColor.black, for: .normal)

            let endTime     = timesArray[indexPath.row]["endTime"]

            cell.endTime.setTitle(endTime as! String?, for: .normal)
            cell.endTime.setTitleColor(UIColor.black, for: .normal)

            // Closure
            cell.startTimeTapped = { (button  : UIButton) -> Void in

                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

            }

            // Closure
            cell.endTimeTapped = { (button) -> Void in
                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: endTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath{
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)
                    self.selectedCellIndexPath = nil
                }else{
                    self.selectedCellIndexPath = indexPath
                }
            }
            return cell
      }
}

DailyTimesTableViewCell code:

import UIKit

class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {
    typealias  buttonTappedBlock = (_ button:UIButton) -> Void
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!

    @IBAction func startTimeClicked(_ sender: subclassedUIButton) {
        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
    }

    @IBAction func endTimeClicked(_ sender: UIButton) {
        if endTimeTapped != nil{
            endTimeTapped(sender as UIButton)
        }
    }
}

Body:
The answer for this part of the question:

I am unable to update the time in the date picker to the time on the
  time button

is the below code:

the issue was with this line of code tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) and by adding tableView.beginUpdates(), tableView.beginUpdates() and returning the cell helped.

In the function cellForRow At updated to the below code

cell.startTimeTapped = { (button) -> DailyTimesTableViewCell in
                self.tableView.beginUpdates()
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

                tableView.endUpdates()

                return cell

            }

In the class DailyTimesTableViewCell, updated to the below code

class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {

typealias  buttonTappedBlock = (_ button:UIButton) -> DailyTimesTableViewCell
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!
    @IBAction func startTimeClicked(_ sender: UIButton) {

        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
   }

}


来源: stackexchange

问:
apache rewrite unless condition met
I'm trying to set up Apache (2.4.25 on Amazon Linux) to redirect users to a certain site if their remote address is NOT in a given list of authorized IP addresses. For example, if their IP address is 123.321.123.1 or 192.192.192.5 or within 169.22.123.x, then proceed to mysite.com; otherwise, redirect to google.com.

I'm not sure how to handle this aside from knowing that it will involve shenanigans with Rewrite, which I'm comfortable doing.

Any help or suggestions or ideas would be appreciated.

TIA!

ContentLicense: CC BY-SA 3.0

Title: apache rewrite unless condition met

Body:
Fortunately you're on 2.4!

<If "%{REMOTE_ADDR} == '123.321.123.1' || %{REMOTE_ADDR} ==  '192.192.192.5' || -R '169.22.123.0/24'">
  Redirect /what /matched
</If>


问:
When do you create a custom function in mysql
I'm new to MySQL. I have a database that is accessed by many servers. I need to create a custom MySQL function like this for example:

```<code>DELIMITER $$

create function calcDistance(lat float, lng float, pnt_lat float, pnt_lng float)

Returns float
BEGIN

Declare dist float;
SET dist =
  3959 * acos (
  cos ( radians(pnt_lat) )
  * cos( radians( lat ) )
  * cos( radians( lng ) - radians(pnt_lng) )
  + sin ( radians(pnt_lat) )
  * sin( radians( lat ) )
);

RETURN dist;

END
</code>```

Since i want this function to be used by many servers, im wondering HOW and WHEN do i send this function to the database?

Since i have many servers that can crash and rebooted at anytime, do i resend this same function to MySQL everytime a server boots up, but before i start making queries? What happens if i send the same function more than once, since the servers wont know if the function was already sent to the database by another server.

I dont really know how it works...Does anybody know the answers to this?

Thanks

答: You don't need to resend it. This is a stored function, it's saved on the database server just like tables are. Once it's created, any client can use it until you explicitly drop it.

Body:
I'm new to MySQL. I have a database that is accessed by many servers. I need to create a custom MySQL function like this for example:

DELIMITER $$

create function calcDistance(lat float, lng float, pnt_lat float, pnt_lng float)

Returns float
BEGIN

Declare dist float;
SET dist =
  3959 * acos (
  cos ( radians(pnt_lat) )
  * cos( radians( lat ) )
  * cos( radians( lng ) - radians(pnt_lng) )
  + sin ( radians(pnt_lat) )
  * sin( radians( lat ) )
);

RETURN dist;

END

Since i want this function to be used by many servers, im wondering HOW and WHEN do i send this function to the database?

Since i have many servers that can crash and rebooted at anytime, do i resend this same function to MySQL everytime a server boots up, but before i start making queries? What happens if i send the same function more than once, since the servers wont know if the function was already sent to the database by another server.

I dont really know how it works...Does anybody know the answers to this?

Thanks


问:
Analog of function range in golang
Range in php http://php.net/manual/en/function.range.php
To create such an array, need use a slice?
I only know the method using the slice and loop for, but can there be another, more efficient way?</p>

答:
In golang, there is only one iteration construct and that's the for loop. There are multiple ways to configure the for loop itself, but overall there is just the single construct:

https://tour.golang.org/flowcontrol/1

https://play.golang.org/p/wBSGJqHuLK

```<code>The C method -- for i := 0; i < 10; i++ { }
The python method -- for k, v := range map[string]string{"key": "val"} { }
The python method -- for idx, val := range []string{"one", "two"} { }
The empty for -- for { }
</code>```

Title: Analog of function range in golang

Body:
In golang, there is only one iteration construct and that's the for loop. There are multiple ways to configure the for loop itself, but overall there is just the single construct:

https://tour.golang.org/flowcontrol/1

https://play.golang.org/p/wBSGJqHuLK

The C method -- for i := 0; i < 10; i++ { }
The python method -- for k, v := range map[string]string{"key": "val"} { }
The python method -- for idx, val := range []string{"one", "two"} { }
The empty for -- for { }


问:
Implementing custom filters using GPUImage Swift library
This probably is a dumb question, but I am stuck with this for a while so going to ask it anyway.

I'm trying to implement a Hudson/Nashville filter on a pet project. I googled a little and checkout out a few open-source projects and found some Objective-C (which I don't understand) based projects. They do have the filters implemented using GPUImage2, but I wasn't sure about their approach.

I have the overlay and other images that they have used and the GLSL files.

So my question is how do I go about using this images and shader files to implement a custom filter?

Note: I tried using the LookupFilter approach as suggested, but the result wasn't so good. It would be super helpful if you can show me some code. Thanks

Update:

What I am trying to understand this. Given a custom shader like the one below, how am I supposed to pass the input images for uniform inputImageTexture2, inputImageTexture3 & inputImageTexture4. Do I pass it as a PictureInput to BasicOperation by subclassing it? If so, how? What am I missing? I haven't been able to walk through the code much because of the lack of a proper documentation. I have read up on shaders and its different components now, but still not able to figure out a way to work with custom filters on GPUImage2. Please help.

```<code>precision highp float;

varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2; //blowout;
uniform sampler2D inputImageTexture3; //overlay;
uniform sampler2D inputImageTexture4; //map

uniform float strength;

void main()
{
    vec4 originColor = texture2D(inputImageTexture, textureCoordinate);

    vec4 texel = texture2D(inputImageTexture, textureCoordinate);

    vec3 bbTexel = texture2D(inputImageTexture2, textureCoordinate).rgb;

    texel.r = texture2D(inputImageTexture3, vec2(bbTexel.r, texel.r)).r;
    texel.g = texture2D(inputImageTexture3, vec2(bbTexel.g, texel.g)).g;
    texel.b = texture2D(inputImageTexture3, vec2(bbTexel.b, texel.b)).b;

    vec4 mapped;
    mapped.r = texture2D(inputImageTexture4, vec2(texel.r, .16666)).r;
    mapped.g = texture2D(inputImageTexture4, vec2(texel.g, .5)).g;
    mapped.b = texture2D(inputImageTexture4, vec2(texel.b, .83333)).b;
    mapped.a = 1.0;

    mapped.rgb = mix(originColor.rgb, mapped.rgb, strength);

    gl_FragColor = mapped;
}
</code>```

答:
The GPUImage convention is that the first input texture to a shader is called inputTextureCoordinate, the second inputTextureCoordinate2, and so on. In the original Objective-C version of GPUImage, you can to manually subclass a filter type that matched the number of input textures in your shader.

In the Swift GPUImage 2, I've made it so that you just need to use a BasicOperation class or subclass, and it automatically attaches textures to the number of inputs needed for your shader. You do this by initializing a BasicOperation and setting the number of inputs:

```<code>let myOperation = BasicOperation(fragmentShaderFile:myFragmentShader, numberOfInputs:4)
</code>```

The above sets numberOfInputs to 4, matching your above shader. By leaving the vertexShaderFile argument as nil (the default), the BasicOperation will pick an appropriate simple vertex shader with four texture inputs.

All that you need to do then is set your inputs to that filter like you would any other, by adding your new BasicOperation as a target of an image source. The order in which you attach the inputs matters, because that will start with the first texture in your shader and progress on down.

In most cases, BasicOperation is flexible enough as-is, so you won't need to subclass. At most, you might need to provide a custom vertex shader, but that's not needed for the fragment shader code above.

Body:
This probably is a dumb question, but I am stuck with this for a while so going to ask it anyway.

I'm trying to implement a Hudson/Nashville filter on a pet project. I googled a little and checkout out a few open-source projects and found some Objective-C (which I don't understand) based projects. They do have the filters implemented using GPUImage2, but I wasn't sure about their approach.

I have the overlay and other images that they have used and the GLSL files.

So my question is how do I go about using this images and shader files to implement a custom filter?

Note: I tried using the LookupFilter approach as suggested, but the result wasn't so good. It would be super helpful if you can show me some code. Thanks

Update:

What I am trying to understand this. Given a custom shader like the one below, how am I supposed to pass the input images for uniform inputImageTexture2, inputImageTexture3 & inputImageTexture4. Do I pass it as a PictureInput to BasicOperation by subclassing it? If so, how? What am I missing? I haven't been able to walk through the code much because of the lack of a proper documentation. I have read up on shaders and its different components now, but still not able to figure out a way to work with custom filters on GPUImage2. Please help.

precision highp float;

varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2; //blowout;
uniform sampler2D inputImageTexture3; //overlay;
uniform sampler2D inputImageTexture4; //map

uniform float strength;

void main()
{
    vec4 originColor = texture2D(inputImageTexture, textureCoordinate);

    vec4 texel = texture2D(inputImageTexture, textureCoordinate);

    vec3 bbTexel = texture2D(inputImageTexture2, textureCoordinate).rgb;

    texel.r = texture2D(inputImageTexture3, vec2(bbTexel.r, texel.r)).r;
    texel.g = texture2D(inputImageTexture3, vec2(bbTexel.g, texel.g)).g;
    texel.b = texture2D(inputImageTexture3, vec2(bbTexel.b, texel.b)).b;

    vec4 mapped;
    mapped.r = texture2D(inputImageTexture4, vec2(texel.r, .16666)).r;
    mapped.g = texture2D(inputImageTexture4, vec2(texel.g, .5)).g;
    mapped.b = texture2D(inputImageTexture4, vec2(texel.b, .83333)).b;
    mapped.a = 1.0;

    mapped.rgb = mix(originColor.rgb, mapped.rgb, strength);

    gl_FragColor = mapped;
}

Body:
The GPUImage convention is that the first input texture to a shader is called inputTextureCoordinate, the second inputTextureCoordinate2, and so on. In the original Objective-C version of GPUImage, you can to manually subclass a filter type that matched the number of input textures in your shader.

In the Swift GPUImage 2, I've made it so that you just need to use a BasicOperation class or subclass, and it automatically attaches textures to the number of inputs needed for your shader. You do this by initializing a BasicOperation and setting the number of inputs:

let myOperation = BasicOperation(fragmentShaderFile:myFragmentShader, numberOfInputs:4)

The above sets numberOfInputs to 4, matching your above shader. By leaving the vertexShaderFile argument as nil (the default), the BasicOperation will pick an appropriate simple vertex shader with four texture inputs.

All that you need to do then is set your inputs to that filter like you would any other, by adding your new BasicOperation as a target of an image source. The order in which you attach the inputs matters, because that will start with the first texture in your shader and progress on down.

In most cases, BasicOperation is flexible enough as-is, so you won't need to subclass. At most, you might need to provide a custom vertex shader, but that's not needed for the fragment shader code above.


问:
VBoxManage: error: Failed to create the host-only adapter
I am running vagrant 1.4 and virtual box 4.3 on fedora 17 machine. When I do "vagrant up", I get this error:

```<code>Bringing machine 'default' up with 'virtualbox' provider...

[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["hostonlyif", "create"]

Stderr: 0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to create the host-only adapter
VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: VBoxNetAdpCtl: ioctl failed for /dev/vboxnetctl: Inappropriate ioctl for devic
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterface, interface IHostNetworkInterface
VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)" at line 66 of file VBoxManageHostonly.cpp
</code>```

答:
I'm running Oracle VM Virtualbox on Ubuntu 16.04 LTS.

The solution that worked was to reinstall virtualbox as mentioned here:

sudo apt remove virtualbox virtualbox-5.0 virtualbox-4.*

sudo apt-get install virtualbox

I couldn't find my VirtualBox installation folder, as such could not issue the command:

$sudo /Library/StartupItems/VirtualBox/VirtualBox restart

Body:
I am running vagrant 1.4 and virtual box 4.3 on fedora 17 machine. When I do "vagrant up", I get this error:

Bringing machine 'default' up with 'virtualbox' provider...

[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["hostonlyif", "create"]

Stderr: 0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to create the host-only adapter
VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: VBoxNetAdpCtl: ioctl failed for /dev/vboxnetctl: Inappropriate ioctl for devic
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterface, interface IHostNetworkInterface
VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)" at line 66 of file VBoxManageHostonly.cpp


问:
.rodata section loaded in executable page
So out of curiosity, I tried to run this code today (compiled with gcc -m32 1.c):

```<code>int main(void)
{
    // EB is the opcode for jmp rel/8
    // FE is hex for -2
    // So this is essentially an infinite loop

    ((void(*)(void))"\xEB\xFE")();
}
</code>```

... and it worked! No segfaults, the program (correctly?) goes into an infinite loop. Looking at the disassembly (objdump -d a.out), you can see the call to... whatever is at address 0x8048480:

```<code>080483d6 <main>:
 ....
 80483e7:   b8 80 84 04 08          mov    $0x8048480,%eax
 80483ec:   ff d0                   call   *%eax
 ....
</code>```

objdump -s -j .rodata a.out gives:

```<code>Contents of section .rodata:
 8048478 03000000 01000200 ebfe00             ...........
                           ~~~~
</code>```

So it is indeed executing the string, which is stored in the .rodata section. So I ran readelf --sections a.out and got:

```<code>Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1
  [ 2] .note.ABI-tag     NOTE            08048168 000168 000020 00   A  0   0  4
  [ 3] .note.gnu.build-i NOTE            08048188 000188 000024 00   A  0   0  4
  [ 4] .gnu.hash         GNU_HASH        080481ac 0001ac 000020 04   A  5   0  4
  [ 5] .dynsym           DYNSYM          080481cc 0001cc 000040 10   A  6   1  4
  [ 6] .dynstr           STRTAB          0804820c 00020c 000045 00   A  0   0  1
  [ 7] .gnu.version      VERSYM          08048252 000252 000008 02   A  5   0  2
  [ 8] .gnu.version_r    VERNEED         0804825c 00025c 000020 00   A  6   1  4
  [ 9] .rel.dyn          REL             0804827c 00027c 000008 08   A  5   0  4
  [10] .rel.plt          REL             08048284 000284 000008 08  AI  5  23  4
  [11] .init             PROGBITS        0804828c 00028c 000023 00  AX  0   0  4
  [12] .plt              PROGBITS        080482b0 0002b0 000020 04  AX  0   0 16
  [13] .plt.got          PROGBITS        080482d0 0002d0 000008 00  AX  0   0  8
  [14] .text             PROGBITS        080482e0 0002e0 000182 00  AX  0   0 16
  [15] .fini             PROGBITS        08048464 000464 000014 00  AX  0   0  4
  [16] .rodata           PROGBITS        08048478 000478 00000b 00   A  0   0  4
  [17] .eh_frame_hdr     PROGBITS        08048484 000484 000034 00   A  0   0  4
  [18] .eh_frame         PROGBITS        080484b8 0004b8 0000e0 00   A  0   0  4
  [19] .init_array       INIT_ARRAY      08049f0c 000f0c 000004 04  WA  0   0  4
  [20] .fini_array       FINI_ARRAY      08049f10 000f10 000004 04  WA  0   0  4
  [21] .dynamic          DYNAMIC         08049f14 000f14 0000e8 08  WA  6   0  4
  [22] .got              PROGBITS        08049ffc 000ffc 000004 04  WA  0   0  4
  [23] .got.plt          PROGBITS        0804a000 001000 000010 04  WA  0   0  4
  [24] .data             PROGBITS        0804a010 001010 000008 00  WA  0   0  4
  [25] .bss              NOBITS          0804a018 001018 000004 00  WA  0   0  1
  [26] .comment          PROGBITS        00000000 001018 00001a 01  MS  0   0  1
  [27] .symtab           SYMTAB          00000000 001034 0003f0 10     28  45  4
  [28] .strtab           STRTAB          00000000 001424 0001bd 00      0   0  1
  [29] .shstrtab         STRTAB          00000000 0015e1 000105 00      0   0  1
</code>```

So in the ELF binary, the section is marked non-executable. But in memory, the page is executable (cat /proc/xxx/maps):

```<code>08048000-08049000 r-xp 00000000 08:01 663551 /home/andrew/Desktop/a.out
08049000-0804a000 r--p 00000000 08:01 663551 /home/andrew/Desktop/a.out
0804a000-0804b000 rw-p 00001000 08:01 663551 /home/andrew/Desktop/a.out
</code>```

My original guess was that the sections too closely-spaced (there are both AX and A sections in the 08048000-08049000 range), so Linux is forced to give the page the union of the ELF permission bits (AX | A == AX). However, even after increasing the size of the .rodata section (by adding many long strings), all of the pages containing the .rodata section are still executable. Why is this?

(For the record, I'm running on Linux kernel 4.11.7, GCC 7.1.1, and compiling as 64-bit still exhibits this behavior)

答:
My original guess was that the segments too closely-spaced

You should not call sections segments (ELF has both, and they mean different things).

Sections only matter at static link time, and can be completely removed (are not needed at runtime). Only segments matter at runtime, and a typical ELF binary will have two segments with R-X and RW- permissions.

The .rodata section is usually merged with .text section and put into the executable segment. You can change that with the --rosegment flag if you use gold linker (patch which introduced this).

You can see section to segment mapping in the readelf -Wl a.out output.

Update:

Can there ever be a situation where .rodata needs to be executable, or is it for optimization, or something else?

There are no portable situations where .rodata needs to be executable. It is possible to construct a non-portable program that requires it, as you've done in your question.

Merging of .rodata and .text is an optimization: it requires two mmap calls instead of three (a program linked with --rosegment will have three separate PT_LOAD segments with R-X, R-- and R-W protections) and also fragments the virtual space less. In addition, on Linux there is a system-wide limit on total mappings, so you'll reduce the total number of programs you can run at once by 50% if you link everything with --rosegment.

Update 2:

Recent Linux distributions stopped merging .text and .rodata, and now have three or four separate LOAD segments. See this answer.

Body:
So out of curiosity, I tried to run this code today (compiled with gcc -m32 1.c):

int main(void)
{
    // EB is the opcode for jmp rel/8
    // FE is hex for -2
    // So this is essentially an infinite loop

    ((void(*)(void))"\xEB\xFE")();
}

... and it worked! No segfaults, the program (correctly?) goes into an infinite loop. Looking at the disassembly (objdump -d a.out), you can see the call to... whatever is at address 0x8048480:

080483d6 :
 ....
 80483e7:   b8 80 84 04 08          mov    $0x8048480,%eax
 80483ec:   ff d0                   call   *%eax
 ....

objdump -s -j .rodata a.out gives:

Contents of section .rodata:
 8048478 03000000 01000200 ebfe00             ...........
                           ~~~~

So it is indeed executing the string, which is stored in the .rodata section. So I ran readelf --sections a.out and got:

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1
  [ 2] .note.ABI-tag     NOTE            08048168 000168 000020 00   A  0   0  4
  [ 3] .note.gnu.build-i NOTE            08048188 000188 000024 00   A  0   0  4
  [ 4] .gnu.hash         GNU_HASH        080481ac 0001ac 000020 04   A  5   0  4
  [ 5] .dynsym           DYNSYM          080481cc 0001cc 000040 10   A  6   1  4
  [ 6] .dynstr           STRTAB          0804820c 00020c 000045 00   A  0   0  1
  [ 7] .gnu.version      VERSYM          08048252 000252 000008 02   A  5   0  2
  [ 8] .gnu.version_r    VERNEED         0804825c 00025c 000020 00   A  6   1  4
  [ 9] .rel.dyn          REL             0804827c 00027c 000008 08   A  5   0  4
  [10] .rel.plt          REL             08048284 000284 000008 08  AI  5  23  4
  [11] .init             PROGBITS        0804828c 00028c 000023 00  AX  0   0  4
  [12] .plt              PROGBITS        080482b0 0002b0 000020 04  AX  0   0 16
  [13] .plt.got          PROGBITS        080482d0 0002d0 000008 00  AX  0   0  8
  [14] .text             PROGBITS        080482e0 0002e0 000182 00  AX  0   0 16
  [15] .fini             PROGBITS        08048464 000464 000014 00  AX  0   0  4
  [16] .rodata           PROGBITS        08048478 000478 00000b 00   A  0   0  4
  [17] .eh_frame_hdr     PROGBITS        08048484 000484 000034 00   A  0   0  4
  [18] .eh_frame         PROGBITS        080484b8 0004b8 0000e0 00   A  0   0  4
  [19] .init_array       INIT_ARRAY      08049f0c 000f0c 000004 04  WA  0   0  4
  [20] .fini_array       FINI_ARRAY      08049f10 000f10 000004 04  WA  0   0  4
  [21] .dynamic          DYNAMIC         08049f14 000f14 0000e8 08  WA  6   0  4
  [22] .got              PROGBITS        08049ffc 000ffc 000004 04  WA  0   0  4
  [23] .got.plt          PROGBITS        0804a000 001000 000010 04  WA  0   0  4
  [24] .data             PROGBITS        0804a010 001010 000008 00  WA  0   0  4
  [25] .bss              NOBITS          0804a018 001018 000004 00  WA  0   0  1
  [26] .comment          PROGBITS        00000000 001018 00001a 01  MS  0   0  1
  [27] .symtab           SYMTAB          00000000 001034 0003f0 10     28  45  4
  [28] .strtab           STRTAB          00000000 001424 0001bd 00      0   0  1
  [29] .shstrtab         STRTAB          00000000 0015e1 000105 00      0   0  1

So in the ELF binary, the section is marked non-executable. But in memory, the page is executable (cat /proc/xxx/maps):

08048000-08049000 r-xp 00000000 08:01 663551 /home/andrew/Desktop/a.out
08049000-0804a000 r--p 00000000 08:01 663551 /home/andrew/Desktop/a.out
0804a000-0804b000 rw-p 00001000 08:01 663551 /home/andrew/Desktop/a.out

My original guess was that the sections too closely-spaced (there are both AX and A sections in the 08048000-08049000 range), so Linux is forced to give the page the union of the ELF permission bits (AX | A == AX). However, even after increasing the size of the .rodata section (by adding many long strings), all of the pages containing the .rodata section are still executable. Why is this?

(For the record, I'm running on Linux kernel 4.11.7, GCC 7.1.1, and compiling as 64-bit still exhibits this behavior)

ContentLicense: CC BY-SA 4.0


问:
Programatically switch stereo audio channels (left <> right) in headphones using C#

SCENARIO

For personal reasons I need to put my headphones in the opposite orientation, so what should be the left channel/headphone I put it in my right ear, and the right channel/headphone in the left ear.

When playing videogames this turns a big issue on games where the player must concentrate to find out where the sounds of the game come from (left or right audio channel) for example in a online shooter videogame, because... well, what comes from the left channel in-game I hear it on my right ear, and what comes from the right channel, on my left one. And here is where this question makes sense.

QUESTION

How can I programatically switch the (stereo)audio channels of the master sound device/headphones (or the channels of a target executable) in Windows using C# or VB.NET?.

I have no problem in order to depend of NAudio or VistaCoreAudioApi libraries.

答: The best way that I've found is to download and configure Equalizer APO as described in this post (should work for Windows 10 too): how-do-i-reverse-audio-channels-win-windows-7</p>


问:
How do I use a form to change the SQL query to only display registered dates between a specific range?
The code below is what I have so far, if anyone has any knowledge of how BETWEEN works and could point me in the right direction I would really appreciate it.</p>

```<code><form action="index.php" method="GET">
    Starting from:<br>
    <input type="date" name="startDate" ><br><br>
    Upto:<br>
    <input type="date" name="uptoDate" ><br><br>
    <input type="submit">
</form>

<?php
    // I removed the connection details for obvious reasons
    // It does connect and display the data with no problems
    $startingFrom = $_GET[startDate];
    $upto = $_GET[uptoDate];

    // I tried this but it does not seem to work
    // $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
    $query = "SELECT * FROM table";
    $result = mysql_query($query);

    echo "<table><th>Name</th><th>Registered Date</th>";

    while($row = mysql_fetch_array($result)){
        echo "<tr><td>" . $row['name'] . "</td><td>" . $row['registered'] . "</td></tr>";
    }
    echo "</table>";
    mysql_close();
?>
</code>```

答:
If you are returning results between two given dates use this code

```<code>SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03' AS DATE) AND CAST('2015-05-28' AS
DATE);
</code>```

With BETWEEN with dates you need to use CAST() to convert the value to appropriate datatype such as DATE or DATETIME. If you are using BETWEEN with DATETIME cast your value to DATETIME:

```<code>SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03 08:40:09' AS DATETIME) AND CAST('2015-05-28 02:50:09' AS DATETIME);
</code>```

As a side note, use MySQL improved extension (mysqli) and you are forgetting to close your input fields which is not a good code.

Body:
The code below is what I have so far, if anyone has any knowledge of how BETWEEN works and could point me in the right direction I would really appreciate it.

<form action="index.php" method="GET">
    Starting from:

    <input type="date" name="startDate" >

    Upto:

    <input type="date" name="uptoDate" >

    <input type="submit">
</form>

<?php
    // I removed the connection details for obvious reasons
    // It does connect and display the data with no problems
    $startingFrom = $_GET[startDate];
    $upto = $_GET[uptoDate];

    // I tried this but it does not seem to work
    // $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
    $query = "SELECT * FROM table";
    $result = mysql_query($query);

    echo "
Name	Registered Date	";

    while($row = mysql_fetch_array($result)){
        echo "
" . $row['name'] . "	" . $row['registered'] . "
";
    }
    echo "
";
    mysql_close();
?>

Body:
If you are returning results between two given dates use this code

SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03' AS DATE) AND CAST('2015-05-28' AS
DATE);

With BETWEEN with dates you need to use CAST() to convert the value to appropriate datatype such as DATE or DATETIME. If you are using BETWEEN with DATETIME cast your value to DATETIME:

SELECT *
FROM table
WHERE date BETWEEN CAST('2015-04-03 08:40:09' AS DATETIME) AND CAST('2015-05-28 02:50:09' AS DATETIME);

As a side note, use MySQL improved extension (mysqli) and you are forgetting to close your input fields which is not a good code.


问:
Scrapy CrawlSpider doesn't scrape with callback = 'parse_page'
I'm using Scrapy's CrawlSpider to scrape product info on     https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527.
This is what my rules look like:

```<code>   rules = (Rule(LinkExtractor(
            restrict_xpaths=('//*[@id="mainSearchContent"]/div[3]/div[2]/button[2]',)
        ),
                callback = 'parse_page',
                follow =True),)
</code>```

And this is the result. It doesn't scrape anything.

```<code>017-07-05 13:32:33 [scrapy] INFO: Enabled item pipelines: ImagesPipeline
2017-07-05 13:32:33 [scrapy] INFO: Spider opened
2017-07-05 13:32:33 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-07-05 13:32:33 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6026
2017-07-05 13:32:35 [scrapy] DEBUG: Crawled (200) <GET https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527> (referer: None)
2017-07-05 13:32:35 [scrapy] INFO: Closing spider (finished)
2017-07-05 13:32:35 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 322,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 157281,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 10, 32, 35, 320638),
 'log_count/DEBUG': 2,
 'log_count/INFO': 7,
 'log_count/WARNING': 6,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 10, 32, 33, 900621)}
</code>```

If I change callback to parse, it only scrapes the first page.
Can anyone tell me how to scrape all pages?

答: Your 'callback' should be a method name, not a string.</p>

Body:
I'm using Scrapy's CrawlSpider to scrape product info on     https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527.
This is what my rules look like:

   rules = (Rule(LinkExtractor(
            restrict_xpaths=('//*[@id="mainSearchContent"]/div[3]/div[2]/button[2]',)
        ),
                callback = 'parse_page',
                follow =True),)

And this is the result. It doesn't scrape anything.

017-07-05 13:32:33 [scrapy] INFO: Enabled item pipelines: ImagesPipeline
2017-07-05 13:32:33 [scrapy] INFO: Spider opened
2017-07-05 13:32:33 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-07-05 13:32:33 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6026
2017-07-05 13:32:35 [scrapy] DEBUG: Crawled (200) <GET https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527> (referer: None)
2017-07-05 13:32:35 [scrapy] INFO: Closing spider (finished)
2017-07-05 13:32:35 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 322,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 157281,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 10, 32, 35, 320638),
 'log_count/DEBUG': 2,
 'log_count/INFO': 7,
 'log_count/WARNING': 6,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 10, 32, 33, 900621)}

If I change callback to parse, it only scrapes the first page.
Can anyone tell me how to scrape all pages?


问:
Python string conversion to integer
I want to parse some data using Python and do further calculations. I have provided an example of the data i have parsed in the soup variable below. I want to convert the 5th value (after comma slicing) from a string into an integer for further processing, but am getting a message saying invalid literal for int() with base 10: '36.60'.  Could you help me find what I am doing wrong?

Script:

```<code>soup = '3-Jan-17,36.61,36.93,36.27,36.60,20196466'
soupy = soup.split('\n')

for line in soupy:
    z = line.split(',')
    yy = z[4]
    zz = int(yy)
</code>```

Message:

```<code>ValueError: invalid literal for int() with base 10: '36.60'
</code>```

答:
zz = int(yy) should be zz = float(yy)
if you want to convert that to an int do this:

int(float(yy))

This will truncate towards 0

Title: Python string conversion to integer

Body:
I want to parse some data using Python and do further calculations. I have provided an example of the data i have parsed in the soup variable below. I want to convert the 5th value (after comma slicing) from a string into an integer for further processing, but am getting a message saying invalid literal for int() with base 10: '36.60'.  Could you help me find what I am doing wrong?

Script:

soup = '3-Jan-17,36.61,36.93,36.27,36.60,20196466'
soupy = soup.split('\n')

for line in soupy:
    z = line.split(',')
    yy = z[4]
    zz = int(yy)

Message:

ValueError: invalid literal for int() with base 10: '36.60'


问:
REST - What is standard file format for RESTful API design?
I would like to have my design stored as file for version control.

Are there any standards or commonly used formats?

For example, I can write one file for structure definition:

```<code>User {
  uid,
  name
}
</code>```

And another file for API definition:

```<code>GET /users/:uid => User
GET /users?name=:name => [User]
</code>```

However, these are in my own preferences. Are there any commonly used formats for representing these?

I expect it to be something like UML, regardless of language, just focusing on API itself.

答:
The notation you mention is quite close to what developers would expect to get as a design or specification, so that might be enough.

However, if your project will get certain scale you can try to use some notation that might be then used by tools to automate either code generation, testing or documentation.

In particular, Swagger is a quite common tool to use for this. If you write your specification following these standards you'll get documentation and even some code generation if you use that tool.

https://swagger.io/specification/

Body:
I would like to have my design stored as file for version control.

Are there any standards or commonly used formats?

For example, I can write one file for structure definition:

User {
  uid,
  name
}

And another file for API definition:

GET /users/:uid => User
GET /users?name=:name => [User]

However, these are in my own preferences. Are there any commonly used formats for representing these?

I expect it to be something like UML, regardless of language, just focusing on API itself.


问:
Network Request failed when trying to fetch data from a localhost
My code works fine when I fetch data from "http://www3.septa.org/beta/TransitView/23"

But while I try to fetch data from "http://localhost:3000/allDetails" I get an error in react-native saying "Network Request Failed".

i can get the data from "http://localhost:3000/allDetails" using google chrome but not when i fetch it in my react-native code.

I also tried to fetch data using "http://127.0.0.1:3000/allDetails" still same error

答: I ran into this problem before. 127.0.0.1 will point to the emulator itself in your computer where the server is currently running. Try replacing 127.0.0.1 with 10.0.2.2 if you are on AVD or 10.0.3.2 if you are on Genymotion or with your computer's actual IP address.</p>


问:
Keen IO bulk add operation suddenly stops working
I’m starting to get this error message “One or more events was rejected during the bulk add operation” since July 3rd, every time I run my batch job to upload files from S3 to Keen using the .net SDK.

I'm not sure if this error is coming from Keen IO's server or somewhere else.

Do you have any idea why I’m getting this message?

Thanks in advance.

答:
I have figured the root cause of the issue. Hopefully this can help others too.

I have one analytics envelop (AnalyticsEnvelope) which contains 20 activities (S3ToKeen.Activity). There are three of these activity objects (S3ToKeen.Activity) which contain a really long gibberish text (9241 chars each).

Someone (it can also be a bot because of the structure of the text) entered this text in one of our textbox. Our JavaScript captured and stored it in our analytics file in S3. To prevent, please put a limit on how many characters the user can enter in your website's textboxes.

It was hard to figure this out at the beginning, because we are sending the data in bulk of 100 item (S3ToKeen.AnalyticsItem). So I had to configure the batch job slightly and send the item one-by-one.


问:
GemFire getRegion() returns null whereas OQL query gives result
I am using Pivotal GemFire 9.0.0 with 1 Locator and 1 Server. The Server has a Region called "submissions", like below -

```<code><gfe:replicated-region id="submissionsRegion" name="submissions"
statistics="true" template="replicateRegionTemplate">
...
</gfe:replicated-region>
</code>```

I am getting Region as null when executing the following code -

```<code>Region<K, V> region = clientCache.getRegion("submissions");
</code>```

Surprisingly, the same ClientCache returns all the records when I query using OQL and QueryService as shown below -

```<code>String queryString = "SELECT * FROM /submissions";
QueryService queryService = clientCache.getQueryService();
Query query = queryService.newQuery(queryString);
SelectResults results = (SelectResults) query.execute();
</code>```

I am initializing my ClientCache like this -

```<code>ClientCache clientCache = new ClientCacheFactory()
            .addPoolLocator("localhost", 10479)
            .set("name", "MyClientCache")
            .set("log-level", "error")
            .create();
</code>```

I am really baffled by this. Any pointer or help would be great.

答:
Yes, you need to "define" the corresponding client-side Region, matching the server-side REPLICATE Region by name (i.e. "submissions").  Actually this is a requirement independent of the server Regions' DataPolicy type (e.g. REPLICATE or PARTITION).

This is necessary since not every client wants to know about or even needs have data/events from every possible server Region.  Of course, this is also configurable through subscription and "Interests Registration" (with Client/Server Event Messaging, or alternatively, CQs).

Anyway, you can completely avoid the use of the GemFire API directly or even GemFire's native cache.xml (highly recommend avoiding) by using either SDG's XML namespace...

```<code><gfe:client-cache properties-ref="gemfireProperties" ... />

<gfe:client-region id="submissions" shortcut="PROXY"/>
</code>```

Or by using Spring JavaConfig with SDG's API...

```<code>@Configuration
class GemFireConfiguration {

  Properties gemfireProperties() {

    Properties gemfireProperties = new Properties();

    gemfireProperties.setProperty("log-level", "config");
    ...

    return gemfireProperties;
  }

  @Bean
  ClientCacheFactoryBean gemfireCache() {

    ClientCacheFactoryBean gemfireCache = new ClientCacheFactoryBean();

    gemfireCache.setClose(true);
    gemfireCache.setProperties(gemfireProperties());
    ...

    return gemfireCache;
  }

  @Bean(name = "submissions");
  ClientRegionFactoryBean submissionsRegion(GemFireCache gemfireCache) {

    ClientRegionFactoryBean submissions = new ClientRegionFactoryBean();

    submissions.setCache(gemfireCache);
    submissions.setClose(false);
    submissions.setShortcut(ClientRegionShortcut.PROXY);
    ...

    return submissions;
  }

  ...
}
</code>```

The "submissions" Region can be wrapped with SDG's GemfireTemplate, which will handle getting the "correct" QueryService on your behalf when running queries using the find(..) method.

Of course, you may be interested in making your client "submissions" Region a CACHING_PROXY" too.  Of course, you will then need to register "interests" in the keys or data of interests.  CQs are the best way to do this as it uses query criteria to define the data of "interests".

CACHING_PROXY is exactly as it sounds, caching data locally in the client based on the interests policies.  This also gives you the ability to use the "local" QueryService to query data locally, avoiding the network hop.

Anyway, many options here.

Cheers,
John

Body:
I am using Pivotal GemFire 9.0.0 with 1 Locator and 1 Server. The Server has a Region called "submissions", like below -

<gfe:replicated-region id="submissionsRegion" name="submissions"
statistics="true" template="replicateRegionTemplate">
...
</gfe:replicated-region>

I am getting Region as null when executing the following code -

Region<K, V> region = clientCache.getRegion("submissions");

Surprisingly, the same ClientCache returns all the records when I query using OQL and QueryService as shown below -

String queryString = "SELECT * FROM /submissions";
QueryService queryService = clientCache.getQueryService();
Query query = queryService.newQuery(queryString);
SelectResults results = (SelectResults) query.execute();

I am initializing my ClientCache like this -

ClientCache clientCache = new ClientCacheFactory()
            .addPoolLocator("localhost", 10479)
            .set("name", "MyClientCache")
            .set("log-level", "error")
            .create();

I am really baffled by this. Any pointer or help would be great.

Body:
Yes, you need to "define" the corresponding client-side Region, matching the server-side REPLICATE Region by name (i.e. "submissions").  Actually this is a requirement independent of the server Regions' DataPolicy type (e.g. REPLICATE or PARTITION).

This is necessary since not every client wants to know about or even needs have data/events from every possible server Region.  Of course, this is also configurable through subscription and "Interests Registration" (with Client/Server Event Messaging, or alternatively, CQs).

Anyway, you can completely avoid the use of the GemFire API directly or even GemFire's native cache.xml (highly recommend avoiding) by using either SDG's XML namespace...

<gfe:client-cache properties-ref="gemfireProperties" ... />

<gfe:client-region id="submissions" shortcut="PROXY"/>

Or by using Spring JavaConfig with SDG's API...

@Configuration
class GemFireConfiguration {

  Properties gemfireProperties() {

    Properties gemfireProperties = new Properties();

    gemfireProperties.setProperty("log-level", "config");
    ...

    return gemfireProperties;
  }

  @Bean
  ClientCacheFactoryBean gemfireCache() {

    ClientCacheFactoryBean gemfireCache = new ClientCacheFactoryBean();

    gemfireCache.setClose(true);
    gemfireCache.setProperties(gemfireProperties());
    ...

    return gemfireCache;
  }

  @Bean(name = "submissions");
  ClientRegionFactoryBean submissionsRegion(GemFireCache gemfireCache) {

    ClientRegionFactoryBean submissions = new ClientRegionFactoryBean();

    submissions.setCache(gemfireCache);
    submissions.setClose(false);
    submissions.setShortcut(ClientRegionShortcut.PROXY);
    ...

    return submissions;
  }

  ...
}

The "submissions" Region can be wrapped with SDG's GemfireTemplate, which will handle getting the "correct" QueryService on your behalf when running queries using the find(..) method.

Of course, you may be interested in making your client "submissions" Region a CACHING_PROXY" too.  Of course, you will then need to register "interests" in the keys or data of interests.  CQs are the best way to do this as it uses query criteria to define the data of "interests".

CACHING_PROXY is exactly as it sounds, caching data locally in the client based on the interests policies.  This also gives you the ability to use the "local" QueryService to query data locally, avoiding the network hop.

Anyway, many options here.

Cheers,
John


问:
else if & curly brackets
Why do these two code snippets have different outputs ?

The only difference between them is the curly brackets around each if/else-if statement, but that shouldn't matter here, right?

```<code>while (1){
    if (i>=n&&j<0)
        break;

    else if (j<0)
        if (Arr[i])
            c++;

    else if (i>=n)
        if(Arr[j])
            c++;

    else if (Arr[i]==1&&Arr[j]==1)
        c+=2;

    i++;
    j--;
}
</code>```

..

```<code>while (1){
    if (i>=n&&j<0){
        break;
    }
    else if (j<0){
        if (Arr[i])
            c++;
    }
    else if (i>=n){
        if(Arr[j])
            c++;
    }
    else if (Arr[i]==1&&Arr[j]==1){
        c+=2;
    }
    i++;
    j--;
}
</code>```

答:
If you format correctly the first code snippet

```<code>while (1){
    if (i>=n&&j<0)
        break;

    else if (j<0)
        if (Arr[i])
            c++;

        else if (i>=n)
            if(Arr[j])
                c++;
            else if (Arr[i]==1&&Arr[j]==1)
                c+=2;

    i++;
    j--;
}
</code>```

then it is seen that else or else if correspond to the closest if statement.

Title: else if & curly brackets

Body:
Why do these two code snippets have different outputs ?

The only difference between them is the curly brackets around each if/else-if statement, but that shouldn't matter here, right?

while (1){
    if (i>=n&&j<0)
        break;

    else if (j<0)
        if (Arr[i])
            c++;

    else if (i>=n)
        if(Arr[j])
            c++;

    else if (Arr[i]==1&&Arr[j]==1)
        c+=2;

    i++;
    j--;
}

..

while (1){
    if (i>=n&&j<0){
        break;
    }
    else if (j<0){
        if (Arr[i])
            c++;
    }
    else if (i>=n){
        if(Arr[j])
            c++;
    }
    else if (Arr[i]==1&&Arr[j]==1){
        c+=2;
    }
    i++;
    j--;
}

Body:
If you format correctly the first code snippet

while (1){
    if (i>=n&&j<0)
        break;

    else if (j<0)
        if (Arr[i])
            c++;

        else if (i>=n)
            if(Arr[j])
                c++;
            else if (Arr[i]==1&&Arr[j]==1)
                c+=2;

    i++;
    j--;
}

then it is seen that else or else if correspond to the closest if statement.


问:
UIView isHidden function, what does "the view's next valid key view" means?
I'm currently studying the isHidden method of UIView class.

In the Apple documentation, it mentioned

Hiding the view that is the window’s current first responder causes
  the view’s next valid key view to become the new first responder.

I was just wondering, what does the view's next valid key view means?

答: Causes that the next valid key (the next view of the stack) will be the responder, which if there is nothing "behind" that view that you are hiding will be the super view.</p>


答:
You are getting this error because the program doesn't recognize the . symbol in the string. An integer shouldn't have a decimal part, but your string "36.60" looks like having a decimal part.

You can use int(float(yy)) instead to get 36.

Title: Python string conversion to integer


问:
How to replace such substring in shell?
I want to replace substring in oldstring by new substring in linux shell:

old string may be one line of these:

```<code>-i eth0 -a abc -w a.pcap host 10.10.10.10
-i eth0 -a abc -w   a.pcap host 10.10.10.10
</code>```

substring is one of these:

```<code>-w a.pcap
-w  a.pcap
</code>```

new substring, '/home/test/test' is defined by 'PWD' in shell:

```<code>-w /home/test/test/a.pcap
</code>```

so the new string is:

```<code>-i eth0 -a abc -w /home/test/test/a.pcap host 10.10.10.10
</code>```

I don't know how to do this, as I have write a script like this, but this if 'a.pcap' change to 'e', the '-i eth' will be replace into '-i /home/test/test/eth'.

```<code>PWD=`pwd`
PARAM="$@"
OLD_W_PATH=
NEW_W_PATH=

process_w()
{
    if [ -z "$1" ]
    then
        echo "empty -w path param."
        exit -1
    else
        if [[ $1 == /*  ]]
        then
            # this is absolute path
            NEW_W_PATH=$1
        else
            NEW_W_PATH="${PWD}""/""$1"
        fi
    fi
}

while getopts "i:d:p:w:" arg; do
    case $arg in
        h | --help)
            echo "ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]"
            exit 0
            ;;
        w )
            OLD_W_PATH=$OPTARG
            #NEW_W_PATH is set in process_w
            process_w $OPTARG
            ;;
        ?)
            ;;
    esac
done

# process PARAM
PARAM=${PARAM/$OLD_W_PATH/$NEW_W_PATH}
echo $PARAM
</code>```

So will regular expresion in shell be better? Thank you~

答:
Don't try to transform your command into a string at all -- it starts out as an array; keep it as an array.

```<code>#!/bin/bash

# create an empty array called "args"
args=( )

canonicalize() {
  case $1 in
    /*) printf '%s\n' "${PWD}/$1"
    *)  printf '%s\n' "$1"
  esac
}

while (( $# )); do
  case $1 in
    # if $1 is -w, then we canonicalize the path and shift a second argument off
    -w) args+=( -w "$(canonicalize "$2")" ); shift;;

    # other arguments get copied as-is
    *)  args+=( "$1" ) ;;
  esac
  shift
done

# copy that updated array back to "$@"
set -- "${args[@]}"
</code>```

Title: How to replace such substring in shell?

Body:
I want to replace substring in oldstring by new substring in linux shell:

old string may be one line of these:

-i eth0 -a abc -w a.pcap host 10.10.10.10
-i eth0 -a abc -w   a.pcap host 10.10.10.10

substring is one of these:

-w a.pcap
-w  a.pcap

new substring, '/home/test/test' is defined by 'PWD' in shell:

-w /home/test/test/a.pcap

so the new string is:

-i eth0 -a abc -w /home/test/test/a.pcap host 10.10.10.10

I don't know how to do this, as I have write a script like this, but this if 'a.pcap' change to 'e', the '-i eth' will be replace into '-i /home/test/test/eth'.

PWD=`pwd`
PARAM="$@"
OLD_W_PATH=
NEW_W_PATH=

process_w()
{
    if [ -z "$1" ]
    then
        echo "empty -w path param."
        exit -1
    else
        if [[ $1 == /*  ]]
        then
            # this is absolute path
            NEW_W_PATH=$1
        else
            NEW_W_PATH="${PWD}""/""$1"
        fi
    fi
}

while getopts "i:d:p:w:" arg; do
    case $arg in
        h | --help)
            echo "ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]"
            exit 0
            ;;
        w )
            OLD_W_PATH=$OPTARG
            #NEW_W_PATH is set in process_w
            process_w $OPTARG
            ;;
        ?)
            ;;
    esac
done

# process PARAM
PARAM=${PARAM/$OLD_W_PATH/$NEW_W_PATH}
echo $PARAM

So will regular expresion in shell be better? Thank you~

Body:
Don't try to transform your command into a string at all -- it starts out as an array; keep it as an array.

#!/bin/bash

# create an empty array called "args"
args=( )

canonicalize() {
  case $1 in
    /*) printf '%s\n' "${PWD}/$1"
    *)  printf '%s\n' "$1"
  esac
}

while (( $# )); do
  case $1 in
    # if $1 is -w, then we canonicalize the path and shift a second argument off
    -w) args+=( -w "$(canonicalize "$2")" ); shift;;

    # other arguments get copied as-is
    *)  args+=( "$1" ) ;;
  esac
  shift
done

# copy that updated array back to "$@"
set -- "${args[@]}"


问:
prototype in typescript:Element implicitly has an 'any' type because type '_BaseOption' has no index signature
I want use prototype in typescript.

```<code>export class base{
    constructor() {
        base.prototype["g"] = new option({});
    }
}
</code>```

Line 3  shows this:[ts] Element implicitly has an 'any' type because type 'base' has no index signature.

Help!

答:
You can add the index signature to your base class:

```<code>export class base{
    [prop: string]: option
    constructor() {
        base.prototype["g"] = new option({});
    }
}
</code>```

But doing so means that any property you access via index signature on base instance will also be typed as option. Example:

```<code>let doesNotExist = new base()["doesNotExist"]; // Will compile fine without throwing error.
</code>```

If you are going to add only a limited set of properties to the prototype you can just add those properties alone:

```<code>export class base{
    g: option
    constructor() {
        base.prototype["g"] = new option({});
    }
}

let g = new base()["g"] // OK
let doesNotExist = new base()["doesNotExist"] // Error
</code>```

Body:
I want use prototype in typescript.

export class base{
    constructor() {
        base.prototype["g"] = new option({});
    }
}

Line 3  shows this:[ts] Element implicitly has an 'any' type because type 'base' has no index signature.

Help!

Body:
You can add the index signature to your base class:

export class base{
    [prop: string]: option
    constructor() {
        base.prototype["g"] = new option({});
    }
}

But doing so means that any property you access via index signature on base instance will also be typed as option. Example:

let doesNotExist = new base()["doesNotExist"]; // Will compile fine without throwing error.

If you are going to add only a limited set of properties to the prototype you can just add those properties alone:

export class base{
    g: option
    constructor() {
        base.prototype["g"] = new option({});
    }
}

let g = new base()["g"] // OK
let doesNotExist = new base()["doesNotExist"] // Error


问:
Realm write transaction failing, despite being in transaction
I have this code, which should append messages with a new message:

```<code>func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}
</code>```

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

答:
You need to create a Realm object before applying the write module.

According to the GitHub documentation, you can try code like this:

```<code>func addMessage(_ message: Message) {
    do {
        let realm = try! Realm()
        try! realm.write {
            self.messages.append(message)
        }
    } catch let error {
        print("Could not add message due to error:\n\(error)")
    }
}
</code>```

Hope it helps!

Body:
I have this code, which should append messages with a new message:

func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

Body:
You need to create a Realm object before applying the write module.

According to the GitHub documentation, you can try code like this:

func addMessage(_ message: Message) {
    do {
        let realm = try! Realm()
        try! realm.write {
            self.messages.append(message)
        }
    } catch let error {
        print("Could not add message due to error:\n\(error)")
    }
}

Hope it helps!


问:
animating a stem plot in matplotlib
I'm trying to animate a stem plot in matplotlib and I can't find the necessary documentation to help me.  I have a series of data files which each look like this:

```<code>1 0.345346
2 0.124325
3 0.534585
</code>```

and I want plot each file as a separate frame.

According to this and this other tutorial, I should create a function which updates the data contained in each plot object (artist? I'm not sure about the terminology)

From the second link, this is the update function

```<code>def update(frame):
global P, C, S

# Every ring is made more transparent
C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

# Each ring is made larger
S += (size_max - size_min) / n

# Reset ring specific ring (relative to frame number)
i = frame % 50
P[i] = np.random.uniform(0,1,2)
S[i] = size_min
C[i,3] = 1

# Update scatter object
scat.set_edgecolors(C)
scat.set_sizes(S)
scat.set_offsets(P)

# Return the modified object
return scat,
</code>```

How can I adapt this kind of update function for a stem plot? The documentation for stem is horribly brief (in fact this is a recurring issue as I'm learning matplotlib), but the example code shows that the output of stem is a tuple markerline, stemlines, baseline rather than an artist object like for plt.plot or plt.imshow.

So when I write my update function for the animation, how can I update the data inside the stem plot?

答:
Here you go!

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

import numpy as np

fig, ax = plt.subplots()
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = ax.stem(x, np.cos(x), '-.')

def update(i):
    ax.cla()
    markerline, stemlines, baseline = ax.stem(x, np.cos(x+i/10), '-.')
    ax.set_ylim((-1, 1))

anim = FuncAnimation(fig, update, frames=range(10, 110, 10), interval=500)
anim.save('so.gif', dpi=80, writer='imagemagick')
</code>```

I think there can be better ways of achieving this- not requiring to clear the plot each time. However, this works!

Title: animating a stem plot in matplotlib

Body:
I'm trying to animate a stem plot in matplotlib and I can't find the necessary documentation to help me.  I have a series of data files which each look like this:

1 0.345346
2 0.124325
3 0.534585

and I want plot each file as a separate frame.

According to this and this other tutorial, I should create a function which updates the data contained in each plot object (artist? I'm not sure about the terminology)

From the second link, this is the update function

def update(frame):
global P, C, S

# Every ring is made more transparent
C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

# Each ring is made larger
S += (size_max - size_min) / n

# Reset ring specific ring (relative to frame number)
i = frame % 50
P[i] = np.random.uniform(0,1,2)
S[i] = size_min
C[i,3] = 1

# Update scatter object
scat.set_edgecolors(C)
scat.set_sizes(S)
scat.set_offsets(P)

# Return the modified object
return scat,

How can I adapt this kind of update function for a stem plot? The documentation for stem is horribly brief (in fact this is a recurring issue as I'm learning matplotlib), but the example code shows that the output of stem is a tuple markerline, stemlines, baseline rather than an artist object like for plt.plot or plt.imshow.

So when I write my update function for the animation, how can I update the data inside the stem plot?

Body:
Here you go!

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

import numpy as np

fig, ax = plt.subplots()
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = ax.stem(x, np.cos(x), '-.')

def update(i):
    ax.cla()
    markerline, stemlines, baseline = ax.stem(x, np.cos(x+i/10), '-.')
    ax.set_ylim((-1, 1))

anim = FuncAnimation(fig, update, frames=range(10, 110, 10), interval=500)
anim.save('so.gif', dpi=80, writer='imagemagick')

I think there can be better ways of achieving this- not requiring to clear the plot each time. However, this works!


问:
How do I replace zeroes in multiple variable dataframes within a for loop?
So I have 1,000 dataframes to process using a FOR loop in R, say they are named DF1 to DF1000. I need to replace all 0 values within the data frames to 1's.  I try to write this as follows.

```<code>for (i in 1:1000){
eval(as.symbol(paste0("DF","i")))[eval(as.symbol(paste0("DF","i")))==0]<-1
}
</code>```

This brings up an error ("could not find eval<-").  How do I resolve this issue?  I tried using "assign" but get a different error ("target of assignment expands to non-language object").

Thanks in advance,
Alvo

答:
One way is to assign every character value DF to a new DF in the global environment, using base replace function.

```<code>for (i in 1:1000){
      assign(paste0("DF", i),
             replace(eval(parse(text = paste0("DF", i))), eval(parse(text = paste0("DF", i))) == 0, 1),
             envir = .GlobalEnv)
    }
</code>```

This is similar to replace(DF,DF == 0, 1) outside the for loop.

Body:
So I have 1,000 dataframes to process using a FOR loop in R, say they are named DF1 to DF1000. I need to replace all 0 values within the data frames to 1's.  I try to write this as follows.

for (i in 1:1000){
eval(as.symbol(paste0("DF","i")))[eval(as.symbol(paste0("DF","i")))==0]<-1
}

This brings up an error ("could not find eval<-").  How do I resolve this issue?  I tried using "assign" but get a different error ("target of assignment expands to non-language object").

Thanks in advance,
Alvo

Body:
One way is to assign every character value DF to a new DF in the global environment, using base replace function.

for (i in 1:1000){
      assign(paste0("DF", i),
             replace(eval(parse(text = paste0("DF", i))), eval(parse(text = paste0("DF", i))) == 0, 1),
             envir = .GlobalEnv)
    }

This is similar to replace(DF,DF == 0, 1) outside the for loop.


问:
How to save [x, y] in yaml file
In .yaml file. I know how to save x, y in

```<code>world:

   radius: 20
        x: -70
        y: -30
</code>```

My question is can I save it in the below format

```<code>world:

        radius: 20
        [-30, -70]
</code>```

Basically, I want to store two float number (x, y) in one line.

I program in c++

答:
When emitting a sequence, you can preface it with YAML::Flow. From the documentation:

```<code>YAML::Emitter out;
out << YAML::Flow;
out << YAML::BeginSeq << 2 << 3 << 5 << 7 << 11 << YAML::EndSeq;
</code>```

produces

```<code>[2, 3, 5, 7, 11]
</code>```

Title: How to save [x, y] in yaml file

Body:
In .yaml file. I know how to save x, y in

world:

   radius: 20
        x: -70
        y: -30

My question is can I save it in the below format

world:

        radius: 20
        [-30, -70]

Basically, I want to store two float number (x, y) in one line.

I program in c++

Body:
When emitting a sequence, you can preface it with YAML::Flow. From the documentation:

YAML::Emitter out;
out << YAML::Flow;
out << YAML::BeginSeq << 2 << 3 << 5 << 7 << 11 << YAML::EndSeq;

produces

[2, 3, 5, 7, 11]


问:
How to prevent react component click event bubble to document?

How to prevent react component click event from bubble up to document ?

I can sure that there must be something was wrong with it!

So, may be I should help myself fix it!

I just have a box component which has a click event listener, and there are some link components in that box which are effected by a document click event. How can I remove this document click event?

Can someone do me a favor?

More details info can be found in following links!

Here is the code link : https://github.com/ant-design/ant-design/issues/6576

Click has no effect, it should link to item3!

Remove document's click event

After that, it works!

What's wrong with this?

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import logo from './logo.svg';
import './App.css';

// import SideBox from './SideBox.js';

// import ContentBox from './ContentBox.js';

/*import SidebarExample from './test.js';*/

// import ReactDOMServer from 'react-dom/server';

import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom';

import Item1 from './components/Item1.js';
import Item2 from './components/Item2.js';
import Item3 from './components/Item3.js';

import {Menu, Icon} from 'antd';

import 'antd/dist/antd.css';

const SubMenu = Menu.SubMenu;

const element =
Hello, world
;

const elements = () => {
    return(

Hello, world

    );
};

const routes = [
    {
        path: '/',
        exact: true,
        sidebar: () =>
item1
,
        main: () =>
<Item1 />

    },
    {
        path: '/item2',
        sidebar: () =>
item2
,
        main: () =>
<Item2 />

    },
    {
        path: '/item3',
        sidebar: () =>
item3
,
        main: () =>
<Item3 />

    }
]

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            message: props.message,
            styles: props.styles,
            Any: props.any,
            width: props.width,
            theme: 'dark',
            current: '1'
        };
        this.handleMenuClick = this.handleMenuClick.bind(this);
        this.handleClick = this.handleClick.bind(this);
    };
    handleClick(e) {
        console.log('click ', e);
        this.setState({
            current: e.key,
        });
    };
    // ES7 property initializer syntax
    handleMenuClick = (e) => {
        e.preventDefault();
        // e.stopPropagation();
        // e.nativeEvent.stopImmediatePropagation();
        console.log('this is:', this);
        console.log("clicked === \n", e);
        if(this.state.styles === "App-SideBox-init"){
            this.setState({
                message: "e.key",
                styles: "App-SideBox-New",
                width: "width: 40px;"
            });
        }
        if(this.state.styles === "App-SideBox-New"){
            this.setState({
                message: "Hello!",
                styles: "App-SideBox-init",
                width: "width: 300px;"
            });
        }
        console.log("this.state.message === ", this.state.message);
        console.log("this.state.styles === ", this.state.styles);
    };
    componentDidMount() {
        /*window.addEventListener('scroll', this.onScroll.bind(this), false);*/
        // window.removeEventListener('click', this.handleMenuClick.bind(this), false);
        // window.removeEventListener('click', this.handleClick.bind(this), false);
    };
    render() {
        return (

Welcome to React

                        <Router>

                                                <Menu
                                                        theme={this.state.theme}
                                                        onClick={this.handleClick}
                                                        style={{ width: 240 }}
                                                        defaultOpenKeys={['sub1']}
                                                        selectedKeys={[this.state.current]}
                                                        mode="inline"
                                                    >
                                                    <SubMenu
                                                            key="sub1"
                                                            title={

                                                                    <Icon type="mail" />
                                                                    Navigation One

                                                            }
                                                        >
                                                        <Menu.Item key="1">
                                                            <Link to="/"> item1</Link>
                                                        </Menu.Item>
                                                        <Menu.Item key="2">
                                                            <Link to="/item2">item2</Link>
                                                        </Menu.Item>
                                                        <Menu.Item key="3">
                                                            <Link to="/item3">item3</Link>
                                                        </Menu.Item>
                                                    </SubMenu>
                                                </Menu>

                            </Router>

                    {/*onClick={this.handleMenuClick}*/}

                        icon

                    <Router>

                                    {
                                        routes.map((route, index) => (
                                            <Route
                                                key={index}
                                                path={route.path}
                                                exact={route.exact}
                                                component={route.main}
                                            />
                                        ))
                                    }

                    </Router>

        );
    }
};

App.defaultProps = {
    message: 'Hello!',
    styles: 'App-SideBox-init'
};

App.propTypes = {
    message: PropTypes.string.isRequired,
    styles: PropTypes.string.isRequired,
    width: PropTypes.string
};

export default App;```

答: Just make all event handlers on the parent component, and then pass them to children by using props!


问:
How do I write a unit test that verifies a subroutine is called?
```<code>Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class
</code>```

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?

答: Use an isolation framework such as Rhino Mocks or Moq</p>

ContentLicense: CC BY-SA 2.5

Body:
Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?


问:
Python - Kivy - Builtdozer : Having a button call the android keyboard
Framework: I am talking about an Android app written in Python 2.7 and packaged with Builtdozer

I have a Builder inside the app with a button

```<code>Builder.load_string('''
FloatLayout:
                    orientation: 'horizontal'
                    Button:
                        text: str(root.name)
                        font_size: '20sp'
                        pos_hint: {'x':.0, 'y':.3}
                        size_hint: .4, .8
''')
</code>```

I want to create a function, change_name, that,  if I press the above button, opens the android keyboard to accept an user raw_input

The raw_input provided by the user has to replace the text of the above button.

What I thought is:

1) Create a variable name = StringProperty('Me')

2) Create a function:

```<code>def change_name(self):
    self.name = raw_input()
</code>```

3) Call the function inside my button with a on_release

```<code>Builder.load_string('''
    FloatLayout:
                        orientation: 'horizontal'
                        Button:
                            text: str(root.name)
                            font_size: '20sp'
                            pos_hint: {'x':.0, 'y':.3}
                            size_hint: .4, .8
                            on_release: root.change_name()
    ''')
</code>```

It is correct? Because actually, running the app on Ubuntu, I am trying to click on the button but the app does not ask for an input (it seems blocked).

As a consequence I believe it will not work also on Android.

Could you please help me understanding where am I wrong?

答:
raw_input allows to get input from stdin (terminal). On Android you will not have the terminal available. In addition, raw_input is blocking, this causes the main event loop of your app to be freeze and will cause your app to stop responding.

You shouldn't use raw_input but Kivy's own methods.

On the other hand, you want to make your button editable (as if it were a TextInput). You can create your own custom Button class or use WindowBase.request_keyboard() to request the keyboard manually. However, you can do a little trick by hiding a TextInput and use it to enter the text:

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput

kv_text= ('''
<MyWidget>:
    FloatLayout:
        orientation: 'horizontal'
        Button:
            text: 'Hello'
            font_size: '20sp'
            pos_hint: {'x':.0, 'y':.3}
            size_hint: .4, .8
            on_release: root.change_name(self)

        Button:
            text: 'World'
            font_size: '20sp'
            pos_hint: {'x':0.6, 'y':.3}
            size_hint: .4, 0.8
            on_release: root.change_name(self)
''')

class MyWidget(FloatLayout):

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.hide_input = TextInput(size_hint=(None,  None),
                                    size = (0, 0),
                                    multiline = False)
        self.hide_input_bind = None

    def change_name(self,  instance):
        if self.hide_input_bind:
            self.hide_input.unbind_uid('text',  self.hide_input_bind)

        self.hide_input.text = instance.text
        self.hide_input.focus = True
        self.hide_input_bind = self.hide_input.fbind('text',  self._update_text,  instance)

    def _update_text(self, button,  instance,  value):
        button.text = value

class MyKivyApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyKivyApp()
    app.run()

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

App working on Android (Kivy Launcher):

Body:
Framework: I am talking about an Android app written in Python 2.7 and packaged with Builtdozer

I have a Builder inside the app with a button

Builder.load_string('''
FloatLayout:
                    orientation: 'horizontal'
                    Button:
                        text: str(root.name)
                        font_size: '20sp'
                        pos_hint: {'x':.0, 'y':.3}
                        size_hint: .4, .8
''')

I want to create a function, change_name, that,  if I press the above button, opens the android keyboard to accept an user raw_input

The raw_input provided by the user has to replace the text of the above button.

What I thought is:

1) Create a variable name = StringProperty('Me')

2) Create a function:

def change_name(self):
    self.name = raw_input()

3) Call the function inside my button with a on_release

Builder.load_string('''
    FloatLayout:
                        orientation: 'horizontal'
                        Button:
                            text: str(root.name)
                            font_size: '20sp'
                            pos_hint: {'x':.0, 'y':.3}
                            size_hint: .4, .8
                            on_release: root.change_name()
    ''')

It is correct? Because actually, running the app on Ubuntu, I am trying to click on the button but the app does not ask for an input (it seems blocked).

As a consequence I believe it will not work also on Android.

Could you please help me understanding where am I wrong?

Body:
raw_input allows to get input from stdin (terminal). On Android you will not have the terminal available. In addition, raw_input is blocking, this causes the main event loop of your app to be freeze and will cause your app to stop responding.

You shouldn't use raw_input but Kivy's own methods.

On the other hand, you want to make your button editable (as if it were a TextInput). You can create your own custom Button class or use WindowBase.request_keyboard() to request the keyboard manually. However, you can do a little trick by hiding a TextInput and use it to enter the text:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput

kv_text= ('''
<MyWidget>:
    FloatLayout:
        orientation: 'horizontal'
        Button:
            text: 'Hello'
            font_size: '20sp'
            pos_hint: {'x':.0, 'y':.3}
            size_hint: .4, .8
            on_release: root.change_name(self)

        Button:
            text: 'World'
            font_size: '20sp'
            pos_hint: {'x':0.6, 'y':.3}
            size_hint: .4, 0.8
            on_release: root.change_name(self)
''')

class MyWidget(FloatLayout):

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.hide_input = TextInput(size_hint=(None,  None),
                                    size = (0, 0),
                                    multiline = False)
        self.hide_input_bind = None

    def change_name(self,  instance):
        if self.hide_input_bind:
            self.hide_input.unbind_uid('text',  self.hide_input_bind)

        self.hide_input.text = instance.text
        self.hide_input.focus = True
        self.hide_input_bind = self.hide_input.fbind('text',  self._update_text,  instance)

    def _update_text(self, button,  instance,  value):
        button.text = value

class MyKivyApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyKivyApp()
    app.run()

if __name__ == '__main__':
    main()

App working on Android (Kivy Launcher):


问:
What is difference to extend abstract class and non abstract class?
What is difference between abstract class and non abstract class when extending derived classes? Both class I didn't use the method overriding and abstract methods (i.e. abstract class). Just I inherited the properties. What and why did prefer the class?

Ex:

Code 1:

```<code>abstract class a {
    protected int empnno;
    protected String empname;
}

class b extends a {
    ...
}
</code>```

Code 2:

```<code>class a {
    protected int empnno;
    protected String empname;
}

class b extends a {
    ...
}
</code>```

答:
To have a better understanding, we can compare Abstract Classes with Interfaces, the main differences are:

While abstract classes may contain fields/properties and concrete
methods, interfaces may contain only abstract methods (method
signatures).

One class can implement several interfaces, whereas it can extend just one class, abstract or not.

Therefore, when you create a subclass extended an abstract class, you need to implement the abstract method that was in the abstract class(if any), otherwise, the subclass would be still an abstract class -- which cannot be instantiated!!

Also, you can use interfaces instead of abstract classes if you only want to declare some methods signatures.

Body:
What is difference between abstract class and non abstract class when extending derived classes? Both class I didn't use the method overriding and abstract methods (i.e. abstract class). Just I inherited the properties. What and why did prefer the class?

Ex:

Code 1:

abstract class a {
    protected int empnno;
    protected String empname;
}

class b extends a {
    ...
}

Code 2:

class a {
    protected int empnno;
    protected String empname;
}

class b extends a {
    ...
}


问:
[ React.js ]Child component props not working
I'm learning React and was trying to write a program which shows the Unicode of the pressed key on screen.
No error popped up but the state( pressed key and Unicode) wasn't printed on the screen, either ( the state changed accordingly well). The props were set but it's not working.

Codepen

The code(Javascript):

```<code>const key = props=>{
return (<p className="key" onTransitionEnd={props.transitionHandle}>{props.key}</p>);
    }

const charCode = props=>{
  return (<p className="charCode">{props.charCode}</p>);
}

class App extends React.Component{
  constructor(props){
    super(props);

    this.state = {key: "A", charCode: "65"}
    this.keydownHandle = this.keydownHandle.bind(this);

  document.addEventListener("keydown",function(event){
      this.keydownHandle(event);
      }.bind(this));
  }
  render(state){
    return (
      <div className="box">
        <charCode charCode={this.state.charCode}></charCode>
        <key onTransitionEnd={this.transitionHandle} key={this.state.key}></key>
      </div>
    );
  }
    keydownHandle(event){
    this.setState({
      key: String.fromCharCode(event.keyCode),
      charCode: event.keyCode
      });

  }
      transitionHandle(){
  document.getElementsByClassName("key").classList.remove("pressed");

  }
}

ReactDOM.render(<App/>,document.querySelector(".container"));
</code>```

Thanks a lot.

答:
Couple of things

codepen

key is one of the special attributes that cannot be passed as props (source: https://facebook.github.io/react/docs/lists-and-keys.html)

User defined components must be capitalized - use Key and CharCode instead of key and charCode (source: https://facebook.github.io/react/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)

Body:
I'm learning React and was trying to write a program which shows the Unicode of the pressed key on screen.
No error popped up but the state( pressed key and Unicode) wasn't printed on the screen, either ( the state changed accordingly well). The props were set but it's not working.

Codepen

The code(Javascript):

const key = props=>{
return (
{props.key}
);
    }

const charCode = props=>{
  return (
{props.charCode}
);
}

class App extends React.Component{
  constructor(props){
    super(props);

    this.state = {key: "A", charCode: "65"}
    this.keydownHandle = this.keydownHandle.bind(this);

  document.addEventListener("keydown",function(event){
      this.keydownHandle(event);
      }.bind(this));
  }
  render(state){
    return (

        <charCode charCode={this.state.charCode}></charCode>
        <key onTransitionEnd={this.transitionHandle} key={this.state.key}></key>

    );
  }
    keydownHandle(event){
    this.setState({
      key: String.fromCharCode(event.keyCode),
      charCode: event.keyCode
      });

  }
      transitionHandle(){
  document.getElementsByClassName("key").classList.remove("pressed");

  }
}

ReactDOM.render(<App/>,document.querySelector(".container"));

Thanks a lot.


问:
How to create a new image format?
I have been playing around with some image processing tools in java and was wondering how to create my own image format (with its own file extension and header).

Say I am trying to store 2 jpeg images into a new file with extension .abcde

How would I approach this and modify the file header?
I did some research and found this, but it didnt have any sort of example.
https://gamedevelopment.tutsplus.com/tutorials/create-custom-binary-file-formats-for-your-games-data--gamedev-206

Any advice/references/examples would be great, thanks.

答:
Okay. Here you should ask yourself a question — what is binary file? It is some type of "box" that contains 8-bit values (0-255 range). And what actually images are? The same. But data in images is stored specifically. If you look at bitmaps (*.BMP files) for example, you'll see that it contains RGB values (it actually depends on the color depth, but we are talking about 24-bit colors now). So, what does it mean? It means that each pixel is stored with 3 bytes (24 bits) for Red Green and Blue values.
EG: 0x00 0x00 0x00 — This is black pixel in hex representation
0xFF 0xFF 0xFF — White.
But storing image data in such way is quite inefficient. For example, 1024x1024 image would be 1024*1024*3=3145728 bytes!!  Or 3 MEGABYTES. And that is not including alpha channel, which also stored with one byte.
 So, here the data compression comes in, it can be lossy or lossless. If you open for example a PNG file in the hex editor, you'll see a DEFLATE compressed data (LZ77+Huffman coding). It is lossless.
 GIF files are compressed with LZW, which is quite inefficient nowadays. There lots of really nice image formats such as FLIF or BPG, which compress images better than PNG and JPEG.
  So, if you want to create your own file format, you can create just a raw pixel container file (like BMP or PCX), or compressed pixel file (here you should write a custom data compression algorithm, C or C++ suits the best for this purpose).</p>

Title: How to create a new image format?