问:
using date in if condition in php?
I make a condition like this

```<code><?php $todays_date = date("d F Y"); ?> //echo 04 June 2017
<?php $deadline_date = date("d F Y",strtotime($tugas->deadline_tugas));?> //echo 25 May 2017
<?php if ($todays_date < $deadline_date){  <--- I confused in this condition!
 echo "<a class='btn btn-primary btn-lg btn-block' href=\"student_tugas/".$tugas->id_tgs."\">Go Activate!</a>";
 }else {
    echo "<button type='button' class='btn btn-primary btn-lg btn-block' disabled='disabled'>Oops!</button>";
} ?>
</code>```

I want this code run when $deadline_date has reached $todays_date and
  so then the button is "Oops!" but when the $deadline_date has reached
  $todays_date yet then the button will be show "Go Activate!". As long
  as $deadline_date has not reach $todays_date and so the button "Go
  Activate!" will be show.

Could you help me?

答:
your if statement is compare 2 string come from the date() function. So it will now be correctly, for example 'June' < 'May', but actually not.

Refer to this post for compare the date and the manual of date()

Title: using date in if condition in php?

Body:
I make a condition like this

<?php $todays_date = date("d F Y"); ?> //echo 04 June 2017
<?php $deadline_date = date("d F Y",strtotime($tugas->deadline_tugas));?> //echo 25 May 2017
<?php if ($todays_date < $deadline_date){  <--- I confused in this condition!
 echo "id_tgs."\">Go Activate!";
 }else {
    echo "<button type='button' class='btn btn-primary btn-lg btn-block' disabled='disabled'>Oops!</button>";
} ?>

I want this code run when $deadline_date has reached $todays_date and
  so then the button is "Oops!" but when the $deadline_date has reached
  $todays_date yet then the button will be show "Go Activate!". As long
  as $deadline_date has not reach $todays_date and so the button "Go
  Activate!" will be show.

Could you help me?


来源: stackexchange

问:
Scheduled local notifications are irregular
I'm having significant trouble with my iOS local notifications. I have an app, written in Objective-C, that allows the user to pick the time the notification fires, as well as the days of the week (it should fire every week on the specified days at the specified time). I have no trouble with the time of day the notification fires, that works correctly. However, when I specify the day(s) it should fire, odd things happen. At first, they fire once, but every day rather than only the specified days. Then, after the first week, they fire every day, but not only once. Instead, they fire as many times as days are specified (so if Sunday, Monday and Tuesday are chosen, each day, the user will receive 3 consecutive notifications at the specified time).

This is the code I'm using to set up the notifications.

When the "Save" button is tapped, the first thing that happens is a clearing of all notifications, to make way for the new ones.

```<code>//cancels all notifications upon save
[[UIApplication sharedApplication] cancelAllLocalNotifications];
</code>```

Next, I use NSDate, NSCalendar and NSCalendarComponents to get the specifics for the current time, as well as the components from my UIPicker (which is used to select the time of day)

```<code>NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];//get the required calendar units
</code>```

Then, I get the units for the time from the UIPicker, and the actual time, also from the picker.

```<code>NSDateComponents *pickedComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];
NSDate *minuteHour = [calendar dateFromComponents:pickedComponents];
[[NSUserDefaults standardUserDefaults] setObject:minuteHour forKey:@"FireTime"];
</code>```

After that, I set the text I want to show up in the notification

```<code>NSString *reminder = @"Reminder text!";
</code>```

Next is the actual setup of the notification. They're all the same (with the day of the week changed, of course), so I'll just show the one for Sunday.

```<code>//sunday
UILocalNotification *localNotificationSunday = [[UILocalNotification alloc] init];
if ([sundayTempStatus isEqual:@"1"])
{

    //permanently save the status
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"Sunday"];

    //set up notifications
    //if it is past sunday, push next week
    if (components.weekday > 1)
    {
        components.day = components.day + 7; //if already passed sunday, make it next sunday
    }

    //components.day = 1;
    components.hour = [pickedComponents hour];
    components.minute = [pickedComponents minute];

    NSDate *fireDate = [calendar dateFromComponents:components];

    localNotificationSunday.fireDate = fireDate;
    localNotificationSunday.alertBody = reminder;
    localNotificationSunday.timeZone = [NSTimeZone systemTimeZone];
    localNotificationSunday.repeatInterval = NSCalendarUnitWeekOfYear;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotificationSunday];
}
else
{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"Sunday"];
}
</code>```

Any help is greatly appreciated, and if any additional info or code is needed, I'll gladly provide it.

答:
When code becomes repetitive, it often becomes more error-prone. I've written out a simple method that should take care of the scheduling of the reminders.

```<code>- (void)scheduleNotificationForDayOfWeek:(int)dayOfWeek withPickedComponents:(NSDateComponents *)pickedComponents andReminderString:(NSString *)reminderString {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    UILocalNotification *notification = [[UILocalNotification alloc] init];

    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[NSDate date]];
    components.hour = [pickedComponents hour];
    components.minute = [pickedComponents minute];

    NSDateComponents *additionalComponents = [[NSDateComponents alloc] init]; // to be added onto our date
    if ([components weekday] < dayOfWeek) {
        additionalComponents.day = (dayOfWeek - [components weekday]); // add the number of days until the next occurance of this weekday
    } else if ([components weekday] > dayOfWeek) {
        additionalComponents.day = (dayOfWeek - [components weekday] + 7); // add the number of days until the next occurance of this weekday
    }

    NSDate *fireDate = [calendar dateFromComponents:components];
    fireDate = [calendar dateByAddingComponents:additionalComponents toDate:fireDate options:0]; // add on our days

    notification.fireDate = fireDate;
    notification.alertBody = reminderString;
    notification.timeZone = [NSTimeZone systemTimeZone];
    notification.repeatInterval = NSCalendarUnitWeekOfYear;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
</code>```

What this does is actually pretty simple. Call it with a day of the week (e.g., 0 = Sunday, 1 = Monday), and it will schedule a repeating reminder for that day. I couldn't reproduce your issues in my tests with your Sunday code, so I figured that somewhere among repeating that code you must have made an error.

In this method, the fire date getting has been simplified. It uses NSDateComponents to easily get the next occurrence of that weekday. Call it like this: [self scheduleNotificationForDayOfWeek:0 withPickedComponents:pickedComponents andReminderString:@"Hello, world!"]; (which would show "Hello, world!" every Sunday at the specified components)

With this snippet, you should be able to get rid of most of the repeated statements in your code, and simplify how setting notifications is done. For me, this worked perfectly.

ContentLicense: CC BY-SA 3.0

Body:
I'm having significant trouble with my iOS local notifications. I have an app, written in Objective-C, that allows the user to pick the time the notification fires, as well as the days of the week (it should fire every week on the specified days at the specified time). I have no trouble with the time of day the notification fires, that works correctly. However, when I specify the day(s) it should fire, odd things happen. At first, they fire once, but every day rather than only the specified days. Then, after the first week, they fire every day, but not only once. Instead, they fire as many times as days are specified (so if Sunday, Monday and Tuesday are chosen, each day, the user will receive 3 consecutive notifications at the specified time).

This is the code I'm using to set up the notifications.

When the "Save" button is tapped, the first thing that happens is a clearing of all notifications, to make way for the new ones.

//cancels all notifications upon save
[[UIApplication sharedApplication] cancelAllLocalNotifications];

Next, I use NSDate, NSCalendar and NSCalendarComponents to get the specifics for the current time, as well as the components from my UIPicker (which is used to select the time of day)

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];//get the required calendar units

Then, I get the units for the time from the UIPicker, and the actual time, also from the picker.

NSDateComponents *pickedComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];
NSDate *minuteHour = [calendar dateFromComponents:pickedComponents];
[[NSUserDefaults standardUserDefaults] setObject:minuteHour forKey:@"FireTime"];

After that, I set the text I want to show up in the notification

NSString *reminder = @"Reminder text!";

Next is the actual setup of the notification. They're all the same (with the day of the week changed, of course), so I'll just show the one for Sunday.

//sunday
UILocalNotification *localNotificationSunday = [[UILocalNotification alloc] init];
if ([sundayTempStatus isEqual:@"1"])
{

    //permanently save the status
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"Sunday"];

    //set up notifications
    //if it is past sunday, push next week
    if (components.weekday > 1)
    {
        components.day = components.day + 7; //if already passed sunday, make it next sunday
    }

    //components.day = 1;
    components.hour = [pickedComponents hour];
    components.minute = [pickedComponents minute];

    NSDate *fireDate = [calendar dateFromComponents:components];

    localNotificationSunday.fireDate = fireDate;
    localNotificationSunday.alertBody = reminder;
    localNotificationSunday.timeZone = [NSTimeZone systemTimeZone];
    localNotificationSunday.repeatInterval = NSCalendarUnitWeekOfYear;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotificationSunday];
}
else
{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"Sunday"];
}

Any help is greatly appreciated, and if any additional info or code is needed, I'll gladly provide it.

Body:
When code becomes repetitive, it often becomes more error-prone. I've written out a simple method that should take care of the scheduling of the reminders.

- (void)scheduleNotificationForDayOfWeek:(int)dayOfWeek withPickedComponents:(NSDateComponents *)pickedComponents andReminderString:(NSString *)reminderString {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    UILocalNotification *notification = [[UILocalNotification alloc] init];

    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[NSDate date]];
    components.hour = [pickedComponents hour];
    components.minute = [pickedComponents minute];

    NSDateComponents *additionalComponents = [[NSDateComponents alloc] init]; // to be added onto our date
    if ([components weekday] < dayOfWeek) {
        additionalComponents.day = (dayOfWeek - [components weekday]); // add the number of days until the next occurance of this weekday
    } else if ([components weekday] > dayOfWeek) {
        additionalComponents.day = (dayOfWeek - [components weekday] + 7); // add the number of days until the next occurance of this weekday
    }

    NSDate *fireDate = [calendar dateFromComponents:components];
    fireDate = [calendar dateByAddingComponents:additionalComponents toDate:fireDate options:0]; // add on our days

    notification.fireDate = fireDate;
    notification.alertBody = reminderString;
    notification.timeZone = [NSTimeZone systemTimeZone];
    notification.repeatInterval = NSCalendarUnitWeekOfYear;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

