问:
Forcing unaligned bitfield packing in MSVC
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

```<code>struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};
</code>```

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

```<code>struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"
</code>```

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?

答:
I don't think so, and I think it's MSVC's behavior that is actually correct, and GCC that deviates from the standard.

AFAIK, the standard does not permit bitfields to cross word boundaries of the underlying type.

Body:
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?


来源: stackexchange

问:
How to show a frame of a video file (image) with tkinter in python
I am trying to show video frames (not from a stream) with tkinter. The next step are buttons which allow the user to get a frame backward or forward in the video. I have to say that I am quite new in programming with python.
So first I read the following articles:

Python snippets: Converting video to images http://srand.fr/blog/python%20import%20video.html

The Tkinter PhotoImage Class: http://effbot.org/tkinterbook/photoimage.htm

The problem is that I can’t use the image converted with imageio or VideoFileClip to show it with tkinter photoimage. I get the following error:

```<code>_tkinter.TclError: image "[[  …(some numbers)…   ]]" doesn't exist
</code>```

Here is my simple code. I hope you can help me :)

```<code>from moviepy.editor import VideoFileClip
from tkinter import *
import pylab

vid =VideoFileClip("example.mp4")

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_frame(count)
label =Label(window, image = photo)
label.pack()
</code>```

Other Code, same problem:

```<code>import imageio
from tkinter import *
import pylab

filename = './example.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_data(count)
label =Label(window, image = photo)
label.pack()
</code>```

答:
This is a bit late but better late than never.

Here is a working example I found and modify a little, this works with '.mp4', videos but not with '.flv', don't know why.

Note:

python 2.7 import Tkinter

python 3   import tkinter

```<code>import Tkinter as tk
import threading
import imageio
from PIL import Image, ImageTk

video_name = "test_video.mp4" #This is your video file path
video = imageio.get_reader(video_name)

def stream(label):

    frame = 0
    for image in video.iter_data():
        frame += 1                                    #counter to save new frame number
        image_frame = Image.fromarray(image)
        image_frame.save('FRAMES/frame_%d.png' % frame)      #if you need the frame you can save each frame to hd
        frame_image = ImageTk.PhotoImage(image_frame)
        label.config(image=frame_image)
        label.image = frame_image
        if frame == 40: break                         #after 40 frames stop, or remove this line for the entire video

if __name__ == "__main__":

    root = tk.Tk()
    my_label = tk.Label(root)
    my_label.pack()
    thread = threading.Thread(target=stream, args=(my_label,))
    thread.daemon = 1
    thread.start()
    root.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to show video frames (not from a stream) with tkinter. The next step are buttons which allow the user to get a frame backward or forward in the video. I have to say that I am quite new in programming with python.
So first I read the following articles:

Python snippets: Converting video to images http://srand.fr/blog/python%20import%20video.html

The Tkinter PhotoImage Class: http://effbot.org/tkinterbook/photoimage.htm

The problem is that I can’t use the image converted with imageio or VideoFileClip to show it with tkinter photoimage. I get the following error:

_tkinter.TclError: image "[[  …(some numbers)…   ]]" doesn't exist

Here is my simple code. I hope you can help me :)

from moviepy.editor import VideoFileClip
from tkinter import *
import pylab

vid =VideoFileClip("example.mp4")

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_frame(count)
label =Label(window, image = photo)
label.pack()

Other Code, same problem:

import imageio
from tkinter import *
import pylab

filename = './example.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')

window = Tk()
window.title("Choose Frame")
window.geometry ("900x600")

count =20

photo = vid.get_data(count)
label =Label(window, image = photo)
label.pack()

Body:
This is a bit late but better late than never.

Here is a working example I found and modify a little, this works with '.mp4', videos but not with '.flv', don't know why.

Note:

python 2.7 import Tkinter

python 3   import tkinter

import Tkinter as tk
import threading
import imageio
from PIL import Image, ImageTk

video_name = "test_video.mp4" #This is your video file path
video = imageio.get_reader(video_name)

def stream(label):

    frame = 0
    for image in video.iter_data():
        frame += 1                                    #counter to save new frame number
        image_frame = Image.fromarray(image)
        image_frame.save('FRAMES/frame_%d.png' % frame)      #if you need the frame you can save each frame to hd
        frame_image = ImageTk.PhotoImage(image_frame)
        label.config(image=frame_image)
        label.image = frame_image
        if frame == 40: break                         #after 40 frames stop, or remove this line for the entire video

if __name__ == "__main__":

    root = tk.Tk()
    my_label = tk.Label(root)
    my_label.pack()
    thread = threading.Thread(target=stream, args=(my_label,))
    thread.daemon = 1
    thread.start()
    root.mainloop()


问:
Tensorflow error when running first time
I ran a simple tensorflow script to see if it was working. After I ran my code, I got the following errors:

```<code> E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "CountExtremelyRandomStats" device_type: "CPU"') for unknown op: CountExtremelyRandomStats
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "FinishedNodes" device_type: "CPU"') for unknown op: FinishedNodes
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "GrowTree" device_type: "CPU"') for unknown op: GrowTree
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ReinterpretStringToFloat" device_type: "CPU"') for unknown op: ReinterpretStringToFloat
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "SampleInputs" device_type: "CPU"') for unknown op: SampleInputs
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ScatterAddNdim" device_type: "CPU"') for unknown op: ScatterAddNdim
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNInsert" device_type: "CPU"') for unknown op: TopNInsert
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNRemove" device_type: "CPU"') for unknown op: TopNRemove
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TreePredictions" device_type: "CPU"') for unknown op: TreePredictions
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "UpdateFertileSlots" device_type: "CPU"') for unknown op: UpdateFertileSlots
</code>```

I tried the solution posted here (TensorFlow version 1.0.0-rc2 on Windows: "OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits" with test code), but that link given did not work for me. Can anyone help me fix this? Thanks!

答:
This problem has been fixed in TensorFlow 1.1, which is now available as a release candidate. You can upgrade to that version using the command:</p>

```<code>C:\> pip install --upgrade tensorflow==1.1.0rc0
</code>```

Body:
I ran a simple tensorflow script to see if it was working. After I ran my code, I got the following errors:

 E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "CountExtremelyRandomStats" device_type: "CPU"') for unknown op: CountExtremelyRandomStats
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "FinishedNodes" device_type: "CPU"') for unknown op: FinishedNodes
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "GrowTree" device_type: "CPU"') for unknown op: GrowTree
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ReinterpretStringToFloat" device_type: "CPU"') for unknown op: ReinterpretStringToFloat
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "SampleInputs" device_type: "CPU"') for unknown op: SampleInputs
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ScatterAddNdim" device_type: "CPU"') for unknown op: ScatterAddNdim
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNInsert" device_type: "CPU"') for unknown op: TopNInsert
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNRemove" device_type: "CPU"') for unknown op: TopNRemove
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TreePredictions" device_type: "CPU"') for unknown op: TreePredictions
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "UpdateFertileSlots" device_type: "CPU"') for unknown op: UpdateFertileSlots

I tried the solution posted here (TensorFlow version 1.0.0-rc2 on Windows: "OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits" with test code), but that link given did not work for me. Can anyone help me fix this? Thanks!

Body:
This problem has been fixed in TensorFlow 1.1, which is now available as a release candidate. You can upgrade to that version using the command:

C:\> pip install --upgrade tensorflow==1.1.0rc0


问:
MSSQL/TSQL Joining against a subquery
I'm analyzing IIS log files from sharepoint and need to match each entry to it's SPWeb.

This SQL code works for a single value (@var1):

```<code>DECLARE @var1 varchar(128);
set @var1 = '/sites/Site1/Subsite1/Subsite2/Documents/marketing.docx';

select
    TOP 1 *,
    charindex(urlstub, @var1) as found
from
    spwebs
where
    charindex(urlstub, @var1)  = 1
order by
    urlstub DESC;
</code>```

I'm looking for a way to get this to work for a tables worth of data instead of just the single variable @var1.

Example data

```<code>SPwebs:
/sites/Site1
/sites/Site1/Subsite1
/sites/Site1/Subsite1/Subsite2
/sites/Site2
etc..

