问:
Image Retrain Inception only check the own specific category not tensor dataset
I have retrained the inception model from my data set of traffic sign.Its working fine but when I am trying to check other image e.g panda it's resulting with the name of traffic sign with some probabilities.I don't understand why its doing it.I need both tensor-flow data-set and my own category too.
My steps:

I have installed the python 3.5.2 in windows 7

I installed tensor-flow with
pip --install tensorflow

I download these two files retrain.py to train my data and label_image.py to check image.

Files downloaded from:
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_retraining

答:
You have misunderstood the fundamentals of transfer learning wrt this image retraining program.

In the image retraining program you are referencing, you are taking the inception CNN model that is already pretraining on the imageNET dataset. You are then retraining the final classification layers on your NEW classes and data.

The transfer learning occurs because you are retaining all the learnt feature extraction filters etc. in the early layers and you are just reclassifying the activations of those layers to new classes based on your new dataset. This means you are replacing the classification part with a new one. AFAIK there is no way to simply add classes to a CNN model via transfer learning because you have already trained a softmax layer (for example) with the classification distribution for each class.

To achieve what you are suggesting will require you to retrain the final layers of inception with the original dataset PLUS your additional data. This will take a long time due to the size of imageNET.

I would re-evaluate whether you actually need to be able to utilise all these classes in your application or whether it is sufficient to just have your traffic signs etc.

You can learn more about the program at the tensorflow tutorial here.


来源: stackexchange

问:
Multiple number from EditText with assigned number Android
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

```<code>public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}
</code>```

答:
you should do this :

```<code>summary.setText("Ukupno za platit: " + calculatedPrice + "kn");
</code>```

String + Double = String

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}

Body:
you should do this :

summary.setText("Ukupno za platit: " + calculatedPrice + "kn");

String + Double = String


问:
can we combine php server pages in a rails application?
Is there any way so that we can combine PHP pages in ruby on rails application?</p>

答: You can run them on the same webserver if you use apache. They are able to share the same database. One thing you won't be able to do is sharing data directly amongst them, for that an API to communicate between the apps will be required.</p>


问:
What is .subscribe in Angular?
I'm going through angular-tour-of-heroes app, and I encountered .subscribe method in routing. Can someone explain what's going on here?

Link for the app: https://embed.plnkr.co/?show=preview

Inside hero-detail.component.ts file,

```<code>ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);
}
</code>```

答:
.subscribe is not an Angular2 thing.

It's a method that comes from rxjs library which Angular is using internally.

If you can imagine yourself subscribing to a newsletter, every time  there is a new newsletter, they will send it to your home (the method inside subscribe gets called).

That's what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)

All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when writing this code <button (click)="doSomething()">, Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.

Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :

```<code> let subscription = magazineStore.getMagazines().subscribe(
   (newMagazine)=>{

         console.log('newMagazine',newMagazine);

    });
</code>```

And when you don't want to get the magazines anymore:

```<code>   subscription.unsubscribe();
</code>```

Also, the same goes for

```<code> this.route.paramMap
</code>```

which is returning an Observable and then you're subscribing to it.

My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.

There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap

ContentLicense: CC BY-SA 4.0

Title: What is .subscribe in Angular?

Body:
I'm going through angular-tour-of-heroes app, and I encountered .subscribe method in routing. Can someone explain what's going on here?

Link for the app: https://embed.plnkr.co/?show=preview

Inside hero-detail.component.ts file,

ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);
}

Body:
.subscribe is not an Angular2 thing.

It's a method that comes from rxjs library which Angular is using internally.

If you can imagine yourself subscribing to a newsletter, every time  there is a new newsletter, they will send it to your home (the method inside subscribe gets called).

That's what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)

All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when writing this code <button (click)="doSomething()">, Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.

Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :

 let subscription = magazineStore.getMagazines().subscribe(
   (newMagazine)=>{

         console.log('newMagazine',newMagazine);

    });

And when you don't want to get the magazines anymore:

   subscription.unsubscribe();

Also, the same goes for

 this.route.paramMap

which is returning an Observable and then you're subscribing to it.

My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.

There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap


问:
If i login with a user it logs in with any password

<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
 $select_user_query="select id , email from users where email='$email' and password= $password";
 //removed 'email' to email//
        $select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));

               if (mysqli_num_rows($select_user_result==0))
               {
                   echo 'There no such user ';
               }

               else
               {
                   $row=mysqli_fetch_array($select_user_result);
                   $_SESSION['email']=$email;
                   $_SESSION['id']= $row[0];
                   header('location:products.php');
               }

?>           ```

 here is the code

**

here i am geting

email and password from post method

From my login page

i think most of the code is right

If i login with a user it logs in with any password

**

答:
I'm assuming password is a string..

$select_user_query="select id , email from users where email='$email' and password= $password";
is what you wrote,

you've maybe forgotten to put single quotes around $password here.

Body:
<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
 $select_user_query="select id , email from users where email='$email' and password= $password";
 //removed 'email' to email//
        $select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));

               if (mysqli_num_rows($select_user_result==0))
               {
                   echo 'There no such user ';
               }

               else
               {
                   $row=mysqli_fetch_array($select_user_result);
                   $_SESSION['email']=$email;
                   $_SESSION['id']= $row[0];
                   header('location:products.php');
               }

?>

 here is the code

**

here i am geting

email and password from post method

From my login page

i think most of the code is right

If i login with a user it logs in with any password

**


问:
How to make results of a join statement a new table
I have the following mysql query. How can i make the result of the query be a new table;</p>

```<code>SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));
</code>```

答:
You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement:

```<code>CREATE TABLE new_tbl [AS] SELECT select_statement;
</code>```

Replace the select statement with the select statement that you have above.

Ref: https://dev.mysql.com/doc/refman/5.7/en/create-table-select.html

Edit: As jyothi suggested in a comment, you might wanna use a View instead of a new table in this case. If that's the case, you could use something like this:

```<code>CREATE VIEW view_name AS SELECT select_statement;
</code>```

Ref: http://www.guru99.com/views.html

Body:
I have the following mysql query. How can i make the result of the query be a new table;

SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));

Body:
You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement:

CREATE TABLE new_tbl [AS] SELECT select_statement;

Replace the select statement with the select statement that you have above.

Ref: https://dev.mysql.com/doc/refman/5.7/en/create-table-select.html

Edit: As jyothi suggested in a comment, you might wanna use a View instead of a new table in this case. If that's the case, you could use something like this:

CREATE VIEW view_name AS SELECT select_statement;

Ref: http://www.guru99.com/views.html


问:
Three-dimensional array in PHP
How can I iterate over this array? Syntax of loop</p>

```<code>$t = array(
  'grn_id' => array(
    'status_id' => array(1, 2, 3, 4)
  )
)
</code>```

答:
Perhaps a recursive iterator is what you're looking for ?

You can check the example given :

```<code><?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {

    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {

            traverseStructure($iterator -> getChildren());

        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
        }

        $iterator -> next();
    }
}
?>
</code>```

And the output is :

```<code>0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c
</code>```

Title: Three-dimensional array in PHP

Body:
How can I iterate over this array? Syntax of loop

$t = array(
  'grn_id' => array(
    'status_id' => array(1, 2, 3, 4)
  )
)

Body:
Perhaps a recursive iterator is what you're looking for ?

You can check the example given :

<?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {

    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {

            traverseStructure($iterator -> getChildren());

        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
        }

        $iterator -> next();
    }
}
?>

And the output is :

0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c


问:
How to set a random color for each group of elements looping through an array?
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

```<code><div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div>
</code>```

Javascript : This is what I tried but everything stay on the same color.

```<code>function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});
</code>```

Any solution ?

答:
All the answers provided are correct, where you need to just replace '.element' with this. But I will take it one step further also to show how to get unique color for each element div.

Solution: Just remove the color from the array once applied, so it does not apply again.

```<code>function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
  items.splice(items.indexOf(item), 1); //remove the color just applied
}

