问:
yii2 transaction doesn't rollback
I am trying to implement transaction in my code. but even after validation fail of one of the model ($timesheet model) transaction doesn't rollback.
Below is my code:

```<code>public function actionCreate() {
    $model = new Timesheet();
    $subscriber = null;
    // get current subscriber id.
    $subscriber_id = General::getSubscriberIdByUserId(\Yii::$app->user->id);
    if ($subscriber_id > 0) {
        $subscriber = Subscriber::findOne($subscriber_id);
        if ($subscriber) {
            $model->subscriber_id = $subscriber->id;
            $model->subscriber_name = $subscriber->name;
        }
    }

    if ($model->load(Yii::$app->request->post())) {

        //Transaction starts here
        $transaction = Yii::$app->db->beginTransaction();
        try
        {
            if (!empty($model->date)) {
                $model->date = General::convertDDMMYYYYToMysqlCompliant($model->date);
                $model->user_id = \Yii::$app->user->id;
            }

            // to find total hours of the day already logged
            $total_daily_hours = (Timesheet::find()->where(['user_id' => Yii::$app->user->id])->andWhere(['date' => $model->date])->sum('hours'));

            $model->hours = ($model->hours + $model->minute);
            $dayofweek = date('w', strtotime($model->date));
            if($dayofweek == 6)
            {
                $monday = date('Y-m-d', strtotime('last monday', strtotime($model->date)));
            }
            else
            {
                $monday = date('Y-m-d', strtotime('this monday', strtotime($model->date)));
            }
            $saturday = date('Y-m-d', strtotime('this saturday', strtotime($model->date)));

            // to find total hours of the week already logged
            $team_member_weekly_hours = Timesheet::find()->where(['user_id' => \Yii::$app->user->id])->andWhere(['between', 'date', $monday, $saturday])->sum('hours');

            $role = \Yii::$app->authManager->getRolesByUser(\Yii::$app->user->id);

            if(array_key_exists('intern', $role) == false)
            {
                $TEAM_MEMBER_WEEK_LIMIT = 48;
            }
            else
            {
                $TEAM_MEMBER_WEEK_LIMIT = Timesheet::TEAM_MEMBER_WEEK_LIMIT;
            }

            if ((
                    (Timesheet::PER_DAY_HOURS_LIMIT) >= ($total_daily_hours + $model->hours)
                    || ((Timesheet::PER_DAY_HOURS_LIMIT) >= ($total_daily_hours + $model->hours)
                        && (array_key_exists('team-member', $role)))
                )
                && (Timesheet::blockMonthEntry($model->date) == true)
                && ($TEAM_MEMBER_WEEK_LIMIT >= $team_member_weekly_hours + $model->hours)
                && ($model->hours != 0))
            {
                // get user hourly rate
                $usertohourlyrate = UserToHourlyRate::getHourlyRateByUserId($model->user_id);
                $model->total_amount = $usertohourlyrate * $model->hours;
                $model->hourly_rate = $usertohourlyrate;

                // echo "```";var_dump($model);die;

                if($model->save())
                {
                    $model_id = $model->id;
                }
                // echo "$model_id";

                //For Notification
                $userToNotify = [];
                $user_id = \Yii::$app->user->id;
                $userForNotify = UserToSubscriber::find()->select('senior_user_id')->where(['user_id'=>$user_id])->all();

                if($userForNotify != NULL)
                {
                    $userToNotify = [];
                    foreach($userForNotify as $ufn){
                        array_push($userToNotify,$ufn->senior_user_id);
                    }

                    foreach($userToNotify as $value)
                    {
                        $noticemodel = new Notifications();
                        $noticemodel->user_id = $value;
                        $noticemodel->relation_name = 'timesheet';
                        $noticemodel->relation_id = $model->id;
                        $noticemodel->notice_abstract = "Timesheet Created Notification.";
                        $noticemodel->action = '0';
                        $noticemodel->created_on = date('Y-m-d h:i:s');
                        $noticemodel->save();
                    }
                }
                //

                if (General::ifUserPermitted('timesheetAutoTimesheetApproval')) {
                    // echo "in if";
                    // timesheet auto approval
                    // WIP update
                    General::onTimesheetChange($model->job_id, $model->user_id, $model->date, "timesheet");
                    //For update timesheet model
                    $timesheet_model = Timesheet::findOne($model_id);
                    echo "```";var_dump($timesheet_model);//die;
                    $timesheet_model->action_taken_at = date("Y-m-d h:m:s");
                    $timesheet_model->action_taken_by = \Yii::$app->user->id;
                    $timesheet_model->status = "Approved";
                    echo "```";var_dump($timesheet_model);
                    $timesheet_model->save();
                    if($timesheet_model->save())
                    {
                        echo "True";
                    }
                    else
                    {
                        echo "False";
                        $errors = $timesheet_model->errors;
                        echo "```";var_dump($errors);
                    }
                    //For Notification
                    if($userForNotify != NULL)
                    {
                        $userToNotify = [];
                        foreach($userForNotify as $ufn){
                            array_push($userToNotify,$ufn->senior_user_id);
                        }

                        foreach($userToNotify as $value)
                        {
                            $notification = Notifications::find()->where(['user_id'=>$value , 'relation_id'=>$model->id, 'notice_abstract'=>'Timesheet Created Notification.'])->one();
                            if($notification != NULL)
                            {
                                $notification->action = '1';
                                $notification->save();
                            }
                        }
                    }
                    //
                }
                if (array_key_exists('team-member', $role)) {
                    $msg = "Entry Inserted Successfully and Your remaining weekly hours is <b>" . ((Timesheet::TEAM_MEMBER_WEEK_LIMIT) - ($team_member_weekly_hours + $model->hours)) . " hrs.</b>";
                } else {
                    $msg = "Entry Inserted Successfully and Your remaining hours is <b>" . ((Timesheet::PER_DAY_HOURS_LIMIT) - ($totel_hours + $model->hours)) . " hrs.</b>";
                }
                \Yii::$app->session->setFlash('success', $msg);

                $transaction->commit();

                return $this->redirect(['view', 'id' => $model->id]);

            }
            elseif (Timesheet::blockMonthEntry($model->date) != true) {
                $msg = "This date has been blocked";
            }elseif ($totel_hours == (Timesheet::PER_DAY_HOURS_LIMIT) || $team_member_weekly_hours == (Timesheet::TEAM_MEMBER_WEEK_LIMIT)) {
                $msg = "Your Daily hours is over";
            } elseif (($totel_hours + $model->hours) > Timesheet::PER_DAY_HOURS_LIMIT) {
                $msg = "Your remaining daily hours only is <b>" . ((Timesheet::PER_DAY_HOURS_LIMIT) - $totel_hours) . " hrs.</b>";
            } elseif ($model->hours == 0) {
                $msg = "Please select hours";
            } else {
                $msg = "Your remaining Weekly hours only is <b>" . ((Timesheet::TEAM_MEMBER_WEEK_LIMIT) - $team_member_weekly_hours) . " hrs.</b>";
            }
            \Yii::$app->session->setFlash('error', $msg);
            list($model->hours, $minute) = explode('.', $model->hours);
            $model->minute = "0." . $minute;

            if(empty($model->date)){
                $model->date = date('j/n/Y');
            }else{
                $model->date = General::convertMysqlDateToDDMMYYYY($model->date);
            }
            return $this->render('create', [
                        'model' => $model,
                        'master_mode' => Yii::$app->user->can('associateSubscriberWithDetails'),
            ]);
        }
        catch(Exception $e)
        {
            \Yii::$app->session->setFlash('error', $e);
            $transaction->rollBack();
        }
        //Transaction ends here
    }
    else
    {
        if(empty($model->date)){
            $model->date = date('j/n/Y');
        }else{
            $model->date = General::convertMysqlDateToDDMMYYYY($model->date);
        }

        return $this->render('create', [
                    'model' => $model,
                    'master_mode' => Yii::$app->user->can('associateSubscriberWithDetails'),
        ]);
    }
}
</code>```

What should I do? where to amend the code?
$timesheet model is failing while updating the model but model saved before it is not rolled back.

I want to rollback all save() if any one of the model save() fails.

答:
Yii save() not throw an exception when the execution of this method fails (for an Exception). Thus you have to check the result of save() and throw an Exception in case of fail.

When you use a save() in your try{}catch(Exception $e){} statement use as here:

```<code>if (!$model->save()) {
   throw new Exception("Trigger transaction rollback");
} else {
    // something
}
</code>```

Title: yii2 transaction doesn't rollback

Body:
I am trying to implement transaction in my code. but even after validation fail of one of the model ($timesheet model) transaction doesn't rollback.
Below is my code:

public function actionCreate() {
    $model = new Timesheet();
    $subscriber = null;
    // get current subscriber id.
    $subscriber_id = General::getSubscriberIdByUserId(\Yii::$app->user->id);
    if ($subscriber_id > 0) {
        $subscriber = Subscriber::findOne($subscriber_id);
        if ($subscriber) {
            $model->subscriber_id = $subscriber->id;
            $model->subscriber_name = $subscriber->name;
        }
    }

    if ($model->load(Yii::$app->request->post())) {

        //Transaction starts here
        $transaction = Yii::$app->db->beginTransaction();
        try
        {
            if (!empty($model->date)) {
                $model->date = General::convertDDMMYYYYToMysqlCompliant($model->date);
                $model->user_id = \Yii::$app->user->id;
            }

            // to find total hours of the day already logged
            $total_daily_hours = (Timesheet::find()->where(['user_id' => Yii::$app->user->id])->andWhere(['date' => $model->date])->sum('hours'));

            $model->hours = ($model->hours + $model->minute);
            $dayofweek = date('w', strtotime($model->date));
            if($dayofweek == 6)
            {
                $monday = date('Y-m-d', strtotime('last monday', strtotime($model->date)));
            }
            else
            {
                $monday = date('Y-m-d', strtotime('this monday', strtotime($model->date)));
            }
            $saturday = date('Y-m-d', strtotime('this saturday', strtotime($model->date)));

            // to find total hours of the week already logged
            $team_member_weekly_hours = Timesheet::find()->where(['user_id' => \Yii::$app->user->id])->andWhere(['between', 'date', $monday, $saturday])->sum('hours');

            $role = \Yii::$app->authManager->getRolesByUser(\Yii::$app->user->id);

            if(array_key_exists('intern', $role) == false)
            {
                $TEAM_MEMBER_WEEK_LIMIT = 48;
            }
            else
            {
                $TEAM_MEMBER_WEEK_LIMIT = Timesheet::TEAM_MEMBER_WEEK_LIMIT;
            }

            if ((
                    (Timesheet::PER_DAY_HOURS_LIMIT) >= ($total_daily_hours + $model->hours)
                    || ((Timesheet::PER_DAY_HOURS_LIMIT) >= ($total_daily_hours + $model->hours)
                        && (array_key_exists('team-member', $role)))
                )
                && (Timesheet::blockMonthEntry($model->date) == true)
                && ($TEAM_MEMBER_WEEK_LIMIT >= $team_member_weekly_hours + $model->hours)
                && ($model->hours != 0))
            {
                // get user hourly rate
                $usertohourlyrate = UserToHourlyRate::getHourlyRateByUserId($model->user_id);
                $model->total_amount = $usertohourlyrate * $model->hours;
                $model->hourly_rate = $usertohourlyrate;

                // echo "
";var_dump($model);die;

                if($model->save())
                {
                    $model_id = $model->id;
                }
                // echo "$model_id";

                //For Notification
                $userToNotify = [];
                $user_id = \Yii::$app->user->id;
                $userForNotify = UserToSubscriber::find()->select('senior_user_id')->where(['user_id'=>$user_id])->all();

                if($userForNotify != NULL)
                {
                    $userToNotify = [];
                    foreach($userForNotify as $ufn){
                        array_push($userToNotify,$ufn->senior_user_id);
                    }

                    foreach($userToNotify as $value)
                    {
                        $noticemodel = new Notifications();
                        $noticemodel->user_id = $value;
                        $noticemodel->relation_name = 'timesheet';
                        $noticemodel->relation_id = $model->id;
                        $noticemodel->notice_abstract = "Timesheet Created Notification.";
                        $noticemodel->action = '0';
                        $noticemodel->created_on = date('Y-m-d h:i:s');
                        $noticemodel->save();
                    }
                }
                //

                if (General::ifUserPermitted('timesheetAutoTimesheetApproval')) {
                    // echo "in if";
                    // timesheet auto approval
                    // WIP update
                    General::onTimesheetChange($model->job_id, $model->user_id, $model->date, "timesheet");
                    //For update timesheet model
                    $timesheet_model = Timesheet::findOne($model_id);
                    echo "
";var_dump($timesheet_model);//die;
                    $timesheet_model->action_taken_at = date("Y-m-d h:m:s");
                    $timesheet_model->action_taken_by = \Yii::$app->user->id;
                    $timesheet_model->status = "Approved";
                    echo "
";var_dump($timesheet_model);
                    $timesheet_model->save();
                    if($timesheet_model->save())
                    {
                        echo "True";
                    }
                    else
                    {
                        echo "False";
                        $errors = $timesheet_model->errors;
                        echo "
";var_dump($errors);
                    }
                    //For Notification
                    if($userForNotify != NULL)
                    {
                        $userToNotify = [];
                        foreach($userForNotify as $ufn){
                            array_push($userToNotify,$ufn->senior_user_id);
                        }

                        foreach($userToNotify as $value)
                        {
                            $notification = Notifications::find()->where(['user_id'=>$value , 'relation_id'=>$model->id, 'notice_abstract'=>'Timesheet Created Notification.'])->one();
                            if($notification != NULL)
                            {
                                $notification->action = '1';
                                $notification->save();
                            }
                        }
                    }
                    //
                }
                if (array_key_exists('team-member', $role)) {
                    $msg = "Entry Inserted Successfully and Your remaining weekly hours is " . ((Timesheet::TEAM_MEMBER_WEEK_LIMIT) - ($team_member_weekly_hours + $model->hours)) . " hrs.";
                } else {
                    $msg = "Entry Inserted Successfully and Your remaining hours is " . ((Timesheet::PER_DAY_HOURS_LIMIT) - ($totel_hours + $model->hours)) . " hrs.";
                }
                \Yii::$app->session->setFlash('success', $msg);

                $transaction->commit();

                return $this->redirect(['view', 'id' => $model->id]);

            }
            elseif (Timesheet::blockMonthEntry($model->date) != true) {
                $msg = "This date has been blocked";
            }elseif ($totel_hours == (Timesheet::PER_DAY_HOURS_LIMIT) || $team_member_weekly_hours == (Timesheet::TEAM_MEMBER_WEEK_LIMIT)) {
                $msg = "Your Daily hours is over";
            } elseif (($totel_hours + $model->hours) > Timesheet::PER_DAY_HOURS_LIMIT) {
                $msg = "Your remaining daily hours only is " . ((Timesheet::PER_DAY_HOURS_LIMIT) - $totel_hours) . " hrs.";
            } elseif ($model->hours == 0) {
                $msg = "Please select hours";
            } else {
                $msg = "Your remaining Weekly hours only is " . ((Timesheet::TEAM_MEMBER_WEEK_LIMIT) - $team_member_weekly_hours) . " hrs.";
            }
            \Yii::$app->session->setFlash('error', $msg);
            list($model->hours, $minute) = explode('.', $model->hours);
            $model->minute = "0." . $minute;

            if(empty($model->date)){
                $model->date = date('j/n/Y');
            }else{
                $model->date = General::convertMysqlDateToDDMMYYYY($model->date);
            }
            return $this->render('create', [
                        'model' => $model,
                        'master_mode' => Yii::$app->user->can('associateSubscriberWithDetails'),
            ]);
        }
        catch(Exception $e)
        {
            \Yii::$app->session->setFlash('error', $e);
            $transaction->rollBack();
        }
        //Transaction ends here
    }
    else
    {
        if(empty($model->date)){
            $model->date = date('j/n/Y');
        }else{
            $model->date = General::convertMysqlDateToDDMMYYYY($model->date);
        }

        return $this->render('create', [
                    'model' => $model,
                    'master_mode' => Yii::$app->user->can('associateSubscriberWithDetails'),
        ]);
    }
}

What should I do? where to amend the code?
$timesheet model is failing while updating the model but model saved before it is not rolled back.

I want to rollback all save() if any one of the model save() fails.

Body:
Yii save() not throw an exception when the execution of this method fails (for an Exception). Thus you have to check the result of save() and throw an Exception in case of fail.

When you use a save() in your try{}catch(Exception $e){} statement use as here:

if (!$model->save()) {
   throw new Exception("Trigger transaction rollback");
} else {
    // something
}


来源: stackexchange

问:
How to merge array of object containing same id
I have one array of objects like this:

```<code>[
  {
    id:1,
    val: 5
  },
  {
    id:1,
    val: 5
  },
  {
    id:2,
    val: 6
  },
  {
    id:2,
    val: 7
  }
]
</code>```

and I want something like this

```<code>[
  {
    id:1,
    val: 10
  },
  {
    id:2,
    val: 13
  },
]
</code>```

How can I do this?

答:
```<code>var t=[
  {
    id:1,
    val: 5
  },
  {
    id:1,
    val: 5
  },
  {
    id:2,
    val: 6
  },
  {
    id:2,
    val: 7
  }
]