IISlog: (this is the table I'd like to take the place of @var1 above)
/sites/Site1/Subsite1/Subsite2/Documents/marketing.docx
/sites/Site1/Subsite1/Subsite2/Documents/sales.docx
/sites/Site1/Subsite1/Subsite2/Documents/hr.docx
/sites/Site1/research/funding.docx
</code>```

The expected outcome of the above would be:
Foreach record in the IISLog table:
Find the best/deepest matching record from the spwebs table:

```<code>|table                                                    | matchingSPweb                   |
|---------------------------------------------------------| --------------------------------|
| /sites/Site1/Subsite1/Subsite2/Documents/marketing.docx | /sites/Site1/Subsite1/Subsite2/ |
| /sites/Site1/Subsite1/Subsite2/Documents/sales.docx     | /sites/Site1/Subsite1/Subsite2/  |
| /sites/Site1/Subsite1/Subsite2/Documents/hr.docx        | /sites/Site1/Subsite1/Subsite2/  |
| /sites/Site1/research/funding.docx                      | /sites/Site1                     |
</code>```

I've tried

```<code>select iislogs2.*, spwebs.urlstub
from
iislogs2
inner join
(
  select TOP 1 urlstub, csURIStem as found
  from spwebs
   where charindex(urlstub, iislogs2.csUriStem)  = 1
  order by urlstub DESC
)   as x
on x.csuristem = iislogs2.csUriStem
</code>```

but this just errors, it doesn't seem to understand csUriStem in the context of the subselect statement.

答:
The easiest ways to fix your issue are either to change your current query to use a subquery in the select statement, e.g.:

```<code>SELECT iislogs2.*,
       urlstub = (SELECT TOP 1 urlstub FROM spwebs WHERE CHARINDEX(urlstub, iislogs2.csUriStem) = 1 ORDER BY urlstub DESC)
from iislogs2;
</code>```

... or change your current join to a cross apply, e.g.:

```<code>SELECT iislogs2.*, x.urlstub
from iislogs2
cross apply (SELECT TOP 1 urlstub FROM spwebs WHERE CHARINDEX(urlstub, iislogs2.csUriStem) = 1 ORDER BY urlstub DESC) AS x;
</code>```

EDIT:
The query optimiser might do all sorts of weird sorts and spools, so one option to avoid that might be to use an explicit join with a CTE and then left join this back to your original table. For example:

```<code>;WITH CTE AS
(
    SELECT i.csUriStem, s.urlstub, RN = ROW_NUMBER() OVER (PARTITION BY i.csUriStem ORDER BY s.urlstub DESC)
    FROM iislogs2 AS i
    JOIN spwebs AS s
        ON i.csUriStem LIKE s.urlstub + '%'
)
SELECT i.*, c.urlstub
FROM iislogs2 AS i
LEFT JOIN CTE AS c
    ON c.csUriStem = i.csUriStem
    AND c.RN = 1;
</code>```

Unfortunately, with strings and substrings, it's hard to get an execution plan that is really optimal for what you want to do, but I expect  this sort of query will perform better with indexes than the other two.

Title: MSSQL/TSQL Joining against a subquery

Body:
I'm analyzing IIS log files from sharepoint and need to match each entry to it's SPWeb.

This SQL code works for a single value (@var1):

DECLARE @var1 varchar(128);
set @var1 = '/sites/Site1/Subsite1/Subsite2/Documents/marketing.docx';

select
    TOP 1 *,
    charindex(urlstub, @var1) as found
from
    spwebs
where
    charindex(urlstub, @var1)  = 1
order by
    urlstub DESC;

I'm looking for a way to get this to work for a tables worth of data instead of just the single variable @var1.

Example data

SPwebs:
/sites/Site1
/sites/Site1/Subsite1
/sites/Site1/Subsite1/Subsite2
/sites/Site2
etc..

IISlog: (this is the table I'd like to take the place of @var1 above)
/sites/Site1/Subsite1/Subsite2/Documents/marketing.docx
/sites/Site1/Subsite1/Subsite2/Documents/sales.docx
/sites/Site1/Subsite1/Subsite2/Documents/hr.docx
/sites/Site1/research/funding.docx

The expected outcome of the above would be:
Foreach record in the IISLog table:
Find the best/deepest matching record from the spwebs table:

|table                                                    | matchingSPweb                   |
|---------------------------------------------------------| --------------------------------|
| /sites/Site1/Subsite1/Subsite2/Documents/marketing.docx | /sites/Site1/Subsite1/Subsite2/ |
| /sites/Site1/Subsite1/Subsite2/Documents/sales.docx     | /sites/Site1/Subsite1/Subsite2/  |
| /sites/Site1/Subsite1/Subsite2/Documents/hr.docx        | /sites/Site1/Subsite1/Subsite2/  |
| /sites/Site1/research/funding.docx                      | /sites/Site1                     |

I've tried

select iislogs2.*, spwebs.urlstub
from
iislogs2
inner join
(
  select TOP 1 urlstub, csURIStem as found
  from spwebs
   where charindex(urlstub, iislogs2.csUriStem)  = 1
  order by urlstub DESC
)   as x
on x.csuristem = iislogs2.csUriStem

but this just errors, it doesn't seem to understand csUriStem in the context of the subselect statement.

Body:
The easiest ways to fix your issue are either to change your current query to use a subquery in the select statement, e.g.:

SELECT iislogs2.*,
       urlstub = (SELECT TOP 1 urlstub FROM spwebs WHERE CHARINDEX(urlstub, iislogs2.csUriStem) = 1 ORDER BY urlstub DESC)
from iislogs2;

... or change your current join to a cross apply, e.g.:

SELECT iislogs2.*, x.urlstub
from iislogs2
cross apply (SELECT TOP 1 urlstub FROM spwebs WHERE CHARINDEX(urlstub, iislogs2.csUriStem) = 1 ORDER BY urlstub DESC) AS x;

EDIT:
The query optimiser might do all sorts of weird sorts and spools, so one option to avoid that might be to use an explicit join with a CTE and then left join this back to your original table. For example:

;WITH CTE AS
(
    SELECT i.csUriStem, s.urlstub, RN = ROW_NUMBER() OVER (PARTITION BY i.csUriStem ORDER BY s.urlstub DESC)
    FROM iislogs2 AS i
    JOIN spwebs AS s
        ON i.csUriStem LIKE s.urlstub + '%'
)
SELECT i.*, c.urlstub
FROM iislogs2 AS i
LEFT JOIN CTE AS c
    ON c.csUriStem = i.csUriStem
    AND c.RN = 1;

Unfortunately, with strings and substrings, it's hard to get an execution plan that is really optimal for what you want to do, but I expect  this sort of query will perform better with indexes than the other two.


问:
keyboard not disappear when used resignFirstResponder in iOS
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

```<code>  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`
</code>```

答:
First step for dismiss keyboard Give textfeild delegate in storyboard

Or Also give by code :

```<code>self.txtName.delegate = self;
</code>```

Dismiss keyboard when tap gesture method called:

```<code>- (void)dismmiss{
    [self.view endEditing:YES];
    [CFBlurHUD dismiss];
    self.password.enabled = YES;
}
</code>```

or Also Dismiss when touch anywhere in View:

```<code>-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
</code>```

Or when user press return button in keyboard:

```<code>-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
</code>```

Body:
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`

Body:
First step for dismiss keyboard Give textfeild delegate in storyboard

Or Also give by code :

self.txtName.delegate = self;

Dismiss keyboard when tap gesture method called:

- (void)dismmiss{
    [self.view endEditing:YES];
    [CFBlurHUD dismiss];
    self.password.enabled = YES;
}

or Also Dismiss when touch anywhere in View:

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

Or when user press return button in keyboard:

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


问:
Can I use printf() to convert hex to decimal and save the value?
I know that I can convert a hex number to a decimal value using printf(%u, num) where num is a hex value. Can I use this value to also assign the converted number to a variable?

答:
To convert from decimal to hex do...

```<code>string hexValue = decValue.ToString("X");
</code>```

To convert from hex to decimal do either...

```<code>int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
</code>```

or

```<code>int decValue = Convert.ToInt32(hexValue, 16);
</code>```

Body:
To convert from decimal to hex do...

string hexValue = decValue.ToString("X");

To convert from hex to decimal do either...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

or

int decValue = Convert.ToInt32(hexValue, 16);


问:
Resetting MySQL Root Password with XAMPP on Localhost
So for the past hour I've been trying to figure out how to reset my 'root' password for MySQL as I cannot log into PHPMyAdmin. I've tried changing the password in the config.inc.php file and searching through other methods. I cannot find a successful way. A few months ago I changed it as a test password but now I forget what it was. If anyone can help, that would be great. (I'm running on a Windows computer).</p>

答:
On Dashboard,
Go to User Accounts,
Select user,
Click Change Password,
Fill the New Password,
Go.</p>


问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答:
Try this for any nested JSON -

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9,
    "Address": {
          "Country": "US",
          "City": "LA"
  }
}
}];

function get_it(obj){
    for(var prop in obj){
        if(typeof obj[prop]=='object'){
            // object
            get_it(obj[prop]);
        }else{
            // something else
            console.log(obj[prop]+'.');
        }
    }
}

get_it(result);```

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.


问:
How to get filtered object length
I am trying to show that there is no data to display when the size of filtered object is zero. Is there any way to check its size after calling filter method?

```<code>this.state.items
.filter(item => {
    // filter code
})
.map(item => {
    // display data
})
</code>```

For example, this.state.items has ten items and becomes zero after passing through filter method. I'd like to display the message at this point.

答:
```<code>const filteredData = this.state.items((items) => //filter code);
return filteredData.count()
   ? filteredData.map(item => //data);
   : <div>No Data found </div>
</code>```

Try this one with immutable object.

Title: How to get filtered object length

Body:
I am trying to show that there is no data to display when the size of filtered object is zero. Is there any way to check its size after calling filter method?

this.state.items
.filter(item => {
    // filter code
})
.map(item => {
    // display data
})

For example, this.state.items has ten items and becomes zero after passing through filter method. I'd like to display the message at this point.

Body:
const filteredData = this.state.items((items) => //filter code);
return filteredData.count()
   ? filteredData.map(item => //data);
   : <div>No Data found </div>

Try this one with immutable object.


问:
Recursive Saving in Database
Overview:

I've been creating a dashboard framework that suited to my needs in every project that uses Slim 3. One of the features that I would like to implement is the workbench feature. That can create multiple workbench with widgets that the user can include. (Statistics, Single Data [Count], Table Data, etc..)

Database Table Structure:

user_workbench_id = Primary Key | Auto Increment

user_id = Foreign Key connected to sys_user (user table)

workbench_id = Unique workbench identifier in user's id. (Meaning 2 different users can have the same workbench_id but a single user can't have a same multiple workbench_id)

workbench_parent_id = Parent ID of workbench_id

layout_type = Workbench layout type. Parameters: blank / null, split-horizontal, split-vertical, grid

Front End View:

To generate a recursive data, there must be at least a couple of workbenches.

Having said all that, is to give you guys an overview how the data will be generated with user experience. I'm also concerned by the speed of data will be saved or deleted in some way.

Now to store the workbench in my database I'm calling a method to my Controller.

```<code>public function saveWorkBench($request, $response, $args, $workbench_parent_id = 0, $workbenches = []) {

    if ($workbench_parent_id == 0 && empty($workbenches)) {
        $this->auth->user()->userWorkbench()->delete();
        $workbenches = $request->getParam('workbenches');
    }

    foreach ($workbenches as $workbench) {

        $this->auth->user()->userWorkbench()->create([
            'workbench_id'        => $workbench['workbench_id'],
            'workbench_parent_id' => $workbench_parent_id,
            'layout_type'         => $workbench['layout_type']
        ]);

        if (!empty($workbench['workbenches'])) {
            $this->saveWorkBench($request, $response, $args, $workbench['workbench_id'], $workbench['workbenches']);
        }
    }
}
</code>```

What I'm doing here is whenever I save the workbench. I'm deleting all user workbench (truncate it per user who save / deleted workbench). Then loop all over again using recursive method to get the same data that the user generated.

The question is, is this acceptable? I feel that truncating and looping all over again is not good but I've seen this method a couple of times that's being used in a lot of data.

If this is not acceptable, any solution / advice for me to do this the good way? I've been thinking that I'll just update / deleted the specific workbench, but I have no idea how to do it.

答:
First, calling a controller action recursively doesn't seem an elegant solution. Move your "save workbench tree" logic in separate model.

Second, performance wise, it's better to update changes rather than deleting and re-creating the tree completely. But it's really up to you, and it mainly depends whether the amount of data is large and frequency of this operation is high. If it's not, just leave it as it its. "Premature optimization is the root of all evil (c) Donald Knuth".
And one more thing, make sure you perform all DB queries within a single transaction.

Title: Recursive Saving in Database

Body:
Overview:

I've been creating a dashboard framework that suited to my needs in every project that uses Slim 3. One of the features that I would like to implement is the workbench feature. That can create multiple workbench with widgets that the user can include. (Statistics, Single Data [Count], Table Data, etc..)

Database Table Structure:

user_workbench_id = Primary Key | Auto Increment

user_id = Foreign Key connected to sys_user (user table)

workbench_id = Unique workbench identifier in user's id. (Meaning 2 different users can have the same workbench_id but a single user can't have a same multiple workbench_id)

workbench_parent_id = Parent ID of workbench_id

layout_type = Workbench layout type. Parameters: blank / null, split-horizontal, split-vertical, grid

Front End View:

To generate a recursive data, there must be at least a couple of workbenches.

Having said all that, is to give you guys an overview how the data will be generated with user experience. I'm also concerned by the speed of data will be saved or deleted in some way.

Now to store the workbench in my database I'm calling a method to my Controller.

public function saveWorkBench($request, $response, $args, $workbench_parent_id = 0, $workbenches = []) {

    if ($workbench_parent_id == 0 && empty($workbenches)) {
        $this->auth->user()->userWorkbench()->delete();
        $workbenches = $request->getParam('workbenches');
    }

    foreach ($workbenches as $workbench) {

        $this->auth->user()->userWorkbench()->create([
            'workbench_id'        => $workbench['workbench_id'],
            'workbench_parent_id' => $workbench_parent_id,
            'layout_type'         => $workbench['layout_type']
        ]);

        if (!empty($workbench['workbenches'])) {
            $this->saveWorkBench($request, $response, $args, $workbench['workbench_id'], $workbench['workbenches']);
        }
    }
}

What I'm doing here is whenever I save the workbench. I'm deleting all user workbench (truncate it per user who save / deleted workbench). Then loop all over again using recursive method to get the same data that the user generated.

The question is, is this acceptable? I feel that truncating and looping all over again is not good but I've seen this method a couple of times that's being used in a lot of data.

If this is not acceptable, any solution / advice for me to do this the good way? I've been thinking that I'll just update / deleted the specific workbench, but I have no idea how to do it.


问:
To have the records of all the data without writing the segments again and again in the code while adding in the database
In a table I am having 292 records, for these 292 records I wrote 63 segments of parallel asynchronous in DynamoDB. If the records increases again I am writing segments in the code. Without writing the code like that to have added records to display, what is the solution. Please help me.</p>

答: You can enable a DynamoDB Stream on your table, and connect a lambda function that is triggered by the stream to display newly added records.</p>


问:
How to convert all non numeric cells in data frame to NA
I am trying to convert all cells with non-numeric values to missing data (NA). I tried something similar along the lines of converting specific values to missing data, like:

```<code>recode_missing <- function (g, misval)
{
  a <- g == misval
  temp = g
  temp [a] <- NA
  return (temp)
}
</code>```

That works great: an elegant R solution.

I tried to decode like a <- g == is.numeric () (syntactically wrong), a <- is.numeric (g): (Error: (list) object cannot be coerced to type 'double'), or evena [,] <- is.numeric (g[,]` (same). I an aware of the solution of removing columns

```<code>remove_nn <- function (data)
{
  # removes all non-numeric columns
  numeric_columns <- sapply (data, is.numeric)
  return (data [, numeric_columns])
} ### remove_nn ###
</code>```

But that removes the columns and converts the data frame to some matrix.

Could someone please advise on how to convert single non-numeric cells to NA while leaving the data structure intact?

Edit

As the comments point out correctly there is no such thing as an individual string value in an ocean of numeric values. Just vectors which are numeric or something else. What I now wanted to know what caused the non-numeric error in medians <- apply (data, 2, median). I have many vectors and inspection by eye proved useless. I issued num <- sapply (data, is.numeric) and next data [,!num]. That gave me the columns that were non-numeric. In one case that was caused by one cell value containing a superfluous ". The file is preprocessed by a spreadsheet and if just one cell is non-numeric, the complete vector is seen as non-numeric.

答:
Based on your edit, you have vectors which should be numeric, but due to some erroneous data introduced during the reading-in process, the data have been converted to another format (likely character or factor).

Here is an example of that case. mydf1 <- mydf2 <- mydf3 <-
 data.frame(...) just creates three data.frames with the same data.

```<code># I'm going to show three approaches
mydf1 <- mydf2 <- mydf3 <- data.frame(
  A = c(1, 2, "x", 4),
  B = c("y", 3, 4, "-")
)

str(mydf1)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: Factor w/ 4 levels "1","2","4","x": 1 2 4 3
#  $ B: Factor w/ 4 levels "-","3","4","y": 4 2 3 1
</code>```

One way to do this is to just let R coerce any values that cannot be converted to numeric to NA:

```<code>## You WILL get warnings
mydf1[] <- lapply(mydf1, function(x) as.numeric(as.character(x)))
# Warning messages:
# 1: In FUN(X[[i]], ...) : NAs introduced by coercion
# 2: In FUN(X[[i]], ...) : NAs introduced by coercion

str(mydf1)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: num  1 2 NA 4
#  $ B: num  NA 3 4 NA
</code>```

Another option is to use makemeNA from my SOfun package:

```<code>library(SOfun)
makemeNA(mydf2, "[^0-9]", FALSE)
#    A  B
# 1  1 NA
# 2  2  3
# 3 NA  4
# 4  4 NA

str(.Last.value)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: int  1 2 NA 4
#  $ B: int  NA 3 4 NA
</code>```

This function is a bit different in that it uses type.convert to do the conversion, and can handle more specific rules for conversion to NA (just like you can use a vector for na.strings when reading data into R).

About your error, I believe you would have tried as.numeric on your data.frame to get the error you had shown.

Example:

```<code># Your error...
as.numeric(mydf3)
# Error: (list) object cannot be coerced to type 'double'
</code>```

You won't get that error on a matrix though (but you'll still get the warning)....

```<code># You'll get a warning
as.numeric(as.matrix(mydf3))
# [1]  1  2 NA  4 NA  3  4 NA
# Warning message:
# NAs introduced by coercion
</code>```

Why don't we need to explicitly use as.character? as.matrix does that for you:

```<code>str(as.matrix(mydf3))
#  chr [1:4, 1:2] "1" "2" "x" "4" "y" "3" "4" "-"
#  - attr(*, "dimnames")=List of 2
#   ..$ : NULL
#   ..$ : chr [1:2] "A" "B"
</code>```

How can you use that information?

```<code>mydf3[] <- as.numeric(as.matrix(mydf3))
# Warning message:
# NAs introduced by coercion

str(mydf3)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: num  1 2 NA 4
#  $ B: num  NA 3 4 NA
</code>```

Body:
I am trying to convert all cells with non-numeric values to missing data (NA). I tried something similar along the lines of converting specific values to missing data, like:

recode_missing <- function (g, misval)
{
  a <- g == misval
  temp = g
  temp [a] <- NA
  return (temp)
}

That works great: an elegant R solution.

I tried to decode like a <- g == is.numeric () (syntactically wrong), a <- is.numeric (g): (Error: (list) object cannot be coerced to type 'double'), or evena [,] <- is.numeric (g[,]` (same). I an aware of the solution of removing columns

remove_nn <- function (data)
{
  # removes all non-numeric columns
  numeric_columns <- sapply (data, is.numeric)
  return (data [, numeric_columns])
} ### remove_nn ###

But that removes the columns and converts the data frame to some matrix.

Could someone please advise on how to convert single non-numeric cells to NA while leaving the data structure intact?

Edit

As the comments point out correctly there is no such thing as an individual string value in an ocean of numeric values. Just vectors which are numeric or something else. What I now wanted to know what caused the non-numeric error in medians <- apply (data, 2, median). I have many vectors and inspection by eye proved useless. I issued num <- sapply (data, is.numeric) and next data [,!num]. That gave me the columns that were non-numeric. In one case that was caused by one cell value containing a superfluous ". The file is preprocessed by a spreadsheet and if just one cell is non-numeric, the complete vector is seen as non-numeric.

Body:
Based on your edit, you have vectors which should be numeric, but due to some erroneous data introduced during the reading-in process, the data have been converted to another format (likely character or factor).

Here is an example of that case. mydf1 <- mydf2 <- mydf3 <-
 data.frame(...) just creates three data.frames with the same data.

# I'm going to show three approaches
mydf1 <- mydf2 <- mydf3 <- data.frame(
  A = c(1, 2, "x", 4),
  B = c("y", 3, 4, "-")
)

str(mydf1)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: Factor w/ 4 levels "1","2","4","x": 1 2 4 3
#  $ B: Factor w/ 4 levels "-","3","4","y": 4 2 3 1

One way to do this is to just let R coerce any values that cannot be converted to numeric to NA:

## You WILL get warnings
mydf1[] <- lapply(mydf1, function(x) as.numeric(as.character(x)))
# Warning messages:
# 1: In FUN(X[[i]], ...) : NAs introduced by coercion
# 2: In FUN(X[[i]], ...) : NAs introduced by coercion

str(mydf1)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: num  1 2 NA 4
#  $ B: num  NA 3 4 NA

Another option is to use makemeNA from my SOfun package:

library(SOfun)
makemeNA(mydf2, "[^0-9]", FALSE)
#    A  B
# 1  1 NA
# 2  2  3
# 3 NA  4
# 4  4 NA

str(.Last.value)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: int  1 2 NA 4
#  $ B: int  NA 3 4 NA

This function is a bit different in that it uses type.convert to do the conversion, and can handle more specific rules for conversion to NA (just like you can use a vector for na.strings when reading data into R).

About your error, I believe you would have tried as.numeric on your data.frame to get the error you had shown.

Example:

# Your error...
as.numeric(mydf3)
# Error: (list) object cannot be coerced to type 'double'

You won't get that error on a matrix though (but you'll still get the warning)....

# You'll get a warning
as.numeric(as.matrix(mydf3))
# [1]  1  2 NA  4 NA  3  4 NA
# Warning message:
# NAs introduced by coercion

Why don't we need to explicitly use as.character? as.matrix does that for you:

str(as.matrix(mydf3))
#  chr [1:4, 1:2] "1" "2" "x" "4" "y" "3" "4" "-"
#  - attr(*, "dimnames")=List of 2
#   ..$ : NULL
#   ..$ : chr [1:2] "A" "B"

How can you use that information?

mydf3[] <- as.numeric(as.matrix(mydf3))
# Warning message:
# NAs introduced by coercion

str(mydf3)
# 'data.frame': 4 obs. of  2 variables:
#  $ A: num  1 2 NA 4
#  $ B: num  NA 3 4 NA


问:
How find minimum in a array recursive method works?
```<code>public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex){
        return numbers[startIndex];
    }
    else {
        int midIndex = (startIndex + endIndex) / 2;
        int leftMin = findMin(numbers, startIndex, midIndex);
        int rightMin = findMin(numbers, midIndex + 1, endIndex);
        if (leftMin < rightMin)
            return leftMin;
        else
            return rightMin;
    }
}
</code>```

I really have trouble understanding this find min recursion. This recursive method finds the minimum number in an array.

This is how I understand it.

Suppose I have a array 5, 3 , -5, 8, and startIndex is 0, endIndex is 3

First time, midIndex = (0+3)/2 =1. So it divided between 3 and -5.

And then it goes to findMin, so it passes Array, 0, 1 back to findMin.

Then, the midIndex = (0+1)/2 = 0. And passes Array, 0, 0 back to findMin.

Since startIndex 0 = endIndex 0, return numbers[startIndex](which is 5?).

I can't really figure out how this method finds the minimum number. Since the startIndex is alway 0, why does it need to return numbers[startIndex]?

答:
This is the general idea that the code is implementing:

To find the minimum element of an array, we can find the minimum of each half of the array and then take the minimum of those two numbers.

How do we find the minimum of each half? We simply use the same technique of breaking that up into quarters.

Eventually we'll be asking ourselves what the min element of a single element is, which is of course that element.

The algorithm shown in the image implements this recipe.

Body:
public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex){
        return numbers[startIndex];
    }
    else {
        int midIndex = (startIndex + endIndex) / 2;
        int leftMin = findMin(numbers, startIndex, midIndex);
        int rightMin = findMin(numbers, midIndex + 1, endIndex);
        if (leftMin < rightMin)
            return leftMin;
        else
            return rightMin;
    }
}