$(".elements").each(function() {
  eachEl(this);
});
</code>```

Body:
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

1

2

3

4

5

6

7

8

Javascript : This is what I tried but everything stay on the same color.

function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});

Any solution ?

Body:
All the answers provided are correct, where you need to just replace '.element' with this. But I will take it one step further also to show how to get unique color for each element div.

Solution: Just remove the color from the array once applied, so it does not apply again.

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
  items.splice(items.indexOf(item), 1); //remove the color just applied
}

$(".elements").each(function() {
  eachEl(this);
});


问:
Laravel 5.3 Seeder - undefined method table?
I'm trying to learn Laravel, but it seems the documentation is written with faulty examples... I want to create a table migration, run it, and seed it with some content.

First:

```<code>php artisan make:migration create_projects_and_tasks_tables
</code>```

With the following content:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsAndTasksTables extends Migration
{
    /**
      * Run the migrations.
      *
      * @return void
      */
      public function up()
      {
          Schema::create('projects', function (Blueprint $table) {
              $table->increments('id');
              $table->string('name')->default('');
              $table->string('slug')->default('');
              $table->timestamps();
      });

      Schema::create('tasks', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('project_id')->unsigned()->default(0);
          $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
          $table->string('name')->default('');
          $table->string('slug')->default('');
          $table->boolean('completed')->default(false);
          $table->text('description');
          $table->timestamps();
      });
  }

  /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::drop('tasks');
        Schema::drop('projects');
     }
}
</code>```

It migrated Ok. So I want to seed the projects table.

First:

```<code>php artisan make:seeder ProjectsTableSeeder
</code>```

The contents:

```<code><?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ProjectsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $projects = array(
            ['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
        );
        DB::table('projects')->insert($projects);
    }
}
</code>```

All set, I tried to rollback the migration, migrate and seed it:

```<code>php artisan migrate:refresh --seed
Rolled back: 2016_09_28_160459_create_projects_and_tasks_tables
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_09_28_160459_create_projects_and_tasks_tables

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to undefined method Illuminate\Database\MySqlConnection::setTable()
</code>```

And that's it. My table is empty, and the method DB::table() seems to not exist anymore in the framework, even if the 5.3 docs shows it. What can I do?

I'm using the Laravel Homestead vagrant box, so php version or composer isn't the issue. I'm also using MySQL as my database driver.

答:
Add the following to the top of your seeder class:

```<code>use Illuminate\Support\Facades\DB;
</code>```

Somehow, DB is not within the scope.

Body:
I'm trying to learn Laravel, but it seems the documentation is written with faulty examples... I want to create a table migration, run it, and seed it with some content.

First:

php artisan make:migration create_projects_and_tasks_tables

With the following content:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsAndTasksTables extends Migration
{
    /**
      * Run the migrations.
      *
      * @return void
      */
      public function up()
      {
          Schema::create('projects', function (Blueprint $table) {
              $table->increments('id');
              $table->string('name')->default('');
              $table->string('slug')->default('');
              $table->timestamps();
      });

      Schema::create('tasks', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('project_id')->unsigned()->default(0);
          $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
          $table->string('name')->default('');
          $table->string('slug')->default('');
          $table->boolean('completed')->default(false);
          $table->text('description');
          $table->timestamps();
      });
  }

  /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::drop('tasks');
        Schema::drop('projects');
     }
}

It migrated Ok. So I want to seed the projects table.

First:

php artisan make:seeder ProjectsTableSeeder

The contents:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class ProjectsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $projects = array(
            ['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
            ['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
        );
        DB::table('projects')->insert($projects);
    }
}

All set, I tried to rollback the migration, migrate and seed it:

php artisan migrate:refresh --seed
Rolled back: 2016_09_28_160459_create_projects_and_tasks_tables
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_09_28_160459_create_projects_and_tasks_tables

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to undefined method Illuminate\Database\MySqlConnection::setTable()

And that's it. My table is empty, and the method DB::table() seems to not exist anymore in the framework, even if the 5.3 docs shows it. What can I do?

I'm using the Laravel Homestead vagrant box, so php version or composer isn't the issue. I'm also using MySQL as my database driver.

Body:
Add the following to the top of your seeder class:

use Illuminate\Support\Facades\DB;

Somehow, DB is not within the scope.


问:
Fill a Column for Every Row in a Database
I just added a new column to a table which has over 1000 rows of data. I am wondering how I can update the new column with a piece of data for all of the rows in the database without having to manually do it.

What is the easiest way to accomplish this?

I am working with a MS SQL 2005 server. Thank you in advance for your advice.

答:
```<code>UPDATE  mytable
SET     newcolumn = 'newvalue'
</code>```

ContentLicense: CC BY-SA 2.5


问:
Golang strconv.ParseFloat fails to parse the string correctly when using 32 for bitSize parameter
Why the converted float64 variable has 1.590000033378601 as value?
1.59 seems small enough to be fitted into 32 bits:

```<code>package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    float, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    fmt.Printf("%T -> %+v\n", float, float)
}
</code>```

Go playground link

答:
It is precision issue of 32bit variable. This is not an issue of Go. See following URLs.

IEEE 754 - Wikipedia

Single-precision floating-point format - Wikipedia

You will understand what happen with 1.59 in this C code.

```<code>#include <stdio.h>

int
main(int argc, char* argv[]) {
  float f = 1.59;
  if (f == 1.59) {
    puts("float: equal!");
  } else {
    puts("float: not equal!");
  }

  double d = 1.59;
  if (d == 1.59) {
    puts("double: equal!");
  } else {
    puts("double: not equal!");
  }
  return 0;
}
</code>```

http://ideone.com/WobYbU

1.590000033378601 is 1.59 in 32bit variables. So you can use the value with cast to float32. i.e. float32(1.590000033378601)

```<code>package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    f64, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    f32 := float32(f64)
    fmt.Printf("%T -> %+v\n", f32, f32)
}
</code>```

Go Playground

UPDATE

On Most of computer, floating point value is stored as following elements.

Sign (zero or one)

Significand (Coefficient)

Exponent

For example, representations 0.75 is +1.1 x 2^-1

+ is Sign, .1 is Significand, -1 is Exponent. This is stored like below on 32bit memory space.

```<code>Sign                                 Significand
+-+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  +-+-+-+-+-+-+-+-+
      Exponent
</code>```

For example, 0.75 is stored like below

```<code>0-01111110-10000000000000000000000

     +- Significand
     |
+ 1[.1] x 2 ^ -1
|         |    |
+- Sign   |    +- Exponent
          |
          +------ Base
</code>```

+ 1.1 x 2^-1 = 1 x 2^0 + 1 x 2^-1 x 2^-1 = 0.75

Since floating point value is represented as above, it is different between the mathematical value and the computer's value. This is precision issue.

Body:
Why the converted float64 variable has 1.590000033378601 as value?
1.59 seems small enough to be fitted into 32 bits:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    float, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    fmt.Printf("%T -> %+v\n", float, float)
}

Go playground link

Body:
It is precision issue of 32bit variable. This is not an issue of Go. See following URLs.

IEEE 754 - Wikipedia

Single-precision floating-point format - Wikipedia

You will understand what happen with 1.59 in this C code.

#include <stdio.h>