What this does is actually pretty simple. Call it with a day of the week (e.g., 0 = Sunday, 1 = Monday), and it will schedule a repeating reminder for that day. I couldn't reproduce your issues in my tests with your Sunday code, so I figured that somewhere among repeating that code you must have made an error.

In this method, the fire date getting has been simplified. It uses NSDateComponents to easily get the next occurrence of that weekday. Call it like this: [self scheduleNotificationForDayOfWeek:0 withPickedComponents:pickedComponents andReminderString:@"Hello, world!"]; (which would show "Hello, world!" every Sunday at the specified components)

With this snippet, you should be able to get rid of most of the repeated statements in your code, and simplify how setting notifications is done. For me, this worked perfectly.


问:
WebGL Earth restart animation at current location
I'm using WebGL's Globe API and its rotating animation capability, but I want the user to be able to stop and restart the animation by double-clicking on the globe.

Currently I have the following animation code that runs onload:

```<code>function performAnimation() {
      requestAnimationFrame(function animate(now) {
        if (animated) {
          var c = earth.getPosition();
          var elapsed = before? now - before: 0;
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          requestAnimationFrame(animate);
        }

      });
    }
</code>```

And the following code stops and restarts the animation on double-click:

```<code>performAnimation()
    var animated = true;
    var touchtime = 0;

    $('#globe').on('click', function() {
      if(touchtime == 0) {
        touchtime = new Date().getTime();
      } else {
        if(((new Date().getTime()) - touchtime) < 200) {
          if (animated) {
            animated = false;
          } else {
            animated = true;
            performAnimation()
          }
          console.log(animated);
          //alert(animated);

          touchtime = 0;
        } else {
          touchtime = 0;
        }
      }
    });
</code>```

The stop and stop works on double-click. The problem is that when the animation is stopped, the time still elapses, and when the animation is restarted the globe's center is immediately shifted to the position it would have been in had it not stopped.

How can I ensure that when the globe animation restarts, it restarts from its current center and not the hypothetical center?

答:
So I've finally solved this issue by simply creating a variable called dontAllowTimeElapse that is initially set to false. When the user stops the animation and restarts it, dontAllowTimeElapse is set to true:

```<code>         if (animated) {
            animated = false;
          } else {
            animated = true;

            dontAllowTimeElapse = true;
            performAnimation()
          }
</code>```

In the animation code, if dontAllowTimeElapse is true, the time elapsed is reset to 0, which means the animation restarts from where it was stopped. Once the new center is set, time elapse is allowed again:

```<code>         if (dontAllowTimeElapse) {
            elapsed = 0;
          }
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          dontAllowTimeElapse = false;
          requestAnimationFrame(animate);
</code>```

Body:
I'm using WebGL's Globe API and its rotating animation capability, but I want the user to be able to stop and restart the animation by double-clicking on the globe.

Currently I have the following animation code that runs onload:

function performAnimation() {
      requestAnimationFrame(function animate(now) {
        if (animated) {
          var c = earth.getPosition();
          var elapsed = before? now - before: 0;
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          requestAnimationFrame(animate);
        }

      });
    }

And the following code stops and restarts the animation on double-click:

performAnimation()
    var animated = true;
    var touchtime = 0;

    $('#globe').on('click', function() {
      if(touchtime == 0) {
        touchtime = new Date().getTime();
      } else {
        if(((new Date().getTime()) - touchtime) < 200) {
          if (animated) {
            animated = false;
          } else {
            animated = true;
            performAnimation()
          }
          console.log(animated);
          //alert(animated);

          touchtime = 0;
        } else {
          touchtime = 0;
        }
      }
    });

The stop and stop works on double-click. The problem is that when the animation is stopped, the time still elapses, and when the animation is restarted the globe's center is immediately shifted to the position it would have been in had it not stopped.

How can I ensure that when the globe animation restarts, it restarts from its current center and not the hypothetical center?

Body:
So I've finally solved this issue by simply creating a variable called dontAllowTimeElapse that is initially set to false. When the user stops the animation and restarts it, dontAllowTimeElapse is set to true:

         if (animated) {
            animated = false;
          } else {
            animated = true;

            dontAllowTimeElapse = true;
            performAnimation()
          }

In the animation code, if dontAllowTimeElapse is true, the time elapsed is reset to 0, which means the animation restarts from where it was stopped. Once the new center is set, time elapse is allowed again:

         if (dontAllowTimeElapse) {
            elapsed = 0;
          }
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          dontAllowTimeElapse = false;
          requestAnimationFrame(animate);


问:
How to make tiled image frame without using exec function?
Original image:

Here what i need:

It should be created from this small tile:

A lot of people suggest to use ImageMagick solution (it using php exec function) - http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=21867:

```<code>convert frame_template.gif \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-gravity center thumbnail.gif -composite frame_filled.gif
</code>```

or

PICFrame solution (it using php exec function) - http://www.fmwconcepts.com/imagemagick/picframe/index.php:

```<code>picframe [-f frameid] [-m mattesize] [-c mattecolor] [-b bordersize] [-s shade] [-a adjust] [-o opacity ] [-d distance] infile outfile
</code>```

PHP imagick has great ability to create color borders with:

```<code>$imagick = new \Imagick('image.jpg');
$imagick->scaleImage(300, 300, false);

// Create frame placeholder
$imagick->frameimage( 'red','30','30', 30, 0);

// Flood fill with color
$imagick->floodFillPaintImage('green', 10, '#6e0000',0, 0,false
);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
</code>```

But PHP imagick can't use your own image tile to create frame, only solid colors. Here is very related question - How to flood fill the frame with a pattern image using imagick php class?

Another good solution from - https://stackoverflow.com/a/28778953/2337706 but it creates image from big PNG frames and you should know correct image size.

I know that i can create it with php GD - http://php.net/manual/en/ref.image.php but i don't know correct way how implement it this way.

答:
In ImageMagick, you could just do something simple like this:

```<code>convert a1Wit.jpg -mattecolor black -frame 10x10+3+3 -gravity west -chop 3x0 -bordercolor gold -border 3 frame_result.jpg
</code>```

These commands should be easy enough to translate into Imagick.  See http://us3.php.net/manual/en/imagick.frameimage.php and http://us3.php.net/manual/en/imagick.chopimage.php and http://us3.php.net/manual/en/imagick.borderimage.php

Or simply:

```<code>convert a1Wit.jpg -bordercolor black -border 7 -bordercolor "gray(35%)" -border 3 -bordercolor "#D0A456" -border 3 frame_result2.jpg
</code>```

Or

```<code>convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -shave 5x5 -bordercolor "#D0A456" -border 3 frame_result3.jpg
</code>```

Or

```<code>convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -bordercolor "#D0A456" -border 3 frame_result4.jpg
</code>```

Adjust the color thicknesses as desired

Body:
Original image:

Here what i need:

It should be created from this small tile:

A lot of people suggest to use ImageMagick solution (it using php exec function) - http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=21867:

convert frame_template.gif \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-gravity center thumbnail.gif -composite frame_filled.gif

or

PICFrame solution (it using php exec function) - http://www.fmwconcepts.com/imagemagick/picframe/index.php:

picframe [-f frameid] [-m mattesize] [-c mattecolor] [-b bordersize] [-s shade] [-a adjust] [-o opacity ] [-d distance] infile outfile

PHP imagick has great ability to create color borders with:

$imagick = new \Imagick('image.jpg');
$imagick->scaleImage(300, 300, false);

// Create frame placeholder
$imagick->frameimage( 'red','30','30', 30, 0);

// Flood fill with color
$imagick->floodFillPaintImage('green', 10, '#6e0000',0, 0,false
);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();

But PHP imagick can't use your own image tile to create frame, only solid colors. Here is very related question - How to flood fill the frame with a pattern image using imagick php class?

Another good solution from - https://stackoverflow.com/a/28778953/2337706 but it creates image from big PNG frames and you should know correct image size.

I know that i can create it with php GD - http://php.net/manual/en/ref.image.php but i don't know correct way how implement it this way.

Body:
In ImageMagick, you could just do something simple like this:

convert a1Wit.jpg -mattecolor black -frame 10x10+3+3 -gravity west -chop 3x0 -bordercolor gold -border 3 frame_result.jpg

These commands should be easy enough to translate into Imagick.  See http://us3.php.net/manual/en/imagick.frameimage.php and http://us3.php.net/manual/en/imagick.chopimage.php and http://us3.php.net/manual/en/imagick.borderimage.php

Or simply:

convert a1Wit.jpg -bordercolor black -border 7 -bordercolor "gray(35%)" -border 3 -bordercolor "#D0A456" -border 3 frame_result2.jpg

Or

convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -shave 5x5 -bordercolor "#D0A456" -border 3 frame_result3.jpg

Or

convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -bordercolor "#D0A456" -border 3 frame_result4.jpg

Adjust the color thicknesses as desired


问:
Subversion for web development
I've read a lot of articles about Subversion and pushing the information to a web server, but I'm still having difficulties.

I can understand the basics about creating the repository and checking out etc., but I need help for the web server part.

I'm running Apache and Subverion is running on the development server I'm working on.

Now do I create my repository in the **htdocs** folder along with my live web documents or do I create it outside of my htdocs folder.;