t.reduce((acc,elem)=>{
    if(acc.filter((elemi)=>elemi.id==elem.id)[0])acc.filter((elemi)=>elemi.id==elem.id)[0].val+=elem.val;
    else acc.push(elem);
    return acc
}
,[])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one array of objects like this:

[
  {
    id:1,
    val: 5
  },
  {
    id:1,
    val: 5
  },
  {
    id:2,
    val: 6
  },
  {
    id:2,
    val: 7
  }
]

and I want something like this

[
  {
    id:1,
    val: 10
  },
  {
    id:2,
    val: 13
  },
]

How can I do this?


问:
What are BASE, LOCAL, REMOTE and cppMerged files?
I'm working on a Visual C++ project on Win7 64bit and using git as my repository and VS2010 as my IDE. Lately I've started seeing files with the following endings:

```<code>.cpp.BASE.cpp
.cpp.LOCAL.cpp
.cpp.REMOTE.cpp
.cppMerged
</code>```

Are these git merge conflict resolution files? VS2010 files? or something else?

答: This seems to be an open issue in TortoiseGit</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a Visual C++ project on Win7 64bit and using git as my repository and VS2010 as my IDE. Lately I've started seeing files with the following endings:

.cpp.BASE.cpp
.cpp.LOCAL.cpp
.cpp.REMOTE.cpp
.cppMerged