int
main(int argc, char* argv[]) {
  float f = 1.59;
  if (f == 1.59) {
    puts("float: equal!");
  } else {
    puts("float: not equal!");
  }

  double d = 1.59;
  if (d == 1.59) {
    puts("double: equal!");
  } else {
    puts("double: not equal!");
  }
  return 0;
}

http://ideone.com/WobYbU

1.590000033378601 is 1.59 in 32bit variables. So you can use the value with cast to float32. i.e. float32(1.590000033378601)

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    f64, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    f32 := float32(f64)
    fmt.Printf("%T -> %+v\n", f32, f32)
}

Go Playground

UPDATE

On Most of computer, floating point value is stored as following elements.

Sign (zero or one)

Significand (Coefficient)

Exponent

For example, representations 0.75 is +1.1 x 2^-1

+ is Sign, .1 is Significand, -1 is Exponent. This is stored like below on 32bit memory space.

Sign                                 Significand
+-+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
  +-+-+-+-+-+-+-+-+
      Exponent

For example, 0.75 is stored like below

0-01111110-10000000000000000000000

     +- Significand
     |
+ 1[.1] x 2 ^ -1
|         |    |
+- Sign   |    +- Exponent
          |
          +------ Base

+ 1.1 x 2^-1 = 1 x 2^0 + 1 x 2^-1 x 2^-1 = 0.75

Since floating point value is represented as above, it is different between the mathematical value and the computer's value. This is precision issue.


问:
"Unable to launch the IIS Express Web server." in Visual Studio
I attempted to run my web service through visual studio. I faced an issue like :

```<code>---------------------------
Microsoft Visual Studio
---------------------------
Unable to launch the IIS Express Web server.

Failed to register URL "http://localhost:63591/" for site "xxxxxx" application
"/". Error description: The process cannot access the file because it is being
used by another process. (0x80070020)

---------------------------
OK
---------------------------
</code>```

I saw the task manager and found that PID 4 is used by System and its Description is NT Kernel & System.
So I tried to stop the http service.
All dependency services stopped. But I am facing an issue in stopping http service like

```<code>The service is starting or stopping.  Please try again later.
</code>```

So, I tried to stop and start the service manually. But the End process is disabled.
It will be helpful if anyone could help with this issue

答:
I had the same Issue. As @Kautsky Lozano mentions above Another application is using that port.

So [for a Windows OS] just:

Open Resource Monitor (Task Manager -> Performance -> Open Resource Monitor )

Click on the Network tab.

And at TCP Connections find the application that uses the Local Port that IIS Express uses and close it. (it was firefox on my case)

Body:
I attempted to run my web service through visual studio. I faced an issue like :

---------------------------
Microsoft Visual Studio
---------------------------
Unable to launch the IIS Express Web server.

Failed to register URL "http://localhost:63591/" for site "xxxxxx" application
"/". Error description: The process cannot access the file because it is being
used by another process. (0x80070020)

---------------------------
OK
---------------------------

I saw the task manager and found that PID 4 is used by System and its Description is NT Kernel & System.
So I tried to stop the http service.
All dependency services stopped. But I am facing an issue in stopping http service like

The service is starting or stopping.  Please try again later.

So, I tried to stop and start the service manually. But the End process is disabled.
It will be helpful if anyone could help with this issue


问:
rpc.gssd - krb5.conf with includedir
I am trying to create a nfs kerberos configuration with includedir. The context is the following :

default realm points to TEST.REALM.COM (hadoop installation)

nas/nfs realm points to NFS.ANOTHER.REALM.COM

When I put all realms and domain realms in the krb5.conf file, I am able to mount my nfs share. When I use the includedir tag, thinks won't work out.

Here is my krb5.conf

```<code>includedir /etc/krb5.conf.d/

[logging]
 default = FILE:/var/log/krb5libs.log
 kdc = FILE:/var/log/krb5kdc.log
 admin_server = FILE:/var/log/kadmind.log

[libdefaults]
 dns_lookup_realm = false
 dns_lookup_kdc = false
 forwardable = true
 allow_weak_crypto = false
</code>```

Here is the config file for the default hadoop realm

```<code>[libdefaults]
 default_realm = TEST.REALM.COM

 TEST.REALM.COM = {
  ticket_lifetime = 1d
  renew_lifetime = 14d
 }

[realms]
 TEST.REALM.COM = {
  kdc = admhadoop1.realm.com
  kdc = admhadoop1.realm.com
  admin_server = admhadoop1.realm.com
 }

[domain_realm]
 .realm.com = TEST.REALM.COM
 realm.com = TEST.REALM.COM
</code>```

Here is the config for the nfs realm

```<code>[libdefaults]
 NFS.ANOTHER.REALM.COM = {
  ticket_lifetime = 14d
  renew_lifetime = 180d
 }

[realms]
 NFS.ANOTHER.REALM.COM = {
  kdc = admnfs1.realm.com
  kdc = admnfs2.realm.com
  admin_server = admnfs1.realm.com
 }

[domain_realm]
 nfs01.realm.com = NFS.ANOTHER.REALM.COM
</code>```

The /etc/krb5.keytab only containes the users host, nfs and root for the test01 server

Whit this configuration when I try to mount a share from nfs01.realm.com I'll get this kind of error :

```<code>rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a185b0 data 0x7fff55a18480
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: handling gssd upcall (/var/lib/nfs/rpc_pipefs/nfs/clnt16)
rpc.gssd[7078]: handle_gssd_upcall: 'mech=krb5 uid=0 enctypes=18,17,16,23,3,1,2 '
rpc.gssd[7078]: handling krb5 upcall (/var/lib/nfs/rpc_pipefs/nfs/clnt16)
rpc.gssd[7078]: process_krb5_upcall: service is '<null>'
rpc.gssd[7078]: Full hostname for 'nfs01.realm.com' is 'nfs01.realm.com'
rpc.gssd[7078]: Full hostname for 'test01.realm.com' is 'test01.realm.com'
rpc.gssd[7078]: No key table entry found for TEST01$@TEST.REALM.COM while getting keytab entry for 'TEST01$@TEST.REALM.COM'
rpc.gssd[7078]: No key table entry found for root/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'root/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: No key table entry found for nfs/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'nfs/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: No key table entry found for host/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'host/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: ERROR: gssd_refresh_krb5_machine_credential: no usable keytab entry found in keytab /etc/krb5.keytab for connection with host nfs01.realm.com
rpc.gssd[7078]: ERROR: No credentials found for connection to server nfs01.realm.com
rpc.gssd[7078]: doing error downcall
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: destroying client /var/lib/nfs/rpc_pipefs/nfs/clnt17
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
</code>```

It looks like the nfs deamon doesn not work with the includedir tag.

What do you think ?

答: the problem was that the files in the included directory should only have alphanumerical names (with "-" and "_") but no "." like in my case.

Title: rpc.gssd - krb5.conf with includedir

Body:
I am trying to create a nfs kerberos configuration with includedir. The context is the following :

default realm points to TEST.REALM.COM (hadoop installation)

nas/nfs realm points to NFS.ANOTHER.REALM.COM

When I put all realms and domain realms in the krb5.conf file, I am able to mount my nfs share. When I use the includedir tag, thinks won't work out.

Here is my krb5.conf

includedir /etc/krb5.conf.d/

[logging]
 default = FILE:/var/log/krb5libs.log
 kdc = FILE:/var/log/krb5kdc.log
 admin_server = FILE:/var/log/kadmind.log

[libdefaults]
 dns_lookup_realm = false
 dns_lookup_kdc = false
 forwardable = true
 allow_weak_crypto = false

Here is the config file for the default hadoop realm

[libdefaults]
 default_realm = TEST.REALM.COM

 TEST.REALM.COM = {
  ticket_lifetime = 1d
  renew_lifetime = 14d
 }