Once I have my repository I import the newly created repository into my live web folder, which is allowing me to call the files onto my local machine edit them and then commit them to the development server.

I want to know firstly the correct way and secondly, how do I automatically move the files from the newly updated repository to the live web folder?

Please any advice I've been searching for a long time. Thanks

EDIT

Is there anyway you could help me with the post-commit scripts, I think if I can get this to work I'd be able to achieve what I need.

I'd like to be able to make changes to my code locally then when I'm finished committing it, which is sent to the respository and then automatically sent to the htdocs folder.

答: This Stack Overflow question seams to cover what you are trying to do: How can I use post-commit hooks to copy committed files to a web directory from SVN?</p>

OwnerDisplayName: Ben Robinson

LastEditorDisplayName: Ben Robinson

Title: Subversion for web development

OwnerDisplayName: maz

ContentLicense: CC BY-SA 2.5


问:
Internal call inside a function object, (Boost::apply_visitor specific)
I am currently writing a set expression evaluator which generates set< T > and set< set< T > >, the code below is to display the result of the expression.

```<code>class string_visitor : public boost::static_visitor<string>
{
public:
    string operator()(bool value) const
    {
        return "{}";
    }

    string operator()(set<T> value) const
    {
        set<T>::const_iterator it = value.begin();
        string output = "{";

        if(!value.empty())
        {
            output += *it; // Return an empty set if necessary.
            ++it;
        }

        for(; it != value.end(); ++it)
        {
            output += " " + *it;
        }
        output += "}";

        return output;
    }

    string operator()(set<set<T> > value) const
    {
        set<set<T> >::const_iterator it = value.begin();
        string output = "{";

        if(!value.empty())
        {
            output += boost::apply_visitor(string_visitor(), *it); // Return an empty set if necessary.
            ++it;
        }

        for(; it != value.end(); ++it)
        {
            output += " " + boost::apply_visitor(string_visitor(), *it);
        }
        output += "}";

        return output;
    }
};
</code>```

The problem I am experiencing is happening when I try to evaluate sets of sets using the set code, obviously I am using this as it is good practice but the compiler doesn't appear to like the syntax I am using to construct the call.

```<code>output += boost::apply_visitor(string_visitor(), *it);
</code>```

There are two lines like that, they produce the trace..