I really have trouble understanding this find min recursion. This recursive method finds the minimum number in an array.

This is how I understand it.

Suppose I have a array 5, 3 , -5, 8, and startIndex is 0, endIndex is 3

First time, midIndex = (0+3)/2 =1. So it divided between 3 and -5.

And then it goes to findMin, so it passes Array, 0, 1 back to findMin.

Then, the midIndex = (0+1)/2 = 0. And passes Array, 0, 0 back to findMin.

Since startIndex 0 = endIndex 0, return numbers[startIndex](which is 5?).

I can't really figure out how this method finds the minimum number. Since the startIndex is alway 0, why does it need to return numbers[startIndex]?


问:
Multiple lines not reading into one list item
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

```<code>private void button2_Click_1(object sender, EventArgs e)
    {

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }
</code>```

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

答:
This code works fine for me, but I think it's basically what you're doing, only slightly cleaned up (and I didn't use the second file since you're not using it in the example).

My suggestion would be to create a single method that does this operation, and then call that method from wherever you need it. This way you will ensure that you're doing the exact same thing in both (all) places.

UPDATE

I updated the method to save the clipboard text as-is, plus adding a ¢ character to the end, when saving to the file. Then, when reading the file the second time, first join all the lines with a space character, then split on the ¢ character, and use that list for your data source.