[realms]
 TEST.REALM.COM = {
  kdc = admhadoop1.realm.com
  kdc = admhadoop1.realm.com
  admin_server = admhadoop1.realm.com
 }

[domain_realm]
 .realm.com = TEST.REALM.COM
 realm.com = TEST.REALM.COM

Here is the config for the nfs realm

[libdefaults]
 NFS.ANOTHER.REALM.COM = {
  ticket_lifetime = 14d
  renew_lifetime = 180d
 }

[realms]
 NFS.ANOTHER.REALM.COM = {
  kdc = admnfs1.realm.com
  kdc = admnfs2.realm.com
  admin_server = admnfs1.realm.com
 }

[domain_realm]
 nfs01.realm.com = NFS.ANOTHER.REALM.COM

The /etc/krb5.keytab only containes the users host, nfs and root for the test01 server

Whit this configuration when I try to mount a share from nfs01.realm.com I'll get this kind of error :

rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a185b0 data 0x7fff55a18480
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: handling gssd upcall (/var/lib/nfs/rpc_pipefs/nfs/clnt16)
rpc.gssd[7078]: handle_gssd_upcall: 'mech=krb5 uid=0 enctypes=18,17,16,23,3,1,2 '
rpc.gssd[7078]: handling krb5 upcall (/var/lib/nfs/rpc_pipefs/nfs/clnt16)
rpc.gssd[7078]: process_krb5_upcall: service is '<null>'
rpc.gssd[7078]: Full hostname for 'nfs01.realm.com' is 'nfs01.realm.com'
rpc.gssd[7078]: Full hostname for 'test01.realm.com' is 'test01.realm.com'
rpc.gssd[7078]: No key table entry found for TEST01$@TEST.REALM.COM while getting keytab entry for 'TEST01$@TEST.REALM.COM'
rpc.gssd[7078]: No key table entry found for root/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'root/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: No key table entry found for nfs/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'nfs/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: No key table entry found for host/test01.realm.com@TEST.REALM.COM while getting keytab entry for 'host/test01.realm.com@TEST.REALM.COM
rpc.gssd[7078]: ERROR: gssd_refresh_krb5_machine_credential: no usable keytab entry found in keytab /etc/krb5.keytab for connection with host nfs01.realm.com
rpc.gssd[7078]: ERROR: No credentials found for connection to server nfs01.realm.com
rpc.gssd[7078]: doing error downcall
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: destroying client /var/lib/nfs/rpc_pipefs/nfs/clnt17
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000
rpc.gssd[7078]: dir_notify_handler: sig 37 si 0x7fff55a1d130 data 0x7fff55a1d000

It looks like the nfs deamon doesn not work with the includedir tag.

What do you think ?


问:
why do we even need VPTR?
And why don't we use the same method for non virtual functions?

I mean, why do we use virtual functions in that way? Can't we just use them as non-virtaul ones and override them?

And if this method is saving us time/space or what ever, why don't we use the same method for non-virtual functions? I mean it would make sense that there would be one table of functions for a specific class.

Anyway, thanks in advance, I am just a bit confused.

答:
You can't have run-time polymorphism without using a level of indirection. That's what the vptr is for.

The vptr is not used for non-polymorphic functions because that indirection costs something. The C++ philosophy is that you don't pay for what you don't use.

EDIT:

Here's some info on how virtual tables work: http://en.wikipedia.org/wiki/Virtual_table

Title: why do we even need VPTR?


问:
AssertionError: Element odoo has extra content: report, line 7
When i try to give report_name in report tag it throws below error:
AssertionError: Element odoo has extra content: report, line 7

*.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   report_name="PPPPPPPPPPpppp" //Here is the problem
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>
</code>```

If i remove attribute report_name it will work fine, and use value of string as report name. I need to give other name. How can i resolve this issue?

答:
The attribute that you are trying to use here, "report_name", is the culprit. There is no attribute such as "report_name". Use the attribute "name" instead.

See the example below:

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>
</code>```

Body:
When i try to give report_name in report tag it throws below error:
AssertionError: Element odoo has extra content: report, line 7

*.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   report_name="PPPPPPPPPPpppp" //Here is the problem
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>

If i remove attribute report_name it will work fine, and use value of string as report name. I need to give other name. How can i resolve this issue?

Body:
The attribute that you are trying to use here, "report_name", is the culprit. There is no attribute such as "report_name". Use the attribute "name" instead.

See the example below:

<?xml version="1.0" encoding="utf-8"?>
<odoo>

   <report id="action_report_followup"
   model="account_followup.followup"
   string="Follow-up Report"
   report_type="qweb-pdf"
   name="payment_followup.report_followup"
   file="payment_followup.report_followup"
   menu="True"/>

</odoo>


问:
Apply order by on a joining table field in eloquent
I have a query which joins one table with another one in a one to one relation. How can I sort the result by a column in the joining relation

```<code>$relation = ModelObject::where('status', '=', 1)
                            ->with('related_table')
                            ->get()
</code>```

I need to sort this with a column(Eg: name) of related_table. How to do this in eloquent.

答:
you may use this</p>

```<code> $categories = Category::select(DB::raw('categories.*, count(*) as
`aggregate`'))
->join('pictures', 'categories.id', '=', 'pictures.category_id')
->groupBy('category_id')
->orderBy('aggregate', 'desc');
</code>```

Body:
I have a query which joins one table with another one in a one to one relation. How can I sort the result by a column in the joining relation

$relation = ModelObject::where('status', '=', 1)
                            ->with('related_table')
                            ->get()

I need to sort this with a column(Eg: name) of related_table. How to do this in eloquent.

Body:
you may use this

 $categories = Category::select(DB::raw('categories.*, count(*) as
`aggregate`'))
->join('pictures', 'categories.id', '=', 'pictures.category_id')
->groupBy('category_id')
->orderBy('aggregate', 'desc');


问:
How to append the datetime to the file name which publish to Azure Data Lake Store by Data factory?
I try to use the Azure Data Factory to push the data from table storage to Azure Data Lake Store. And in Data Factory.

I defined the output entity and try to add the datetime to the output file, but seems it doesn't work.

See the code below:

```<code> *"published": false,
        "type": "AzureDataLakeStore",
        "linkedServiceName": "Destination-DataLakeStore-bwb",
        "typeProperties": {
            "fileName": "tbTotalTollData{year}{Month}{Day}{Hour}",
            "folderPath": "Samples",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": ","
            }
        }
</code>```

Use the {year}{Month}{Day}{Hour} for the file name, but not work.

答:
The variables year, Month, Day that are used in the above code should be declared. Update the code as follows and try again                                   *"published": false,
        "type": "AzureDataLakeStore",
        "linkedServiceName": "Destination-DataLakeStore-bwb",
        "typeProperties": {
            "fileName": "tbTotalTollData{year}{Month}{Day}{Hour}",
            "folderPath": "Samples",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": ","
            }
        },
        "partitionedBy": [
                {
                    "name": "Year",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "yyyy"
                    }
                },
                {
                    "name": "Month",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "MM"
                    }
                },
                {
                    "name": "Day",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "dd"
                    }
                },
                {
                    "name": "Hour",
                    "value": {
                        "type": "DateTime",
                        "date": "SliceStart",
                        "format": "hh"
                    }
                }
            ]

Body:
I try to use the Azure Data Factory to push the data from table storage to Azure Data Lake Store. And in Data Factory.

I defined the output entity and try to add the datetime to the output file, but seems it doesn't work.