e:\documents\level 3\advanced software engineering\coursework\coursework\boost\variant\detail\apply_visitor_unary.hpp(76) : error C2039: 'apply_visitor' : is not a member of 'std::set<_Kty>'
  1>        with
  1>        [
  1>            _Kty=std::string
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.h(96) : see reference to function template instantiation 'std::basic_string<_Elem,_Traits,_Ax> boost::apply_visitor::ExpressionTree::string_visitor,const std::set<_Kty>>(const Visitor &,Visitable &)' being compiled
  1>        with
  1>        [
  1>            _Elem=char,
  1>            _Traits=std::char_traits,
  1>            _Ax=std::allocator,
  1>            T=std::string,
  1>            _Kty=std::string,
  1>            Visitor=Context::ExpressionTree::string_visitor,
  1>            Visitable=const std::set
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.h(90) : while compiling class template member function 'std::string Context::ExpressionTree::string_visitor::operator ()(std::set<_Kty>) const'
  1>        with
  1>        [
  1>            T=std::string,
  1>            _Kty=std::set
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.cpp(337) : see reference to class template instantiation 'Context::ExpressionTree::string_visitor' being compiled
  1>        with
  1>        [
  1>            T=std::string
  1>        ]

Does anyone have any idea of how to phrase that sort of call?

Cheers,
Alex

答:
Managed to fix the problem by simply type-casting the variable back to the type of variant I defined. so in my case it was solved by:

```<code>output += boost::apply_visitor(string_visitor(), (Context<T>::ExpressionTree::stackType) *it);
</code>```

Hope that helps out others!

Body:
I am currently writing a set expression evaluator which generates set< T > and set< set< T > >, the code below is to display the result of the expression.

class string_visitor : public boost::static_visitor<string>
{
public:
    string operator()(bool value) const
    {
        return "{}";
    }

    string operator()(set<T> value) const
    {
        set<T>::const_iterator it = value.begin();
        string output = "{";

        if(!value.empty())
        {
            output += *it; // Return an empty set if necessary.
            ++it;
        }

        for(; it != value.end(); ++it)
        {
            output += " " + *it;
        }
        output += "}";

        return output;
    }

    string operator()(set<set<T> > value) const
    {
        set<set<T> >::const_iterator it = value.begin();
        string output = "{";

        if(!value.empty())
        {
            output += boost::apply_visitor(string_visitor(), *it); // Return an empty set if necessary.
            ++it;
        }

        for(; it != value.end(); ++it)
        {
            output += " " + boost::apply_visitor(string_visitor(), *it);
        }
        output += "}";

        return output;
    }
};

The problem I am experiencing is happening when I try to evaluate sets of sets using the set code, obviously I am using this as it is good practice but the compiler doesn't appear to like the syntax I am using to construct the call.

output += boost::apply_visitor(string_visitor(), *it);

There are two lines like that, they produce the trace..

e:\documents\level 3\advanced software engineering\coursework\coursework\boost\variant\detail\apply_visitor_unary.hpp(76) : error C2039: 'apply_visitor' : is not a member of 'std::set<_Kty>'
  1>        with
  1>        [
  1>            _Kty=std::string
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.h(96) : see reference to function template instantiation 'std::basic_string<_Elem,_Traits,_Ax> boost::apply_visitor::ExpressionTree::string_visitor,const std::set<_Kty>>(const Visitor &,Visitable &)' being compiled
  1>        with
  1>        [
  1>            _Elem=char,
  1>            _Traits=std::char_traits,
  1>            _Ax=std::allocator,
  1>            T=std::string,
  1>            _Kty=std::string,
  1>            Visitor=Context::ExpressionTree::string_visitor,
  1>            Visitable=const std::set
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.h(90) : while compiling class template member function 'std::string Context::ExpressionTree::string_visitor::operator ()(std::set<_Kty>) const'
  1>        with
  1>        [
  1>            T=std::string,
  1>            _Kty=std::set
  1>        ]
  1>        e:\documents\level 3\advanced software engineering\coursework\coursework\context.cpp(337) : see reference to class template instantiation 'Context::ExpressionTree::string_visitor' being compiled
  1>        with
  1>        [
  1>            T=std::string
  1>        ]

Does anyone have any idea of how to phrase that sort of call?

Cheers,
Alex

Body:
Managed to fix the problem by simply type-casting the variable back to the type of variant I defined. so in my case it was solved by:

output += boost::apply_visitor(string_visitor(), (Context<T>::ExpressionTree::stackType) *it);

Hope that helps out others!


问:
Responsive Web Design Not working
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

```<code>    <!doctype html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">
<head>
<meta charset="utf-8">
<title>OneClickLearn - Home</title>
</head>

<body>
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div class="head">
<center>
  <h1 class="centered-divcontent txt-jumbo">OneClickLearn</h1>
  </center>
</div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent"><h3>Learn the Cascading Style Sheet of web development!<br><br>Start Learning CSS <em>now</em></h3>
        <button class="blue-btn txt-marginall">Learn CSS!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn data storing in web development!<br><br>Start Learning PHP <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn PHP!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
    <h3>Create actions and animations!<br>
      <br>
      Start Learning Javascript <em>now</em></h3>
    <button class="blue-btn txt-marginall">Learn Javascript!</button>
        </div>
    </div>
<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML5 <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>
</body>
</html>
</code>```

CSS

```<code>    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}
</code>```

Your help would be appreciated! Thanks!

答:
1)For Header I use 2 Media Query Like This :

```<code>@media screen and (max-width:803px) {

    .centered-divcontent {
        font-size: 50px;
    }

}

@media screen and (max-width:415px) {

    .centered-divcontent {
        font-size: 30px;
    }
}
</code>```

2)For navbar I use % instead of px.Like this :

```<code>li {
    margin: 10px 2% 10px 1px;
    //More Code
}

li a {
     padding: 5% 7%;
     //More Code
}
</code>```

3)For Footer Information Languages,I have changed your code a little bit.

Full Code:

@import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
margin:0;
padding:0;
 }

/*nav*/
@media (min-width:600px) {
.txt-jumbo {
    font-size:-40px;
}
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

li {
float:left;
margin: 10px 2% 10px 1px;
}

li a {
display: block;
color: white;
text-align: center;
text-decoration: none;
padding: 5% 7%;
}

li a:hover {
background-color: #111;
}

.head {
width:100%;
height:350px;
background-color:#05D7C6;
color:white;
text-align:center;
}

.centered-divcontent {
text-align:center;
height: 350px;
display: table-cell;
vertical-align: middle;
width: 100%;
}

.green-btn {
height:40px;
width:auto;
border-radius:5px;
background-color:#04D43C;
border:none;
color:white;
}

.green-btn:hover {
height:40px;
width:auto;
border-radius:5px;
background-color:#00F040;
border:none;
color:white;
cursor:pointer;
}

.blue-btn {
height:40px;
width:auto;
border-radius:5px;
background-color:#05D7C6;
border:none;
color:white;
}

.blue-btn:hover {
height:40px;
width:auto;
border-radius:5px;
background-color:#00E9D6;
border:none;
color:white;
cursor:pointer;
}

.white-btn {
border-radius:5px;
height:40px;
width:auto;
text-align:center;
border: #BFBFBF 1px solid;
text-decoration:none;
color:black;
background-color:white;
}

.txt-jumbo {
font-size:100px;
}

.txt-centered {
text-align:center;
}

.txt-margin {
margin-left:25px;
}

.txt-marginall {
margin-left:15px;
margin-right:15px;
margin-top:15px;
margin-bottom:15px;
}

.con {
margin-top: 10px;
width: 100%;
clear: both;
}

.content {
padding: 10px;
}

.box {
width: 30%;
text-align: center;
float: left;
box-sizing: border-box;
}
h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}

@media screen and (max-width:803px) {

.centered-divcontent {
 font-size: 50px;
}

}

@media screen and (max-width:415px) {

.centered-divcontent {
 font-size: 30px;
}

}

@media screen and (max-width:920px) {

.sidecontentleft {
 width: 50%;
 box-sizing: border-box;
}

}

@media screen and (max-width:650px) {

.box {
 width: 100%;
 float:none;
 padding: 20px;
}

.content {
 width: 70%;
 margin: auto;
}

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
   <li>Home</li>
   <li>News</li>
   <li>Contact</li>
   <li>About</li>
</ul>

<div class="head">
   <center>
  <h1 class="centered-divcontent txt-jumbo">OneClickLearn</h1>
   </center>
</div>

<div class="con">
   <div class="box left">
  <div class="content">
 <h3>Learn how to construct the blocks of a website!</h3>
 <h4>Start Learning HTML <em>now</em></h4>
<button class="green-btn txt-marginall">Learn HTML5!</button>
   </div>
</div>

<div class="box right">
   <div class="content">
  <h3>Learn the Cascading Style Sheet of web development!</h3>
  <h4>Start Learning <em>now</em></h4>
  <button class="blue-btn txt-marginall">Learn CSS!</button>
   </div>
</div>

<div class="box left">
   <div class="content">
  <h3>LLearn data storing in web development!</h3>
  <h4>Start Learning PHP <em>now</em></h4>
  <button class="green-btn txt-marginall">Learn PHP!</button>
   </div>
 </div>
</div>

<div class="con">
   <div class="box right">
  <div class="content">
     <h3>Create actions and animations!</h3>
     <h4>Start Learning Javascript <em>now</em></h4>
   <button class="green-btn txt-marginall">Learn JavaScript!</button>
  </div>
</div>

<div class="box left">
   <div class="content">
  <h3>Learn how to construct the blocks of a website!</h3>
  <h4>Start Learning HTML5 <em>now</em></h4>
  <button class="blue-btn txt-marginall">Learn HTML5!</button>
</div>
   </div>
</div></code>```

Title: Responsive Web Design Not working

Body:
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

    <!doctype html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">

<meta charset="utf-8">
<title>OneClickLearn - Home</title>

Home

News

Contact

About

OneClickLearn

Learn how to construct the blocks of a website!

Start Learning HTML now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

Learn the Cascading Style Sheet of web development!

Start Learning CSS now

        <button class="blue-btn txt-marginall">Learn CSS!</button>

Learn data storing in web development!

Start Learning PHP now

        <button class="green-btn txt-marginall">Learn PHP!</button>

Create actions and animations!

      Start Learning Javascript now

    <button class="blue-btn txt-marginall">Learn Javascript!</button>

Learn how to construct the blocks of a website!

Start Learning HTML5 now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

CSS

    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}

Your help would be appreciated! Thanks!

Body:
1)For Header I use 2 Media Query Like This :

@media screen and (max-width:803px) {

    .centered-divcontent {
        font-size: 50px;
    }

}

@media screen and (max-width:415px) {

    .centered-divcontent {
        font-size: 30px;
    }
}

2)For navbar I use % instead of px.Like this :

li {
    margin: 10px 2% 10px 1px;
    //More Code
}

li a {
     padding: 5% 7%;
     //More Code
}

3)For Footer Information Languages,I have changed your code a little bit.

Full Code:

@import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
margin:0;
padding:0;
 }

/*nav*/
@media (min-width:600px) {
.txt-jumbo {
    font-size:-40px;
}
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

li {
float:left;
margin: 10px 2% 10px 1px;
}

li a {
display: block;
color: white;
text-align: center;
text-decoration: none;
padding: 5% 7%;
}

li a:hover {
background-color: #111;
}

.head {
width:100%;
height:350px;
background-color:#05D7C6;
color:white;
text-align:center;
}

.centered-divcontent {
text-align:center;
height: 350px;
display: table-cell;
vertical-align: middle;
width: 100%;
}

.green-btn {
height:40px;
width:auto;
border-radius:5px;
background-color:#04D43C;
border:none;
color:white;
}

.green-btn:hover {
height:40px;
width:auto;
border-radius:5px;
background-color:#00F040;
border:none;
color:white;
cursor:pointer;
}

.blue-btn {
height:40px;
width:auto;
border-radius:5px;
background-color:#05D7C6;
border:none;
color:white;
}

.blue-btn:hover {
height:40px;
width:auto;
border-radius:5px;
background-color:#00E9D6;
border:none;
color:white;
cursor:pointer;
}

.white-btn {
border-radius:5px;
height:40px;
width:auto;
text-align:center;
border: #BFBFBF 1px solid;
text-decoration:none;
color:black;
background-color:white;
}

.txt-jumbo {
font-size:100px;
}

.txt-centered {
text-align:center;
}

.txt-margin {
margin-left:25px;
}

.txt-marginall {
margin-left:15px;
margin-right:15px;
margin-top:15px;
margin-bottom:15px;
}

.con {
margin-top: 10px;
width: 100%;
clear: both;
}

.content {
padding: 10px;
}

.box {
width: 30%;
text-align: center;
float: left;
box-sizing: border-box;
}
h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}

@media screen and (max-width:803px) {

.centered-divcontent {
 font-size: 50px;
}

}

@media screen and (max-width:415px) {

.centered-divcontent {
 font-size: 30px;
}

}

@media screen and (max-width:920px) {

.sidecontentleft {
 width: 50%;
 box-sizing: border-box;
}

}

@media screen and (max-width:650px) {

.box {
 width: 100%;
 float:none;
 padding: 20px;
}

.content {
 width: 70%;
 margin: auto;
}

}

<ul>
   <li><a href="#home">Home</a></li>
   <li><a href="#news">News</a></li>
   <li><a href="#contact">Contact</a></li>
   <li><a href="#about">About</a></li>
</ul>

<div class="head">
   <center>
  <h1 class="centered-divcontent txt-jumbo">OneClickLearn</h1>
   </center>
</div>

<div class="con">
   <div class="box left">
  <div class="content">
 <h3>Learn how to construct the blocks of a website!</h3>
 <h4>Start Learning HTML <em>now</em></h4>
<button class="green-btn txt-marginall">Learn HTML5!</button>
   </div>
</div>

<div class="box right">
   <div class="content">
  <h3>Learn the Cascading Style Sheet of web development!</h3>
  <h4>Start Learning <em>now</em></h4>
  <button class="blue-btn txt-marginall">Learn CSS!</button>
   </div>
</div>

<div class="box left">
   <div class="content">
  <h3>LLearn data storing in web development!</h3>
  <h4>Start Learning PHP <em>now</em></h4>
  <button class="green-btn txt-marginall">Learn PHP!</button>
   </div>
 </div>
</div>

<div class="con">
   <div class="box right">
  <div class="content">
     <h3>Create actions and animations!</h3>
     <h4>Start Learning Javascript <em>now</em></h4>
   <button class="green-btn txt-marginall">Learn JavaScript!</button>
  </div>
</div>

<div class="box left">
   <div class="content">
  <h3>Learn how to construct the blocks of a website!</h3>
  <h4>Start Learning HTML5 <em>now</em></h4>
  <button class="blue-btn txt-marginall">Learn HTML5!</button>
</div>
   </div>
</div>


问:
Does shuffling happens before reduce function is called in the reducer task?
eg in a word count job,
I have 2 mappers Mapper A and Mapper B.

The output of mapper A is: {hi,1},{hello,1},{hey,1}

The output of mapper B is: {hi,1},{bye,1},{hey,1}

Suppose, there is no combiner and 1 reducer

then, first, shuffling happens

so, in shuffling the output of both the mappers merge and the resultant is:

```<code>{hi,[1,1]},{hello,1},{hey,[1,1]},{bye,1}
</code>```

then sorting happens:

```<code>{bye,1},{hello,1},{hey,[1,1]},{hi,[1,1]}
</code>```

then the reduce function in the reducer task is called which makes the o/p as:

```<code>bye,2
hello,1
hey,2
hi,2
</code>```

Is the above process correct? And does shuffling happens before reduce function is called? or the scheduler just accumulates data together from different mappers but do not group the data with the same key together and this process happens after sorting? Why is sorting useful here?

答:
Yes, shuffling (and sorting) are performed before the reduce method is called.

Note :
However, if you specify zero reducers (setNumReduceTasks(0)), then shuffling and sorting are not performed at all.

Body:
eg in a word count job,
I have 2 mappers Mapper A and Mapper B.

The output of mapper A is: {hi,1},{hello,1},{hey,1}

The output of mapper B is: {hi,1},{bye,1},{hey,1}

Suppose, there is no combiner and 1 reducer

then, first, shuffling happens

so, in shuffling the output of both the mappers merge and the resultant is:

{hi,[1,1]},{hello,1},{hey,[1,1]},{bye,1}

then sorting happens:

{bye,1},{hello,1},{hey,[1,1]},{hi,[1,1]}

then the reduce function in the reducer task is called which makes the o/p as:

bye,2
hello,1
hey,2
hi,2

Is the above process correct? And does shuffling happens before reduce function is called? or the scheduler just accumulates data together from different mappers but do not group the data with the same key together and this process happens after sorting? Why is sorting useful here?


问:
How to reverse a string in Go?
How can we reverse a simple string in Go?</p>

答:
I wrote the following Reverse function which respects UTF8 encoding and combined characters:

```<code>// Reverse reverses the input while respecting UTF8 encoding and combined characters
func Reverse(text string) string {
    textRunes := []rune(text)
    textRunesLength := len(textRunes)
    if textRunesLength <= 1 {
        return text
    }

    i, j := 0, 0
    for i < textRunesLength && j < textRunesLength {
        j = i + 1
        for j < textRunesLength && isMark(textRunes[j]) {
            j++
        }

        if isMark(textRunes[j-1]) {
            // Reverses Combined Characters
            reverse(textRunes[i:j], j-i)
        }

        i = j
    }

    // Reverses the entire array
    reverse(textRunes, textRunesLength)

    return string(textRunes)
}

func reverse(runes []rune, length int) {
    for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
}

// isMark determines whether the rune is a marker
func isMark(r rune) bool {
    return unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Me, r) || unicode.Is(unicode.Mc, r)
}
</code>```

I did my best to make it as efficient and readable as possible. The idea is simple, traverse through the runes looking for combined characters then reverse the combined characters' runes in-place. Once we have covered them all, reverse the runes of the entire string also in-place.

Say we would like to reverse this string bròwn. The ò is represented by two runes, one for the o and one for this unicode \u0301a that represents the "grave".

For simplicity, let's represent the string like this bro'wn. The first thing we do is look for combined characters and reverse them. So now we have the string br'own. Finally, we reverse the entire string and end up with nwo'rb. This is returned to us as nwòrb

You can find it here https://github.com/shomali11/util if you would like to use it.

Here are some test cases to show a couple of different scenarios:

```<code>func TestReverse(t *testing.T) {
    assert.Equal(t, Reverse(""), "")
    assert.Equal(t, Reverse("X"), "X")
    assert.Equal(t, Reverse("b\u0301"), "b\u0301")
    assert.Equal(t, Reverse("⚽"), "⚽")
    assert.Equal(t, Reverse("Les Mise\u0301rables"), "selbare\u0301siM seL")
    assert.Equal(t, Reverse("ab\u0301cde"), "edcb\u0301a")
    assert.Equal(t, Reverse("This `\xc5` is an invalid UTF8 character"), "retcarahc 8FTU dilavni na si `�` sihT")
    assert.Equal(t, Reverse("The quick bròwn 狐 jumped over the lazy 犬"), "犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT")
}
</code>```

Title: How to reverse a string in Go?

Body:
I wrote the following Reverse function which respects UTF8 encoding and combined characters:

// Reverse reverses the input while respecting UTF8 encoding and combined characters
func Reverse(text string) string {
    textRunes := []rune(text)
    textRunesLength := len(textRunes)
    if textRunesLength <= 1 {
        return text
    }

    i, j := 0, 0
    for i < textRunesLength && j < textRunesLength {
        j = i + 1
        for j < textRunesLength && isMark(textRunes[j]) {
            j++
        }

        if isMark(textRunes[j-1]) {
            // Reverses Combined Characters
            reverse(textRunes[i:j], j-i)
        }

        i = j
    }

    // Reverses the entire array
    reverse(textRunes, textRunesLength)

    return string(textRunes)
}

func reverse(runes []rune, length int) {
    for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
}

// isMark determines whether the rune is a marker
func isMark(r rune) bool {
    return unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Me, r) || unicode.Is(unicode.Mc, r)
}

I did my best to make it as efficient and readable as possible. The idea is simple, traverse through the runes looking for combined characters then reverse the combined characters' runes in-place. Once we have covered them all, reverse the runes of the entire string also in-place.

Say we would like to reverse this string bròwn. The ò is represented by two runes, one for the o and one for this unicode \u0301a that represents the "grave".

For simplicity, let's represent the string like this bro'wn. The first thing we do is look for combined characters and reverse them. So now we have the string br'own. Finally, we reverse the entire string and end up with nwo'rb. This is returned to us as nwòrb

You can find it here https://github.com/shomali11/util if you would like to use it.

Here are some test cases to show a couple of different scenarios:

func TestReverse(t *testing.T) {
    assert.Equal(t, Reverse(""), "")
    assert.Equal(t, Reverse("X"), "X")
    assert.Equal(t, Reverse("b\u0301"), "b\u0301")
    assert.Equal(t, Reverse("⚽"), "⚽")
    assert.Equal(t, Reverse("Les Mise\u0301rables"), "selbare\u0301siM seL")
    assert.Equal(t, Reverse("ab\u0301cde"), "edcb\u0301a")
    assert.Equal(t, Reverse("This `\xc5` is an invalid UTF8 character"), "retcarahc 8FTU dilavni na si `�` sihT")
    assert.Equal(t, Reverse("The quick bròwn 狐 jumped over the lazy 犬"), "犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT")
}


问:
Using static classes and overriding values
I am reading in a list of pets from a file, I have a simple text file and it has each attribute o a new line. It reads through my first pet perfect and uses my dictionary to create the pet. However when it clears the two lists it clears those details for the first created pet and as they get read in for the second pet they end up having matching traits and this goes on for all 8 of my pets. I know it's when I clear my lists it clears it for my previously created pet, however why does it not write over the name as well? I'm very new to OOP so please forgive me if I sound completely incompetent. </p>

```<code>public static List<Pet> LoadPetDetails(string filename)
    {
        RegisterPet("Sheep", typeof(Sheep));
        RegisterPet("Dog", typeof(Dog));
        RegisterPet("Cat", typeof(Cat));
        RegisterPet("Rabbit", typeof(Rabbit));

        StreamReader reader = new StreamReader(filename);
        string kind, name, id, breed, desc;
        int age;
        bool gender;
        petSize size;
        List<string> petTraits = new List<string>();
        List<string> require = new List<string>();
        List<Pet> loadedPets = new List<Pet>();

        try
        {
            //read in the count of how many pets in care currently
            int count = Convert.ToInt32(reader.ReadLine());

            //read in details for pet 1 through to we reach the count
            for (int j = 1; j <= count; j++)
            {
                //clear both of these list from the previous pet
                petTraits.Clear();
                require.Clear();

                //read in the kind
                kind = reader.ReadLine();
                //read in name
                name = reader.ReadLine();
                //read in id
                id = reader.ReadLine();
                //read in the pet traits
                for (int i = 0; i <= 2; i++)
                    petTraits.Add(reader.ReadLine());
                //read in pet breed
                breed = reader.ReadLine();
                //read in the pet's description
                desc = reader.ReadLine();
                //read in list of requirments
                for (int i = 0; i <= 1; i++)
                    require.Add(reader.ReadLine());
                //read in age
                age = Convert.ToInt32(reader.ReadLine());
                //read in size
                size = ConvertToPetSize(reader.ReadLine());
                //read in gender
                gender = Convert.ToBoolean(reader.ReadLine());

                //create the pet and add it to the list of pets to return
                loadedPets.Add(Pet.CreatePet(kind, name, id, petTraits, breed, desc, require, age, size, gender));
            }
        }
        finally
        {
            reader.Close();
        }
        return loadedPets;
    }
</code>```

答:
Somewhere in CreatePet you probably have some code like pet.Traits = petTraits;. You're passing a reference to the same list to all pets created by your function. There's 2 ways you can fix this, the easy way is to create a copy the list inside CreatePet() like pet.Traits = petTraits.ToList();

A better solution is to declare all of the temporary variables (kind, name, petTraits, etc.) inside your for loop. In C# you prefer to have variables that stick around for the shortest possible lifetime scope. Avoiding bugs like this is more important than some tiny performance edge from reusing variables.

Body:
I am reading in a list of pets from a file, I have a simple text file and it has each attribute o a new line. It reads through my first pet perfect and uses my dictionary to create the pet. However when it clears the two lists it clears those details for the first created pet and as they get read in for the second pet they end up having matching traits and this goes on for all 8 of my pets. I know it's when I clear my lists it clears it for my previously created pet, however why does it not write over the name as well? I'm very new to OOP so please forgive me if I sound completely incompetent.

public static List<Pet> LoadPetDetails(string filename)
    {
        RegisterPet("Sheep", typeof(Sheep));
        RegisterPet("Dog", typeof(Dog));
        RegisterPet("Cat", typeof(Cat));
        RegisterPet("Rabbit", typeof(Rabbit));

        StreamReader reader = new StreamReader(filename);
        string kind, name, id, breed, desc;
        int age;
        bool gender;
        petSize size;
        List<string> petTraits = new List<string>();
        List<string> require = new List<string>();
        List<Pet> loadedPets = new List<Pet>();

        try
        {
            //read in the count of how many pets in care currently
            int count = Convert.ToInt32(reader.ReadLine());

            //read in details for pet 1 through to we reach the count
            for (int j = 1; j <= count; j++)
            {
                //clear both of these list from the previous pet
                petTraits.Clear();
                require.Clear();

                //read in the kind
                kind = reader.ReadLine();
                //read in name
                name = reader.ReadLine();
                //read in id
                id = reader.ReadLine();
                //read in the pet traits
                for (int i = 0; i <= 2; i++)
                    petTraits.Add(reader.ReadLine());
                //read in pet breed
                breed = reader.ReadLine();
                //read in the pet's description
                desc = reader.ReadLine();
                //read in list of requirments
                for (int i = 0; i <= 1; i++)
                    require.Add(reader.ReadLine());
                //read in age
                age = Convert.ToInt32(reader.ReadLine());
                //read in size
                size = ConvertToPetSize(reader.ReadLine());
                //read in gender
                gender = Convert.ToBoolean(reader.ReadLine());

                //create the pet and add it to the list of pets to return
                loadedPets.Add(Pet.CreatePet(kind, name, id, petTraits, breed, desc, require, age, size, gender));
            }
        }
        finally
        {
            reader.Close();
        }
        return loadedPets;
    }


问:
How to use Bamboo plan variables in an inline script task?
When defining a Bamboo plan variable, the page has this.

For task configuration fields, use the syntax
  ${bamboo.myvariablename}. For inline scripts, variables are exposed as
  shell environment variables which can be accessed using the syntax
  $BAMBOO_MY_VARIABLE_NAME (Linux/Mac OS X) or %BAMBOO_MY_VARIABLE_NAME%
  (Windows).

However, that doesn't work in my Linux inline script. For example, I have the following defined a a plan variable

```<code>name: my_plan_var    value: some_string
</code>```

My inline script is simply...

```<code>PLAN_VAR=$BAMBOO_MY_PLAN_VAR
echo "Plan var: $PLAN_VAR"
</code>```

and I just get a blank string.

I've tried this

```<code>PLAN_VAR=${bamboo.my_plan_var}
</code>```

But I get

```<code>${bamboo.my_plan_var}: bad substitution
</code>```

on the log viewer window.

Any pointers?

答:
I tried the following and it works:

On the plan, I set my_plan_var to "it works" (w/o quotes)

In the inline script (don't forget the first line):

```<code>#/bin/sh

PLAN_VAR=$bamboo_my_plan_var
echo "testing: $PLAN_VAR"
</code>```

And I got the expected result:

testing: it works

Body:
When defining a Bamboo plan variable, the page has this.

For task configuration fields, use the syntax
  ${bamboo.myvariablename}. For inline scripts, variables are exposed as
  shell environment variables which can be accessed using the syntax
  $BAMBOO_MY_VARIABLE_NAME (Linux/Mac OS X) or %BAMBOO_MY_VARIABLE_NAME%
  (Windows).

However, that doesn't work in my Linux inline script. For example, I have the following defined a a plan variable

name: my_plan_var    value: some_string

My inline script is simply...

PLAN_VAR=$BAMBOO_MY_PLAN_VAR
echo "Plan var: $PLAN_VAR"

and I just get a blank string.

I've tried this

PLAN_VAR=${bamboo.my_plan_var}

But I get

${bamboo.my_plan_var}: bad substitution

on the log viewer window.

Any pointers?

Body:
I tried the following and it works:

On the plan, I set my_plan_var to "it works" (w/o quotes)

In the inline script (don't forget the first line):

#/bin/sh

PLAN_VAR=$bamboo_my_plan_var
echo "testing: $PLAN_VAR"

And I got the expected result:

testing: it works


问:
TypeError: unhashable type: 'list' when use groupby in python
There is something wrong when I use groupby method:

```<code>data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))
keys = lambda x: [x.year,x.month]
data.groupby(keys).mean()
</code>```

but it has an error: TypeError: unhashable type: 'list'.
I want group by year and month, then calculate the means,why it has wrong?

答:
list object cannot be used as key because it's not hashable. You can use tuple object instead:

```<code>>>> {[1, 2]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1, 2): 3}
{(1, 2): 3}
</code>```

```<code>data = pd.Series(np.random.randn(100), index=pd.date_range('01/01/2001', periods=100))
keys = lambda x: (x.year,x.month)  # <----
data.groupby(keys).mean()
</code>```

Body:
There is something wrong when I use groupby method:

data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))
keys = lambda x: [x.year,x.month]
data.groupby(keys).mean()

but it has an error: TypeError: unhashable type: 'list'.
I want group by year and month, then calculate the means,why it has wrong?

Body:
list object cannot be used as key because it's not hashable. You can use tuple object instead:

>>> {[1, 2]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1, 2): 3}
{(1, 2): 3}

data = pd.Series(np.random.randn(100), index=pd.date_range('01/01/2001', periods=100))
keys = lambda x: (x.year,x.month)  # <----
data.groupby(keys).mean()


问:
RxJava and parallel execution of observer code
I am having the following code using RxJava Observable api :

```<code>Observable<Info> observable = fileProcessor.processFileObservable(processedFile.getAbsolutePath());
    observable
      .buffer(10000)
      .observeOn(Schedulers.computation())
      .subscribe(recordInfo -> {
        _logger.info("Running stage2 on thread with id : " + Thread.currentThread().getId());
          for(Info info : recordInfo) {
            // some I/O operation logic
         }
      },
      exception -> {
      },
      () -> {
      });
