问:
Ember syntax errors
I am learning ember.js with a tutorial that is built in to their documentation. Having installed it successfully, I followed the steps and created a new application with ember new ember-quickstart, generated a template and defined a route.  However, the data that I've included in the route model is not being rendered (there appears to be a parsing error due to an unexpected token default), but I have no idea what it might be referring to.  I have pasted the code exactly as it appears.  Any suggestions as to what might be causing the error?

```<code>SyntaxError: ember-quickstart/routes/scientists.js: Unexpected token (3:2)
</code>```

routes/scientists.js

```<code>import Ember from 'ember';

  default Ember.Route.extend({
  model(){
    return['Marie Curie', 'Albert Einstein', 'Andrei Sakharov']
  }
});
</code>```

templates/scientists.hbs

```<code><h2>List of Scientists</h2>

<ul>
  {{#each model as |scientist|}}
  <li>{{scientist}}</li>
  {{/each}}
</ul>
</code>```

 templates/application.hbs

```<code><h2 id="title">Welcome To Ember</h2>

{{outlet}}
</code>```

app/router.js

```<code>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('scientists');
});

export default Router;
</code>```

答:
```<code>default Ember.Route.extend({
</code>```

should be:

```<code>export default Ember.Route.extend({
</code>```

Title: Ember syntax errors

Body:
I am learning ember.js with a tutorial that is built in to their documentation. Having installed it successfully, I followed the steps and created a new application with ember new ember-quickstart, generated a template and defined a route.  However, the data that I've included in the route model is not being rendered (there appears to be a parsing error due to an unexpected token default), but I have no idea what it might be referring to.  I have pasted the code exactly as it appears.  Any suggestions as to what might be causing the error?

SyntaxError: ember-quickstart/routes/scientists.js: Unexpected token (3:2)

routes/scientists.js

import Ember from 'ember';

  default Ember.Route.extend({
  model(){
    return['Marie Curie', 'Albert Einstein', 'Andrei Sakharov']
  }
});

templates/scientists.hbs

List of Scientists

  {{#each model as |scientist|}}

{{scientist}}

  {{/each}}

 templates/application.hbs

Welcome To Ember

{{outlet}}

app/router.js

import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('scientists');
});

export default Router;