See the code below:

 *"published": false,
        "type": "AzureDataLakeStore",
        "linkedServiceName": "Destination-DataLakeStore-bwb",
        "typeProperties": {
            "fileName": "tbTotalTollData{year}{Month}{Day}{Hour}",
            "folderPath": "Samples",
            "format": {
                "type": "TextFormat",
                "columnDelimiter": ","
            }
        }

Use the {year}{Month}{Day}{Hour} for the file name, but not work.


问:
Jenkins not triggering gerrit verify +1 after successfull build
My Jenkins version is 2.32.2, Gerrit is 2.14.1. When I made push to gerrit I can see that my voter starts. However, after successful building following ssh message is sent to gerrit by jenkins:

gerrit review 392,1 --message 'Build Successfull http://jenkins/job/voter/298/ : SUCCESS' --verified 0 --code-review 0

I've already checked gerrit plugin settings and as I can see correct vote for verify label is set. Please, see screenshot enter image description here. Can someone tell me how I can fix this?

答: Issue resolved itself somehow. Magic :)</p>

Body: Issue resolved itself somehow. Magic :)


问:
R Shiny how to add 'select all' in checkbox within renderui
I am using renderui in R Shiny to generate a checkbox, I'm wondering how to add a 'select all' option, which can be used to check and uncheck all the boxed.
here is an example of the checkbox I want

This link shows how to add the 'select all' button, but is not for the checkbox inside renderui. Currently the method I used is

```<code>  output$trmt_id <- renderUI({

if(is.null(ep_info())) {
  return()
}

trmt_ids <- unique(ep_info()$TRMT_ID)
# add 'selected = ' to pre-select ctrl
checkboxGroupInput("input_trmt_id", "Choose Treatment ID (Include Control)", choices = c(trmt_ids, 'All'))})

observeEvent(input$input_trmt_id, {
if (input$input_trmt_id %in% 'All') {

  updateCheckboxGroupInput(session, "input_trmt_id", "Choose Treatment ID (Include Control)", choices = c(unique(ep_info()$TRMT_ID), 'all'), selected = unique(ep_info()$TRMT_ID))
}})
</code>```

But the problem of this piece of code is user cannot unselect all boxed just by clicking 'all' again.

Do you have some better ideas? Thanks in advance!

答:
No checkboxes, but an easy alternative with pickerInput :

```<code>library("shiny")
library("shinyWidgets")

ui <- fluidPage(
  column(
    width = 4,
    pickerInput(
      inputId = "id", label = "Choices :",
      choices = c("Banana", "Blueberry", "Cherry", "Coconut", "Grapefruit",
                  "Kiwi", "Lemon", "Lime", "Mango", "Orange", "Papaya"),
      options = list(`actions-box` = TRUE, `selected-text-format` = "count > 2",
                     `count-selected-text` = "{0}/{1} fruits"),
      multiple = TRUE
    ),
    verbatimTextOutput(outputId = "res")
  )
)

server <- function(input, output) {
  output$res <- renderPrint({
    input$id
  })
}

shinyApp(ui = ui, server = server)
</code>```

Result looks like :

Body:
I am using renderui in R Shiny to generate a checkbox, I'm wondering how to add a 'select all' option, which can be used to check and uncheck all the boxed.
here is an example of the checkbox I want

This link shows how to add the 'select all' button, but is not for the checkbox inside renderui. Currently the method I used is

  output$trmt_id <- renderUI({

if(is.null(ep_info())) {
  return()
}

trmt_ids <- unique(ep_info()$TRMT_ID)
# add 'selected = ' to pre-select ctrl
checkboxGroupInput("input_trmt_id", "Choose Treatment ID (Include Control)", choices = c(trmt_ids, 'All'))})

observeEvent(input$input_trmt_id, {
if (input$input_trmt_id %in% 'All') {

  updateCheckboxGroupInput(session, "input_trmt_id", "Choose Treatment ID (Include Control)", choices = c(unique(ep_info()$TRMT_ID), 'all'), selected = unique(ep_info()$TRMT_ID))
}})

But the problem of this piece of code is user cannot unselect all boxed just by clicking 'all' again.

Do you have some better ideas? Thanks in advance!

Body:
No checkboxes, but an easy alternative with pickerInput :

library("shiny")
library("shinyWidgets")

ui <- fluidPage(
  column(
    width = 4,
    pickerInput(
      inputId = "id", label = "Choices :",
      choices = c("Banana", "Blueberry", "Cherry", "Coconut", "Grapefruit",
                  "Kiwi", "Lemon", "Lime", "Mango", "Orange", "Papaya"),
      options = list(`actions-box` = TRUE, `selected-text-format` = "count > 2",
                     `count-selected-text` = "{0}/{1} fruits"),
      multiple = TRUE
    ),
    verbatimTextOutput(outputId = "res")
  )
)

server <- function(input, output) {
  output$res <- renderPrint({
    input$id
  })
}

shinyApp(ui = ui, server = server)

Result looks like :


问:
Joomla - delay on publishing new things
If I disable the cache on Joomla 1.5 and I publish a new menu item or any other information on the site the new element don't appear immediately after.

If I enable the cache on Joomla 1.5 and I set it to 1 minute delay, and I publish a new menu item, I wait a minute, I do refresh, and I see no menu item.

I only see those new elements, after a certain period of time, regardless joomla configuration options on cache page.

What could this be?

Thanks a lot,
MEM

答:
For anyone else that may have this same issue:

It seems that this is something related with Joomla 1.5.x only. Not sure on what configurations. The only way that we found to solve it was to:

If we go to Extensions (or addons not sure since this one is not in English).
Then we click under "plugin management" and then, we need to find the system-cache option, and disabled it.

Title: Joomla - delay on publishing new things


问:
Getting elements from XML file in Perl
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

```<code><csixml version="1.0">
    <head>
    <details>
        <name-link>linkName</name-link>
        <table>links</table>
        <model>XS1-556</model>
    </details>
        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>
    </head>
    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>
</code>```

And this is the code :

```<code>my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};
</code>```

When I try it with XML:LibXML it gives me an error that says:

```<code>Start tag expected, '<' not found
</code>```

答:
XML::LibXML is likely complaining about some slightly broken XML. The XML spec is strict, and says amongst other things - errors are fatal. But it works:

```<code>#!/usr/bin/env perl
use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML->load_xml ( IO => \*DATA );
foreach my $node ( $doc -> findnodes ( '//record/v2' ) ) {
   print $node -> textContent;
}

__DATA__
<csixml version="1.0">
    <head>
    <details>
        <name-link>linkName</name-link>
        <table>links</table>
        <model>XS1-556</model>
    </details>
        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>
    </head>
    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>
</code>```

XML::LibXML supports xpath which is invaluable for the sort of thing you're trying to do - you can either specify a full path in the document, or use // to indicate 'anywhere in document'.

So either:

```<code>/csixml/data/record/v2
</code>```

Or:

```<code>//record/v2
</code>```

Will find the value you want.

But can also do other useful things like:

```<code>foreach my $node ( $doc -> findnodes ( '//record/*[string()="34.1"]' ) ) {
   print $node -> nodeName;
}
</code>```

So I think the problem at heart here, is that you're loading your XML incorrectly. It certainly works in the example above (IO => \*DATA loads from the special inline DATA filehandle, but it works fine for your example).

Title: Getting elements from XML file in Perl

Body:
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

<csixml version="1.0">

        <name-link>linkName</name-link>

links

        <model>XS1-556</model>

        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>

    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>

And this is the code :

my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};

When I try it with XML:LibXML it gives me an error that says:

Start tag expected, '<' not found

Body:
XML::LibXML is likely complaining about some slightly broken XML. The XML spec is strict, and says amongst other things - errors are fatal. But it works:

#!/usr/bin/env perl
use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML->load_xml ( IO => \*DATA );
foreach my $node ( $doc -> findnodes ( '//record/v2' ) ) {
   print $node -> textContent;
}

__DATA__
<csixml version="1.0">
    <head>
    <details>
        <name-link>linkName</name-link>
        <table>links</table>
        <model>XS1-556</model>
    </details>
        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>
    </head>
    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>

XML::LibXML supports xpath which is invaluable for the sort of thing you're trying to do - you can either specify a full path in the document, or use // to indicate 'anywhere in document'.

So either:

/csixml/data/record/v2

Or:

//record/v2

Will find the value you want.

But can also do other useful things like:

foreach my $node ( $doc -> findnodes ( '//record/*[string()="34.1"]' ) ) {
   print $node -> nodeName;
}

So I think the problem at heart here, is that you're loading your XML incorrectly. It certainly works in the example above (IO => \*DATA loads from the special inline DATA filehandle, but it works fine for your example).


问:
Add circle to map with carto.js and leaflet libraries
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

```<code>layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);
</code>```

Error and log are the same...

EDIT 2

With this code

```<code>var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);
</code>```

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

答:
SOLVED

The correct way is

```<code>L.circle([data.lat, data.lon], data.distance, {}).addTo(map);
</code>```

where data.distance is the radius of circle. Official doc's example L.circle([50.5, 30.5], {radius: 200}).addTo(map); seems to be wrong.

Body:
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);

Error and log are the same...

EDIT 2

With this code

var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

Body:
SOLVED

The correct way is

L.circle([data.lat, data.lon], data.distance, {}).addTo(map);

where data.distance is the radius of circle. Official doc's example L.circle([50.5, 30.5], {radius: 200}).addTo(map); seems to be wrong.


问:
Condition on rows content of dataframe in Spark scala
I have the following dataframe:

```<code>+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+
</code>```

I would like to put the result of value2/value3 of the rows when value1=b, then add it for all the rows (even the rows that do not belong to b) in a new field with name of "result". It means that another column must be added to the dataframe. For example for all the rows, the result of 5/4 (I choose it since, it is for b) should be added to dataframe. I know that, I should use this code:

```<code> val dataframe_new = Dataframe.withColumn("result", $"value1" / $"value2")
 Dataframe.show()
</code>```

However how can I put the condition in such a way that, it added it to all rows. The output should be like below:

```<code>+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  1.25|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  1.25|
+---+---+---+------+
</code>```

Can you help me? Thanks in advance.

Body:
I have the following dataframe:

+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+

I would like to put the result of value2/value3 of the rows when value1=b, then add it for all the rows (even the rows that do not belong to b) in a new field with name of "result". It means that another column must be added to the dataframe. For example for all the rows, the result of 5/4 (I choose it since, it is for b) should be added to dataframe. I know that, I should use this code:

 val dataframe_new = Dataframe.withColumn("result", $"value1" / $"value2")
 Dataframe.show()

However how can I put the condition in such a way that, it added it to all rows. The output should be like below:

+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  1.25|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  1.25|
+---+---+---+------+

Can you help me? Thanks in advance.

Body:
The answer is almost similar to eliasah but with different flavors. I am writing it so that others can benefit from this approach too

import sqlContext.implicits._

val df = Seq(
  ("a", 2, 3),
  ("b", 5, 4),
  ("b", 5, 4),
  ("c", 3, 4)
).toDF("value1", "value2", "value3")

should have

+------+------+------+
|value1|value2|value3|
+------+------+------+
|a     |2     |3     |
|b     |5     |4     |
|b     |5     |4     |
|c     |3     |4     |
+------+------+------+

And

df.withColumn("result", lit(data.filter($"value1" === "b").select($"value2"/$"value3").first.get(0)))

should generate the output

+------+------+------+------+
|value1|value2|value3|result|
+------+------+------+------+
|a     |2     |3     |1.25  |
|b     |5     |4     |1.25  |
|b     |5     |4     |1.25  |
|c     |3     |4     |1.25  |
+------+------+------+------+


问:
Finding Class Elements in a List of Classes
I am trying to use the "List.Find" method to find a match with an element in my class.  Here is an example...

```<code>class MyClass
{
    String item1;
    String item2;
}

List<MyClass> myClassList = new List<MyClass>();

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????
</code>```

Anyway, I hope that explains a bit better.  I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

答:
Use the where extension method:

```<code>var items = myClassList.Where(x => x.item1 == "abc");
</code>```

The above snippet will return all objects with property item1 equal to "abc".

Body:
I am trying to use the "List.Find" method to find a match with an element in my class.  Here is an example...

class MyClass
{
    String item1;
    String item2;
}

List<MyClass> myClassList = new List<MyClass>();

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????

Anyway, I hope that explains a bit better.  I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

Body:
Use the where extension method:

var items = myClassList.Where(x => x.item1 == "abc");

The above snippet will return all objects with property item1 equal to "abc".


问:
How to make results of a join statement a new table
I have the following mysql query. How can i make the result of the query be a new table;</p>

```<code>SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));
</code>```

答:
Simple create the view instead of table

view is nothing but , a view is a virtual table based on the result-set of an SQL statement.

```<code>CREATE VIEW view_name AS SELECT t1.referree .....
</code>```

Take look on documentation for more info about view

Body:
I have the following mysql query. How can i make the result of the query be a new table;

SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));

Body:
Simple create the view instead of table

view is nothing but , a view is a virtual table based on the result-set of an SQL statement.

CREATE VIEW view_name AS SELECT t1.referree .....

Take look on documentation for more info about view


问:
Symfony 2.8 Services issue
Since the last 4 hours I'm trying to understand the logic of Symfony 2 services and how they integrate in the application...

Basically I'm trying to set my EntityManager via a service and use it in a controller

I have the following structure

```<code>Bundle1/Controller/Bundle1Controller.php
Bundle1/Services/EntityService.php
Bundle2/Controller/Bundle2Controller.php
Bundle3/Controller/Bundle3Controller.php
....
</code>```

I'm trying to make a REST API with different entry points, that's why I use multiple bundles bundle2,bundle3....

The logic is the following:

A POST is fired to Bundle2/Controller/Bundle2Controller.php

Bundle2Controller.php instances a new() Bundle1Controller.php

Inside Bundle1Controller I want to access a service entity_service in order to get my EntityManager

I have 2 cases in which I manage to land...

In Bundle1/Controller/Bundle1Controller if I try $this->container or $this->get('entity_service') I get a null everytime

If I set the container in Bundle2/Controller/Bundle2Controller and try $this->get('entity_service') I get You have requested a non-existent service "entity_service"

I will place all the code below

Bundle1/Controller/Bundle1Controller

```<code><?php

namespace Bundle1\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use EntityBundle\Entity\TestEntity;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class Bundle1Controller extends Controller
{

    /**
     * @param $response
     * @return array
     */
    public function verifyWebHookRespone($response){

        $em = $this->get('entity_service')->getEm();

        $array = json_decode($response);

        $mapping = $em->getRepository('EntityBundle:TestEntity')
               ->findBy(["phone" => $array['usernumber']]);

        return $mapping;

    }
}
</code>```

Bundle2/Controller/Bundle2Controller.php

```<code><?php

namespace Bundle2\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Bundle1\Controller\Bundle1Controller;

class Bundle2Controller extends Controller
{

    public function webhookAction(Request $request)
    {
        $data = $request->request->get('messages');

        $model = new Bundle1Controller();
        $responseMessage = $model->verifyWebHookRespone($data);

        return new Response($responseMessage, Response::HTTP_CREATED, ['X-My-Header' => 'My Value']);

    }
}
</code>```

Bundle1/Services/EntityService.php