</code>```

My expectation was that the observation code i.e. code inside the subscribe() method will be executed in parallel after I have specified the computation scheduler. Instead the code is still being executed sequentially on single thread. How can make the code run in parallel using RxJava api.

答:
Using flatMap and specify to subscribe on Schedulers.computation() will achieve concurrency.

Here is a more practical example using Callable, from the output, we can see it will take about 2000 milliseconds to finish all the tasks.

```<code>static class MyCallable implements Callable<Integer> {

    private static final Object CALLABLE_COUNT_LOCK = new Object();
    private static int callableCount;

    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        synchronized (CALLABLE_COUNT_LOCK) {
            return callableCount++;
        }
    }

    public static int getCallableCount() {
        synchronized (CALLABLE_COUNT_LOCK) {
            return callableCount;
        }
    }
}

private static void runMyCallableConcurrentlyWithRxJava() {
    long startTimeMillis = System.currentTimeMillis();

    final Semaphore semaphore = new Semaphore(1);
    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Observable.just(new MyCallable(), new MyCallable(), new MyCallable(), new MyCallable())
            .flatMap(new Function<MyCallable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(@NonNull MyCallable myCallable) throws Exception {
                    return Observable.fromCallable(myCallable).subscribeOn(Schedulers.computation());
                }
            })
            .subscribeOn(Schedulers.computation())
            .subscribe(new Observer<Object>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull Object o) {
                    System.out.println("onNext " + o);
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {
                    if (MyCallable.getCallableCount() >= 4) {
                        semaphore.release();
                    }
                }
            });

    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        semaphore.release();
    }
    System.out.println("durationMillis " + (System.currentTimeMillis()-startTimeMillis));
}
</code>```

Body:
I am having the following code using RxJava Observable api :

Observable<Info> observable = fileProcessor.processFileObservable(processedFile.getAbsolutePath());
    observable
      .buffer(10000)
      .observeOn(Schedulers.computation())
      .subscribe(recordInfo -> {
        _logger.info("Running stage2 on thread with id : " + Thread.currentThread().getId());
          for(Info info : recordInfo) {
            // some I/O operation logic
         }
      },
      exception -> {
      },
      () -> {
      });

My expectation was that the observation code i.e. code inside the subscribe() method will be executed in parallel after I have specified the computation scheduler. Instead the code is still being executed sequentially on single thread. How can make the code run in parallel using RxJava api.

Body:
Using flatMap and specify to subscribe on Schedulers.computation() will achieve concurrency.

Here is a more practical example using Callable, from the output, we can see it will take about 2000 milliseconds to finish all the tasks.

static class MyCallable implements Callable<Integer> {

    private static final Object CALLABLE_COUNT_LOCK = new Object();
    private static int callableCount;

    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        synchronized (CALLABLE_COUNT_LOCK) {
            return callableCount++;
        }
    }

    public static int getCallableCount() {
        synchronized (CALLABLE_COUNT_LOCK) {
            return callableCount;
        }
    }
}

private static void runMyCallableConcurrentlyWithRxJava() {
    long startTimeMillis = System.currentTimeMillis();

    final Semaphore semaphore = new Semaphore(1);
    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Observable.just(new MyCallable(), new MyCallable(), new MyCallable(), new MyCallable())
            .flatMap(new Function<MyCallable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(@NonNull MyCallable myCallable) throws Exception {
                    return Observable.fromCallable(myCallable).subscribeOn(Schedulers.computation());
                }
            })
            .subscribeOn(Schedulers.computation())
            .subscribe(new Observer<Object>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull Object o) {
                    System.out.println("onNext " + o);
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {
                    if (MyCallable.getCallableCount() >= 4) {
                        semaphore.release();
                    }
                }
            });

    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        semaphore.release();
    }
    System.out.println("durationMillis " + (System.currentTimeMillis()-startTimeMillis));
}


问:
Plyer Example Applications break down on a real device
I tried to deploy some of plyer examples on a real device (android 6) using buildozer. At first I tried camera example, but app breaks down when I tried take a picture with following error:

```<code>DEBUG : Abort message: 'art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: static jfieldID 0xb052a4b0 not valid for class java.lang.Class<org.renpy.android.PythonActivity>'
DEBUG : r0 00000000 r1 00000c03 r2 00000006 r3 a0fa9978 DEBUG : r4 a0fa9980 r5 a0fa9930 r6 0000000b r7 0000010c
DEBUG : r8 b4b3f378 r9 b4d2a800 sl 00000001 fp 00000001 DEBUG : ip 00000006 sp a0fa3200 lr b6d16c41 pc b6d19030 cpsr 40070010 DEBUG : DEBUG : backtrace:
DEBUG : #00 pc 00042030 /system/lib/libc.so (tgkill+12)
DEBUG : #01 pc 0003fc3d /system/lib/libc.so (pthread_kill+32) DEBUG : #02 pc 0001c3db /system/lib/libc.so (raise+10)
DEBUG : #03 pc 0001958d /system/lib/libc.so (__libc_android_abort+34) DEBUG : #04 pc 000174e0 /system/lib/libc.so (abort+4) DEBUG : #05 pc 00333a39 /system/lib/libart.so (_ZN3art7Runtime5AbortEv+228)
DEBUG : #06 pc 000f464b /system/lib/libart.so (_ZN3art10LogMessageD2Ev+2226)
DEBUG : #07 pc 0025aa9f /system/lib/libart.so (_ZN3art9JavaVMExt8JniAbortEPKcS2_+1550)
DEBUG : #08 pc 0025ae4d /system/lib/libart.so (_ZN3art9JavaVMExt9JniAbortVEPKcS2_St9__va_list+64)
DEBUG : #09 pc 000fd221 /system/lib/libart.so (_ZN3art11ScopedCheck6AbortFEPKcz+32) 05-30 22:32:28.979 346 346 F
DEBUG : #10 pc 00114b01 /system/lib/libart.so (_ZN3art11ScopedCheck16CheckFieldAccessERNS_18ScopedObjectAccessEP8_jobjectP9_jfieldIDbNS_9Primitive4TypeE+452) 05-30 22:32:28.979 346 346 F
DEBUG : #11 pc 00116525 /system/lib/libart.so (_ZN3art8CheckJNI8GetFieldEPKcP7_JNIEnvP8_jobjectP9_jfieldIDbNS_9Primitive4TypeE+524) 05-30 22:32:28.979 346 346 F DEBUG : #12 pc 00116abf /system/lib/libart.so (_ZN3art8CheckJNI20GetStaticObjectFieldEP7_JNIEnvP7_jclassP9_jfieldID+30) 05-30 22:32:28.979 346 346 F DEBUG : #13 pc 00027357 /data/data/test.com.cameraexample/files/app/lib/python2.7/site-packages/jnius/jnius.so
</code>```

It hapends with all plyer examples.
I use:
kivy==1.10.0
plyer==1.3.0

Can someone help me with it? I would be very grateful, Thanks!

答:
Are you using the SDL toolchain?  It could be related to https://github.com/kivy/plyer/issues/245.  It looks like they may have fixed in it April (though they haven't indicated that, and I haven't checked).  Try updating plyer; it looks like they're on 1.3.1 now.

Edit:
I tried the latest version, and it didn't seem to fix the issue I'm referring to.  However, if you want a quick test to see if you're running into this problem, here's a quick hack:

```<code>@wrapt.patch_function_wrapper('jnius', 'autoclass')
def hack_autoclass(wrapped, instance, args, kwargs):
    if args[0] == 'org.renpy.android.PythonActivity':
        return wrapped('org.kivy.android.PythonActivity',
                       *args[1:], **kwargs)
    else:
        return wrapped(*args, **kwargs)