Are these git merge conflict resolution files? VS2010 files? or something else?


问:
Laravel 5.5. queue push
I have upgraded my app from Laravel 4.2 to 5.5 and I am getting issues with the queue.

```<code>public function saved(Model $review)
{
    if (App::runningInConsole()) {
        return;
    }

    $data = [
        'review' => serialize($review),
        'action' => self::ACTION_SAVE
    ];
    Queue::push(new UpdateReviewSummaryQueue, $data);
}
</code>```

When I run this on model save, I am getting an error that the UpdateReviewSummaryQueue class does not exist. I've ran composer dump-autoload and namespacing seems to be fine. Are there any other issues I might look into?

I've also added

```<code>use SerializesModels;
</code>```

as Laravel upgrade guide suggested

答:
In laravel 5.5 you now dispatch jobs rather than push. See https://laravel.com/docs/5.5/queues#dispatching-jobs for full documentation.
Try :

```<code>dispatch((new UpdateReviewSummaryQueue($data));
</code>```

Title: Laravel 5.5. queue push

Body:
I have upgraded my app from Laravel 4.2 to 5.5 and I am getting issues with the queue.

public function saved(Model $review)
{
    if (App::runningInConsole()) {
        return;
    }

    $data = [
        'review' => serialize($review),
        'action' => self::ACTION_SAVE
    ];
    Queue::push(new UpdateReviewSummaryQueue, $data);
}

When I run this on model save, I am getting an error that the UpdateReviewSummaryQueue class does not exist. I've ran composer dump-autoload and namespacing seems to be fine. Are there any other issues I might look into?

I've also added

use SerializesModels;

as Laravel upgrade guide suggested

Body:
In laravel 5.5 you now dispatch jobs rather than push. See https://laravel.com/docs/5.5/queues#dispatching-jobs for full documentation.
Try :

dispatch((new UpdateReviewSummaryQueue($data));


问:
Solve 500 response Laravel (Uncaught UnexpectedValueException: Laravel.log)
I have a problem with my (new/clean) Laravel (tried v5.2 and v5.5) application on Centos 7. It shows a 500 error when i visited the URL of the application with no error. I checked the log file of apache (/etc/httpd/logs/error-log.log) what contained the 2 errors bellow:

[Mon Dec 04 10:32:34.108956 2017] [:error] [pid 25889] [client 192.168.1.240:63437] PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/public/blog_project/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107\nStack trace:\n#0 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)\n#1 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Logger.php(337): Monolog\Handler\AbstractProcessingHandler->handle(Array)\n#2 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Logger.php(616): Monolog\Logger->addRecord(400, Object(UnexpectedValueException), Array)\n#3 /var/www/public/blog_project/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\Logger->error(Object(UnexpectedValueException), Array)\n#4 /var/www/public/blog_project/vendor/laravel/framework/src/Illuminate/Log/Writer.php(113): Illuminate\Log\Writer->writeLog('error', Object(U in /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107

&

[Mon Dec 04 10:32:34.109334 2017] [:error] [pid 25889] [client 192.168.1.240:63437] PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/public/blog_project/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107\nStack trace:\n#0 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)\n#1 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Logger.php(337): Monolog\Handler\AbstractProcessingHandler->handle(Array)\n#2 /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Logger.php(616): Monolog\Logger->addRecord(400, Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#3 /var/www/public/blog_project/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\Logger->error(Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#4 /var/www/public/blog_project/vendor/laravel/framework/src/Illuminate/Log/Writer.p in /var/www/public/blog_project/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107

To solve these problems i Googled a lot. Solutions i found where all related to permissions so I tried to set chmod 777 to all directories and files (for test purposes, not recommended at live environment!) in /var/www/public/blog_project but this did not solve the problem.

I also found that the owner/group could be the problem (unlikely with chmod 777 but ok) so I changed the owner and group to "apache". Unfortunately this did still not solve my problem.

I also tried a "php artisan cache:clear" (suggested in some topic what described the same problem as i have)

答:
At the moment of writing i already had found the solution (after many hours of Googling) for my problem but i still want to post this question because i could not find another question what solved my problem. I hope to help other people who have the same problem this way.

The problem was that SELinux was enabled which prevent Apache to write files even with 777 mode. It seems that SELinux is active by Centos 4 or higher by default. I also found that Fedora has SELinux activated what results in the same problem (no own experience with Fedora).

I solved the problem by disabling SELinux. For CentosOS7 id did this by editing /etc/sysconfig/selinux
and changing the line SELINUX=enforcing into SELINUX=disabled. After that i rebooted the server and the problem was solved.


问:
Adding lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER) not working for Cubic Line Chart
I want to add Cubic Line Chart.I have reffered this ans:How to enable cubic lines in MPAndroidChart library?  but the solution is not working.Is there any solution?
I have Mp Android Chart version-3.0.1