```<code><?php

namespace EntityBundle\Services;

use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\Container;

class EntityService
{
    protected $em;
    private $container;

    public function __construct(EntityManager $entityManager, Container $container)
    {
        $this->em = $entityManager;
        $this->container = $container;
    }

    /**
     * @return EntityManager
     */

    public function getEm()
    {
        return $this->em;
    }
}
</code>```

services.yml

```<code>services:
entity_service:
        class: Bundle1\Services\EntityService
        arguments: [ "@doctrine.orm.entity_manager" , "@service_container"   ]
</code>```

Can anyone please help me with something regarding this issue?
How can I register a service and call it from anywhere no matter the bundle or another service?

答:
You should check where your services.yml is located and whether it is imported in the config.yml

You can't just instantiate a controller and expect it to work, you need to set the container.

But you can call EntityManager without needing any other service by using;

$this->get('doctrine.orm.entity_manager');

I can't understand your structure or what you are trying to achieve, but those are the options to go about if you want to keep this structure.

Title: Symfony 2.8 Services issue

Body:
Since the last 4 hours I'm trying to understand the logic of Symfony 2 services and how they integrate in the application...

Basically I'm trying to set my EntityManager via a service and use it in a controller

I have the following structure

Bundle1/Controller/Bundle1Controller.php
Bundle1/Services/EntityService.php
Bundle2/Controller/Bundle2Controller.php
Bundle3/Controller/Bundle3Controller.php
....

I'm trying to make a REST API with different entry points, that's why I use multiple bundles bundle2,bundle3....

The logic is the following:

A POST is fired to Bundle2/Controller/Bundle2Controller.php

Bundle2Controller.php instances a new() Bundle1Controller.php

Inside Bundle1Controller I want to access a service entity_service in order to get my EntityManager

I have 2 cases in which I manage to land...

In Bundle1/Controller/Bundle1Controller if I try $this->container or $this->get('entity_service') I get a null everytime

If I set the container in Bundle2/Controller/Bundle2Controller and try $this->get('entity_service') I get You have requested a non-existent service "entity_service"

I will place all the code below

Bundle1/Controller/Bundle1Controller

<?php

namespace Bundle1\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use EntityBundle\Entity\TestEntity;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class Bundle1Controller extends Controller
{

    /**
     * @param $response
     * @return array
     */
    public function verifyWebHookRespone($response){

        $em = $this->get('entity_service')->getEm();

        $array = json_decode($response);

        $mapping = $em->getRepository('EntityBundle:TestEntity')
               ->findBy(["phone" => $array['usernumber']]);

        return $mapping;

    }
}

Bundle2/Controller/Bundle2Controller.php

<?php

namespace Bundle2\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Bundle1\Controller\Bundle1Controller;

class Bundle2Controller extends Controller
{

    public function webhookAction(Request $request)
    {
        $data = $request->request->get('messages');

        $model = new Bundle1Controller();
        $responseMessage = $model->verifyWebHookRespone($data);

        return new Response($responseMessage, Response::HTTP_CREATED, ['X-My-Header' => 'My Value']);

    }
}

Bundle1/Services/EntityService.php

<?php

namespace EntityBundle\Services;

use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\Container;

class EntityService
{
    protected $em;
    private $container;

    public function __construct(EntityManager $entityManager, Container $container)
    {
        $this->em = $entityManager;
        $this->container = $container;
    }

    /**
     * @return EntityManager
     */

    public function getEm()
    {
        return $this->em;
    }
}

services.yml

services:
entity_service:
        class: Bundle1\Services\EntityService
        arguments: [ "@doctrine.orm.entity_manager" , "@service_container"   ]

Can anyone please help me with something regarding this issue?
How can I register a service and call it from anywhere no matter the bundle or another service?


问:
How to overlap .NET UI control on a map
I wanted to set multiple Symbols on a same Layer but, as far as I know, SharpMap (v4.0) does not support this. So I decided to set a lonely Layer populated by Points and "paste" dotNet UserInterfaces over each point.

Each interactive UI have its own object declared inside that will condition its attributes such as the image shown, if its visible or not, etc...

So, how can I link those UI location to their corresponding layer points? I've been trying method "MapControl.PointToScreen()" but does nothing, need something like this:

myUI.Location = myPoint.Coordinate;

Simple examples or just other points of view of the problem would be awesome and very welcome. Thx!!!

答:
Solved:

PointF myScreen_Fpoint = mapControl.Map.WorldToImage(MapCoord);

Title: How to overlap .NET UI control on a map


问:
Regular expression to match 1.* only
I've tried various regular expression but can't get this one quite right.

I need to match 1.* so that means it has to be a 1 followed by a dot and any 1 or 2 digit number following the dot.

So examples of valid matches:

```<code>1.8
1.9
1.11
1.99
</code>```

Invalid:

```<code>2.1
9.19
1.111
</code>```

答:
The regex you are looking for is 1\.\d{1,2}$. Try the demo here on Regex101.com.

To split it out:

1 - matches literal number one.

\. - matches literal dot character (you need the escape slash)

\d - matches any number character (it's culture invariant, so it's not only 0-9 characters - if you want only these, use [0-9] as comments to your question suggest)

{1,2} - is a quantifier applied to \d - minimum 1 occurence, maximum 2 occurences

$ - anchors the text to the end of the string/line (depending whether multiline regex option is set to true)

Title: Regular expression to match 1.* only

Body:
I've tried various regular expression but can't get this one quite right.

I need to match 1.* so that means it has to be a 1 followed by a dot and any 1 or 2 digit number following the dot.

So examples of valid matches:

1.8
1.9
1.11
1.99

Invalid:

2.1
9.19
1.111


问:
AngularJS-Smart-Table Deleting row does not delete row's selection in options menu
Stack,

I have a smart table generating rows when the user clicks add and deleting them when they click the relevant row remove button. This, for the most part, works, except there is a "common type" selection box to autofill most of the data in a row which is only being deleted if it is in the final row of the table and then removed.

I have made an image attempting to explain how this works from the output:

Upon removal of the second row of data in the data above

I'm unsure of the problem solving approach to fix this, as the removal of wunits and their data from the row is working fine. Would someone be able to explain how one might go about fixing the issue with select or point me in the right direction for material (I'm still a complete novice to web development in general).

Below are the relevant snippets of code from the function called on the removal button being pressed and the html for the body of the table, where the model is being manipulated to generate new rows.

        $scope.removeItem = function removeItem(removeID)
        {
            for(var i = 0; i < $scope.wunits.length; i++)
            {
                if($scope.wunits[i].id === removeID.id)
                {
                    $scope.wunits.splice(i, 1);
                    $scope.selectedCommonType.splice(i, 1);
                    break;
                }
            }
        };```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <table class="w3-container w3-red" st-table="displayedCollection" st-safe-src="wunits" class="table table-striped">

            <tbody>
            <tr ng-repeat="wunit in wunits | filter:selected.iwtfReference  track by $index">
                <td>
                    <input ng-model = "wunit.reference" placeholder="{{wunit.reference}}">
                </td>
                <td>
                    <select ng-model="selectedCommonType"
                            ng-options="common.name for common in commonWastes" >
                    </select>
                </td>
                <td>
                    <input ng-if="!selectedCommonType" ng-model="wunit.name">
                    <input ng-model="wunit.name" ng-if="selectedCommonType" placeholder="{{selectedCommonType.name}}">
                </td>
                <td>
                    <input ng-if="!selectedCommonType" ng-model="wunit.description">
                    <input ng-model="wunit.description" ng-if="selectedCommonType" placeholder="{{selectedCommonType.desc}}">
                </td>
                <td>
                    <input ng-model="wunit.quantity">
                </td>
                <td>
                    <input ng-if="!selectedCommonType" ng-model="wunit.weight">
                    <input ng-model="wunit.weight" ng-if="selectedCommonType" placeholder="{{selectedCommonType.weight}}">
                </td>
                <td>
                    <input ng-if="!selectedCommonType" ng-model="wunit.volume">
                    <input ng-model="wunit.volume" ng-if="selectedCommonType" placeholder="{{selectedCommonType.volume}}">
                </td>
                <td class="w3-size w3-tiny">
                    <input ng-if="!selectedCommonType" ng-model="wunit.codes">
                    <input ng-model="wunit.codes" ng-if="selectedCommonType" placeholder="{{selectedCommonType.codes}}">
                </td>
                <td>{{wunit.producer}}</td>
                <td>{{wunit.producerReference}}</td>
                <td>{{wunit.producerSite}}</td>
                <td>
                    <button ng-click="removeItem(wunit)">Remove Record</button>
                </td>
            </tr>
            </tbody>
        </table></code>```