</code>```

This depends on the wrapt module (available on pypi) for monkey patching, but it shouldn't be too hard to monkey patch it yourself if you don't want to bother messing with the dependency (this is just the hack that I've tested personally).

Note that you'll want to call this code as early as possible.

Body:
I tried to deploy some of plyer examples on a real device (android 6) using buildozer. At first I tried camera example, but app breaks down when I tried take a picture with following error:

DEBUG : Abort message: 'art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: static jfieldID 0xb052a4b0 not valid for class java.lang.Class<org.renpy.android.PythonActivity>'
DEBUG : r0 00000000 r1 00000c03 r2 00000006 r3 a0fa9978 DEBUG : r4 a0fa9980 r5 a0fa9930 r6 0000000b r7 0000010c
DEBUG : r8 b4b3f378 r9 b4d2a800 sl 00000001 fp 00000001 DEBUG : ip 00000006 sp a0fa3200 lr b6d16c41 pc b6d19030 cpsr 40070010 DEBUG : DEBUG : backtrace:
DEBUG : #00 pc 00042030 /system/lib/libc.so (tgkill+12)
DEBUG : #01 pc 0003fc3d /system/lib/libc.so (pthread_kill+32) DEBUG : #02 pc 0001c3db /system/lib/libc.so (raise+10)
DEBUG : #03 pc 0001958d /system/lib/libc.so (__libc_android_abort+34) DEBUG : #04 pc 000174e0 /system/lib/libc.so (abort+4) DEBUG : #05 pc 00333a39 /system/lib/libart.so (_ZN3art7Runtime5AbortEv+228)
DEBUG : #06 pc 000f464b /system/lib/libart.so (_ZN3art10LogMessageD2Ev+2226)
DEBUG : #07 pc 0025aa9f /system/lib/libart.so (_ZN3art9JavaVMExt8JniAbortEPKcS2_+1550)
DEBUG : #08 pc 0025ae4d /system/lib/libart.so (_ZN3art9JavaVMExt9JniAbortVEPKcS2_St9__va_list+64)
DEBUG : #09 pc 000fd221 /system/lib/libart.so (_ZN3art11ScopedCheck6AbortFEPKcz+32) 05-30 22:32:28.979 346 346 F
DEBUG : #10 pc 00114b01 /system/lib/libart.so (_ZN3art11ScopedCheck16CheckFieldAccessERNS_18ScopedObjectAccessEP8_jobjectP9_jfieldIDbNS_9Primitive4TypeE+452) 05-30 22:32:28.979 346 346 F
DEBUG : #11 pc 00116525 /system/lib/libart.so (_ZN3art8CheckJNI8GetFieldEPKcP7_JNIEnvP8_jobjectP9_jfieldIDbNS_9Primitive4TypeE+524) 05-30 22:32:28.979 346 346 F DEBUG : #12 pc 00116abf /system/lib/libart.so (_ZN3art8CheckJNI20GetStaticObjectFieldEP7_JNIEnvP7_jclassP9_jfieldID+30) 05-30 22:32:28.979 346 346 F DEBUG : #13 pc 00027357 /data/data/test.com.cameraexample/files/app/lib/python2.7/site-packages/jnius/jnius.so

It hapends with all plyer examples.
I use:
kivy==1.10.0
plyer==1.3.0

Can someone help me with it? I would be very grateful, Thanks!

Body:
Are you using the SDL toolchain?  It could be related to https://github.com/kivy/plyer/issues/245.  It looks like they may have fixed in it April (though they haven't indicated that, and I haven't checked).  Try updating plyer; it looks like they're on 1.3.1 now.

Edit:
I tried the latest version, and it didn't seem to fix the issue I'm referring to.  However, if you want a quick test to see if you're running into this problem, here's a quick hack:

@wrapt.patch_function_wrapper('jnius', 'autoclass')
def hack_autoclass(wrapped, instance, args, kwargs):
    if args[0] == 'org.renpy.android.PythonActivity':
        return wrapped('org.kivy.android.PythonActivity',
                       *args[1:], **kwargs)
    else:
        return wrapped(*args, **kwargs)

This depends on the wrapt module (available on pypi) for monkey patching, but it shouldn't be too hard to monkey patch it yourself if you don't want to bother messing with the dependency (this is just the hack that I've tested personally).

Note that you'll want to call this code as early as possible.


问:
VSCode: opening a folder and a file from the same routine
What would be the right way of opening a folder and a file from an extension as a part of the same operation?

Seems like a simple task but I spent quite some time and cannot solve it.
I can easily do one or another but not both as a single operation.

```<code>commands.executeCommand('vscode.openFolder',
                        Uri.parse('E:\\dev\\proj'))
        .then(() => commands.executeCommand('vscode.open',
                                            Uri.file('E:\\dev\\files\\file.json'));
</code>```

The code above opens a folder but not the file. From the debugger I see that vscode.open command is triggered but file is not opened. And having 'vscode.open`only opens the file as expected.

It seems like after opening folder the whole execution context is gone.

I did this brutal experiment:

```<code>setTimeout(() => commands.executeCommand('vscode.open',
                                          Uri.file('E:\\dev\\files\\file.json'), 3000);
commands.executeCommand('vscode.openFolder',
                        Uri.parse('E:\\dev\\proj'))
</code>```

And it reviled that setTimeout's callback is never called if the vscode.openFolder is invoked.

Will appreciate any help/hint.

答:
I found the cause of the problem. But not the solution.

Apparently opening folder completely terminates the execution context. This is what the VSCode documentation says:

Note that opening in the same window will shutdown the current extension host process and start a new one on the given folder unless the newWindow parameter is set to true.

Thus currently seems to be no way of opening in the current window a folder with a specific file opened and active.

Body:
What would be the right way of opening a folder and a file from an extension as a part of the same operation?

Seems like a simple task but I spent quite some time and cannot solve it.
I can easily do one or another but not both as a single operation.

commands.executeCommand('vscode.openFolder',
                        Uri.parse('E:\\dev\\proj'))
        .then(() => commands.executeCommand('vscode.open',
                                            Uri.file('E:\\dev\\files\\file.json'));

The code above opens a folder but not the file. From the debugger I see that vscode.open command is triggered but file is not opened. And having 'vscode.open`only opens the file as expected.

It seems like after opening folder the whole execution context is gone.

I did this brutal experiment:

setTimeout(() => commands.executeCommand('vscode.open',
                                          Uri.file('E:\\dev\\files\\file.json'), 3000);
commands.executeCommand('vscode.openFolder',
                        Uri.parse('E:\\dev\\proj'))

And it reviled that setTimeout's callback is never called if the vscode.openFolder is invoked.

Will appreciate any help/hint.


问:
Close a running program from java application
I open up an external application from my java application. How can I close this application from the same Java application?
thanks</p>

答:
Why don't you have a batch (Windows) or script (*nix) file that start and stops that application, and then run your runtime.exec with the parameter start/stop?

UPDATE:

This may help: http://it.toolbox.com/blogs/database-solutions/kill-a-process-in-windows-bat-19875

Second Update

You can also search by exe name using: 'tasklist ^| findstr /i excel.exe'


问:
Is performing .ToList() more than once is a bad idea?
I've written the below function to query the SQLite DB in my Xamarin forms app. But, since I have to call .ToList() twice, I'm not very confident about it. Is this bad code? Any feedback will be highly appreciated.

```<code>public static List<string> GetAllLocationIds()
    {
        try
        {
            lock (CollisionLock)
            {
               //TableQuery<TResult> First .ToList() result
               //List<string> Second .ToList() result
                return Database.Table<Location>().ToList().Select(loc=>loc.LocationId).ToList();
            }
        }
        catch (Exception ex)
        {
            Insights.Report(ex);
            return null;
        }
    }
</code>```

Performing .Select directly on  Database.Table<Location>() results in the following exception.`

```<code>System.MissingMethodException: Default constructor not found for type
System.String at System.RuntimeType.CreateInstanceMono`
</code>```

答:
Yes it is.

On

```<code>Database.Table<Location>().ToList()
</code>```

You are materializing all of Table Location. Then you are only selecting the LocationId in Memory.

Instead use:

```<code>Database.Table<Location>().Select(loc=>loc.LocationId).ToList();
</code>```

Which is working directly on IQueryable<Location> and only materializes the LocationId. Assuming Table<Location> is IQueryable<Location>.

Body:
I've written the below function to query the SQLite DB in my Xamarin forms app. But, since I have to call .ToList() twice, I'm not very confident about it. Is this bad code? Any feedback will be highly appreciated.

public static List<string> GetAllLocationIds()
    {
        try
        {
            lock (CollisionLock)
            {
               //TableQuery<TResult> First .ToList() result
               //List<string> Second .ToList() result
                return Database.Table<Location>().ToList().Select(loc=>loc.LocationId).ToList();
            }
        }
        catch (Exception ex)
        {
            Insights.Report(ex);
            return null;
        }
    }

Performing .Select directly on  Database.Table<Location>() results in the following exception.`

System.MissingMethodException: Default constructor not found for type
System.String at System.RuntimeType.CreateInstanceMono`

Body:
Yes it is.

On

Database.Table<Location>().ToList()

You are materializing all of Table Location. Then you are only selecting the LocationId in Memory.

Instead use:

Database.Table<Location>().Select(loc=>loc.LocationId).ToList();

Which is working directly on IQueryable<Location> and only materializes the LocationId. Assuming Table<Location> is IQueryable<Location>.


问:
Difference in allocating char type and int type in C++
I have a class foo like this:

```<code>class foo
{
private:
    int* a;
public:
    foo()
    {
        a = new int[4];
        cout << "a" << endl;
    }
};
</code>```

When I create new object named foo1 and then I debug, after the allocating line, it yields the result:
 a   0x005a4580 {-842150451}.

But when I replace all int-s by char-s in class definition, it yields an undesired result:

```<code>a   0x005694a0 "ÍÍÍÍýýýý\x6ŒÒ•\x5Ÿ"
</code>```

that the size of a is now greater than 4.

I dont know what happened. Could you please give me an explanation?

Full code:

```<code>#include <iostream>
#include <string>
using namespace std;

class String
{
public:
    String(char* data)
    {
        setSize(0);
        while (*(data + size) != '\0')
            size++;
        this->data = new char[size];
        //need to allocate memory for 'data' pointer because 'data' pointer is now on the stack and the data must be on the heap
        memcpy(this->data, data, size * sizeof(char));
    }
    void operator=(String rhs)
    {
        if (this->data != NULL)
            delete[] this->data, data = NULL;
        this->data = new char[rhs.getSize()]; //allocate
        memcpy(this->data, data, size * sizeof(char));
    }
    int getSize()
    {
        setSize(0);
        while (*(data + size))
            size++;
        return size;
    }
    void setSize(int size)
    {
        this->size = size;
    }
    void display()
    {
        for (int i = 0; i < size; i++)
            cout << *(data + i);
    }
    ~String()
    {
        if (data != NULL)
            delete[] data, data = NULL;
    }
private:
    char* data;
    int size;
};

void main()
{
    String a("abcd");
    String b("1");
    a.display();
    cout << endl;
    cout << b.getSize() << endl;
    a = b;
    cout << a.getSize() << endl;
    system("pause");
}
</code>```

答:
Whatever you're using to look at a doesn't know how much you allocated. It just knows the type.

In the first version it sees int *, so it shows a single int.

In the second version it sees char *, so it assumes it's a C string and prints whatever is in memory up to the first '\0' byte.

Body:
I have a class foo like this:

class foo
{
private:
    int* a;
public:
    foo()
    {
        a = new int[4];
        cout << "a" << endl;
    }
};

When I create new object named foo1 and then I debug, after the allocating line, it yields the result:
 a   0x005a4580 {-842150451}.

But when I replace all int-s by char-s in class definition, it yields an undesired result:

a   0x005694a0 "ÍÍÍÍýýýý\x6ŒÒ•\x5Ÿ"

that the size of a is now greater than 4.

I dont know what happened. Could you please give me an explanation?

Full code:

#include <iostream>
#include <string>
using namespace std;

class String
{
public:
    String(char* data)
    {
        setSize(0);
        while (*(data + size) != '\0')
            size++;
        this->data = new char[size];
        //need to allocate memory for 'data' pointer because 'data' pointer is now on the stack and the data must be on the heap
        memcpy(this->data, data, size * sizeof(char));
    }
    void operator=(String rhs)
    {
        if (this->data != NULL)
            delete[] this->data, data = NULL;
        this->data = new char[rhs.getSize()]; //allocate
        memcpy(this->data, data, size * sizeof(char));
    }
    int getSize()
    {
        setSize(0);
        while (*(data + size))
            size++;
        return size;
    }
    void setSize(int size)
    {
        this->size = size;
    }
    void display()
    {
        for (int i = 0; i < size; i++)
            cout << *(data + i);
    }
    ~String()
    {
        if (data != NULL)
            delete[] data, data = NULL;
    }
private:
    char* data;
    int size;
};

void main()
{
    String a("abcd");
    String b("1");
    a.display();
    cout << endl;
    cout << b.getSize() << endl;
    a = b;
    cout << a.getSize() << endl;
    system("pause");
}


问:
ajax post data not working on shared hosting
I'm very confuse for this problem ajax post data, on localhost working but on shared hosting not working. This is my code

```<code><script type="text/javascript">
        $(document).ready(function(){
            $("#login").click(function(){
              alert('asdf');
                var page = "login";
                var username = $("#username").val().trim();
                var password = $("#password").val().trim();
                $.ajax({
                        url:'pages/content/input_query.php',
                        type:'post',
                        data:{page:page,username:username,password:password},
                        success:function(response){
                            var msg = "";
                            if(response ==1){
                                window.location = "index.php?pages=home";
                            }else{
                                $("#result").html(response);
                            }
                         }
                    });

            });

        });
</code>```

and my code html is

```<code> <form role="form" action="pages/content/input_query.php" method="post">
      <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder="username" id="username" />
        <span class="glyphicon glyphicon-user form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder="Password" id="password" />
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="row">
        <div class="col-xs-8">
          <div class="checkbox icheck">

          </div>
        </div><!-- /.col -->
        <div class="col-xs-4">
          <button type="button" class="btn btn-primary btn-block btn-flat" id="login">Sign In</button>
        </div><!-- /.col -->
      </div>
    </form>
</code>```

And I have add code alert('asdf') , but there are no alert message  every click the button. What is the problem. Please help me. Every answer I appricated

答:
Try preventing the default action of the #login element and when you pass the POST type, you must use uppercases. Something like:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $("#login").click(function(event){
          event.preventDefault();
          alert('asdf');
            var page = "login";
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $.ajax({
                    url:'pages/content/input_query.php',
                    type:'POST',
                    data:{page:page,username:username,password:password},
                    success:function(response){
                        var msg = "";
                        if(response ==1){
                            window.location = "index.php?pages=home";
                        }else{
                            $("#result").html(response);
                        }
                     }
                });
        });
    });