Body:
default Ember.Route.extend({

should be:

export default Ember.Route.extend({


来源: stackexchange

问:
$window.location = pdfLocation; not downloading PDF AngularJs
I am receiving the location of a pdf document in angular, and I cant get it to consistently download.

It works on my home laptop, but not whilst at work.
Code below

```<code>RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    $window.location = pdfLocation;
});
</code>```

Works in Chrome on Ubuntu at home, not on the same set up at work. Does anyone know any reason why the operation of '$window.location' wouldn't be idempotent?

Update:
Also works on FF on my work machine, just not Chrome

答:
Thanks to @lin I realised the issue was chrome blocking my download due to the advanced security option in Chrome:
"Protect you and your device from dangerous sites"

I'm not sure how to get around it yet, and will update this answer if I find a solution

ContentLicense: CC BY-SA 3.0

Body:
I am receiving the location of a pdf document in angular, and I cant get it to consistently download.

It works on my home laptop, but not whilst at work.
Code below

RenderService.document('document.pdf', spec).then(function(pdfLocation) {
    $window.location = pdfLocation;
});

Works in Chrome on Ubuntu at home, not on the same set up at work. Does anyone know any reason why the operation of '$window.location' wouldn't be idempotent?

Update:
Also works on FF on my work machine, just not Chrome


问:
Is it common to create a new case class for join tables?
I have 2 tables like:

```<code>users
id
name

lists
-id
-name

user_lists
id
list_id
user_id
</code>```

So I currently have a query that returns:

```<code>def getUsersByList(int listId): Future[Seq[UserList]] = {
  db.run( userLists.filter(f => f.listId === listId) )
}
</code>```

Now I need to join with the User table in order to get the User fields.

What options do I have in what I return?  I guess I have to create a new case class and map to the fields somehow?

答:
I think that your question (though maybe I am wrong) doesn't actually refer only to case class by rather to case class (aka unpacked type) and table mapping (aka mixed type). Also it is important to understand that Slick won't help you in any way with one-to-many / many-to-many relationships (it's not an ORM). Here a little bit more: https://stackoverflow.com/a/42218139/2239369

Long story short - your join table is table as any other. The general straightforward answer is: yes. Just create one more case class and table definition.

You for sure need your join table definition (in short - this class that inherits from Slicks Table type - mixed type). Otherwise you wouldn't be able to generate appropriate query. You could probably go away from creating case class - but I am not sure if it is worth doing it - after all it's one additional line, right? ( case class UserList(id: Id, listId: Id, userId: Id) - or something close to this).

It's perhaps worth to mention that you can also go away from all of above by creating a view on DB level.

Body:
I have 2 tables like:

users
id
name

lists
-id
-name

user_lists
id
list_id
user_id

So I currently have a query that returns:

def getUsersByList(int listId): Future[Seq[UserList]] = {
  db.run( userLists.filter(f => f.listId === listId) )
}

Now I need to join with the User table in order to get the User fields.

What options do I have in what I return?  I guess I have to create a new case class and map to the fields somehow?


问:
Is there a shortcut to move between header and source file in VC++?
This is a feature I have grown accustomed to in Eclipse (Ctrl+Tab). Is there an equivalent in Visual C++?

答: If you position your mouse over a function declaration in the header and press F12, the cpp file will be opened at the definition of the cpp file...  I use this feature extensively!</p>

ContentLicense: CC BY-SA 4.0


问:
how to get the name tag of an image
i have an image from my database in a different table displayed as $draft['draft_image'] and i want to send this data to a different table but im having a problem cause this code doesnt seems to work.. when i tried to click the published button there is no data that is being sent.i use var_dump to show the inserted data but nothing shows up in the inspect element.. any idea how can i get the image? this is what's inside my draft_image.. ../images/article/md.png

```<code><form method="POST" enctype="multipart/form-data">
   <img data-name="title_image" src="./<?= $draft['draft_image'];?>" style="margin-top:5px;" width="70%" height="55%"><br><br>
<?php
  }
?>
<button type="submit" name="submit" class="btn3 btn-default">Publish</button>
</form>

if (isset($_POST['submit'])) {
        $id = $session_id;
        $file = $_POST['title_image'];

        $ress = $db->draftpublished($id,$file);
        echo $ress;
          }
      ?>
</code>```

答:
```<code><form method="POST" enctype="multipart/form-data">
 <!-- added ----------------- -->
 <input type="hidden" name="title_image" value="<?=$draft['draft_image']?>">

   <img data-name="title_image" src="./<?= $draft['draft_image'];?>" style="margin-top:5px;" width="70%" height="55%"><br><br>
<?php
  }
?>
<button type="submit" name="submit" class="btn3 btn-default">Publish</button>
</form>

if (isset($_POST['submit'])) {
    $id = $session_id;
    $file = $_POST['title_image'];

    $ress = $db->draftpublished($id,$file);
    echo $ress;
      }
  ?>
</code>```

Title: how to get the name tag of an image

Body:
i have an image from my database in a different table displayed as $draft['draft_image'] and i want to send this data to a different table but im having a problem cause this code doesnt seems to work.. when i tried to click the published button there is no data that is being sent.i use var_dump to show the inserted data but nothing shows up in the inspect element.. any idea how can i get the image? this is what's inside my draft_image.. ../images/article/md.png

<form method="POST" enctype="multipart/form-data">
   <img data-name="title_image" src="./<?= $draft['draft_image'];?>" style="margin-top:5px;" width="70%" height="55%">

<?php
  }
?>
<button type="submit" name="submit" class="btn3 btn-default">Publish</button>
</form>

if (isset($_POST['submit'])) {
        $id = $session_id;
        $file = $_POST['title_image'];

        $ress = $db->draftpublished($id,$file);
        echo $ress;
          }
      ?>


问:
Unable to listen for a click event inside a bootstrap button-group from VueJS
I have the following bootstrap button group in a VueJS based project...

 <input type="radio" name="options" id="option1" autocomplete="off" v-on:click="clearEntries"> A

 <input type="radio" name="options" id="option2" autocomplete="off" v-on:click="clearEntries"> B

 <input type="radio" name="options" id="option3" autocomplete="off" checked v-on:click="clearEntries"> C

 <input type="radio" name="options" id="option4" autocomplete="off" v-on:click="clearEntries"> D

```

All I want to do is call a method when one of the radio buttons is selected/checked.

But the click event is never fired. I'm not sure if it is being suppressed by the bootstrap css.

Any ideas?

答:
Put the v-on:click="clearEntries" on the label and not the input.

new Vue({
  el: "#app",
  methods: {
    clearEntries: function() {
      alert('clearEntries !');
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div id="app">
<div class="btn-group btn-group-xs pull-right" data-toggle="buttons">
  <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option1" autocomplete="off"> A
  </label>
  <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option2" autocomplete="off"> B
  </label>
  <label v-on:click="clearEntries" class="btn btn-primary active label-primary">
 <input type="radio" name="options" id="option3" autocomplete="off" checked> C
  </label>
   <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option4" autocomplete="off"> D
  </label>
</div>
</div></code>```

Body:
I have the following bootstrap button group in a VueJS based project...

 <input type="radio" name="options" id="option1" autocomplete="off" v-on:click="clearEntries"> A

 <input type="radio" name="options" id="option2" autocomplete="off" v-on:click="clearEntries"> B

 <input type="radio" name="options" id="option3" autocomplete="off" checked v-on:click="clearEntries"> C

 <input type="radio" name="options" id="option4" autocomplete="off" v-on:click="clearEntries"> D

All I want to do is call a method when one of the radio buttons is selected/checked.

But the click event is never fired. I'm not sure if it is being suppressed by the bootstrap css.

Any ideas?

Body:
Put the v-on:click="clearEntries" on the label and not the input.

new Vue({
  el: "#app",
  methods: {
    clearEntries: function() {
      alert('clearEntries !');
    }
  }
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div id="app">
<div class="btn-group btn-group-xs pull-right" data-toggle="buttons">
  <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option1" autocomplete="off"> A
  </label>
  <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option2" autocomplete="off"> B
  </label>
  <label v-on:click="clearEntries" class="btn btn-primary active label-primary">
 <input type="radio" name="options" id="option3" autocomplete="off" checked> C
  </label>
   <label v-on:click="clearEntries" class="btn btn-primary label-primary">
 <input type="radio" name="options" id="option4" autocomplete="off"> D
  </label>
</div>
</div>


答:
You can pass the value using hidden type ex:</p>

```<code><form method="POST" enctype="multipart/form-data">
       <img data-name="title_image" src="./<?= $draft['draft_image'];?>" style="margin-top:5px;" width="70%" height="55%"><br><br>
       <input type="hidden" name="imgsrc" value="<?= $draft['draft_image'];?>">
<?php
  }
?>
<button type="submit" name="submit" class="btn3 btn-default">Publish</button>
</form>

if (isset($_POST['submit'])) {
        $id = $session_id;
        $file = $_POST['imgsrc'];

        $ress = $db->draftpublished($id,$file);
        echo $ress;
          }
      ?>
</code>```

Title: how to get the name tag of an image

Body:
You can pass the value using hidden type ex:

<form method="POST" enctype="multipart/form-data">
       <img data-name="title_image" src="./<?= $draft['draft_image'];?>" style="margin-top:5px;" width="70%" height="55%"><br><br>
       <input type="hidden" name="imgsrc" value="<?= $draft['draft_image'];?>">
<?php
  }
?>
<button type="submit" name="submit" class="btn3 btn-default">Publish</button>
</form>

if (isset($_POST['submit'])) {
        $id = $session_id;
        $file = $_POST['imgsrc'];

        $ress = $db->draftpublished($id,$file);
        echo $ress;
          }
      ?>


问:
Refreshing static content with Spring MVC and Boot
I'm evaluating Spring MVC & Boot and AngularJs for building web applications. I've run into the problem that when I make modifications to my static content (html, js, css), I have to restart the application every time. I hope there is a some way of solving that because restarting the whole application for static content changes is not efficient. Every other web app framework I've tried allows updating static content files on the fly(even just Spring MVC and plain old WAR application).

I've setup my project from "Building a RESTful Web Service with Spring Boot Actuator" guide (http://spring.io/guides/gs/actuator-service/). Basically it uses Spring Boot and MVC controllers to create a REST service. In addition, I've used "Consuming a RESTful Web Service with AngularJS" guide (http://spring.io/guides/gs/consuming-rest-angularjs/) to build a frontend with AngularJS. It creates a web page that displays the response from the REST service. The only change I've made is that the requests are made to my application instead of "http://rest-service.guides.spring.io/greeting". My static content is stored in "src/main/resources/public" folder. This setup works correctly except it doesn't reload static content.

答:
@eigil metioned addResources config for maven build. I'm using spring-boot-gradle-plugin in a gradle build, and I found this Spring Boot github issue
, and the Spring Boot doc mentioned this option too. Just add this directive to build.gradle and run Gradle task bootRun, then resource file refreshes immediately when saved. FYI.


问:
Select * from this week
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

```<code>$week = Date('W');
</code>```

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

```<code>$sql = 'SELECT * FROM my_table WHERE week = $week';
</code>```

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

答:
you have to use double quotes for the string:

```<code>$sql = "SELECT * FROM my_table WHERE week = $week";
</code>```

If not, $week will not substituted.

You should use prepared statements to prevent SQL injection.

Title: Select * from this week

Body:
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

$week = Date('W');

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

$sql = 'SELECT * FROM my_table WHERE week = $week';

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

Body:
you have to use double quotes for the string:

$sql = "SELECT * FROM my_table WHERE week = $week";

If not, $week will not substituted.

You should use prepared statements to prevent SQL injection.


问:
Update a db record in DJANGO with out having to use a form? EXAMPLE: Click to complete UPDATES a record
I have an item in a list. I want to click something and have that click trigger a view. That view updates that list item's status in the db.

For example, add to cart, or save the date, or completed.

In each case, clicking that link will update the db record with a new status. Right now these are just boolean fields.

You can see where this is going. A URL tied to that view will be called with Ajax. But I'm trying to do this with graceful degradation. I know how to do the Ajax part, just not the db update part.

I've never done much more than the basic form.is_valid and form.save. So I'm a little lost.

Ideas welcome.

Thanks

答:
Something like:

```<code>def some_view(request, *args, **kwargs):
    my_obj = MyModel.object.filter(pk=kwargs['id'])
    if my_obj:
        my_obj = my_obj[0]
        my_obj.fancy_status = "someone wants to buy me!"
        my_obj.save()
    return some_appropriate_response()
</code>```

with a url pattern like

```<code>(r'^/my_objects/(?P<id>\d{1,9})/buy/$', some_view)
</code>```

seems to be what you're looking for, right?

Basically, you can save instances of your models just like you might think.

ContentLicense: CC BY-SA 2.5

Body:
Something like:

def some_view(request, *args, **kwargs):
    my_obj = MyModel.object.filter(pk=kwargs['id'])
    if my_obj:
        my_obj = my_obj[0]
        my_obj.fancy_status = "someone wants to buy me!"
        my_obj.save()
    return some_appropriate_response()

with a url pattern like

(r'^/my_objects/(?P<id>\d{1,9})/buy/$', some_view)

seems to be what you're looking for, right?

Basically, you can save instances of your models just like you might think.


问:
Ionic cordova-facebook-plugin4 fails api graph call
I've got an application that I'm building and the code I've got works absolutely fine on Android devices but gives me a graph api error on iOS.

Here is the code I'm using for facebook login.

```<code>   constructor(private menuCtrl: MenuController, private nav: NavController, private playerService: Players, private userService: Users, private packService: Packs, private modalCtrl: ModalController, private loadingCtrl: LoadingController) {
        Facebook.browserInit(this.FB_APP_ID, "v2.8");
        menuCtrl.enable(false, 'navMenu');
    }

    ionViewLoaded() {
    }

    doFbLogin() {
        var permissions = new Array();
        let nav = this.nav;
        let userService = this.userService;
        let playerService = this.playerService;
        let packService = this.packService;
        var menuCtrl = this.menuCtrl;
        //the permissions your facebook app needs from the user
        permissions = ["public_profile", "email", "user_friends"];

        Facebook.login(permissions)
            .then(function (response) {
                let userId = response.authResponse.userID;
                //Getting name and gender properties
                Facebook.api("me/?fields=name,gender,email,friends", permissions)
                    .then(function (user) {
                        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
                        user.fbid = user.id;
                        //now we have the users info, let's save it in the NativeStorage
                        NativeStorage.setItem('user',
                            {
                                userid: userId,
                                name: user.name,
                                gender: user.gender,
                                picture: user.picture,
                                email: user.email,
                                fbid: user.id
                            })
                            .then(function (user) {
                                console.log("email to check", user.email);
                                //now we check if there is an existing account with this email address.
                                userService.accountExists(user.email).then((data) => {
                                    let founduser = data;
                                    if (founduser) {
                                        user = founduser;
                                        console.log("existing user no account created");
                                        menuCtrl.enable(true, 'navMenu');
                                        nav.setRoot(Dashboard);
                                        nav.pop();
                                        nav.push(Dashboard);
                                    } else {
                                        user.wins = 0;
                                        user.draws = 0;
                                        user.losses = 0;
                                        user.authenticated = true;
                                        user.maroon_points = 0;
                                        userService.createUser(user);
                                        var createdUser = {};

                                        //get user id of newly created user from db
                                        userService.accountExists(user.email).then((data) => {
                                            createdUser = { '_id': data._id };
                                            if (createdUser) {
                                                playerService.getStarterPlayers().then((data) => {
                                                    var starters = data;
                                                    let i = 0;
                                                    while (i < _.keys(starters).length) {
                                                        let playerObj = {
                                                            userid: createdUser['_id'],
                                                            playerid: starters[i]._id,
                                                            position: starters[i].position
                                                        };
                                                        console.log("playerObj[" + i + "]", playerObj);
                                                        playerService.giveOwnedPlayer(playerObj);
                                                        i++
                                                    }
                                                });

                                                packService.getStarter().then((data) => {
                                                    var packsChosen = data;
                                                    let j = 0;
                                                    while (j < _.keys(packsChosen).length) {
                                                        let packObj = {
                                                            _id: packsChosen[j]._id,
                                                            owner: createdUser['_id']
                                                        };
                                                        console.log("packObj[" + j + "]", packObj);
                                                        packService.giveSingle(packObj);
                                                        j++
                                                    }
                                                });

                                                menuCtrl.enable(true, 'navMenu');
                                                nav.setRoot(Dashboard);
                                                nav.pop();
                                                nav.push(Dashboard);
                                            } else {
                                                console.error("NO USER FOUND");
                                            }
                                        });
                                        console.log("no existing user account created!");
                                    }
                                });
                            }, function (error) {
                                console.log(error);
                            })
                    })
            }, function (error) {
                console.log("error - FB graph call failed", error);
            });
    }
</code>```

Here is the error which is thrown in safari web console when inspecting the app live on an iOS 10 iphone 6.

```<code>[Error] EXCEPTION: Uncaught (in promise): There was an error making the graph call.
    handleError (main.js:81941)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)

[Error] ORIGINAL STACKTRACE:
    handleError (main.js:81946)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)

[Error] v@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4869
s@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4298
s@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4113
file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4653
invokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:10289
onInvokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/main.js:41762:47
invokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:10232
runTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:7647
i@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:3714
invoke@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:11438
file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:2:30198
    handleError (main.js:81947)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)
</code>```

答: The issue was the other user who was compiling the code in xcode had out of date versions of most of the global plugins I was using including cordova.  Updating these, removing and adding the ios platform and then adding the cordova-facebook-plugin4 from the github master and doing a rebuild seemed to fix the issue.</p>

Body:
I've got an application that I'm building and the code I've got works absolutely fine on Android devices but gives me a graph api error on iOS.

Here is the code I'm using for facebook login.

   constructor(private menuCtrl: MenuController, private nav: NavController, private playerService: Players, private userService: Users, private packService: Packs, private modalCtrl: ModalController, private loadingCtrl: LoadingController) {
        Facebook.browserInit(this.FB_APP_ID, "v2.8");
        menuCtrl.enable(false, 'navMenu');
    }

    ionViewLoaded() {
    }

    doFbLogin() {
        var permissions = new Array();
        let nav = this.nav;
        let userService = this.userService;
        let playerService = this.playerService;
        let packService = this.packService;
        var menuCtrl = this.menuCtrl;
        //the permissions your facebook app needs from the user
        permissions = ["public_profile", "email", "user_friends"];

        Facebook.login(permissions)
            .then(function (response) {
                let userId = response.authResponse.userID;
                //Getting name and gender properties
                Facebook.api("me/?fields=name,gender,email,friends", permissions)
                    .then(function (user) {
                        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
                        user.fbid = user.id;
                        //now we have the users info, let's save it in the NativeStorage
                        NativeStorage.setItem('user',
                            {
                                userid: userId,
                                name: user.name,
                                gender: user.gender,
                                picture: user.picture,
                                email: user.email,
                                fbid: user.id
                            })
                            .then(function (user) {
                                console.log("email to check", user.email);
                                //now we check if there is an existing account with this email address.
                                userService.accountExists(user.email).then((data) => {
                                    let founduser = data;
                                    if (founduser) {
                                        user = founduser;
                                        console.log("existing user no account created");
                                        menuCtrl.enable(true, 'navMenu');
                                        nav.setRoot(Dashboard);
                                        nav.pop();
                                        nav.push(Dashboard);
                                    } else {
                                        user.wins = 0;
                                        user.draws = 0;
                                        user.losses = 0;
                                        user.authenticated = true;
                                        user.maroon_points = 0;
                                        userService.createUser(user);
                                        var createdUser = {};

                                        //get user id of newly created user from db
                                        userService.accountExists(user.email).then((data) => {
                                            createdUser = { '_id': data._id };
                                            if (createdUser) {
                                                playerService.getStarterPlayers().then((data) => {
                                                    var starters = data;
                                                    let i = 0;
                                                    while (i < _.keys(starters).length) {
                                                        let playerObj = {
                                                            userid: createdUser['_id'],
                                                            playerid: starters[i]._id,
                                                            position: starters[i].position
                                                        };
                                                        console.log("playerObj[" + i + "]", playerObj);
                                                        playerService.giveOwnedPlayer(playerObj);
                                                        i++
                                                    }
                                                });

                                                packService.getStarter().then((data) => {
                                                    var packsChosen = data;
                                                    let j = 0;
                                                    while (j < _.keys(packsChosen).length) {
                                                        let packObj = {
                                                            _id: packsChosen[j]._id,
                                                            owner: createdUser['_id']
                                                        };
                                                        console.log("packObj[" + j + "]", packObj);
                                                        packService.giveSingle(packObj);
                                                        j++
                                                    }
                                                });

                                                menuCtrl.enable(true, 'navMenu');
                                                nav.setRoot(Dashboard);
                                                nav.pop();
                                                nav.push(Dashboard);
                                            } else {
                                                console.error("NO USER FOUND");
                                            }
                                        });
                                        console.log("no existing user account created!");
                                    }
                                });
                            }, function (error) {
                                console.log(error);
                            })
                    })
            }, function (error) {
                console.log("error - FB graph call failed", error);
            });
    }

Here is the error which is thrown in safari web console when inspecting the app live on an iOS 10 iphone 6.

[Error] EXCEPTION: Uncaught (in promise): There was an error making the graph call.
    handleError (main.js:81941)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)

[Error] ORIGINAL STACKTRACE:
    handleError (main.js:81946)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)

[Error] v@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4869
s@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4298
s@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4113
file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:4653
invokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:10289
onInvokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/main.js:41762:47
invokeTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:10232
runTask@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:7647
i@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:3714
invoke@file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:3:11438
file:///var/containers/Bundle/Application/704E4F8E-C28D-49C9-9393-0CDA54106CAF/Pitchlife.app/www/build/polyfills.js:2:30198
    handleError (main.js:81947)
    handleError (main.js:152942)
    next (main.js:55809:94)
    (anonymous function) (main.js:57865)
    __tryOrUnsub (main.js:1389)
    next (main.js:1338)
    _next (main.js:1291)
    next (main.js:1255)
    next (main.js:7764)
    emit (main.js:57851)
    triggerError (main.js:41831)
    onHandleError (main.js:41792)
    runGuarded (polyfills.js:3:7279)
    r (polyfills.js:3:3818)
    i (polyfills.js:3:3867)
    invoke (polyfills.js:3:11439)
    (anonymous function) (polyfills.js:2:30199)


问:
How to fix - 41: non-static variable cannot be referenced from a static context -> What is the reason for this?
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

```<code>import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

```<code>import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

答:
This is what you want if you wish to make an instantiated (non-static) call to the function. For the rest of the answer, see EboMike's answer.</p>

```<code>Primes generator=new Primes(50);
generator.print();

  public void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
</code>```

Body:
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}

Body:
This is what you want if you wish to make an instantiated (non-static) call to the function. For the rest of the answer, see EboMike's answer.

Primes generator=new Primes(50);
generator.print();

  public void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }


问:
Display none at the end of animation
I'm trying to make element dissapear at the end of animation but it doesn't work, can someone explain how to make exit animation with element dissappearing at the end of it?:

```<code>var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event){
    event.target.style.animation = "changeOpacity 1s linear";
    if(event.target.style.opacity === 0){
        event.target.style.display = "none";
    }
}
</code>```

.container .test {
  text-align: center;
  padding: 100px;
  color: #fff;
  background-color: #00f;
  max-width: 500px;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}

@-webkit-keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
@keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Custom Text

```

答:
Since you have tagged jQuery, wouldn't be it easier to do it with .fadeOut()? The display attribute of the element is being set to none just after the animation has ended.

$('#test').click(function(){
  $(this).fadeOut();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'>Text</div></code>```

Title: Display none at the end of animation

Body:
I'm trying to make element dissapear at the end of animation but it doesn't work, can someone explain how to make exit animation with element dissappearing at the end of it?:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event){
    event.target.style.animation = "changeOpacity 1s linear";
    if(event.target.style.opacity === 0){
        event.target.style.display = "none";
    }
}

.container .test {
  text-align: center;
  padding: 100px;
  color: #fff;
  background-color: #00f;
  max-width: 500px;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}

@-webkit-keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
@keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Custom Text

Body:
Since you have tagged jQuery, wouldn't be it easier to do it with .fadeOut()? The display attribute of the element is being set to none just after the animation has ended.

$('#test').click(function(){
  $(this).fadeOut();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'>Text</div>


问:
Copying files while there is enough space in linux bash script
I want to create simple bash script which will copy data files from source directory to tmpfs ramdrive. I need this script to be time-effective so it is not an option to try to do copy and check result code of copy command ( I assume copy command will start copying and fail only when there is no space. I want to avoid starting copy when there is not enough space). Here is pseudocode:

```<code>for filename in /data/*.dat; do
    bname="$(basename $filename)"
    ramname="/ramd/$bname"
    if there is not enough space for $filename on ramdrive then
        break
    cp $filename $ramname
done
</code>```

Can you please suggest a replacement for the if-break statement.

答:
You can do this with POSIX defined options for df - report free disk space and du - estimate file space usage, the former with the -P flag for reporting the free space available on the system and parsing out only block size with awk and doing the same for the file with the -k flag in du.

```<code>availMem=$(df -P "$ramname" | awk 'END{print $4}')
fileSize=$(du -k "$filename" | awk '{print $1}')

if (( fileSize > availMem )); then
    break
fi
</code>```

(or) a POSIX-ly integer comparison without bash as

```<code>if [ "$fileSize" -gt "$availMem" ]; then
    break
fi
</code>```

You can also throw in a printf just before the break for a debug purose,

```<code>printf "Requesting %s for copy when there is only %s left\n" "$fileSize" "$availMem"
</code>```

Body:
I want to create simple bash script which will copy data files from source directory to tmpfs ramdrive. I need this script to be time-effective so it is not an option to try to do copy and check result code of copy command ( I assume copy command will start copying and fail only when there is no space. I want to avoid starting copy when there is not enough space). Here is pseudocode:

for filename in /data/*.dat; do
    bname="$(basename $filename)"
    ramname="/ramd/$bname"
    if there is not enough space for $filename on ramdrive then
        break
    cp $filename $ramname
done

Can you please suggest a replacement for the if-break statement.

Body:
You can do this with POSIX defined options for df - report free disk space and du - estimate file space usage, the former with the -P flag for reporting the free space available on the system and parsing out only block size with awk and doing the same for the file with the -k flag in du.

availMem=$(df -P "$ramname" | awk 'END{print $4}')
fileSize=$(du -k "$filename" | awk '{print $1}')

if (( fileSize > availMem )); then
    break
fi

(or) a POSIX-ly integer comparison without bash as

if [ "$fileSize" -gt "$availMem" ]; then
    break
fi

You can also throw in a printf just before the break for a debug purose,

printf "Requesting %s for copy when there is only %s left\n" "$fileSize" "$availMem"


问:
FETCH API return undefined
I want to use Fetch API but i don' t really understand it's mecanism.

I have an  in my HTML and i want to assign the result of my fetch with this code :

```<code>const weather = "http://api.apixu.com/v1/current.json?key=cba287f271e44f88a60143926172803&q=Paris";
const array = [];

fetch(weather)
.then(blob => blob.json())
.then(data => {
  array.push(data.current.humidity)
  console.log(array[0])
      }
);
 document.querySelector('h1').innerHTML = array[0];
</code>```

i have the result with the console.log but the  returns "undefined". can you explain why ?

thanks a lot

答:
This is because the call to the API is asynchronous, meaning that the code is not executed just line by line as you write it. The callback only runs as soon as the call to the API has finished, basically meaning that

```<code>data => {
  array.push(data.current.humidity)
  console.log(array[0])
}
</code>```

runs after

```<code>document.querySelector('h1').innerHTML = array[0];
</code>```

So when you try to set your h1, array is still empty. If you want to set it as soon the data is available, you have to do it within the callback function:

```<code>data => {
  array.push(data.current.humidity)

  document.querySelector('h1').innerHTML = array[0];
}
</code>```

This might seem weird at first, but keep in mind that you're only registering an anonymous function but not running it yet. You just define the function that you want to trigger as soon as something happens, in this case: when your API call has finished.

Title: FETCH API return undefined

Body:
I want to use Fetch API but i don' t really understand it's mecanism.

I have an  in my HTML and i want to assign the result of my fetch with this code :

const weather = "http://api.apixu.com/v1/current.json?key=cba287f271e44f88a60143926172803&q=Paris";
const array = [];

fetch(weather)
.then(blob => blob.json())
.then(data => {
  array.push(data.current.humidity)
  console.log(array[0])
      }
);
 document.querySelector('h1').innerHTML = array[0];

i have the result with the console.log but the  returns "undefined". can you explain why ?

thanks a lot

Body:
This is because the call to the API is asynchronous, meaning that the code is not executed just line by line as you write it. The callback only runs as soon as the call to the API has finished, basically meaning that

data => {
  array.push(data.current.humidity)
  console.log(array[0])
}

runs after

document.querySelector('h1').innerHTML = array[0];

So when you try to set your h1, array is still empty. If you want to set it as soon the data is available, you have to do it within the callback function:

data => {
  array.push(data.current.humidity)

  document.querySelector('h1').innerHTML = array[0];
}

This might seem weird at first, but keep in mind that you're only registering an anonymous function but not running it yet. You just define the function that you want to trigger as soon as something happens, in this case: when your API call has finished.


问:
Issues with "collect()" or "take(n)" on MB-sized data on spark
We are a group of people working with spark (spark 2.1.0 standalone
with 2 workers; the programming is done in scala and everything is
running inside several dockers). We encountered a problem that make
"collect" or "take(n)" go very slow once when the collected data hits
some size cap.

We encountered the problem on several occasions but we have boiled
down the problem to a simple example: it reads a file (either from
local filesystem or from hdfs; we tested both) and then collect the
result. It works fine until a certain size of file (around 2 MB) and
then it is very slow (and around 3 MB it completely breaks). If it
doesn't collect (e.g. it just does a saveAsTextFile) the setup can
deal with files as large as 200 GB. We have tested increasing the
driver memory tenfold (from 2GB of RAM to 20GB of RAM) but it doesn't
solve the issue; in fact our tests show that our little experiment
slows at the very same size of file regardless of how much RAM we give
to the driver or the workers.

I have summed up my experiment here: https://pastebin.com/raw/6yXztq0H

In this experiment the program reads a file "s" and "take(n)" with "n"
gradually increasing. As the timestamped output shows, it work almost
instantly for "n≤104145" (it actually varies just a little despite large changes in setup) and then it is quite slow. For large "n" (see
second run) the driver crashes with a "TaskResultLost" error. The last
experiment (third run) shows that this does not seem to be a memory
problem (and that seems logical since the file is relatively small,
around 2 MB).

(It is not shown in the experiment but we also played with
SPARK_DAEMON_MEM but it doesn't seem to change anything.)

Has anybody ever had the same problem? Has anybody an idea to help us search further?

答:
Ok, we managed to get a hold of what is going on. Here is a description of the problem for future references:

When the collected data size is large enough, the driver will interact directly with the executors instead of going through the master; that is why our problem only appear after a certain size.

There was a network issue in our setup between some of the executors and the driver that makes some connections fail.


问:
Batch docker registry manifest deletion: How to list manifests via v2 REST api?
I would like to delete particular or all manifests in my private docker registry remotely (v2 api) to make it possible images data to be collected by gc. I found this tool, but it only works with tags. I decided to extend it. I would like to enumerate manifests. Is it possible to get manifests list? I can't find something useful on this.

I checked those and I'm also searching the web, but with no success.

https://docs.docker.com/registry/spec/api/

https://docs.docker.com/registry/garbage-collection/

--UPDATE--

Either of both results in 404 error of course (I just prefer using wget). For

```<code>https://<registry-origin>/v2/gk-backend/tags/list
</code>```

I got {"name":"gk-backend","tags":["latest"]} as I expect. When I try father to get the manifest I have 404. I issue the request by using wget like

```<code>wget --method=HEAD --header="Accept: application/vnd.docker.distribution.manifest.v2+json" --no-check-certificate --http-user user --http-password pass https://<registry-origin>/v2/wjs-wealth/manifests/gk-backend:latest -O-
</code>```

And curl also gives me 404

```<code>curl --header "Accept: application/vnd.docker.distribution.manifest.v2+json" -sI --user user:pass https://<registry-origin>/v2/wjs-wealth/manifests/gk-backend:latest
</code>```

答:
I have the same problem. If the a docker image (called manifest) pushed to Docker registry v2.0 with same tag, new manifest will take the tag and the old one will NOT deleted instead of existed with no tag assigned.

Such old manifests cannot list from REST API without knowning their digests, and garbage collection will not delete them.

One way I found to get list of manifests of a docker registry repository is via garbage collection tool. Run docker exec -it registry registry garbage-collect --dry-run /etc/docker/registry/config.yml. This command will print all manifests (including those assigned tag) of all repositories. Such as:

```<code>hello-world
hello-world: marking manifest sha256:fea8895f450959fa676bcc1df0611ea93823a735a01205fd8622846041d0c7cf
hello-world: marking blob sha256:03f4658f8b782e12230c1783426bd3bacce651ce582a4ffb6fbbfa2079428ecb
hello-world: marking blob sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4
hello-world: marking configuration sha256:690ed74de00f99a7d00a98a5ad855ac4febd66412be132438f9b8dbd300a937d
ubuntu

4 blobs marked, 0 blobs eligible for deletion
</code>```

With grep tool, it is easy to filter out manifest information only.

Then you can call delete REST API to delete unused manifests. Take attention not to delete those manifest with tag assigned.

DELETE REST API only remove manifest information, image data in blob will not delete, so run garbage collection command again without --dry-run to remove unused blob: docker exec -it registry registry garbage-collect /etc/docker/registry/config.yml

Body:
I would like to delete particular or all manifests in my private docker registry remotely (v2 api) to make it possible images data to be collected by gc. I found this tool, but it only works with tags. I decided to extend it. I would like to enumerate manifests. Is it possible to get manifests list? I can't find something useful on this.

I checked those and I'm also searching the web, but with no success.

https://docs.docker.com/registry/spec/api/

https://docs.docker.com/registry/garbage-collection/

--UPDATE--

Either of both results in 404 error of course (I just prefer using wget). For

https://<registry-origin>/v2/gk-backend/tags/list

I got {"name":"gk-backend","tags":["latest"]} as I expect. When I try father to get the manifest I have 404. I issue the request by using wget like

wget --method=HEAD --header="Accept: application/vnd.docker.distribution.manifest.v2+json" --no-check-certificate --http-user user --http-password pass https://<registry-origin>/v2/wjs-wealth/manifests/gk-backend:latest -O-

And curl also gives me 404

curl --header "Accept: application/vnd.docker.distribution.manifest.v2+json" -sI --user user:pass https://<registry-origin>/v2/wjs-wealth/manifests/gk-backend:latest

Body:
I have the same problem. If the a docker image (called manifest) pushed to Docker registry v2.0 with same tag, new manifest will take the tag and the old one will NOT deleted instead of existed with no tag assigned.

Such old manifests cannot list from REST API without knowning their digests, and garbage collection will not delete them.

One way I found to get list of manifests of a docker registry repository is via garbage collection tool. Run docker exec -it registry registry garbage-collect --dry-run /etc/docker/registry/config.yml. This command will print all manifests (including those assigned tag) of all repositories. Such as:

hello-world
hello-world: marking manifest sha256:fea8895f450959fa676bcc1df0611ea93823a735a01205fd8622846041d0c7cf
hello-world: marking blob sha256:03f4658f8b782e12230c1783426bd3bacce651ce582a4ffb6fbbfa2079428ecb
hello-world: marking blob sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4
hello-world: marking configuration sha256:690ed74de00f99a7d00a98a5ad855ac4febd66412be132438f9b8dbd300a937d
ubuntu

4 blobs marked, 0 blobs eligible for deletion

With grep tool, it is easy to filter out manifest information only.

Then you can call delete REST API to delete unused manifests. Take attention not to delete those manifest with tag assigned.

DELETE REST API only remove manifest information, image data in blob will not delete, so run garbage collection command again without --dry-run to remove unused blob: docker exec -it registry registry garbage-collect /etc/docker/registry/config.yml


问:
Store textbox values in php array
So basically I have the user enter a number on my first screen.
Here is test1.php which generates the number of text boxes that the user had previously entered. That number is $input

```<code>echo "<form action='test2.php' method='post'>";
for($i=1; $i<=$input; $i++)
{
     echo "Entry $i";
     echo "<input type='text' name='Names'>";
}
echo "<input type='submit' class='button' name='submit' value='submit'>";
echo "</form>";
</code>```

Then my test2.php should print all the values entered, but it only prints out the last value entered from test1.php. For example is $input is 4, only the text entered in the 4th text box prints, which is understandable as I don't know how to print all values.

```<code>$names=$_POST['Names'];
foreach($number as $num){
       echo $num;
}
</code>```

Is the problem with the name I gave to the textboxes, or something else?
Any help is much appreciated.

答:
```<code><form method="post" name="myform">
<input type="text" name="array[]" Value="101"/>
<input type="text" name="array[]" Value="102"/>
<input type="text" name="array[]" Value="103"/>
<input type="text" name="array[]" Value="104"/>
<input type="submit" name="submit" Value="submit"/>
</form>

if(isset($_POST['submit'])){

foreach($_POST['array'] as $myarray) {

    echo $myarray.'<br>';

}
</code>```

OUTPUT

```<code>101
102
103
104
</code>```

Title: Store textbox values in php array

Body:
So basically I have the user enter a number on my first screen.
Here is test1.php which generates the number of text boxes that the user had previously entered. That number is $input

echo "<form action='test2.php' method='post'>";
for($i=1; $i<=$input; $i++)
{
     echo "Entry $i";
     echo "<input type='text' name='Names'>";
}
echo "<input type='submit' class='button' name='submit' value='submit'>";
echo "</form>";

Then my test2.php should print all the values entered, but it only prints out the last value entered from test1.php. For example is $input is 4, only the text entered in the 4th text box prints, which is understandable as I don't know how to print all values.

$names=$_POST['Names'];
foreach($number as $num){
       echo $num;
}

Is the problem with the name I gave to the textboxes, or something else?
Any help is much appreciated.

Body:
<form method="post" name="myform">
<input type="text" name="array[]" Value="101"/>
<input type="text" name="array[]" Value="102"/>
<input type="text" name="array[]" Value="103"/>
<input type="text" name="array[]" Value="104"/>
<input type="submit" name="submit" Value="submit"/>
</form>

if(isset($_POST['submit'])){

foreach($_POST['array'] as $myarray) {

    echo $myarray.'<br>';

}

OUTPUT

101
102
103
104


问:
Most efficient way to get the highest number from a collection of integers
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

```<code>int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }
</code>```

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

答:
Your question hints at it's own answer. It depends on the source of the collection itself. That is, the more you know about the data set, the quicker you can devise heuristics to get to the answer you need.

So, if your list is already sorted, then list[0] or list[len-1] will be the highest...

The secondary answer is also dependent on 'How often will the list be searched?'. If this is a one-off search, then just iterating the list for the highest will be fastest.
If you will be doing it repeatedly (eg, gathering various metrics), then sorting it first, using Quick Sort, might be your best best.

Body:
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?


问:
How come I need to remove the current item in my listview before adding another one?
So im trying something new..
I added a global ListViewItem at the top of the code so I can easily add new subitems to the list whenever I see it fits.

So to try this new method out I made a simple list view and a button to add the current time.
When I click it once it works great but if i try clicking add again it throws me this error.

System.ArgumentException: 'Cannot add or insert the item '11:24' in
  more than one place. You must first remove it from its current
  location or clone it.'

is there a way I can get past this without removing or cloning it?

```<code>using System;
using System.Windows.Forms;

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            lvi.Text = time;
            listView1.Items.Add(lvi);
        }
    }
}
</code>```

答:
```<code>    ListViewItem lvi;
    private void button1_Click(object sender, EventArgs e)
    {
        lvi  = new ListViewItem();
        string time = DateTime.Now.ToString("HH:mm");
        lvi.Text = time;
        listView1.Items.Add(lvi);
    }
</code>```

You can use this .

Body:
So im trying something new..
I added a global ListViewItem at the top of the code so I can easily add new subitems to the list whenever I see it fits.

So to try this new method out I made a simple list view and a button to add the current time.
When I click it once it works great but if i try clicking add again it throws me this error.

System.ArgumentException: 'Cannot add or insert the item '11:24' in
  more than one place. You must first remove it from its current
  location or clone it.'

is there a way I can get past this without removing or cloning it?

using System;
using System.Windows.Forms;

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            lvi.Text = time;
            listView1.Items.Add(lvi);
        }
    }
}

Body:
    ListViewItem lvi;
    private void button1_Click(object sender, EventArgs e)
    {
        lvi  = new ListViewItem();
        string time = DateTime.Now.ToString("HH:mm");
        lvi.Text = time;
        listView1.Items.Add(lvi);
    }

You can use this .


问:
How to show the attributes of an object when clicking a button in Windows forms?
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

```<code>class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}
</code>```

And now, the form code is the following(note that i designed it already):

```<code> public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }
</code>```

Thank you!

答:
You can set the getter and setter in below way.

```<code>public string PizzaIngredients
{
    get
    {
        return String.Join(",",nringrediente);
    }
    set
    {
        nringrediente = value.Split(',');
    }
}
</code>```

And Show(Margherita); can be implemented like in Pizza Class :

```<code>public string GetDisplayMessageForPizza()
{
    return "My Pizza is " + nume + ". It contains " + nringrediente + " ingredients : " + PizzaIngredients;
}
</code>```

And in form ListaPizza  :

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

    string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
    Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

    MessageBox.Show(Margherita.GetDisplayMessageForPizza());
}
</code>```

Body:
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}

And now, the form code is the following(note that i designed it already):

 public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }

Thank you!

Body:
You can set the getter and setter in below way.

public string PizzaIngredients
{
    get
    {
        return String.Join(",",nringrediente);
    }
    set
    {
        nringrediente = value.Split(',');
    }
}

And Show(Margherita); can be implemented like in Pizza Class :

public string GetDisplayMessageForPizza()
{
    return "My Pizza is " + nume + ". It contains " + nringrediente + " ingredients : " + PizzaIngredients;
}

And in form ListaPizza  :

private void Margherita_Click(object sender, EventArgs e)
{

    string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
    Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

    MessageBox.Show(Margherita.GetDisplayMessageForPizza());
}


问:
Custom Bad Gateway Page with Nginx
Is it possible to serve a custom "Bad Gateway" error page in Nginx?

Similar to having custom 404 pages.

答:
Yes it is possible

Type this in your terminal

```<code>cd /etc/nginx

sudo nano nginx.conf
</code>```

and under http add these lines

```<code>    error_page 500 Path_to_your_custom_error_page;
    error_page 503 Path_to_your_custom_error_page;
    error_page 504 Path_to_your_custom_error_page;
</code>```

Now restart nginx by typing this command:

```<code>sudo service nginx restart
</code>```

Bingo now you can see custom error message on gateway error

Title: Custom Bad Gateway Page with Nginx

Body:
Yes it is possible

Type this in your terminal

cd /etc/nginx

sudo nano nginx.conf

and under http add these lines

    error_page 500 Path_to_your_custom_error_page;
    error_page 503 Path_to_your_custom_error_page;
    error_page 504 Path_to_your_custom_error_page;

Now restart nginx by typing this command:

sudo service nginx restart

Bingo now you can see custom error message on gateway error


问:
When and how to give up cpu in a busy kernel thread loop?
I'm writing a Linux module, in which I have a loop to process work like below:

```<code>while (1) {
    while (there's work) {
        process_work
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}
</code>```

When there's lots of work, it would result in softlockup. The message is like this:

```<code>[ 1426.067061] BUG: soft lockup - CPU#3 stuck for 23s! [comp_wqa:2969]
[ 1426.067903] Modules linked in: testmodule(OE+) xt_CHECKSUM ipt_MASQUERADE nf_nat_masquerade_ipv4 tun ip6t_rpfilter ip6t_REJECT ipt_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_nat nf_conntrack_ipv6 nf_defrag_ipv6 nf_nat_ipv6 ip6table_mangle ip6table_security ip6table_raw ip6table_filter ip6_tables iptable_nat nf_conntrack_ipv4 nf_defrag_ipv4 nf_nat_ipv4 nf_nat nf_conntrack iptable_mangle iptable_security iptable_raw iptable_filter hwmon_vid dm_mirror dm_region_hash dm_log dm_mod snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic intel_powerclamp coretemp intel_rapl kvm eeepc_wmi crc32_pclmul asus_wmi ghash_clmulni_intel sparse_keymap rfkill mxm_wmi aesni_intel wmi lrw snd_hda_intel gf128mul glue_helper snd_hda_codec pcspkr ablk_helper sg
[ 1426.067924]  cryptd shpchp snd_hda_core snd_hwdep snd_seq snd_seq_device snd_pcm tpm_infineon acpi_pad snd_timer mei_me mei snd soundcore nfsd auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 sd_mod crc_t10dif crct10dif_generic crct10dif_pclmul crct10dif_common crc32c_intel serio_raw i915 ahci libahci libata i2c_algo_bit drm_kms_helper drm e1000e ptp pps_core i2c_core video
[ 1426.067939] CPU: 3 PID: 2969 Comm: comp_wqa Tainted: G           OE  ------------   3.10.0-327.28.3.el7.x86_64 #1
[ 1426.067940] Hardware name: ASUS All Series/Z97-A, BIOS 2401 04/24/2015
[ 1426.067941] task: ffff88080f212280 ti: ffff880810a68000 task.ti: ffff880810a68000
[ 1426.067942] RIP: 0010:[<ffffffff8107e11f>]  [<ffffffff8107e11f>] vprintk_emit+0x1bf/0x530
[ 1426.067946] RSP: 0018:ffff880810a6bbc0  EFLAGS: 00000246
[ 1426.067947] RAX: 0000000000000001 RBX: 0000000000000003 RCX: 0000000000000000
[ 1426.067948] RDX: 0000000000000001 RSI: ffff88083fb8f6c8 RDI: 0000000000000246
[ 1426.067948] RBP: ffff880810a6bc20 R08: 0000000000000092 R09: 0000000000007d0d
[ 1426.067949] R10: 0000000000008000 R11: ffffc90023effff8 R12: 0000000000000081
[ 1426.067950] R13: ffffffff81a08020 R14: 000000009176cc6c R15: 0000000000000000
[ 1426.067951] FS:  0000000000000000(0000) GS:ffff88083fb80000(0000) knlGS:0000000000000000
[ 1426.067951] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1426.067952] CR2: 00007f42411ff00e CR3: 000000000194a000 CR4: 00000000001407e0
[ 1426.067953] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 1426.067954] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 1426.067954] Stack:
[ 1426.067955]  ffffffff81cae082 0000000000000071 0000000000000000 ffff880810a6bc40
[ 1426.067956]  ffffffffa07a45a0 000000008116c24e 0000000000000246 ffff8807dfbba800
[ 1426.067958]  ffff880810a70000 ffff8807dfbc5030 ffff8807dfbc4e00 ffff8807e65b3000
[ 1426.067959] Call Trace:
</code>```

So after some googling, I change the code to the following:

```<code>while (1) {
    while (there's work) {
        process_work
        cond_resched()
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}
</code>```

And with this code, the softlockups happens less likely. But still, it happens with heavier load. I thought if this thread had been occupying the cpu for long, then cond_resched would give up the cpu. I guess I was wrong.

I want to know how should the softlockups be avoided and at the same without being idle too much (I want the module process lots of work withou long latency).

After thinking more about this, I realize what I want is just make a cpu core run a dedicate thread, without being interrupted. It seems the kernel doesn't support this directly. There is a kernel parameter called watchdog_thresh which decides how many seconds can a thread continuously run. I have read other posts that suggest this kind of softlockups is harmless. And I now understand more deeply that the performance of my driver is heavily dependent on single cpu core performance, since I have to process the work with a single thread.

答:
While kernel thread may hold a CPU in counter to scheduling algorithm, the thread can give up the CPU only if scheduling algorithm decides to do so. See also this question which explains similar things.

You need to adjust your kernel thread so it can be preempted by others. Some of possible solutions:

Lower priority of the thread or change scheduling policy. Use sched_setscheduler function for that.

After processing several (say, 10) "works" in bunch, pause the thread for a short period of time.

Body:
I'm writing a Linux module, in which I have a loop to process work like below:

while (1) {
    while (there's work) {
        process_work
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}

When there's lots of work, it would result in softlockup. The message is like this:

[ 1426.067061] BUG: soft lockup - CPU#3 stuck for 23s! [comp_wqa:2969]
[ 1426.067903] Modules linked in: testmodule(OE+) xt_CHECKSUM ipt_MASQUERADE nf_nat_masquerade_ipv4 tun ip6t_rpfilter ip6t_REJECT ipt_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_nat nf_conntrack_ipv6 nf_defrag_ipv6 nf_nat_ipv6 ip6table_mangle ip6table_security ip6table_raw ip6table_filter ip6_tables iptable_nat nf_conntrack_ipv4 nf_defrag_ipv4 nf_nat_ipv4 nf_nat nf_conntrack iptable_mangle iptable_security iptable_raw iptable_filter hwmon_vid dm_mirror dm_region_hash dm_log dm_mod snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic intel_powerclamp coretemp intel_rapl kvm eeepc_wmi crc32_pclmul asus_wmi ghash_clmulni_intel sparse_keymap rfkill mxm_wmi aesni_intel wmi lrw snd_hda_intel gf128mul glue_helper snd_hda_codec pcspkr ablk_helper sg
[ 1426.067924]  cryptd shpchp snd_hda_core snd_hwdep snd_seq snd_seq_device snd_pcm tpm_infineon acpi_pad snd_timer mei_me mei snd soundcore nfsd auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 sd_mod crc_t10dif crct10dif_generic crct10dif_pclmul crct10dif_common crc32c_intel serio_raw i915 ahci libahci libata i2c_algo_bit drm_kms_helper drm e1000e ptp pps_core i2c_core video
[ 1426.067939] CPU: 3 PID: 2969 Comm: comp_wqa Tainted: G           OE  ------------   3.10.0-327.28.3.el7.x86_64 #1
[ 1426.067940] Hardware name: ASUS All Series/Z97-A, BIOS 2401 04/24/2015
[ 1426.067941] task: ffff88080f212280 ti: ffff880810a68000 task.ti: ffff880810a68000
[ 1426.067942] RIP: 0010:[<ffffffff8107e11f>]  [<ffffffff8107e11f>] vprintk_emit+0x1bf/0x530
[ 1426.067946] RSP: 0018:ffff880810a6bbc0  EFLAGS: 00000246
[ 1426.067947] RAX: 0000000000000001 RBX: 0000000000000003 RCX: 0000000000000000
[ 1426.067948] RDX: 0000000000000001 RSI: ffff88083fb8f6c8 RDI: 0000000000000246
[ 1426.067948] RBP: ffff880810a6bc20 R08: 0000000000000092 R09: 0000000000007d0d
[ 1426.067949] R10: 0000000000008000 R11: ffffc90023effff8 R12: 0000000000000081
[ 1426.067950] R13: ffffffff81a08020 R14: 000000009176cc6c R15: 0000000000000000
[ 1426.067951] FS:  0000000000000000(0000) GS:ffff88083fb80000(0000) knlGS:0000000000000000
[ 1426.067951] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1426.067952] CR2: 00007f42411ff00e CR3: 000000000194a000 CR4: 00000000001407e0
[ 1426.067953] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 1426.067954] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 1426.067954] Stack:
[ 1426.067955]  ffffffff81cae082 0000000000000071 0000000000000000 ffff880810a6bc40
[ 1426.067956]  ffffffffa07a45a0 000000008116c24e 0000000000000246 ffff8807dfbba800
[ 1426.067958]  ffff880810a70000 ffff8807dfbc5030 ffff8807dfbc4e00 ffff8807e65b3000
[ 1426.067959] Call Trace:

So after some googling, I change the code to the following:

while (1) {
    while (there's work) {
        process_work
        cond_resched()
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}

And with this code, the softlockups happens less likely. But still, it happens with heavier load. I thought if this thread had been occupying the cpu for long, then cond_resched would give up the cpu. I guess I was wrong.

I want to know how should the softlockups be avoided and at the same without being idle too much (I want the module process lots of work withou long latency).

After thinking more about this, I realize what I want is just make a cpu core run a dedicate thread, without being interrupted. It seems the kernel doesn't support this directly. There is a kernel parameter called watchdog_thresh which decides how many seconds can a thread continuously run. I have read other posts that suggest this kind of softlockups is harmless. And I now understand more deeply that the performance of my driver is heavily dependent on single cpu core performance, since I have to process the work with a single thread.


问:
Insert from one table into another with commit Intervals
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

```<code>INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)
</code>```

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

```<code>create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;
</code>```

答:
You can use this. There are few errors in your code and that's why you are getting errors while compilation. Please compare your code with the below one and find the places you made mistakes. My comments are inline. </p>

```<code>CREATE OR REPLACE PROCEDURE ACTIVITY1
AS

   fetch_size  pls_integer := 100 ;

   CURSOR gl
   IS
      SELECT prr.EVT_DECLENCHEUR,
             prr.BQ_CDF,
             prr.BQ_DOM,
             prr.NUM_COMMERCANT,
             prr.TYPE_CONTRAT_COM,
             prr.COMMERCANT_SIRET,
             prr.TYPE_PRE_COMP,
             prr.BQ_CDF_ID_EBF,
             prr.BQ_DOM_ID_EBF,
             prr.DAT_TRAITEMENT,
             prr.EVT_TYPE_OPERATION,
             prr.DEV_MT_CRE,
             prr.NBR_DECI_MT_CRE,
             prr.REF_FICHIER_TRAITE,
             prr.NUM_CTC,
             prr.REF_FICHIER_ORIGINE,
             prr.ORIGINE_FLUX,
             prr.NUM_EST_REMISE,
             prr.NUM_REMISE_ORIGINE,
             prr.NUM_MACHINE,
             prr.REF_ARCHIVAGE_REM,
             prr.DAT_REMISE,
             prr.SUPPORT_REMISE,
             prr.DAT_REMISE_CALCULEE,
             prr.DAT_VALEUR_REMISE,
             prr.COD_APPLI,
             TO_DATE (SYSDATE, 'DD/MM/YYYY')
        FROM dlc_pr_remise prr
       WHERE NOT EXISTS
                (SELECT *
                   FROM DLC_PR_ACTIVITY_REMISE prao
                  WHERE prao.num_est_remise = prr.num_est_remise);

   TYPE GL_T IS TABLE OF gl%ROWTYPE;

   gl_array         GL_T;
BEGIN
   OPEN gl;

   LOOP
      FETCH gl BULK COLLECT INTO gl_array LIMIT fetch_size;

      FORALL i IN 1 .. gl_arary.COUNT
         INSERT INTO dlc_pr_activity_remise -- I assume the dlc_pr_activity_remise table has same columns which you are selectig in cursor.
              VALUES gl_arary (i);

      --Exit the loop when you cursor is empty.
      EXIT WHEN gl%NOTFOUND;

   END LOOP;

   COMMIT;

  CLOSE gl;

END ACTIVITY1;
</code>```

Body:
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;

Body:
You can use this. There are few errors in your code and that's why you are getting errors while compilation. Please compare your code with the below one and find the places you made mistakes. My comments are inline.

CREATE OR REPLACE PROCEDURE ACTIVITY1
AS

   fetch_size  pls_integer := 100 ;

   CURSOR gl
   IS
      SELECT prr.EVT_DECLENCHEUR,
             prr.BQ_CDF,
             prr.BQ_DOM,
             prr.NUM_COMMERCANT,
             prr.TYPE_CONTRAT_COM,
             prr.COMMERCANT_SIRET,
             prr.TYPE_PRE_COMP,
             prr.BQ_CDF_ID_EBF,
             prr.BQ_DOM_ID_EBF,
             prr.DAT_TRAITEMENT,
             prr.EVT_TYPE_OPERATION,
             prr.DEV_MT_CRE,
             prr.NBR_DECI_MT_CRE,
             prr.REF_FICHIER_TRAITE,
             prr.NUM_CTC,
             prr.REF_FICHIER_ORIGINE,
             prr.ORIGINE_FLUX,
             prr.NUM_EST_REMISE,
             prr.NUM_REMISE_ORIGINE,
             prr.NUM_MACHINE,
             prr.REF_ARCHIVAGE_REM,
             prr.DAT_REMISE,
             prr.SUPPORT_REMISE,
             prr.DAT_REMISE_CALCULEE,
             prr.DAT_VALEUR_REMISE,
             prr.COD_APPLI,
             TO_DATE (SYSDATE, 'DD/MM/YYYY')
        FROM dlc_pr_remise prr
       WHERE NOT EXISTS
                (SELECT *
                   FROM DLC_PR_ACTIVITY_REMISE prao
                  WHERE prao.num_est_remise = prr.num_est_remise);

   TYPE GL_T IS TABLE OF gl%ROWTYPE;

   gl_array         GL_T;
BEGIN
   OPEN gl;

   LOOP
      FETCH gl BULK COLLECT INTO gl_array LIMIT fetch_size;

      FORALL i IN 1 .. gl_arary.COUNT
         INSERT INTO dlc_pr_activity_remise -- I assume the dlc_pr_activity_remise table has same columns which you are selectig in cursor.
              VALUES gl_arary (i);

      --Exit the loop when you cursor is empty.
      EXIT WHEN gl%NOTFOUND;

   END LOOP;

   COMMIT;

  CLOSE gl;

END ACTIVITY1;


问:
Compare 3 Columns in Excel using VBA
I want to compare 2 to 1 Columns in Excel using VBA..

I already achieve 2 to 2 Columns using this code

```<code>Sub LIST1_LIST2()
    Dim list1 As Range
    Dim LIST2 As Range
    Set list1 = Range("B3:C181")
    Set LIST2 = Range("G3:H729")

    For Each row1 In list1.Rows
        For Each row2 In LIST2.Rows
          If (row1.Cells(1) = row2.Cells(1) And row1.Cells(2) = row2.Cells(2)) Then
              row1.Cells(1).Offset(0, 2) = row1.Cells(1)
              row1.Cells(2).Offset(0, 2) = row1.Cells(2)
              Exit For
          End If
        Next row2

    Next row1

End Sub
</code>```

But now I need something VBA scripts that works somehow like the image below

答:
You can use this pseudocode to guide you:</p>

```<code>If LASTNAME = Left(NAME,LASTNAME.Length) And _
FIRSTNAME = Right(NAME,FIRSTNAME.Length) Then
</code>```

Title: Compare 3 Columns in Excel using VBA

Body:
I want to compare 2 to 1 Columns in Excel using VBA..

I already achieve 2 to 2 Columns using this code

Sub LIST1_LIST2()
    Dim list1 As Range
    Dim LIST2 As Range
    Set list1 = Range("B3:C181")
    Set LIST2 = Range("G3:H729")

    For Each row1 In list1.Rows
        For Each row2 In LIST2.Rows
          If (row1.Cells(1) = row2.Cells(1) And row1.Cells(2) = row2.Cells(2)) Then
              row1.Cells(1).Offset(0, 2) = row1.Cells(1)
              row1.Cells(2).Offset(0, 2) = row1.Cells(2)
              Exit For
          End If
        Next row2

    Next row1

End Sub

But now I need something VBA scripts that works somehow like the image below

Body:
You can use this pseudocode to guide you:

If LASTNAME = Left(NAME,LASTNAME.Length) And _
FIRSTNAME = Right(NAME,FIRSTNAME.Length) Then