If there is any other relevant information you might need, please let me know.

Connor

答:
you can simply pass the index to the function and delete the item from array

```<code><td>
   <button ng-click="removeItem(wunit,$index)">Remove Record</button>
</td>
</code>```

can you try rewriting your java script as this ?

```<code>$scope.removeItem = function removeItem(removeID,index)
    {
        for(var i = 0; i < $scope.wunits.length; i++)
        {
            if($scope.wunits[i].id === removeID.id)
            {
                $scope.wunits.splice(i, 1);
                $scope.selectedCommonType.splice(index, 1);
                break;
            }
        }
    };
</code>```

your deleting from same index from your main object also.
$scope.selectedCommonType index is not i. i is the correct index for wunits

Body:
Stack,

I have a smart table generating rows when the user clicks add and deleting them when they click the relevant row remove button. This, for the most part, works, except there is a "common type" selection box to autofill most of the data in a row which is only being deleted if it is in the final row of the table and then removed.

I have made an image attempting to explain how this works from the output:

Upon removal of the second row of data in the data above

I'm unsure of the problem solving approach to fix this, as the removal of wunits and their data from the row is working fine. Would someone be able to explain how one might go about fixing the issue with select or point me in the right direction for material (I'm still a complete novice to web development in general).

Below are the relevant snippets of code from the function called on the removal button being pressed and the html for the body of the table, where the model is being manipulated to generate new rows.

        $scope.removeItem = function removeItem(removeID)
        {
            for(var i = 0; i < $scope.wunits.length; i++)
            {
                if($scope.wunits[i].id === removeID.id)
                {
                    $scope.wunits.splice(i, 1);
                    $scope.selectedCommonType.splice(i, 1);
                    break;
                }
            }
        };

                    <input ng-model = "wunit.reference" placeholder="{{wunit.reference}}">

                    <select ng-model="selectedCommonType"
                            ng-options="common.name for common in commonWastes" >
                    </select>

                    <input ng-if="!selectedCommonType" ng-model="wunit.name">
                    <input ng-model="wunit.name" ng-if="selectedCommonType" placeholder="{{selectedCommonType.name}}">

                    <input ng-if="!selectedCommonType" ng-model="wunit.description">
                    <input ng-model="wunit.description" ng-if="selectedCommonType" placeholder="{{selectedCommonType.desc}}">

                    <input ng-model="wunit.quantity">

                    <input ng-if="!selectedCommonType" ng-model="wunit.weight">
                    <input ng-model="wunit.weight" ng-if="selectedCommonType" placeholder="{{selectedCommonType.weight}}">

                    <input ng-if="!selectedCommonType" ng-model="wunit.volume">
                    <input ng-model="wunit.volume" ng-if="selectedCommonType" placeholder="{{selectedCommonType.volume}}">

                    <input ng-if="!selectedCommonType" ng-model="wunit.codes">
                    <input ng-model="wunit.codes" ng-if="selectedCommonType" placeholder="{{selectedCommonType.codes}}">

                {{wunit.producer}}
                {{wunit.producerReference}}
                {{wunit.producerSite}}

                    <button ng-click="removeItem(wunit)">Remove Record</button>

If there is any other relevant information you might need, please let me know.

Connor

Body:
you can simply pass the index to the function and delete the item from array

<td>
   <button ng-click="removeItem(wunit,$index)">Remove Record</button>
</td>

can you try rewriting your java script as this ?

$scope.removeItem = function removeItem(removeID,index)
    {
        for(var i = 0; i < $scope.wunits.length; i++)
        {
            if($scope.wunits[i].id === removeID.id)
            {
                $scope.wunits.splice(i, 1);
                $scope.selectedCommonType.splice(index, 1);
                break;
            }
        }
    };

your deleting from same index from your main object also.
$scope.selectedCommonType index is not i. i is the correct index for wunits


问:
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException:
```<code> Caused by: org.springframework.beans.factory.CannotLoadBeanClassException:
 Cannot find class

 [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean]

 for bean with name 'sessionFactory' defined in ServletContext resource >
  [/WEB-INF/cardreaderapp-servlet.xml];
     nested exception is java.lang.ClassNotFoundException:
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
</code>```

答:
```<code>i changed
  org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
 by
</code>```

org.springframework.orm.hibernate4.LocalSessionFactoryBean

```<code>Because in Hibernate4 AnnotationSessionFactoryBean is replaced by LocalSessionFactoryBean
</code>```

replaced

```<code> <bean   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFacoryBean" id="sessionFactory">
</code>```

by

```<code><bean    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
</code>```

Thats fix the issue

Body:
i changed
  org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
 by

org.springframework.orm.hibernate4.LocalSessionFactoryBean

Because in Hibernate4 AnnotationSessionFactoryBean is replaced by LocalSessionFactoryBean

replaced

 <bean   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFacoryBean" id="sessionFactory">

by

<bean    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">

Thats fix the issue


问:
Need Thin Table Borders in PDF Generated by cfDocument
I'm using border-collapse (CSS) to make thin borders on my table.  They render fine on the screen, but when they are sent into a PDF, via cfDocument, they end up as thicker grey borders.

I read that cfDocument doesn't support border-collapse yet, so what's my best option?

ColdFusion 9

答:
```<code>border-bottom: 0.4pt solid #ccc;
</code>```

Body: border-bottom: 0.4pt solid #ccc;


问:
Tkinter : How to set a background color to a cell of a grid?
I have created a Tkinter grid and would like to set different background colors for different cells of the grid.

How can I achieve this ?

答:
I create the grid like this :</p>

```<code>import numpy as np
from tkinter import *

M = np.array([[1, 2], [3, 4]])

root = Tk()

for i in range(len(M)): #Rows
    for j in range(len(M[0])): #Columns
        b = Label(root, text=str(M[i][j]))
        b.grid(row=i, column=j)

mainloop()
</code>```

Body:
I create the grid like this :

import numpy as np
from tkinter import *

M = np.array([[1, 2], [3, 4]])

root = Tk()

for i in range(len(M)): #Rows
    for j in range(len(M[0])): #Columns
        b = Label(root, text=str(M[i][j]))
        b.grid(row=i, column=j)

mainloop()


问:
Failed to reinstall Android APK
I had a small problem with my Android application. I wanted to change the name of the project because I had two of the same name I suppressed one and removed the figure '2' from the one I chose to keep. Now that I want to run it, it shows me an error message. Already two days that I am trying to solve is problem but I am really very very beginner especially on Android.

答: Renaming the project has no effect on it. What you have to do is to chage the application id in the build.gradle file</p>

Title: Failed to reinstall Android APK