</code>```

Body:
Try preventing the default action of the #login element and when you pass the POST type, you must use uppercases. Something like:

<script type="text/javascript">
    $(document).ready(function(){
        $("#login").click(function(event){
          event.preventDefault();
          alert('asdf');
            var page = "login";
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $.ajax({
                    url:'pages/content/input_query.php',
                    type:'POST',
                    data:{page:page,username:username,password:password},
                    success:function(response){
                        var msg = "";
                        if(response ==1){
                            window.location = "index.php?pages=home";
                        }else{
                            $("#result").html(response);
                        }
                     }
                });
        });
    });


问:
How to get max and min values of an Array of Tuples
Say I have a List of Tuples of Integers

```<code>var i = Array(1->3, 5->9, 15->18)
</code>```

How can I return a Tuple of the highest and lowest values from the above?

So for the above input, 1-> 18 should be returned as 1 is the lowest and 18 is the highest value. Here's the skeleton of the function that takes an Array of Tuples and returns the highest & the lowest values as a Tuple.

```<code>    def returnHighest(i: Array[(Int, Int)]): (Int, Int)={

      ....

  }
</code>```

答:
Lot's of ways to do this of course. Here is one:</p>

```<code>val i = Array(1->3, 5->9, 15->18)
i: Array[(Int, Int)] = Array((1,3), (5,9), (15,18))

scala> val flatI = i.flatMap{case(a,b) => List(a, b)}
flatI: Array[Int] = Array(1, 3, 5, 9, 15, 18)

scala> flatI.min -> flatI.max
res3: (Int, Int) = (1,18)
</code>```

Body:
Say I have a List of Tuples of Integers

var i = Array(1->3, 5->9, 15->18)

How can I return a Tuple of the highest and lowest values from the above?

So for the above input, 1-> 18 should be returned as 1 is the lowest and 18 is the highest value. Here's the skeleton of the function that takes an Array of Tuples and returns the highest & the lowest values as a Tuple.

    def returnHighest(i: Array[(Int, Int)]): (Int, Int)={

      ....

  }

Body:
Lot's of ways to do this of course. Here is one:

val i = Array(1->3, 5->9, 15->18)
i: Array[(Int, Int)] = Array((1,3), (5,9), (15,18))

scala> val flatI = i.flatMap{case(a,b) => List(a, b)}
flatI: Array[Int] = Array(1, 3, 5, 9, 15, 18)

scala> flatI.min -> flatI.max
res3: (Int, Int) = (1,18)