Here is my code:

```<code>    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.fragment_graph_test, container, false);

    LineChart lineChart=view.findViewById(R.id.bar_Chart_test);

    List<Entry> entries=new ArrayList<>();
    for(int i=0;i<10;i++){
        entries.add(new Entry(i,i+3));
    }
    LineDataSet lineDataSet=new LineDataSet(entries,"My Line Chart");
    lineDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

    LineData lineData=new LineData(lineDataSet);
    lineChart.setData(lineData);
    lineChart.invalidate();
    lineChart.animateXY(2000,2000);
    lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    return view;
}
</code>```

XML :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
          android:orientation="vertical"
         android:layout_height="match_parent"
         tools:context="finlit.finlit.fragment.GraphTest">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_blank_fragment"/>
<com.github.mikephil.charting.charts.LineChart
    android:id="@+id/bar_Chart_test"
    android:layout_width="match_parent"
    android:layout_height="478dp">
</com.github.mikephil.charting.charts.LineChart>
</code>```

答:
You have to set the mode before you invalidate or animate the chart.
Because that actions will cause a redraw of your chart.</p>

Body:
I want to add Cubic Line Chart.I have reffered this ans:How to enable cubic lines in MPAndroidChart library?  but the solution is not working.Is there any solution?
I have Mp Android Chart version-3.0.1

Here is my code:

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.fragment_graph_test, container, false);

    LineChart lineChart=view.findViewById(R.id.bar_Chart_test);

    List<Entry> entries=new ArrayList<>();
    for(int i=0;i<10;i++){
        entries.add(new Entry(i,i+3));
    }
    LineDataSet lineDataSet=new LineDataSet(entries,"My Line Chart");
    lineDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

    LineData lineData=new LineData(lineDataSet);
    lineChart.setData(lineData);
    lineChart.invalidate();
    lineChart.animateXY(2000,2000);
    lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    return view;
}

XML :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
          android:orientation="vertical"
         android:layout_height="match_parent"
         tools:context="finlit.finlit.fragment.GraphTest">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_blank_fragment"/>
<com.github.mikephil.charting.charts.LineChart
    android:id="@+id/bar_Chart_test"
    android:layout_width="match_parent"
    android:layout_height="478dp">
</com.github.mikephil.charting.charts.LineChart>


问:
In redis, how do I delete one key and get its value at the same time

In redis, how do I delete one key and get its value at the same time,  and, most import, it is executed in one command so it is thread safe.
</p>

答:
There's no single command. You can either write a Lua script or execute a transaction. A transaction would simply look like:

```<code>127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> GET foo
QUEUED
127.0.0.1:6379> DEL foo
QUEUED
127.0.0.1:6379> EXEC
1) "bar"
2) (integer) 1
</code>```

Using a Lua script

```<code>127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> EVAL "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x" 1 foo
"bar"
127.0.0.1:6379> GET foo
(nil)
</code>```

Both operate the same, but with Lua script, the script can be cached and there's no need to repeat the whole code the next time you want to call it. We can use SCRIPT LOAD that caches the scripts and returns a unique id of it to be used as a function name for subsequent calls (Most clients abstract this transparently) e.g.

```<code>127.0.0.1:6379> SCRIPT LOAD "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x"
"89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7"

127.0.0.1:6379> SET foo bar
OK

# Now we use the returned SHA of the script to call it without parsing it again:
127.0.0.1:6379> EVALSHA 89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7 1 foo
"bar"
</code>```

Body:
There's no single command. You can either write a Lua script or execute a transaction. A transaction would simply look like:

127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> GET foo
QUEUED
127.0.0.1:6379> DEL foo
QUEUED
127.0.0.1:6379> EXEC
1) "bar"
2) (integer) 1

Using a Lua script

127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> EVAL "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x" 1 foo
"bar"
127.0.0.1:6379> GET foo
(nil)

Both operate the same, but with Lua script, the script can be cached and there's no need to repeat the whole code the next time you want to call it. We can use SCRIPT LOAD that caches the scripts and returns a unique id of it to be used as a function name for subsequent calls (Most clients abstract this transparently) e.g.

127.0.0.1:6379> SCRIPT LOAD "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x"
"89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7"

127.0.0.1:6379> SET foo bar
OK

# Now we use the returned SHA of the script to call it without parsing it again:
127.0.0.1:6379> EVALSHA 89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7 1 foo
"bar"


问:
Extending a class using categories with identical methods name
I want to extend a class using category NSArray+Populate.h:

```<code>@interface NSArray (Populate)
-(NSArray *) populateArray;
@end
</code>```

How can I detect the situation if there is another category (from another module or library), extending NSArray with method having the same name ?

For example, if there is a NSArray+Fill.h:

```<code>@interface NSArray (Fill)
-(NSArray *) populateArray;
@end
</code>```

As I understand, the run-time engine will choose one of the version silently, without any crash ?

答:
You cannot detect this situation and you cannot determine which implementation of -populateArray takes precedence. Some developers prefer to prefix their category method names for this reason.

Quoting The Objective-C Programming Language document,

A category cannot reliably override methods declared in another category of the same class.

This issue is of particular significance since many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

Body:
I want to extend a class using category NSArray+Populate.h:

@interface NSArray (Populate)
-(NSArray *) populateArray;
@end

How can I detect the situation if there is another category (from another module or library), extending NSArray with method having the same name ?

For example, if there is a NSArray+Fill.h:

@interface NSArray (Fill)
-(NSArray *) populateArray;
@end

As I understand, the run-time engine will choose one of the version silently, without any crash ?


问:
'half space' in matplotlib labels and legend
How can I insert a half space in the text of matplotlib labels or legends, e.g. between numbers and their units? A simple workaround would be to use latex rendering, but is there an other way, e.g. using unicode characters?</p>

答:
You can use the unicode thin space character u"\u2009".

For example, compare the width of the spaces in the legend text here between the "10" and the "km":

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)

ax.plot(np.arange(5), 'r-', label='10 km (normal space)')
ax.plot(5.-np.arange(5), 'b-', label=u"10\u2009km (thin space)")

ax.legend()

plt.show()
</code>```

Body:
You can use the unicode thin space character u"\u2009".

For example, compare the width of the spaces in the legend text here between the "10" and the "km":

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)

ax.plot(np.arange(5), 'r-', label='10 km (normal space)')
ax.plot(5.-np.arange(5), 'b-', label=u"10\u2009km (thin space)")

ax.legend()

plt.show()


问:
JSONArray Parsing in RecyclerView using volley android
I am trying to parse JSONArray in RecyclerView using volley in android,  i have 10 data per page, how can I call next page url when we scroll down recyclerview every time?

My JsonArray

```<code>"data": {
    "total": 146,
    "per_page": 10,
    "current_page": 1,
    "last_page": 15,
    "next_page_url": "http://www.xxxxxxxxxx.com/api/v1/auth/deal?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 10,
    "data": [
        {
            "id": "209",
            "ref": "101hd-209",
            "pid": "437",
            "name": "Office For Rent",
            "deal_mode": {
                "id": "128",
                "category_name": "Lease"
            },
</code>```

My recyclerview load 1st page data at a time, now on scroll down how i call next page url to load next page data.

答:
Replace MainActivity with your activity    </p>