```<code>private const string DefaultSaveFile = @"C:\temp\testfile.txt";

private void CopyUniqueClipboardTextToFile(string filePath = null,
    bool updateListbox = true)
{
    // Use global default file if nothing was passed
    if (filePath == null) filePath = DefaultSaveFile;

    // Ensure our files exist
    if (!File.Exists(filePath)) File.CreateText(filePath).Close();

    string fileContents = File.ReadAllText(filePath);
    string clipboardText = Clipboard.GetText();

    // Update the file with any new clipboard text
    if (Clipboard.ContainsText() && !fileContents.Contains(clipboardText))
    {
        // Save the lines to our file, with a '¢' character at the end
        File.AppendAllText(filePath, $"{Environment.NewLine}{clipboardText}¢");
    }

    // Re-read the new file into a single string
    string entireFileAsOneLine = string.Join(" ",
        File.ReadAllLines(filePath).Distinct().ToList());

    // Now split that string on the '¢' character
    string[] listItems = entireFileAsOneLine.Split('¢');

    // Update listbox if necessary
    if (updateListbox)
    {
        listBox1.BeginUpdate();
        listBox1.DataSource = listItems;
        listBox1.EndUpdate();
    }
}

private void button2_Click(object sender, EventArgs e)
{
    CopyUniqueClipboardTextToFile();
}
</code>```

Body:
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

private void button2_Click_1(object sender, EventArgs e)
    {

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

Body:
This code works fine for me, but I think it's basically what you're doing, only slightly cleaned up (and I didn't use the second file since you're not using it in the example).

My suggestion would be to create a single method that does this operation, and then call that method from wherever you need it. This way you will ensure that you're doing the exact same thing in both (all) places.

UPDATE

I updated the method to save the clipboard text as-is, plus adding a ¢ character to the end, when saving to the file. Then, when reading the file the second time, first join all the lines with a space character, then split on the ¢ character, and use that list for your data source.

private const string DefaultSaveFile = @"C:\temp\testfile.txt";

private void CopyUniqueClipboardTextToFile(string filePath = null,
    bool updateListbox = true)
{
    // Use global default file if nothing was passed
    if (filePath == null) filePath = DefaultSaveFile;

    // Ensure our files exist
    if (!File.Exists(filePath)) File.CreateText(filePath).Close();

    string fileContents = File.ReadAllText(filePath);
    string clipboardText = Clipboard.GetText();

    // Update the file with any new clipboard text
    if (Clipboard.ContainsText() && !fileContents.Contains(clipboardText))
    {
        // Save the lines to our file, with a '¢' character at the end
        File.AppendAllText(filePath, $"{Environment.NewLine}{clipboardText}¢");
    }

    // Re-read the new file into a single string
    string entireFileAsOneLine = string.Join(" ",
        File.ReadAllLines(filePath).Distinct().ToList());

    // Now split that string on the '¢' character
    string[] listItems = entireFileAsOneLine.Split('¢');

    // Update listbox if necessary
    if (updateListbox)
    {
        listBox1.BeginUpdate();
        listBox1.DataSource = listItems;
        listBox1.EndUpdate();
    }
}

private void button2_Click(object sender, EventArgs e)
{
    CopyUniqueClipboardTextToFile();
}


问:
JMeter JSON Path Extractor expression issue while searching arrays
My HTTP request returns an array similar to

```<code>[
{"id":"1", "data":"abc"},
{"id":"2", "data":"def"},
{"id":"3", "data":"ghi"}
]
</code>```

As an input for a ForEach Controller I'm trying to extract the ids of above result into an array using a JSON Path Extractor with a Path expression of $..id.
I'm expecting to get something similar to ["1", "2","3"] but the output I get is

```<code>ids=3
ids_matchNr=3
</code>```

It appears that the JSON Path Extractor only matches/extracts the last occurrence of id instead of collecting all occurrences of the id values and adding them to an aray.

The same expression and data return the expected ["1", "2","3"] result array in jsonpath.curiousconcept.com so the expression seems to be correct.

Am I doing something wrong or is this a bug in the JSON Path Extractor?

Below are some screen prints for a little test

答:
I cannot reproduce your issue:

JSON Extractor

JSON Path Extractor

So double check you are using the latest version of JMeter and JSON Path Extractor, the latter one can be upgraded using JMeter Plugins Manager

Body:
My HTTP request returns an array similar to

[
{"id":"1", "data":"abc"},
{"id":"2", "data":"def"},
{"id":"3", "data":"ghi"}
]

As an input for a ForEach Controller I'm trying to extract the ids of above result into an array using a JSON Path Extractor with a Path expression of $..id.
I'm expecting to get something similar to ["1", "2","3"] but the output I get is

ids=3
ids_matchNr=3

It appears that the JSON Path Extractor only matches/extracts the last occurrence of id instead of collecting all occurrences of the id values and adding them to an aray.

The same expression and data return the expected ["1", "2","3"] result array in jsonpath.curiousconcept.com so the expression seems to be correct.

Am I doing something wrong or is this a bug in the JSON Path Extractor?

Below are some screen prints for a little test


问:
Is there a more concise way to combine many comparisons in Ruby?
I currently have this if statement:

```<code>if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0
</code>```

Is there a more concise way to do this?

ContentLicense: CC BY-SA 2.5

Body:
I currently have this if statement:

if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0

Is there a more concise way to do this?

Body: [:day,:hour,:minute,:second].map{|s|Time.now.send s}==[1,0,0,0]


问:
Ajax query for JSON data not returning data
I'm trying to use World Bank's API to obtain some data. This is how to query their database. Basically to query a country's information, I would need to go to this url:

```<code>http://api.worldbank.org/countries/"alpha2Code of the country"
</code>```

In my code here (Link to CodePen code.) I use use the alpha2Code from a previous query to add to the World Bank query's URL. Here's the method:

```<code>getDetails(alpha2Code) {
  this.load('http://api.worldbank.org/countries/'+alpha2Code)
    .then((countryDetails) => {
      this.generateOverlay(countryDetails);
    });
},
</code>```

the load() method is defined here:

```<code>load(url, type = 'json') {
  return $.ajax({
    dataType: type,
    url: url,
  });
},
</code>```

According to World Bank's basic calling format, I would need to add

```<code>format=json
</code>```

in order to receive response in JSON. Somehow I don't think it's actually obtaining anything from WorldBank.

The query to World Bank is suppose to give me details to put into the overlay that covers the country flags after a click.

Thank you in advance for the help!

答:
One issue with the CodePen you shared that may or may not be the problem with your site is that the CodePen demo is loaded over HTTPS, but you're requesting an insecure resource (HTTP). Browsers don't like this and will usually block it.

Unfortunately, you can't just change the request to be HTTPS since the WorldBank API doesn't have its certificates sorted out, so those requests are blocked by the browser as well. One solution would be to load your site over HTTP; however, this is obviously not advisable if your page contains any user-sensitive information.

The better way is to use your own back-end server as a proxy. You can setup your own API on your server that queries the WorldBank API over HTTP and can then respond to your request over HTTPS. Of course, this assumes you have control over your backend which is not always the case.

Body:
I'm trying to use World Bank's API to obtain some data. This is how to query their database. Basically to query a country's information, I would need to go to this url:

http://api.worldbank.org/countries/"alpha2Code of the country"

In my code here (Link to CodePen code.) I use use the alpha2Code from a previous query to add to the World Bank query's URL. Here's the method:

getDetails(alpha2Code) {
  this.load('http://api.worldbank.org/countries/'+alpha2Code)
    .then((countryDetails) => {
      this.generateOverlay(countryDetails);
    });
},

the load() method is defined here:

load(url, type = 'json') {
  return $.ajax({
    dataType: type,
    url: url,
  });
},

According to World Bank's basic calling format, I would need to add

format=json

in order to receive response in JSON. Somehow I don't think it's actually obtaining anything from WorldBank.

The query to World Bank is suppose to give me details to put into the overlay that covers the country flags after a click.

Thank you in advance for the help!


问:
Sticky footer works on all but one page
Page is here

I am using a sticky footer, which works fine everywhere but my portfolio page. The gallery is relatively positioned, and is overflowing from it's parent div. The footer is sticking to the bottom of the parent, rather than the page.

Help? Preferably in a way where I don't have to rewrite all my code?

答: Fixed it by coding body and html to 110% height, footer wrapper to 100% height, and adding page wrapper with 100% height.</p>

Title: Sticky footer works on all but one page


问:
Transpose matrix in prolog
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

```<code>%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).
</code>```

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

答:
It turns out that the previous solution was inadequate because it was only a description of logical relationships.

What is required in addition to the specification of the relationships is an iteration of facts that are subsequently made subject to the relationships.

In the following program it is foreach that is used to generate the facts.

Tested on swipl.

Example queries follow the program.

```<code>    */

    (
        program(INPUT_VECTOR,OUTPUT_VECTOR)
    )
    :-
    (
        (
            (
                INPUT_TRUTH_GOAL
            )
            =
            (
                item(INPUT_VECTOR,J_INDEX,K_INDEX,ITEM)
            )
        )
        ,
        (
            (
                OUTPUT_TRUTH_GOAL
            )
            =
            (
                item(OUTPUT_VECTOR,K_INDEX,J_INDEX,ITEM)
            )
        )
        ,
        (
            (
                nonvar(INPUT_VECTOR)
            )
            *->
            (
                once(foreach(INPUT_TRUTH_GOAL,OUTPUT_TRUTH_GOAL))
            )
            ;
            (
                (
                    nonvar(OUTPUT_VECTOR)
                )
                *->
                (
                    once(foreach(OUTPUT_TRUTH_GOAL,INPUT_TRUTH_GOAL))
                )
            )
        )
    )
    .

    (
        item(VECTOR,J_INDEX,K_INDEX,ITEM)
    )
    :-
    (
        (
            nth1(J_INDEX,VECTOR,SUBVECTOR)
        )
        ,
        (
            nth1(K_INDEX,SUBVECTOR,ITEM)
        )
    )
    .

    /*
</code>```

Testing:

Three test queries demonstrate that the program is basically fit:

```<code>    ?-
    program([[1,2,3],[4,5,6],[7,8,9]],[[1,4,7],[2,5,8],[3,6,9]])
    .
    true.

    ?-
    program([[1,2,3],[4,5,6],[7,8,9]],OUTPUT_VECTOR)
    .
    OUTPUT_VECTOR = [[1, 4, 7|_830], [2, 5, 8|_962], [3, 6, 9|_1100]|_356]  .

    ?-
    program(INPUT_VECTOR,[[1,4,7],[2,5,8],[3,6,9]])
    .
    INPUT_VECTOR = [[1, 2, 3|_560], [4, 5, 6|_626], [7, 8, 9|_698]|_350]    .

    ?-
</code>```

Unfortunately the program fails a steadfast test:

```<code>    ?-
    program(INPUT_VECTOR,OUTPUT_VECTOR)
    ,
    INPUT_VECTOR = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    .

    false .

    ?-
</code>```

Title: Transpose matrix in prolog

Body:
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

Body:
It turns out that the previous solution was inadequate because it was only a description of logical relationships.

What is required in addition to the specification of the relationships is an iteration of facts that are subsequently made subject to the relationships.

In the following program it is foreach that is used to generate the facts.

Tested on swipl.

Example queries follow the program.

    */

    (
        program(INPUT_VECTOR,OUTPUT_VECTOR)
    )
    :-
    (
        (
            (
                INPUT_TRUTH_GOAL
            )
            =
            (
                item(INPUT_VECTOR,J_INDEX,K_INDEX,ITEM)
            )
        )
        ,
        (
            (
                OUTPUT_TRUTH_GOAL
            )
            =
            (
                item(OUTPUT_VECTOR,K_INDEX,J_INDEX,ITEM)
            )
        )
        ,
        (
            (
                nonvar(INPUT_VECTOR)
            )
            *->
            (
                once(foreach(INPUT_TRUTH_GOAL,OUTPUT_TRUTH_GOAL))
            )
            ;
            (
                (
                    nonvar(OUTPUT_VECTOR)
                )
                *->
                (
                    once(foreach(OUTPUT_TRUTH_GOAL,INPUT_TRUTH_GOAL))
                )
            )
        )
    )
    .

    (
        item(VECTOR,J_INDEX,K_INDEX,ITEM)
    )
    :-
    (
        (
            nth1(J_INDEX,VECTOR,SUBVECTOR)
        )
        ,
        (
            nth1(K_INDEX,SUBVECTOR,ITEM)
        )
    )
    .

    /*

Testing:

Three test queries demonstrate that the program is basically fit:

    ?-
    program([[1,2,3],[4,5,6],[7,8,9]],[[1,4,7],[2,5,8],[3,6,9]])
    .
    true.

    ?-
    program([[1,2,3],[4,5,6],[7,8,9]],OUTPUT_VECTOR)
    .
    OUTPUT_VECTOR = [[1, 4, 7|_830], [2, 5, 8|_962], [3, 6, 9|_1100]|_356]  .

    ?-
    program(INPUT_VECTOR,[[1,4,7],[2,5,8],[3,6,9]])
    .
    INPUT_VECTOR = [[1, 2, 3|_560], [4, 5, 6|_626], [7, 8, 9|_698]|_350]    .

    ?-

Unfortunately the program fails a steadfast test:

    ?-
    program(INPUT_VECTOR,OUTPUT_VECTOR)
    ,
    INPUT_VECTOR = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    .

    false .

    ?-


问:
Regex to require some words and not accept a word
```<code><iframe.+?((width="320")).+?(?!height=".+")src="https?:\/\/www.youtube.com\/embed\/([a-zA-Z0-9_-]{11})"[^>]+?><\/iframe>
</code>```

I need to match a youtube iframe with width="320" but no height. It still returns true even if I put height.
Please guide me.

答:
Use a negative look ahead anchored to start:</p>

```<code>(?!.*height="[^"]+")iframe.+?width="320".+?src="https?://www.youtube.com/embed/([\w-]{11})"[^>]+?></iframe>
</code>```

Body:
]+?><\/iframe>

I need to match a youtube iframe with width="320" but no height. It still returns true even if I put height.
Please guide me.

Body:
Use a negative look ahead anchored to start:

(?!.*height="[^"]+")iframe.+?width="320".+?src="https?://www.youtube.com/embed/([\w-]{11})"[^>]+?></iframe>


问:
JSON string parsing for ordered pairs in ruby
Here is my JSON

```<code>  "status": "ok",
  "name": "blah",
  "unit": "blahblah",
  "period": "bluh",
  "description": "Average blah across major blahs.",
  "values": [
    {
      "x": 1459382400,
      "y": 416.94
    },
    {
      "x": 1459468800,
      "y": 416.25
    },
</code>```

I am wondering if there is a way to subtract each 'y' by the subsequent 'y' value into a independent variable.

```<code>Simplified expression of code
conn = Net::HTTP.get URI('http://www.blah.blahblah/bluhblahbleh')
parsed = JSON.parse(conn)
puts parsed ["values"]  # this prints all ordered pairs child to "values"
#This wouldn't work for me
puts parsed["values"]["y"]
#no luck here either
puts parsed["values", "y"]
</code>```

Should I utilize .each do |line| approach? # Line by Line?

Any guidance, wisdom or meaningless conversation is valued.

答:
I think this works for what you want to do    </p>

```<code>require 'json'

json = '{"status": "ok", "name": "blah", "unit": "blahblah", "period": "bluh", "description": "Average blah across major blahs.", "values": [ { "x": 1459382400, "y": 416.94 }, { "x": 1459468800, "y": 416.25 }, { "x": 1459468800, "y": 417.25 }]}'
data = JSON.parse(json)

values_with_change = [data['values'][0]]

data['values'].each_cons(2) do |value|
  change = value[1]['y'] - value[0]['y']
  value_with_change = value[1].merge({change: change})
  values_with_change.push(value_with_change)
end

values_with_change
</code>```

<p>Outputs </p>

```<code> => [{"x"=>1459382400, "y"=>416.94, :change=>0.0}, {"x"=>1459468800, "y"=>416.25, :change=>-0.6899999999999977}, {"x"=>1459468800, "y"=>417.25, :change=>1.0}]
</code>```

Body:
Here is my JSON

  "status": "ok",
  "name": "blah",
  "unit": "blahblah",
  "period": "bluh",
  "description": "Average blah across major blahs.",
  "values": [
    {
      "x": 1459382400,
      "y": 416.94
    },
    {
      "x": 1459468800,
      "y": 416.25
    },

I am wondering if there is a way to subtract each 'y' by the subsequent 'y' value into a independent variable.

Simplified expression of code
conn = Net::HTTP.get URI('http://www.blah.blahblah/bluhblahbleh')
parsed = JSON.parse(conn)
puts parsed ["values"]  # this prints all ordered pairs child to "values"
#This wouldn't work for me
puts parsed["values"]["y"]
#no luck here either
puts parsed["values", "y"]

Should I utilize .each do |line| approach? # Line by Line?

Any guidance, wisdom or meaningless conversation is valued.

Body:
I think this works for what you want to do

require 'json'

json = '{"status": "ok", "name": "blah", "unit": "blahblah", "period": "bluh", "description": "Average blah across major blahs.", "values": [ { "x": 1459382400, "y": 416.94 }, { "x": 1459468800, "y": 416.25 }, { "x": 1459468800, "y": 417.25 }]}'
data = JSON.parse(json)

values_with_change = [data['values'][0]]

data['values'].each_cons(2) do |value|
  change = value[1]['y'] - value[0]['y']
  value_with_change = value[1].merge({change: change})
  values_with_change.push(value_with_change)
end

values_with_change

Outputs

 => [{"x"=>1459382400, "y"=>416.94, :change=>0.0}, {"x"=>1459468800, "y"=>416.25, :change=>-0.6899999999999977}, {"x"=>1459468800, "y"=>417.25, :change=>1.0}]


问:
Javascript: Nested Callbacks/MySQL Results
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

```<code>SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});
</code>```

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

答:
This is very interesting... I've never heard of "server-side javascript"... but none the less this might help organize your code a bit.  I use this method to organize my ajax request callbacks.

using your example it would look like this.

```<code>SQL.query("select * from some_table", function(result){ runNestedQuery(result); });

function runNestedQuery(result){
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2){ nestedResult(result2); });
  }
}
</code>```

There are no scoping issues with your above code - but this is a nice way I like to organize this kind of thing.

Body:
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

Body:
This is very interesting... I've never heard of "server-side javascript"... but none the less this might help organize your code a bit.  I use this method to organize my ajax request callbacks.

using your example it would look like this.

SQL.query("select * from some_table", function(result){ runNestedQuery(result); });

function runNestedQuery(result){
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2){ nestedResult(result2); });
  }
}

There are no scoping issues with your above code - but this is a nice way I like to organize this kind of thing.


问:
Swift 3 casting or NumberFormatter
Is there any advantage to using a NumberFormatter over simply casting?
For example 1 and 2 below both seem to do the same job, but casting seems to be easier to read so why would the NumberFormatter often be used in code samples I've found?</p>

```<code>var displayValue: Double? {
    get {
        if let text = display.text,
        // 1 let value = NumberFormatter().number(from: text)?.doubleValue
        // 2 let value = Double(text)
}
</code>```

答:
Huge difference. If you want something to handle:

Thousand-digit separator and decimal places: one million is commonly written as 1,000,000 in the US, 1.000.000 in France, and 10,00,000 in India.

Currency symbol: $100 or £100 or €100

Negative numbers in the accounting style, for example -100 is written as (100) (and often in red too)

Percentage: 5% → 0.05

Word spelling: "one hundred six" → 106

etc... then use NumberFormatter.

Title: Swift 3 casting or NumberFormatter

Body:
Is there any advantage to using a NumberFormatter over simply casting?
For example 1 and 2 below both seem to do the same job, but casting seems to be easier to read so why would the NumberFormatter often be used in code samples I've found?

var displayValue: Double? {
    get {
        if let text = display.text,
        // 1 let value = NumberFormatter().number(from: text)?.doubleValue
        // 2 let value = Double(text)
}


问:
First display list according to HTML selection, then direct to particular page based on selection after clicking HTML button
index page

First I am trying to list elements according to the option selected from drop down menu, then open a particular page related to a particular category after clicking Go To Related Page Button. For example if a user selects Fruits, then first it should list fruit items, then fruits.html page should be opened after clicking Go To Related Page button. Another example would be if a user selects Vegetables, then first it should list vegetable items, then vegetables.html page should be opened after clicking Go To Related Page button.

I have successfully accomplished first part, but stuck in second part. I have pasted my codes below. I was trying to accomplish second part with the help of a function named goToPage(), but don't know what to do. It does not have to be this function, any other way that would work are most welcome.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "
" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "
" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>

<div id="categoryDiv">
Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>
<br>
</div>

<div id="displayDiv">

</div>

<div id="buttonDiv">
 <br>
 <input type="button" value="Go to Related Page" onclick="goToPage()">
</div>

</body>
</html></code>```

答:
You're very close, all you have to do is implement the clicking bit.  So, let's add a containing anchor tag (or link) for the button.  Then we can easily modify the href attribute.  A put up a couple dumby pages on my website so you can see how it works.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var fruitsUrl = "http://neil.computer/stack/fruits.html";
var vegetablesUrl = "http://neil.computer/stack/vegetables.html";

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "
" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      $("#buttonDiv a").attr("href",fruitsUrl);
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "
" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      $("#buttonDiv a").attr("href",vegetablesUrl);
      break;
    default:
      $("#buttonDiv a").attr("href","#");
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#buttonDiv a {
  text-decoration:none;
}</code>```

<!DOCTYPE html>

Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>

 <input type="button" value="Go to Related Page" onclick="goToPage()">

```

Body:
index page

First I am trying to list elements according to the option selected from drop down menu, then open a particular page related to a particular category after clicking Go To Related Page Button. For example if a user selects Fruits, then first it should list fruit items, then fruits.html page should be opened after clicking Go To Related Page button. Another example would be if a user selects Vegetables, then first it should list vegetable items, then vegetables.html page should be opened after clicking Go To Related Page button.

I have successfully accomplished first part, but stuck in second part. I have pasted my codes below. I was trying to accomplish second part with the help of a function named goToPage(), but don't know what to do. It does not have to be this function, any other way that would work are most welcome.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "
" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "
" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}

<!DOCTYPE html>

Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>

 <input type="button" value="Go to Related Page" onclick="goToPage()">

Body:
You're very close, all you have to do is implement the clicking bit.  So, let's add a containing anchor tag (or link) for the button.  Then we can easily modify the href attribute.  A put up a couple dumby pages on my website so you can see how it works.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var fruitsUrl = "http://neil.computer/stack/fruits.html";
var vegetablesUrl = "http://neil.computer/stack/vegetables.html";

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "<br>" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      $("#buttonDiv a").attr("href",fruitsUrl);
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "<br>" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      $("#buttonDiv a").attr("href",vegetablesUrl);
      break;
    default:
      $("#buttonDiv a").attr("href","#");
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}

#buttonDiv a {
  text-decoration:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>

<div id="categoryDiv">
Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>
<br>
</div>

<div id="displayDiv">

</div>

<div id="buttonDiv">
 <br>
 <a href="#"><input type="button" value="Go to Related Page" onclick="goToPage()"></a>
</div>

</body>
</html>


问:
Merging differently sized pandas dataframes based on common column
I have a dataframe with datetime index from 2006-01-19 to 2007-01-25 like this:

```<code>         YEAR   DOY  temperature
datetime
2016-01-19  2016.0    NaN
2016-01-20  2016.0    NaN
2016-01-21  2016.0    NaN
2016-01-22  2016.0    NaN
2016-01-23  2016.0    NaN
.....
2017-01-24  2017.0    NaN
</code>```

All temperature values in the dataframe above are NaNs.

I want to join another dataframe containing temperature values for each day of the year (366 in all):

```<code>   YEAR  DOY  temperature
0  2013    1         3.66
1  2013    2         4.00
2  2013    3         1.38
3  2013    4        -0.44
.....
4  2013    366       0.22
</code>```

I want to join these dataframes based on the DOY column so that e.g. day 22 of the first dataframe has temperature value that is obtained for day 22 from the second dataframe. I tried this:

```<code>df_a.merge(df_b, on='DOY', suffixes=('_x', ''))
</code>```

However, this does not work. How do I fix it?

答:
I usually use the full syntax:

```<code>merged = pd.merge(df_a, df_b, how='left', left_on='DOY', right_on='DOY', suffixes=('_x', ''))
</code>```

This way of merging is clearer to me personally.

You can look at the documentation on merging to find out more about merging.

Body:
I have a dataframe with datetime index from 2006-01-19 to 2007-01-25 like this:

         YEAR   DOY  temperature
datetime
2016-01-19  2016.0    NaN
2016-01-20  2016.0    NaN
2016-01-21  2016.0    NaN
2016-01-22  2016.0    NaN
2016-01-23  2016.0    NaN
.....
2017-01-24  2017.0    NaN

All temperature values in the dataframe above are NaNs.

I want to join another dataframe containing temperature values for each day of the year (366 in all):

   YEAR  DOY  temperature
0  2013    1         3.66
1  2013    2         4.00
2  2013    3         1.38
3  2013    4        -0.44
.....
4  2013    366       0.22

I want to join these dataframes based on the DOY column so that e.g. day 22 of the first dataframe has temperature value that is obtained for day 22 from the second dataframe. I tried this:

df_a.merge(df_b, on='DOY', suffixes=('_x', ''))

However, this does not work. How do I fix it?

Body:
I usually use the full syntax:

merged = pd.merge(df_a, df_b, how='left', left_on='DOY', right_on='DOY', suffixes=('_x', ''))

This way of merging is clearer to me personally.

You can look at the documentation on merging to find out more about merging.


问:
Prevent user from selecting a value less than a scale before
I have a scale (radio buttons) in a form that allows the user to select a value from 0 to 10.

I have a second scale (radio buttons) below it, which also allows the user to select a value from 0 to 10.

Using jQuery ideally.. how would I go about preventing the user from selecting a value in the second scale that is less than the value in the first scale?

The markup looks something like below (although this is stripped back for the sake of the example)

```<code><div class="scale_a">

    <div class="frm_scale">
        <label for="field_a">
        <input type="radio" id="field_a_1" value="0">0</label>
    </div>

    <div class="frm_scale">
        <label for="field_a">
        <input type="radio" id="field_a_2" value="1">1</label>
    </div>

</div>
</code>```

答:
you have to create a loop for this work
Its not done just an aprox example</p>

```<code>$(".scale_a input").forEach(function(ele){
    if(ele.val() < [your previous obj val] ){
    ele.attr("disabled",true)
    }
})
</code>```

Body:
I have a scale (radio buttons) in a form that allows the user to select a value from 0 to 10.

I have a second scale (radio buttons) below it, which also allows the user to select a value from 0 to 10.

Using jQuery ideally.. how would I go about preventing the user from selecting a value in the second scale that is less than the value in the first scale?

The markup looks something like below (although this is stripped back for the sake of the example)

        <input type="radio" id="field_a_1" value="0">0

        <input type="radio" id="field_a_2" value="1">1

Body:
you have to create a loop for this work
Its not done just an aprox example

$(".scale_a input").forEach(function(ele){
    if(ele.val() < [your previous obj val] ){
    ele.attr("disabled",true)
    }
})


问:
Can I populate a column in telerik grid from code behind
Hi I am working on an asp.net page and I want to fill 1 column in my grid from code behind is that possible.
If I am using

```<code><telerik:GridBoundColumn AllowSorting="false" UniqueName="AdditionalMargin" DataField="AdditionalMargin"
                                        HeaderText="ADD Margin" HeaderTooltip="ADD Margin" ItemStyle-HorizontalAlign="Right"
                                        Aggregate="Sum" DataFormatString="{0:0.00}" FooterAggregateFormatString="{0:0.00}">
                                    </telerik:GridBoundColumn>
</code>```

It is not possible I guess so please let me know if it is possible or not if possible please give some inputs.

答:
Try the below code to add a column and set value to it.</p>

```<code>DataTable dt = sql.ExecuteDataTable("sp_MyProc");

dt.Columns.Add("NewColumn", typeof(System.Int32)); //change the datatype to your need.

foreach(DataRow row in dt.Rows)
{
    //need to set value to NewColumn column
    row["NewColumn"] = 0;   // or set it to some other value
}
</code>```

Body:
Hi I am working on an asp.net page and I want to fill 1 column in my grid from code behind is that possible.
If I am using

<telerik:GridBoundColumn AllowSorting="false" UniqueName="AdditionalMargin" DataField="AdditionalMargin"
                                        HeaderText="ADD Margin" HeaderTooltip="ADD Margin" ItemStyle-HorizontalAlign="Right"
                                        Aggregate="Sum" DataFormatString="{0:0.00}" FooterAggregateFormatString="{0:0.00}">
                                    </telerik:GridBoundColumn>

It is not possible I guess so please let me know if it is possible or not if possible please give some inputs.

Body:
Try the below code to add a column and set value to it.

DataTable dt = sql.ExecuteDataTable("sp_MyProc");

dt.Columns.Add("NewColumn", typeof(System.Int32)); //change the datatype to your need.

foreach(DataRow row in dt.Rows)
{
    //need to set value to NewColumn column
    row["NewColumn"] = 0;   // or set it to some other value
}


问:
Jquery Validation Not working throwing error $.validation is undefinedj
jQuery validation is working fine on my machine, when i pushed it to test server it won't it's throwing some errors which is kind of surprising.

These are the errors I am getting:

$.validator is null or not an object...

I've never gotten this error before and it throwing an error when I declared a variable like var isValid.

I don't know what to do. I am doing the custom validation methods not in the document.ready(). Does this cause this error? I wonder because all jquery validations are passing and hitting the server side validations.

答: Almost always this type of $.<insert-function-here> is a path or typo error, jQuery cannot find the function.  Check your includes and script for typos and verify the paths are correct.


问:
automatically run %matplotlib inline in jupyter qtconsole
Is there a way to change the config file to make jupyter qtconsole run the following command on startup?:</p>

```<code>%matplotlib inline
</code>```

答:
Open the file ~/.ipython/profile_default/ipython_config.py, and

```<code>c.InteractiveShellApp.code_to_run = ''
</code>```

==>

```<code>c.InteractiveShellApp.code_to_run = '%pylab inline'
</code>```

Body:
Is there a way to change the config file to make jupyter qtconsole run the following command on startup?:

%matplotlib inline

Body:
Open the file ~/.ipython/profile_default/ipython_config.py, and

c.InteractiveShellApp.code_to_run = ''

==>

c.InteractiveShellApp.code_to_run = '%pylab inline'


问:
C++ program (XCode) not running until I enter something into console
I'm writing a text-based game for a class, and I had the majority of it running and working prior to this issue.

I opened it today and tried to build/run it, and it was built successfully and seems to be running, but some of the first lines of code are outputs to the console, and they aren't happening until I input something into the console, which shouldn't be necessary until after the prompt has printed:

Here's the beginning of my main:

```<code>int main() {
string name;
cout << fixed << setprecision(2) << "What's your name? ";
cin >> name;
cin.ignore(INT_MAX, '\n');...
</code>```

and here's the output (It's nothing until I've typed in HELP? and pressed enter)

```<code>HELP?
What's your name?

===========================================================
|                   Welcome,    HELP?!                    |
===========================================================
</code>```

whereas prior to today, when I'd run it, it'd output "What's your name?", at which point I'd type in my name, and then it'd print the welcome.

I feel like it must be something simple since it seems so black and white to me: Why would it wait for any input when essentially the first real thing I ask of it is to output something to the console? It works this way even if I put a cout statement as the first thing. Is this an XCode problem?

Note: It's treating input like this for every cin in the file as well, the questions and prompts wont print until after I've input something.

答:
When writing to a std::ostream in C++, you have to flush the buffer before anything will actually print to the console. You can do this either with std::endl or std::flush.

See the std::ostream reference here.

Example:

```<code>#include <iostream>
#include <string>

int main() {
    std::string s;
    std::cout << "Flushed with a line break." << std::endl;
    std::cin >> s;
    std::cout << "Flushed with no line break." << std::flush;
    std::cin >> s;

    return 0;
}
</code>```

Body:
I'm writing a text-based game for a class, and I had the majority of it running and working prior to this issue.

I opened it today and tried to build/run it, and it was built successfully and seems to be running, but some of the first lines of code are outputs to the console, and they aren't happening until I input something into the console, which shouldn't be necessary until after the prompt has printed:

Here's the beginning of my main:

int main() {
string name;
cout << fixed << setprecision(2) << "What's your name? ";
cin >> name;
cin.ignore(INT_MAX, '\n');...

and here's the output (It's nothing until I've typed in HELP? and pressed enter)

HELP?
What's your name?

===========================================================
|                   Welcome,    HELP?!                    |
===========================================================

whereas prior to today, when I'd run it, it'd output "What's your name?", at which point I'd type in my name, and then it'd print the welcome.

I feel like it must be something simple since it seems so black and white to me: Why would it wait for any input when essentially the first real thing I ask of it is to output something to the console? It works this way even if I put a cout statement as the first thing. Is this an XCode problem?

Note: It's treating input like this for every cin in the file as well, the questions and prompts wont print until after I've input something.

Body:
When writing to a std::ostream in C++, you have to flush the buffer before anything will actually print to the console. You can do this either with std::endl or std::flush.

See the std::ostream reference here.

Example:

#include <iostream>
#include <string>

int main() {
    std::string s;
    std::cout << "Flushed with a line break." << std::endl;
    std::cin >> s;
    std::cout << "Flushed with no line break." << std::flush;
    std::cin >> s;

    return 0;
}


问:
Is it possible to show the restart policy of a running Docker container?
When I create containers I'm specifying a restart policy, but this is not shown in docker ps, and it doesn't appear any format string shows this either.

Does anyone know how to see the restart policy of a running container(s)?

答:
You can get this via docker inspect.

Just the policy name:

docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' <container-id>
```

<p>Or the entire policy (including e.g. max retry count):</p>

<pre class="lang-none prettyprint-override"><code>docker inspect --format '{{json .HostConfig.RestartPolicy}}' <container-id>
</code>```

Body:
You can get this via docker inspect.

Just the policy name:

docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' <container-id>

Or the entire policy (including e.g. max retry count):

docker inspect --format '{{json .HostConfig.RestartPolicy}}' <container-id>