```<code>//this code will be inside adapter in onBindViewHolder
if ((position+1) == dataList.size()){
        Log.d(TAG, "equal");
        ((MainActivity) context).loadNextPage(next_page_url);
}

//this code will be in MainActivity
public void loadNextPage(String pageUrl){
    //Here you make second page request
    //And add second page to list
    //then notify your adapter
}
</code>```

Body:
I am trying to parse JSONArray in RecyclerView using volley in android,  i have 10 data per page, how can I call next page url when we scroll down recyclerview every time?

My JsonArray

"data": {
    "total": 146,
    "per_page": 10,
    "current_page": 1,
    "last_page": 15,
    "next_page_url": "http://www.xxxxxxxxxx.com/api/v1/auth/deal?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 10,
    "data": [
        {
            "id": "209",
            "ref": "101hd-209",
            "pid": "437",
            "name": "Office For Rent",
            "deal_mode": {
                "id": "128",
                "category_name": "Lease"
            },

My recyclerview load 1st page data at a time, now on scroll down how i call next page url to load next page data.

Body:
Replace MainActivity with your activity

//this code will be inside adapter in onBindViewHolder
if ((position+1) == dataList.size()){
        Log.d(TAG, "equal");
        ((MainActivity) context).loadNextPage(next_page_url);
}

//this code will be in MainActivity
public void loadNextPage(String pageUrl){
    //Here you make second page request
    //And add second page to list
    //then notify your adapter
}


问:
JAXB unmarshaling xml without qualified namespace prefixes
I need to marshal object to xml with qualified namespace form (<prefix:tag-name>).
And it works fine.
I have package-info.java file with @XmlShema(elementFormDefault=XmlNsForm.QUALIFIED) but xmls I received comes without namespace prefixes (<tag-name>).
Is there any way to use namespace prefixes just for marshaling with Java 8?

答:
You need to specify the prefix with the @XmlNs annotation inside your @XmlSchema annotation:

```<code>@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = @XmlNs(prefix = "prefix",
                   namespaceURI = "http://mycompany.com/whatever"))
</code>```

Body:
You need to specify the prefix with the @XmlNs annotation inside your @XmlSchema annotation:

@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = @XmlNs(prefix = "prefix",
                   namespaceURI = "http://mycompany.com/whatever"))


问:
Animation completion block goes haywire after dismissing view

I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

```<code>func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }
</code>```

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

答:
The reason is in animation block, you are using strong reference of self which is why when you are poping this viewcontroller its reference count is still not 0, because of which ARC is not able to dealloc the reference of this view controller.

There is a concept of [weak self]. You can modify your code like below and then after poping you won't see those method calls in your debug console. Reason: weak self will not increase the reference count and ARC will be able to remove the reference of the object

```<code>func startAnimation() {
    UIView.animate(withDuration: 0.4, animations: {[weak self] in
        self?.animateView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        print("startAnimation")
    }, completion: {[weak self]
        finished in
        self?.startAnimation2()
    })
}
func startAnimation2() {
    UIView.animate(withDuration: 0.4, animations: {[weak self] in
        self?.animateView.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
        print("startAnimation2")
    }, completion: {[weak self]
        finished in
        self?.startAnimation()
    })
}
</code>```

Body:
I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

Body:
The reason is in animation block, you are using strong reference of self which is why when you are poping this viewcontroller its reference count is still not 0, because of which ARC is not able to dealloc the reference of this view controller.

There is a concept of [weak self]. You can modify your code like below and then after poping you won't see those method calls in your debug console. Reason: weak self will not increase the reference count and ARC will be able to remove the reference of the object

func startAnimation() {
    UIView.animate(withDuration: 0.4, animations: {[weak self] in
        self?.animateView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        print("startAnimation")
    }, completion: {[weak self]
        finished in
        self?.startAnimation2()
    })
}
func startAnimation2() {
    UIView.animate(withDuration: 0.4, animations: {[weak self] in
        self?.animateView.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
        print("startAnimation2")
    }, completion: {[weak self]
        finished in
        self?.startAnimation()
    })
}


问:
Google cloud load balancer with external server
I want to know if it is possible link the Google Cloud load balancer to an external server - a server hosted outside of Google Cloud?

So the load balancer might link to a Google Cloud instance but also an external server.

答: Not by attaching directly to the load balancer but you can add a backend service consisting of an auto scalable instance group hosted on google cloud which will proxy the incoming traffic to the external server. This will result in the overhead of billing and maintenance of such an auto-scalable group of instances. Hence, depending on the volume of traffic you are handling another approach can be to route traffic via existing backend service i.e. configure the servers running in your existing backend service by adding appropriate conditions(path based routing etc.) and proxy to the external server instead of relying on Google HTTP Load Balancer to perform the path based routing part.</p>


问:
OpenNLP find() method
At the moment im trying to find names inside a document. Im using the following method to find the names:

find(String[] tokens)

I also found this method below:

```<code>find(String[] tokens,String[][] additionalContext)
</code>```

what can I do with this method and how do I use it ?

答:
According to opennlp.tools.namefind.NameFinderME apidocs:

```<code>public Span[] find(String[] tokens, String[][] additionalContext)
</code>```

Generates name tags for the given sequence, typically a sentence,
  returning token spans for any identified names.

Parameters:

tokens - an array of the tokens or words of the sequence, typically    a sentence.

additionalContext - features which are based on context outside of    the sentence but which should also be used.

Returns:
      an array of spans for each of the names identified.

That being said, consider your tokens are:

```<code>String[] tokens = { "lorem", "ipsum", "dolor", "sit", "amet", "adipiscing", "elit" };
</code>```

But you also want to take into account the following features, "which are based on context outside of the sentence but which should also be used":

```<code>String[][] additionalContext = {
    { "nullam", "fermentum", "justo", "non", "leo", "rhoncus", "blandit" },
    { "phasellus", "at", "diam", "mattis", "arcu", "congue", "consequat" },
    { "integer", "at", "tincidunt", "turpis", "eget", "pulvinar", "nisl" } };
</code>```

This way you can call find(tokens, additionalContext).

Note that, according to the code on GitHub, find(String[] tokens) is actually find(tokens, EMPTY) (and String[][] EMPTY = new String[0][0]).

Title: OpenNLP find() method

Body:
At the moment im trying to find names inside a document. Im using the following method to find the names:

find(String[] tokens)

I also found this method below:

find(String[] tokens,String[][] additionalContext)

what can I do with this method and how do I use it ?

Body:
According to opennlp.tools.namefind.NameFinderME apidocs:

public Span[] find(String[] tokens, String[][] additionalContext)

Generates name tags for the given sequence, typically a sentence,
  returning token spans for any identified names.

Parameters:

tokens - an array of the tokens or words of the sequence, typically    a sentence.

additionalContext - features which are based on context outside of    the sentence but which should also be used.

Returns:
      an array of spans for each of the names identified.

That being said, consider your tokens are:

String[] tokens = { "lorem", "ipsum", "dolor", "sit", "amet", "adipiscing", "elit" };

But you also want to take into account the following features, "which are based on context outside of the sentence but which should also be used":

String[][] additionalContext = {
    { "nullam", "fermentum", "justo", "non", "leo", "rhoncus", "blandit" },
    { "phasellus", "at", "diam", "mattis", "arcu", "congue", "consequat" },
    { "integer", "at", "tincidunt", "turpis", "eget", "pulvinar", "nisl" } };

This way you can call find(tokens, additionalContext).

Note that, according to the code on GitHub, find(String[] tokens) is actually find(tokens, EMPTY) (and String[][] EMPTY = new String[0][0]).


问:
Jquery acting different on mobile compared to PC, with the same code
The problem is in the website I am developing

http://balticpremier.sem.lv/en/

(https://www.virustotal.com/#/url/e2f05f0f4d6fde378f3f784c8c331849caef1e556fb1b173e4ac2f5ba521405c/detection)

Scroll to the bottom and see the Our delivered products section. It is supposed to expand on hover and click, which it does without problem on PC. However, when it is visited through phone, on click, it does the fade effect and doesn't have the correct logic.

This is the only JS that affects this part is here:

```<code>$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});
</code>```

Help appreciated!!

EDIT: Forgot to say that fade effect is not a part of the code, and only happens on mobile. Is this how toggle(); is interpreted on mobile? Either way, on mobile I also can't close it after it has been expanded. Really weird.

答:
Ok, found the solution. I really hope it satisfies yopu, if not, then sorry :)

So you can check whether there the device is a touch device and if so unbind mouseover event. Or any other event you want to.

var num = 0;
$(".testDiv").on("click mouseover", function() {
  num++;
  $(".testDiv").text(num)
});
if (!!('ontouchstart' in window)) { //check for touch device
  $('.cc').unbind('mouseover');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.testDiv {
  background: lightgreen;
  overflow: hidden;
  height: 200px;
  color: #fff;
  font-size: 40px;
  font-weight: bold;
}</code>```

Div below uses "click mouseover"

    Initial text to test whether hovering this works properly. Initial text to test whether hovering this works properly.

```

I hope this is what you wanted.

Regards, KJ

Body:
The problem is in the website I am developing

http://balticpremier.sem.lv/en/

(https://www.virustotal.com/#/url/e2f05f0f4d6fde378f3f784c8c331849caef1e556fb1b173e4ac2f5ba521405c/detection)

Scroll to the bottom and see the Our delivered products section. It is supposed to expand on hover and click, which it does without problem on PC. However, when it is visited through phone, on click, it does the fade effect and doesn't have the correct logic.

This is the only JS that affects this part is here:

$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});

Help appreciated!!

EDIT: Forgot to say that fade effect is not a part of the code, and only happens on mobile. Is this how toggle(); is interpreted on mobile? Either way, on mobile I also can't close it after it has been expanded. Really weird.

Body:
Ok, found the solution. I really hope it satisfies yopu, if not, then sorry :)

So you can check whether there the device is a touch device and if so unbind mouseover event. Or any other event you want to.

var num = 0;
$(".testDiv").on("click mouseover", function() {
  num++;
  $(".testDiv").text(num)
});
if (!!('ontouchstart' in window)) { //check for touch device
  $('.cc').unbind('mouseover');
}

.testDiv {
  background: lightgreen;
  overflow: hidden;
  height: 200px;
  color: #fff;
  font-size: 40px;
  font-weight: bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Div below uses "click mouseover"</span>
<div class="testDiv">
  <p>
    Initial text to test whether hovering this works properly. Initial text to test whether hovering this works properly.
  </p>
</div>

I hope this is what you wanted.

Regards, KJ


问:
Mysql, Hibernate - When insert to table, it says Field doesn't have a default values
I'm using Hibernate, MySQL, Spring MVC.

My current job is booking a flight ticket.

I got a flight schedule entity from path variable. And, I got a passenger entity from HttpSession.

Below is the controller code:

```<code>@RequestMapping("/booking/{results[0].flightscheduleId}")
public String bookBoardingPass
    (@PathVariable("results[0].flightscheduleId") Integer flightId, HttpSession session) {

    Passenger passenger = (Passenger) session.getAttribute("user");
    FlightSchedule flightSchedule = this.flightScheduleService.get(flightId);

    this.boardingPassService.booking(flightSchedule, passenger);

    return "search";
}
</code>```

Below is booking method code:

```<code>@Override
public void booking (FlightSchedule flightSchedule, Passenger passenger) {

    BoardingPass ticket = new BoardingPass();
    ticket.setFlightschedule(flightSchedule);
    ticket.setPassenger(passenger);

    System.out.println("flight id: "+flightSchedule.getFlightscheduleId());
    System.out.println("passenger id: "+passenger.getPassengerId());

    this.persist(ticket);
    //sessionFactory.getCurrentSession().saveOrUpdate(ticket);
}
</code>```

in booking method, I can print both flightSchedule's id and passenger's id.

But, when I execute 'persist' method, it says Field 'flightschedule_id' doesn't have a default value

In the persist method, it runs sessionFactory.getCurrentSession().saveOrUpdate(ticket);

flightschedule_id is a primary key, auto-increment, not-null.

I cannot give it a default value. Also, I check STRICT mode(?) on phpmyadmin through googling search result. (I am not sure I do well. Anyway it didn't work).

How can I solve this problem?

EDIT:

Below is BoardingPass class:

```<code>@Entity
@Table
public class BoardingPass implements java.io.Serializable {

private Integer boardingpassId;
private FlightSchedule flightschedule;
private Passenger passenger;

public BoardingPass() {
}

public BoardingPass(FlightSchedule flightschedule, Passenger passenger) {
    this.flightschedule = flightschedule;
    this.passenger = passenger;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getBoardingpassId() {
    return this.boardingpassId;
}

public void setBoardingpassId(Integer boardingpassId) {
    this.boardingpassId = boardingpassId;
}

@ManyToOne
@MapsId("flightscheduleId")
public FlightSchedule getFlightschedule() {
    return this.flightschedule;
}

public void setFlightschedule(FlightSchedule flightschedule) {
    this.flightschedule = flightschedule;
}

@ManyToOne
@MapsId("passengerId")
public Passenger getPassenger() {
    return this.passenger;
}

public void setPassenger(Passenger passenger) {
    this.passenger = passenger;
}

}
</code>```

Just in case, I add part of FlightSchedule and Passenger class.

Below is FlightSchedule.java :

```<code>@Entity
@Table
public class FlightSchedule implements java.io.Serializable {

private Integer flightscheduleId;
private Date depDay;
private Date depTime;
private Date arrDay;
private Date arrTime;
private Double flightTime;
private Integer price;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);
private Airplane airplane;
private Airport depAirport;
private Airport arrAirport;

public FlightSchedule() {
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Integer price) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.price = price;
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Double flightTime, Integer price,
        Set<BoardingPass> boardingPasses, Airplane airplane, Airport depAirport, Airport arrAirport) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.flightTime = flightTime;
    this.price = price;
    this.boardingPasses = boardingPasses;
    this.airplane = airplane;
    this.depAirport = depAirport;
    this.arrAirport = arrAirport;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}

public void setFlightscheduleId(Integer flightscheduleId) {
    this.flightscheduleId = flightscheduleId;
}

@OneToMany(mappedBy = "flightschedule", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}
</code>```

Below is Passenger.java:

```<code>@Entity
@Table
public class Passenger implements java.io.Serializable {

private Integer passengerId;
private String password;
private String passportNo;
private String passengerName;
private Date birth;
private Integer mileage;
private String contact;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);

public Passenger() {
}

public Passenger(String password, String passportNo, Date birth, Integer mileage) {
    this.password = password;
    this.passportNo = passportNo;
    this.birth = birth;
    this.mileage = mileage;
}

public Passenger(String password, String passportNo, String passengerName, Date birth, Integer mileage, String contact, Set<BoardingPass> boardingPasses) {
    this.password = password;
    this.passportNo = passportNo;
    this.passengerName = passengerName;
    this.birth = birth;
    this.mileage = mileage;
    this.contact = contact;
    this.boardingPasses = boardingPasses;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getPassengerId() {
    return this.passengerId;
}

public void setPassengerId(Integer passengerId) {
    this.passengerId = passengerId;
}

@OneToMany(mappedBy = "passenger", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}
</code>```

答:
The first thing that i see completely wrong with that mapping is the @MapsId annotations:

Those are used to tell hibernate the attribute within a composite key to which the relationship attribute corresponds.

Meaning without a composite primary key it doesn't make any sense and i suspect it's messing up your mappings... try to remove them and see how it goes

A simple example http://www.objectdb.com/api/java/jpa/MapsId

P.s. i was forgetting you need to add the @JoinColumn annotations too to the mappings

```<code>@JoinColumn(name = "flightschedule_id", referencedColumnName = "boardingPass_id")
</code>```

Edit:
Also the thing causing the problem in the first place is that you specified the name of the db column wrong

```<code>@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}
</code>```

shouldn't that be @Column(name = "flightschedule_id", unique = true, nullable = false) ?

same things for the other 2 entities as well check that the @Column name attribute correspond to db column name

Body:
I'm using Hibernate, MySQL, Spring MVC.

My current job is booking a flight ticket.

I got a flight schedule entity from path variable. And, I got a passenger entity from HttpSession.

Below is the controller code:

@RequestMapping("/booking/{results[0].flightscheduleId}")
public String bookBoardingPass
    (@PathVariable("results[0].flightscheduleId") Integer flightId, HttpSession session) {

    Passenger passenger = (Passenger) session.getAttribute("user");
    FlightSchedule flightSchedule = this.flightScheduleService.get(flightId);

    this.boardingPassService.booking(flightSchedule, passenger);

    return "search";
}

Below is booking method code:

@Override
public void booking (FlightSchedule flightSchedule, Passenger passenger) {

    BoardingPass ticket = new BoardingPass();
    ticket.setFlightschedule(flightSchedule);
    ticket.setPassenger(passenger);

    System.out.println("flight id: "+flightSchedule.getFlightscheduleId());
    System.out.println("passenger id: "+passenger.getPassengerId());

    this.persist(ticket);
    //sessionFactory.getCurrentSession().saveOrUpdate(ticket);
}

in booking method, I can print both flightSchedule's id and passenger's id.

But, when I execute 'persist' method, it says Field 'flightschedule_id' doesn't have a default value

In the persist method, it runs sessionFactory.getCurrentSession().saveOrUpdate(ticket);

flightschedule_id is a primary key, auto-increment, not-null.

I cannot give it a default value. Also, I check STRICT mode(?) on phpmyadmin through googling search result. (I am not sure I do well. Anyway it didn't work).

How can I solve this problem?

EDIT:

Below is BoardingPass class:

@Entity
@Table
public class BoardingPass implements java.io.Serializable {

private Integer boardingpassId;
private FlightSchedule flightschedule;
private Passenger passenger;

public BoardingPass() {
}

public BoardingPass(FlightSchedule flightschedule, Passenger passenger) {
    this.flightschedule = flightschedule;
    this.passenger = passenger;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getBoardingpassId() {
    return this.boardingpassId;
}

public void setBoardingpassId(Integer boardingpassId) {
    this.boardingpassId = boardingpassId;
}

@ManyToOne
@MapsId("flightscheduleId")
public FlightSchedule getFlightschedule() {
    return this.flightschedule;
}

public void setFlightschedule(FlightSchedule flightschedule) {
    this.flightschedule = flightschedule;
}

@ManyToOne
@MapsId("passengerId")
public Passenger getPassenger() {
    return this.passenger;
}

public void setPassenger(Passenger passenger) {
    this.passenger = passenger;
}

}

Just in case, I add part of FlightSchedule and Passenger class.

Below is FlightSchedule.java :

@Entity
@Table
public class FlightSchedule implements java.io.Serializable {

private Integer flightscheduleId;
private Date depDay;
private Date depTime;
private Date arrDay;
private Date arrTime;
private Double flightTime;
private Integer price;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);
private Airplane airplane;
private Airport depAirport;
private Airport arrAirport;

public FlightSchedule() {
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Integer price) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.price = price;
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Double flightTime, Integer price,
        Set<BoardingPass> boardingPasses, Airplane airplane, Airport depAirport, Airport arrAirport) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.flightTime = flightTime;
    this.price = price;
    this.boardingPasses = boardingPasses;
    this.airplane = airplane;
    this.depAirport = depAirport;
    this.arrAirport = arrAirport;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}

public void setFlightscheduleId(Integer flightscheduleId) {
    this.flightscheduleId = flightscheduleId;
}

@OneToMany(mappedBy = "flightschedule", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}

Below is Passenger.java:

@Entity
@Table
public class Passenger implements java.io.Serializable {

private Integer passengerId;
private String password;
private String passportNo;
private String passengerName;
private Date birth;
private Integer mileage;
private String contact;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);

public Passenger() {
}

public Passenger(String password, String passportNo, Date birth, Integer mileage) {
    this.password = password;
    this.passportNo = passportNo;
    this.birth = birth;
    this.mileage = mileage;
}

public Passenger(String password, String passportNo, String passengerName, Date birth, Integer mileage, String contact, Set<BoardingPass> boardingPasses) {
    this.password = password;
    this.passportNo = passportNo;
    this.passengerName = passengerName;
    this.birth = birth;
    this.mileage = mileage;
    this.contact = contact;
    this.boardingPasses = boardingPasses;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getPassengerId() {
    return this.passengerId;
}

public void setPassengerId(Integer passengerId) {
    this.passengerId = passengerId;
}

@OneToMany(mappedBy = "passenger", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}

Body:
The first thing that i see completely wrong with that mapping is the @MapsId annotations:

Those are used to tell hibernate the attribute within a composite key to which the relationship attribute corresponds.

Meaning without a composite primary key it doesn't make any sense and i suspect it's messing up your mappings... try to remove them and see how it goes

A simple example http://www.objectdb.com/api/java/jpa/MapsId

P.s. i was forgetting you need to add the @JoinColumn annotations too to the mappings

@JoinColumn(name = "flightschedule_id", referencedColumnName = "boardingPass_id")

Edit:
Also the thing causing the problem in the first place is that you specified the name of the db column wrong

@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}

shouldn't that be @Column(name = "flightschedule_id", unique = true, nullable = false) ?

same things for the other 2 entities as well check that the @Column name attribute correspond to db column name


问:
Destroy and recreate a jQuery Datatables
I have two jQuery datatables with server side processing. I have a checkbox where I hide and show the two tables. I would like to destroy the none displayed and create another table. How would I do this?

This is what I tried but ajax.reload does not fire.

if ($('#mode').is(':checked')) {
    Table2.ajax.reload();
    Table1.clear();
    Table1.destroy();
} else {
    Table1.ajax.reload();
    Table2.clear();
    Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})
```

答:
according to this : https://datatables.net/reference/api/ajax.reload() ajax.reload() it just for reloading the datas of the datatable from a remote stream, not reloading the datatable itself

I think you have to do something like this:

```<code>if($('#mode').is(':checked')) {

  Table2 = $('#timesheet-table-2').DataTable({})
  Table1.clear();
  Table1.destroy();

} else {
  Table1 = $('#timesheet-table').DataTable({})
  Table2.clear();
  Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})
</code>```

Body:
according to this : https://datatables.net/reference/api/ajax.reload() ajax.reload() it just for reloading the datas of the datatable from a remote stream, not reloading the datatable itself

I think you have to do something like this:

if($('#mode').is(':checked')) {

  Table2 = $('#timesheet-table-2').DataTable({})
  Table1.clear();
  Table1.destroy();

} else {
  Table1 = $('#timesheet-table').DataTable({})
  Table2.clear();
  Table2.destroy()
}

var Table1 = $('#timesheet-table').DataTable({})
var Table2 = $('#timesheet-table-2').DataTable({})


问:
Square Connect API: Retrieving all items within a category
I have been reading over the Square Connect API and messing around with the catalog portion.

I am unable to find how to retrieve all items and their data associated with a particular category. Can someone please point me in the right direction.

I thought it was the

```<code>BatchRetrieveCatalogObjects endpoint
</code>```

I was using the category ID but it was only returning the catalog's data. I need each of the IDs of the items to retrieve their individual data.

I was looking to propagate a list of all the items and their data in one request in JSON.

JSON data to be passed to endpoint:

```<code>data = {
                "object_ids": [
                    "category id"
                ],
                "include_related_objects": True
            }
</code>```

My connection to the API:

```<code> category_item_endpoint =  self.connection.post('/v2/catalog/batch-retrieve', data)
</code>```

I am using python3 and the requests library.

答: You'd probably have the most luck listing your entire catalog GET /v2/catalog/list and then applying filtering (in this case specific catagory_ids ) after you get the data. Based on the documentation doing what you desire doesn't seem possible with an endpoint/query combitionation.

Body:
I have been reading over the Square Connect API and messing around with the catalog portion.

I am unable to find how to retrieve all items and their data associated with a particular category. Can someone please point me in the right direction.

I thought it was the

BatchRetrieveCatalogObjects endpoint

I was using the category ID but it was only returning the catalog's data. I need each of the IDs of the items to retrieve their individual data.

I was looking to propagate a list of all the items and their data in one request in JSON.

JSON data to be passed to endpoint:

data = {
                "object_ids": [
                    "category id"
                ],
                "include_related_objects": True
            }

My connection to the API:

 category_item_endpoint =  self.connection.post('/v2/catalog/batch-retrieve', data)

I am using python3 and the requests library.


问:
How to count green pixel in an image using Scala map reduce
I am new to Scala programming, I am trying to count RGB values in an image using Scala (particularly green color). Below is the code to count only green pixels. My Question here is, How to achieve the same using Scala map reduce algorithms?

```<code>....
val lightGreen = new Color(0,255,0)
val darkGreen = new Color(0,100,0)

var ctrGreen = 0
var ctrTotal = 0
for (x <- 0 until w)
  for (y <- 0 until h) {
    val c = new Color(img.getRGB(x, y))
    if (isBetween(c, lightGreen,darkGreen)) {
      ctrGreen += 1
    }
    ctrTotal += 1;
  }

println("Green pixel count: " + ctrGreen)
println("Total pixel count: " + ctrTotal)

def isBetween(c: Color, c1: Color, c2: Color): Boolean = {
  c.getRed >= c1.getRed && c.getRed <= c2.getRed &&
    c.getBlue >= c1.getBlue && c.getBlue <= c2.getBlue &&
    c.getGreen <= c1.getGreen && c.getGreen >= c2.getGreen
}
</code>```

How to count number of green pixels using map reduce algorithm in Scala?

答:
You can rewritte it as follow :

```<code>val rangeX = (0 until w)
val rangeY = (0 until h)

val (greenPixels, allPixels) = (for ( x <- rangeX; y <- rangeY ) yield( (isGreen(x, y), 1) )).reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )
</code>```

Or in a more functional approach :

```<code>val (greenPixels, allPixels) = rangeX.flatMap( x => rangeY.map( y => (isGreen(x, y), 1) ) )
      .reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )
</code>```

Where isGreen is

```<code>def isGreen(x: Int, y: Int) =
{
  val c = new Color(img.getRGB(x, y))
  val isGreenAsInt = if( isBetween(c, lightGreen,darkGreen) ) 1 else 0
  isGreenAsInt
}
</code>```

Body:
I am new to Scala programming, I am trying to count RGB values in an image using Scala (particularly green color). Below is the code to count only green pixels. My Question here is, How to achieve the same using Scala map reduce algorithms?

....
val lightGreen = new Color(0,255,0)
val darkGreen = new Color(0,100,0)

var ctrGreen = 0
var ctrTotal = 0
for (x <- 0 until w)
  for (y <- 0 until h) {
    val c = new Color(img.getRGB(x, y))
    if (isBetween(c, lightGreen,darkGreen)) {
      ctrGreen += 1
    }
    ctrTotal += 1;
  }

println("Green pixel count: " + ctrGreen)
println("Total pixel count: " + ctrTotal)

def isBetween(c: Color, c1: Color, c2: Color): Boolean = {
  c.getRed >= c1.getRed && c.getRed <= c2.getRed &&
    c.getBlue >= c1.getBlue && c.getBlue <= c2.getBlue &&
    c.getGreen <= c1.getGreen && c.getGreen >= c2.getGreen
}

How to count number of green pixels using map reduce algorithm in Scala?

Body:
You can rewritte it as follow :

val rangeX = (0 until w)
val rangeY = (0 until h)

val (greenPixels, allPixels) = (for ( x <- rangeX; y <- rangeY ) yield( (isGreen(x, y), 1) )).reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )

Or in a more functional approach :

val (greenPixels, allPixels) = rangeX.flatMap( x => rangeY.map( y => (isGreen(x, y), 1) ) )
      .reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )

Where isGreen is

def isGreen(x: Int, y: Int) =
{
  val c = new Color(img.getRGB(x, y))
  val isGreenAsInt = if( isBetween(c, lightGreen,darkGreen) ) 1 else 0
  isGreenAsInt
}


问:
How to update section in the Mongo collection?
This is my server code:

```<code>router.route('/addComment')
.post(function(req, res) {
  appRequest.update({"_id": req.body._id}, {$push:{comments:req.body.comments}}) // appRequest is my collection
});
</code>```

Here is how I am defining my collection:

```<code>var locations = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    comments: [{
        identifier: String,
        text: String
    }]
});
</code>```

I want to update the comments and append the user new comment to the comments array.

When I try to call the /addComment URL, I get the following in the logs (I am hosting it in Heroku):

at=error code=H12 desc="Request timeout" method=POST
  path="/addComment" host=discounts-oman.herokuapp.com
  request_id=f77cc261-e58a-4eea-a7ad-f74af57972f4 fwd="94.185.30.228"
  dyno=web.1 connect=0ms service=30010ms status=503 bytes=0
  protocol=https

What am I doing wrong here?

答:
You get H12 errors when the request times out. It times out because you are not sending any response back to the client. A response can, for example, be sent like this (if the rest of your code is correct):

```<code>router.route('/addComment').post(function (req, res) {
  appRequest.update(
    { _id: req.body._id },
    { $push: { comments: req.body.comments } },
    {},
    function (err) {
      if (err) {
        return res.status(400).json(error);
      }

      return res.status(204).json();
    });
});
</code>```

res.json() is for JSON response. You can use res.send() for generic responses.

Body:
This is my server code:

router.route('/addComment')
.post(function(req, res) {
  appRequest.update({"_id": req.body._id}, {$push:{comments:req.body.comments}}) // appRequest is my collection
});

Here is how I am defining my collection:

var locations = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    comments: [{
        identifier: String,
        text: String
    }]
});

I want to update the comments and append the user new comment to the comments array.

When I try to call the /addComment URL, I get the following in the logs (I am hosting it in Heroku):

at=error code=H12 desc="Request timeout" method=POST
  path="/addComment" host=discounts-oman.herokuapp.com
  request_id=f77cc261-e58a-4eea-a7ad-f74af57972f4 fwd="94.185.30.228"
  dyno=web.1 connect=0ms service=30010ms status=503 bytes=0
  protocol=https

What am I doing wrong here?

Body:
You get H12 errors when the request times out. It times out because you are not sending any response back to the client. A response can, for example, be sent like this (if the rest of your code is correct):

router.route('/addComment').post(function (req, res) {
  appRequest.update(
    { _id: req.body._id },
    { $push: { comments: req.body.comments } },
    {},
    function (err) {
      if (err) {
        return res.status(400).json(error);
      }

      return res.status(204).json();
    });
});

res.json() is for JSON response. You can use res.send() for generic responses.