问:
AKAudioPlayer: No sound in speakers, only with headphones
Using AudioKit for sound management, I noticed an issue (bug?) with this very simple piece of code.

```<code>import AudioKit

class MainViewController: UIViewController {

var audioFile: AKAudioFile?
var audioPlayer: AKAudioPlayer?

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func onPlayButtonClick(_ sender: Any) {

    do {
        audioFile = try AKAudioFile(forReading: Bundle.main.url(forResource: "3e", withExtension: "mp3")!)

        audioPlayer = try AKAudioPlayer(file: audioFile!)

        AudioKit.output = audioPlayer
        AudioKit.start()

        audioPlayer!.play()

    } catch {
        print(error)
    }
}
}
</code>```

When launching the playback with play() method, everything is normal in logs and in the process (player duration, currentTime). BUT I do not hear the audio in speakers (only a kind of wind noise). As soon as I plug my headphones and tap the button again, I normally hear the audio. Then, I unplug my headphones and tap the button, I don’t hear audio (only that wind noise).

I face this on iPhone 5S.

I do not face this on iPad5, I do not face this on simulators. I don’t have the other devices to try to reproduce.

Both devices: iOS 11.1.2 and AudioKit : v4.0.4

NB: my speakers works normally with any other app and I’ve checked the volume. The default outputDevice is set to Speakers when headphones are not plugged.

答:
According to the Configuring an Audio Session guide, by default, the AVAudioSessionCategory is set so that

In iOS, setting the Ring/Silent switch to silent mode silences any audio being played by the app.

Since iPads and the simulator don't have this switch they will always play to the speaker, but in the case of hardware iPhones, they will only play to the headphones and not to the speakers when in silent mode, unless the session category is changed.

You can change the session category directly with AVAudioSession:

```<code>do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
catch {
    print("failed to set category")
}
</code>```

or you can use AudioKit's AKSettings wrapper:

```<code>AudioKit.start()
do {
    try AKSettings.setSession(category: AKSettings.SessionCategory.playback)
} catch {
    print("failed to set category")
}
</code>```

According to the AVSessionCategory docs, the Playback category is

The category for playing recorded music or other sounds that are
  central to the successful use of your app.

so it will assume the user wants the silent mode to be overridden when using the app.

Body:
Using AudioKit for sound management, I noticed an issue (bug?) with this very simple piece of code.

import AudioKit

class MainViewController: UIViewController {

var audioFile: AKAudioFile?
var audioPlayer: AKAudioPlayer?

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func onPlayButtonClick(_ sender: Any) {

    do {
        audioFile = try AKAudioFile(forReading: Bundle.main.url(forResource: "3e", withExtension: "mp3")!)

        audioPlayer = try AKAudioPlayer(file: audioFile!)

        AudioKit.output = audioPlayer
        AudioKit.start()

        audioPlayer!.play()

    } catch {
        print(error)
    }
}
}

When launching the playback with play() method, everything is normal in logs and in the process (player duration, currentTime). BUT I do not hear the audio in speakers (only a kind of wind noise). As soon as I plug my headphones and tap the button again, I normally hear the audio. Then, I unplug my headphones and tap the button, I don’t hear audio (only that wind noise).

I face this on iPhone 5S.

I do not face this on iPad5, I do not face this on simulators. I don’t have the other devices to try to reproduce.

Both devices: iOS 11.1.2 and AudioKit : v4.0.4

NB: my speakers works normally with any other app and I’ve checked the volume. The default outputDevice is set to Speakers when headphones are not plugged.

Body:
According to the Configuring an Audio Session guide, by default, the AVAudioSessionCategory is set so that

In iOS, setting the Ring/Silent switch to silent mode silences any audio being played by the app.

Since iPads and the simulator don't have this switch they will always play to the speaker, but in the case of hardware iPhones, they will only play to the headphones and not to the speakers when in silent mode, unless the session category is changed.

You can change the session category directly with AVAudioSession:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
catch {
    print("failed to set category")
}

or you can use AudioKit's AKSettings wrapper:

AudioKit.start()
do {
    try AKSettings.setSession(category: AKSettings.SessionCategory.playback)
} catch {
    print("failed to set category")
}

According to the AVSessionCategory docs, the Playback category is

The category for playing recorded music or other sounds that are
  central to the successful use of your app.

so it will assume the user wants the silent mode to be overridden when using the app.


来源: stackexchange

问:
Gmail smtp is not working in phpmailer
This my code,

```<code>require_once("PHPMailer/class.PHPMailer.php");
$mail = new PHPMailer();
/* receiver details and message - start */
$toid = "example@gmail.com";
$toname = "Example";

$msg = "First name : ".$_POST["fname"] . "<br>";
$msg .= "Last name : ".$_POST["lname"]. "<br>";;
$msg .= "Email : ".$_POST["email"]. "<br>";;
$msg .= "Mobile : ".$_POST["mobile"]. "<br>";;
$msg .= "Message : ".$_POST["msg"];
$subject = "sample subject";
/* receiver details and message - end */

$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPKeepAlive = true;

/* mail smtp configuration - start */
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'test@gmail.com';
$mail->Password = 'xxxxxx';
/* mail smtp configuration - end */

$mail->From = "test@gmail.com";
$mail->FromName = "from name";

$mail->AddAddress($toid, $toname);

$mail->Subject = $subject;
$mail->Body    = $msg;
$mail->IsHTML(true);
if($mail->Send()){
echo "success";
}else{
echo "Failure";
}
</code>```

When run the above , it throws

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\mail\PHPMailer\class.smtp.php on line 200

答:
It's got nothing to do with your code - your OpenSSL CA cert store does not contain the CA cert and/or your system is running in an environment which masquerades the gmail service and/or your clock is very wrong and/or you are using a very old version of openSSL. You've told us nothing about the platform this sits on so we can't advise how to fix this.

BTW you'll also need to enable "insecure" connectivity at the google side - I don't think PHPmailer supports oauth over SMTP.

ContentLicense: CC BY-SA 3.0

Title: Gmail smtp is not working in phpmailer

Body:
This my code,

require_once("PHPMailer/class.PHPMailer.php");
$mail = new PHPMailer();
/* receiver details and message - start */
$toid = "example@gmail.com";
$toname = "Example";

$msg = "First name : ".$_POST["fname"] . "
";
$msg .= "Last name : ".$_POST["lname"]. "
";;
$msg .= "Email : ".$_POST["email"]. "
";;
$msg .= "Mobile : ".$_POST["mobile"]. "
";;
$msg .= "Message : ".$_POST["msg"];
$subject = "sample subject";
/* receiver details and message - end */

$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPKeepAlive = true;

/* mail smtp configuration - start */
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'test@gmail.com';
$mail->Password = 'xxxxxx';
/* mail smtp configuration - end */

$mail->From = "test@gmail.com";
$mail->FromName = "from name";

$mail->AddAddress($toid, $toname);

$mail->Subject = $subject;
$mail->Body    = $msg;
$mail->IsHTML(true);
if($mail->Send()){
echo "success";
}else{
echo "Failure";
}

When run the above , it throws

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\mail\PHPMailer\class.smtp.php on line 200


问:
Javascript - get array of dates between 2 dates
```<code>var range = getDates(new Date(), new Date().addDays(7));
</code>```

I'd like "range" to be an array of date objects, one for each day between the two dates.

The trick is that it should handle month and year boundaries as well.

答:
I'm using simple while loop to calculate the between dates

var start = new Date("01/05/2017");
var end = new Date("06/30/2017");
var newend = end.setDate(end.getDate()+1);
end = new Date(newend);
while(start < end){
   console.log(new Date(start).getTime() / 1000); // unix timestamp format
   console.log(start); // ISO Date format
   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}```

ContentLicense: CC BY-SA 4.0

Body:
var range = getDates(new Date(), new Date().addDays(7));

I'd like "range" to be an array of date objects, one for each day between the two dates.

The trick is that it should handle month and year boundaries as well.


问:
Change type of list elements from numpy.int64 to int
```<code>{
    "key1" : <list of strings>,
    "key2" : <list of integeres> }
</code>```

I want to change type of 'key2' list to int.
I have already tried looping over and using

v = int(v)

I have also tried mapping int to whole list.

map(int, list)

Any other way I can accomplish this task?

Current Code:

```<code>integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
    col_list = config_data[col]
    col_list = list(map(int, col_list))
</code>```

答:
bug fixed.

assuming you have a dict with each key mapping to a list of numpy.int64.

Setup

```<code>d = {'key2':[np.int64(v) for v in xrange(10)]}
</code>```

Trials

```<code>%timeit -n 1000 d['key2'] = map(int, d['key2'])
1000 loops, best of 3: 1.5 µs per loop

%timeit -n 1000 d['key2'] = [int(v) for v in d['key2']]
1000 loops, best of 3: 2.0 µs per loop

%timeit -n 1000 d['key2'] = [np.asscalar(v) for v in np.array(d['key2'])]
1000 loops, best of 3: 11.6 µs per loop
</code>```

updated with your current codes:

```<code>integer_columns = ["col1","col2","col3","col4"]  # assuming you have a list of list here

for col in integer_columns:
    x = np.array(col)
    config_data[col] = [np.asscalar(v) for v in x]

# >>> type(integer_columns[0][1])
# >>> int
</code>```

numpy.asscalar is a function in numpy for converting numpy types to native python types. here's good answer explaining it.

So there's definitely other ways of doing it, it depends on your particular scenario for a certain solution.

Body:
{
    "key1" : <list of strings>,
    "key2" : <list of integeres> }

I want to change type of 'key2' list to int.
I have already tried looping over and using

v = int(v)

I have also tried mapping int to whole list.

map(int, list)

Any other way I can accomplish this task?

Current Code:

integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
    col_list = config_data[col]
    col_list = list(map(int, col_list))

Body:
bug fixed.

assuming you have a dict with each key mapping to a list of numpy.int64.

Setup

d = {'key2':[np.int64(v) for v in xrange(10)]}

Trials

%timeit -n 1000 d['key2'] = map(int, d['key2'])
1000 loops, best of 3: 1.5 µs per loop

%timeit -n 1000 d['key2'] = [int(v) for v in d['key2']]
1000 loops, best of 3: 2.0 µs per loop

%timeit -n 1000 d['key2'] = [np.asscalar(v) for v in np.array(d['key2'])]
1000 loops, best of 3: 11.6 µs per loop

updated with your current codes:

integer_columns = ["col1","col2","col3","col4"]  # assuming you have a list of list here

for col in integer_columns:
    x = np.array(col)
    config_data[col] = [np.asscalar(v) for v in x]

# >>> type(integer_columns[0][1])
# >>> int

numpy.asscalar is a function in numpy for converting numpy types to native python types. here's good answer explaining it.

So there's definitely other ways of doing it, it depends on your particular scenario for a certain solution.


问:
How do I make dynamic Page Tab URL?

Facebook allowed wildcard domain. So any *.domain.com can be use within single application ID.

Now I want to make every Fan Page will have unique Page Tab URL to my app and the example of URLs one.domain.com, two.domain.com and more.

The subdomain actually point to main app & script will get the subdomain as unique id.

https://developers.facebook.com/docs/appsonfacebook/pagetabs/

I found signed_request can add additional parameter & I'm a bit lost about this one.

May I know the logic how to make sure every Fan Page will have unique URL?

答:
```<code><%@ page import ="java.io.*,java.util.*" %> <%@ page import = "java.util.Arrays,javax.crypto.Mac,javax.crypto.SecretKey,javax.crypto.spec.SecretKeySpec" %> <%@ page import = "org.json.simple.parser.*,org.apache.commons.codec.binary.Base64" %> <%@ page import = "java.io.UnsupportedEncodingException,javax.xml.bind.DatatypeConverter" %> <%

if (request.getParameter("signed_request") != null) {
    String input  =  request.getParameter("signed_request");
    //input ="q3v8X8hbmkKXaF_DZaLBPapMPVjMgpq8bZe-SmYc6Fs.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUxMjYyOTY5MiwicGFnZSI6eyJpZCI6IjEzOTg4MTM1MDM3NTUyMzEiLCJhZG1pbiI6dHJ1ZSwibGlrZWQiOnRydWV9LCJ1c2VyIjp7ImNvdW50cnkiOiJpbiIsImxvY2FsZSI6ImVuX0dCIiwiYWdlIjp7Im1pbiI6MjF9fX0";
    String secretKey = "d8e6e697b9c958a8ee8f2e";
    int max_age = 3600;
    try
    {
        String[] split = input.split("[.]", 2);
        String encoded_sig = split[0];
        String encoded_envelope = split[1];
        JSONParser parser = new JSONParser();
        // check
        //out.println("<br>"+ new String(new Base64(true).decode(encoded_envelope)));
        Map envelope = (Map) parser.parse(new String(new Base64(true).decode(encoded_envelope)));
        String algorithm = (String) envelope.get("algorithm");
        if (!algorithm.equals("HMAC-SHA256")) {
            throw new Exception("Invalid request. (Unsupported algorithm.)");
        }
        if (((Long) envelope.get("issued_at")) < System.currentTimeMillis() / 1000 - max_age) {
            throw new Exception("Invalid request. (Too old.)");
        }
        byte[] key = secretKey.getBytes();
        SecretKey hmacKey = new SecretKeySpec(key, "HMACSHA256");
        Mac mac = Mac.getInstance("HMACSHA256");
        mac.init(hmacKey);
        byte[] digest = mac.doFinal(encoded_envelope.getBytes());
        if (!Arrays.equals( new Base64(true).decode(encoded_sig), digest)) {
            throw new Exception("Invalid request. (Invalid signature.)");
        }
        String pageId = ((Map)envelope.get("page")).get("id").toString();
        if(pageId.equals("1398813503755231")){
            response.sendRedirect("https://yourdomain.com/1111");
        }
        else if(pageId.equals("151433128812548")){
            response.sendRedirect("https://yourdomain1.com/2222");
        }  }
    catch(Exception e)
    {
        out.println("error"+e);
    } } %> <html> <head> Facebook Store <script> var appId = 'your app id'; var pageId=''; window.fbAsyncInit = function() {
    FB.init({
      appId            : appId,
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v2.11'
    });   };   (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);    }(document, 'script', 'facebook-jssdk')); function createPageTab(){
    FB.ui(
        {
            method: 'pagetab',
            redirect_uri:'https://9d5b71a7.ngrok.io/facebook-store.jsp'
        },
        function(response) {
            console.log(JSON.stringify(response));
            if (response != null && response.tabs_added != null) {
                for( pageid in  response.tabs_added){
                      pageId = pageid;
                }
            }
        }
    ); }

function viewPageTab(){
    var url = 'https://facebook.com/pages/-/'+pageId+'?sk=app_'+appId;
    window.open(url,'_blank'); }

</script> </head> <body>
    <button onClick="createPageTab()" >Connect your store with facebook </button>
    <button onClick="viewPageTab();" > View your Store </button> </body> </html

>

 1. `

> Blockquote

`
</code>```

Title: How do I make dynamic Page Tab URL?


问:
c# SpecFlow BeforeScenario hooks
I'm programming several Scenario's in one Feature file.
I'm using one big Steps file to bind the Scenario steps to code.

For example my Feature file looks like this:

```<code>Feature: Feature1
    Description of feature1

@TagA @TagB
Scenario: Scenario1
    Given Some form
    When I press the submit button
    Then I end up at a page

@TagA
Scenario: Scenario2
    Given Some form
    When I press cancel
    Then I should end up at a different page
</code>```

And my Step file looks like this:

```<code>using System;
using TechTalk.SpecFlow;

namespace UpdateServer.AcceptanceTests.StepFiles
{
    [Binding]
    [Scope(Feature = "Feature1")]
    public class Feature1Steps : SeleniumTestsBaseClass
    {
        [BeforeScenario("TagA")]
        public void BeforeScenarioTagA()
        {
            // prepare some stuff
        }

        [BeforeScenario("TagB")]
        public void BeforeScenarioTagB()
        {
            // prepare some other stuff
        }

        [Given(@"Some form")]
        public void GivenSomeForm()
        {
            // navigate to form
        }

        [When(@"I press the submit button")]
        public void WhenIPressTheSubmitButton()
        {
            // press submit button
        }

        [When(@"I press cancel")]
        public void WhenIPressCancel()
        {
            // press cancel button
        }

        [Then(@"I end up at a page")]
        public void ThenIEndUpAtAPage()
        {
            // check url
        }

        [Then(@"I should end up at a different page")]
        public void ThenIShouldEndUpAtADifferentPage()
        {
            // check url
        }
    }
}
</code>```

Notice that my step files inherits from a base class which has some general given,when,then bindings and one AfterScenario which closes the webdriver.

Now when I run Scenario2 it will execute the BeforeScenario of TagB as well.
Ofcourse I don't want this behaviour, why does SpecFlow still execute the TagB code in this context? And how can I stop it from doing that?

Edit

The SeleniumTestsBaseClass is used to initialize a Selenium WebDriver in the constructor of this base class. This is the reason why the Scope has been added to the steps class because all my step classes inherit from the base class.  Removing this Scope attribute results in a WebDriver to be opened for every step file there is, even when only one test is being run.

Follow up question: What's the best place to initialize my WebDriver without risking it being opened more times than necessary?

答:
I believe the reason the BeforeScenario steps are being applied to all your scenarios regardless of tags is because of your scoping the Feature1Steps class to the Feature1 feature.

I did some testing - if you remove all of the tags from your scenarios, both BeforeScenario steps still get run. Same if you add a new scenario with no tags to your existing feature.

I think SpecFlow is seeing you specifying the scope of your steps class and this is a higher precedence than your tag scoping - so it will run the BeforeScenario steps for any scenario in Feature1.

Removing the [Scope(Feature = "Feature1")] attribute from your Feature1Steps class correctly applies the specific BeforeScenario step based on your chosen tags, but without knowing why you've chosen to scope all your bindings to a specific feature I can't comment on whether removing this scope is a good idea.

Although it is considered an anti-pattern to couple step definitions to features and scenarios - read more on the Cucumber wiki.

Title: c# SpecFlow BeforeScenario hooks

Body:
I'm programming several Scenario's in one Feature file.
I'm using one big Steps file to bind the Scenario steps to code.

For example my Feature file looks like this:

Feature: Feature1
    Description of feature1

@TagA @TagB
Scenario: Scenario1
    Given Some form
    When I press the submit button
    Then I end up at a page

@TagA
Scenario: Scenario2
    Given Some form
    When I press cancel
    Then I should end up at a different page

And my Step file looks like this:

using System;
using TechTalk.SpecFlow;

namespace UpdateServer.AcceptanceTests.StepFiles
{
    [Binding]
    [Scope(Feature = "Feature1")]
    public class Feature1Steps : SeleniumTestsBaseClass
    {
        [BeforeScenario("TagA")]
        public void BeforeScenarioTagA()
        {
            // prepare some stuff
        }

        [BeforeScenario("TagB")]
        public void BeforeScenarioTagB()
        {
            // prepare some other stuff
        }

        [Given(@"Some form")]
        public void GivenSomeForm()
        {
            // navigate to form
        }

        [When(@"I press the submit button")]
        public void WhenIPressTheSubmitButton()
        {
            // press submit button
        }

        [When(@"I press cancel")]
        public void WhenIPressCancel()
        {
            // press cancel button
        }

        [Then(@"I end up at a page")]
        public void ThenIEndUpAtAPage()
        {
            // check url
        }

        [Then(@"I should end up at a different page")]
        public void ThenIShouldEndUpAtADifferentPage()
        {
            // check url
        }
    }
}

Notice that my step files inherits from a base class which has some general given,when,then bindings and one AfterScenario which closes the webdriver.

Now when I run Scenario2 it will execute the BeforeScenario of TagB as well.
Ofcourse I don't want this behaviour, why does SpecFlow still execute the TagB code in this context? And how can I stop it from doing that?

Edit

The SeleniumTestsBaseClass is used to initialize a Selenium WebDriver in the constructor of this base class. This is the reason why the Scope has been added to the steps class because all my step classes inherit from the base class.  Removing this Scope attribute results in a WebDriver to be opened for every step file there is, even when only one test is being run.

Follow up question: What's the best place to initialize my WebDriver without risking it being opened more times than necessary?


问:
Django REST Framework: Nested Serializers not appearing
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]
</code>```

What I want it to return:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]
</code>```

views.py

```<code>from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer
</code>```

models.py

```<code>class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)
</code>```

serializers.py

```<code>class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')
</code>```

Any help is appreciated

答:
You don't need to create NameSerializer serializer. Create a method field in UserSerializer for name field such as:

```<code>class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        name = {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }
        return name
</code>```

It will give your desired result.

Body:
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]

What I want it to return:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]

views.py

from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer

models.py

class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)

serializers.py

class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')

Any help is appreciated

Body:
You don't need to create NameSerializer serializer. Create a method field in UserSerializer for name field such as:

class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        name = {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }
        return name

It will give your desired result.


问:
How do I center items of the navbar inside a full-width container?
So I am trying to make a Boostrap 4 navbar to fit in a full width container,but I want to navigation bar items to be centered, like in a normal container.

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                Home (current)
                Features
                Pricing
                Disabled

```

I can't figure out what to modify.

答:
You need to place a .container inside the nav element:

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css" rel="stylesheet" />

      Navbar
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

              </button>

          Home (current)
          Features
          Pricing
          Disabled

```

Body:
So I am trying to make a Boostrap 4 navbar to fit in a full width container,but I want to navigation bar items to be centered, like in a normal container.

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                Home (current)
                Features
                Pricing
                Disabled

I can't figure out what to modify.

Body:
You need to place a .container inside the nav element:

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css" rel="stylesheet" />
<div class="container-full">
  <nav class="navbar navbar-expand-lg  position'navbar-dark bg-dark">
    <div class="container">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
              </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
          <a class="nav-item nav-link" href="#">Features</a>
          <a class="nav-item nav-link" href="#">Pricing</a>
          <a class="nav-item nav-link disabled" href="#">Disabled</a>
        </div>
      </div>
    </div>
  </nav>
</div>


问:
INSERT FROM syntax
logcat

```<code>    12-07 12:24:30.394 7246-7246/me.jaxbot.appfoodgrab E/SQLiteLog: (1) near "FROM": syntax error
    12-07 12:24:30.396 7246-7246/me.jaxbot.appfoodgrab E/AndroidRuntime: FATAL EXCEPTION: main
 Process: me.jaxbot.appfoodgrab, PID: 7246
 android.database.sqlite.SQLiteException: near "FROM": syntax error (code 1): , while compiling: INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('02','Nasi Goreng','5','6','5');
     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
     at me.jaxbot.appfoodgrab.Database.Database.addToCart(Database.java:61)
     at me.jaxbot.appfoodgrab.FoodDetail$1.onClick(FoodDetail.java:55)
     at android.view.View.performClick(View.java:5610)
     at android.view.View$PerformClick.run(View.java:22265)
     at android.os.Handler.handleCallback(Handler.java:751)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    12-07 12:24:30.420 1589-1839/? E/ActivityManager: Found activity ActivityRecord{dc9c9ab u0 me.jaxbot.appfoodgrab/.MainActivity t99 f} in proc activity list using null instead of expected ProcessRecord{226ea2 7246:me.jaxbot.appfoodgrab/u0a82}
    12-07 12:38:42.780 2368-2922/? E/NetworkScheduler: ignoring stale queue check message
</code>```

My coding

```<code>  public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }
</code>```

答:
Problem is with the SQL query.Its like

```<code>INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
</code>```

So for your case

```<code>String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');", order.getProductId(), order.getProductName(), order.getQuantity(), order.getPrice(), order.getDiscount()); db.execSQL(query);
</code>```

Hope this will help.

Title: INSERT FROM syntax

Body:
logcat

    12-07 12:24:30.394 7246-7246/me.jaxbot.appfoodgrab E/SQLiteLog: (1) near "FROM": syntax error
    12-07 12:24:30.396 7246-7246/me.jaxbot.appfoodgrab E/AndroidRuntime: FATAL EXCEPTION: main
 Process: me.jaxbot.appfoodgrab, PID: 7246
 android.database.sqlite.SQLiteException: near "FROM": syntax error (code 1): , while compiling: INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('02','Nasi Goreng','5','6','5');
     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
     at me.jaxbot.appfoodgrab.Database.Database.addToCart(Database.java:61)
     at me.jaxbot.appfoodgrab.FoodDetail$1.onClick(FoodDetail.java:55)
     at android.view.View.performClick(View.java:5610)
     at android.view.View$PerformClick.run(View.java:22265)
     at android.os.Handler.handleCallback(Handler.java:751)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    12-07 12:24:30.420 1589-1839/? E/ActivityManager: Found activity ActivityRecord{dc9c9ab u0 me.jaxbot.appfoodgrab/.MainActivity t99 f} in proc activity list using null instead of expected ProcessRecord{226ea2 7246:me.jaxbot.appfoodgrab/u0a82}
    12-07 12:38:42.780 2368-2922/? E/NetworkScheduler: ignoring stale queue check message

My coding

  public void addToCart (Order order)
    {
        SQLiteDatabase db = getReadableDatabase();
        String query = String.format("INSERT FROM OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');",
                order.getProductId(),
                order.getProductName(),
                order.getQuantity(),
                order.getPrice(),
                order.getDiscount());
        db.execSQL(query);

    }

Body:
Problem is with the SQL query.Its like

INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);

So for your case

String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount)VALUES('%s','%s','%s','%s','%s');", order.getProductId(), order.getProductName(), order.getQuantity(), order.getPrice(), order.getDiscount()); db.execSQL(query);

Hope this will help.


问:
SproutCore Security and Authentication concerns
I've been trying to learn a little about SproutCore, following the "Todos" tutorial, and I have a couple of questions that haven't been able to find online.

SproutCore is supposed to move all of the business logic to the client. How is that not insecure? A malicious user could easily tamper with the code (since it's all on the client) and change the way the app behaves. How am I wrong here?

SproutCore uses "DataStores", and some of them can be remote. How can I avoid that a malicious user does not interact with the backend on his own? Using some sort of API key wouldn't work since the code is on the client side. Is there some sort of convention here? Any ideas? This really bugs me.

Thanks in advance!

PS: Anyone thinks Cappuccino is a better alternative? I decided to go with SproutCore because the documentation on Cappuccino seemed pretty bad, although SproutCore's doesn't get any better.

答:
Ian

your concerns are valid.  The thing is, they apply to all client side code, no matter what framework.  So:

Web applications are complicated things.  Moving processing to the client is a good thing, because it speeds up the responsiveness of the application.  However, it is imperative that the server validate all data inputs, just like in any other web application.

Additionally, all web applications should use the well known authentication/authorization paradigms that are prevalent in system security.  Authentication means you must verify that the user is who they say they are, and they can use the system, with Authorization means that the server must verify that the user can do what they are trying e.g. can they create a new data entry, or edit an existing one.  It is good design to not present users with UI options that they are not allowed to perform, but you should not rely on that.

All web applications must do those things.

With respect to the 'interacting with the back end' concern:  Again, all web applications have this concern.  You can open up firebug/webkit, and look at all the the xhr requests that RIAs use in their operations, and mimic them to try to do something on that system.  Again, this concern is dealt with by the authentication/authorization checks that you must implement. Anybody can use any webclient to send a request to the server.  It is up to the developer to validate that request.

The DataSources in SproutCore are just an abstraction around how SC apps interact with the server.  At the end of the day, however, all SC is doing is making XHR requests to the server, like any other RIA.

ContentLicense: CC BY-SA 2.5


问:
Angular: ViewContainer isn't inserting component adjacent to anchor element, but nesting within the component itself
I have created a tab view, with the following structure:

```<code><tabs>
        <ul #getVCRefHERE >
            <li>tab1</li>
            <li>tab2</li>
        </ul>

        <tab>
            <ng-content></ng-content> <!--screen for tab2 -->
        </tab>
        <tab>
            <ng-content></ng-content> <!--content for tab1 -->
        </tab>
</tabs>
</code>```

I create each component: tabs,tab,and the component placed in the ng-content.  place. The issue is when I insert at the end of the ViewContainer(it uses ul as it's anchor element) the sequential tabs are nest inside of the tab like this:

```<code><tabs>
            <ul #postionVCRef>
                <li>tab1</li>
                <li>tab2</li>
            </ul>

            <tab>
                <ng-content></ng-content> <!--screen for tab1 -->
                <tab>
                    <ng-content></ng-content> <!--content for tab2 -->
                </tab>
            </tab>

    </tabs>
</code>```

It is fancy trick, but not helpful. When I insert at position 0 this weird nesting doesn't occur, but the tabs are inserted in opposite order than they were created which causes me issues later in my app.

The code that creates the tab with its projectable node looks like this:

```<code>// Tab == SubContainer,  Tabs == Container
    makeComp(component: Type<DynamicComponent>){
        let compFactory =this.compFR.resolveComponentFactory(component);
        let compRef = this.viewContainer.createComponent(compFactory);

        let length =this.viewContainer.length - 1;
        console.log(length)
        let subFactory = this.compFR.resolveComponentFactory(SubContainer);
        let subRef = this.viewContainer.createComponent(subFactory,length,undefined,[[compRef.location.nativeElement]]);
        subRef.instance.title = compRef.instance.name;
        this.subList.push(subRef.instance);

      }
</code>```

I feel the issue is probably in how I am creating the ng-content(projectable nodes). Unfortunately, I am unaware why the viewContainer appears to be using the tab's ng-content as the anchor element to insert the next tab.

I would really appreciate someone with better understanding of viewContainer to tell me why this might be occurring. Here is my sample app demonstrating this nesting behavior.

答:
Use this code to insert siblings of element where you apply selector of component.
At your component:

```<code>import { HostListener,ComponentRef,EventEmitter,OnInit,ElementRef, Injectable ,Component,Input,Output,ViewContainerRef,ViewChild  } from '@angular/core';
</code>```

At constructor

```<code>    constructor(private _vcr: ViewContainerRef,private _eref: ElementRef) {
}
</code>```

At class

```<code>@ViewChild('Date') Date;
ngAfterViewInit() {
       this._vcr.createEmbeddedView(this.Date);
    }
</code>```

at template

```<code><ng-template #Date>
// Your Html
</ng-template>
</code>```

The natural behavior of using child selector is to insert the code of child  template html inside the selector tags which are used in parent component. So we have to use createEmbeddedView function of ViewContainerRef [ Parent HTML Element]. If you want to provide some html with in selector tag fro parent to child then use  inside child template.

Body:
I have created a tab view, with the following structure:

<tabs>

tab1

tab2

        <tab>
            <ng-content></ng-content>
        </tab>
        <tab>
            <ng-content></ng-content>
        </tab>
</tabs>

I create each component: tabs,tab,and the component placed in the ng-content.  place. The issue is when I insert at the end of the ViewContainer(it uses ul as it's anchor element) the sequential tabs are nest inside of the tab like this:

<tabs>

tab1

tab2

            <tab>
                <ng-content></ng-content>
                <tab>
                    <ng-content></ng-content>
                </tab>
            </tab>

    </tabs>

It is fancy trick, but not helpful. When I insert at position 0 this weird nesting doesn't occur, but the tabs are inserted in opposite order than they were created which causes me issues later in my app.

The code that creates the tab with its projectable node looks like this:

// Tab == SubContainer,  Tabs == Container
    makeComp(component: Type<DynamicComponent>){
        let compFactory =this.compFR.resolveComponentFactory(component);
        let compRef = this.viewContainer.createComponent(compFactory);

        let length =this.viewContainer.length - 1;
        console.log(length)
        let subFactory = this.compFR.resolveComponentFactory(SubContainer);
        let subRef = this.viewContainer.createComponent(subFactory,length,undefined,[[compRef.location.nativeElement]]);
        subRef.instance.title = compRef.instance.name;
        this.subList.push(subRef.instance);

      }

I feel the issue is probably in how I am creating the ng-content(projectable nodes). Unfortunately, I am unaware why the viewContainer appears to be using the tab's ng-content as the anchor element to insert the next tab.

I would really appreciate someone with better understanding of viewContainer to tell me why this might be occurring. Here is my sample app demonstrating this nesting behavior.

Body:
Use this code to insert siblings of element where you apply selector of component.
At your component:

import { HostListener,ComponentRef,EventEmitter,OnInit,ElementRef, Injectable ,Component,Input,Output,ViewContainerRef,ViewChild  } from '@angular/core';

At constructor

    constructor(private _vcr: ViewContainerRef,private _eref: ElementRef) {
}

At class

@ViewChild('Date') Date;
ngAfterViewInit() {
       this._vcr.createEmbeddedView(this.Date);
    }

at template

<ng-template #Date>
// Your Html
</ng-template>

The natural behavior of using child selector is to insert the code of child  template html inside the selector tags which are used in parent component. So we have to use createEmbeddedView function of ViewContainerRef [ Parent HTML Element]. If you want to provide some html with in selector tag fro parent to child then use  inside child template.


问:
Is implementing client-side validation through an API realistic when it comes to performance?
So in an ideal world both client side validation and server side validation can be defined in one place, so the validation only has to be written once and can be reused where ever.

The idea i have to solve this is to do all the validation through an API using ASP.NET Core. When the form data on the client changes it will send an AJAX request with the updated data model, which the API validates and in turn returns any possible errors. The client then shows these errors to the user directly.
This way it still looks like the good old client-side validation, but it actually all happens on the server.

I can already imagine the server load is going to be increased since a lot more API calls will be send, however the question is:
will this server load be manageable in for example a big enterprise application with huge forms and complex validation?

And are there any other big drawbacks of this solution which i have to watch out for?

答:
You are talking about an API not any other type of application with a back-end.

In this world, yes the validation of the payloads is important and needs to happen on the API side. In a way, the validation is the easiest part and less resource consuming since this is the first thing you check and if it doesn't pass then the API returns a 400 BadRequest HTTP code and nothing else happens.

There are systems where the validation, especially business rules validation does not happen on the API side. You could have for example a financial platform and the API is simply the gateway inside that world. In this case, the API acts as a pass-through and doesn't do much itself.

This being said, everything is susceptible to too much traffic, but you should be able to either throw enough resources at it, or have it deployed in the cloud and let it scale based on demand. You can load test APIs as well, to see how well they do under pressure, you must have an idea of how many calls you can expect in a certain period of time.

I wouldn't worry too much about it, I'd say validate what you can client side, so you don't even hit the API if there is no need for it and leave the rest to the API


问:
How to make a countdown timer in Android?
I have two EditTexts in XML. In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second.

Additionally, how can I keep it updating until it gets to zero minutes and zero seconds?

答:
Try this way:</p>

```<code>private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }

        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}
</code>```

Body:
Try this way:

private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }

        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}


问:
What is the use of EAX register in the context of system calls in Linux?
In the text book Linux Kernel Development by Robert Love, it is mentioned that (pg no. 101):

The return value is sent to user-space also via register. On x86, it
  is written into the eax register.

And in the text book The Linux Programming Interface by Michael Kerrisk, it is mentioned that (pg no. 88):

Since all system calls enter the kernel in the same way, the kernel
  needs some method of identifying the system call. To permit this, the
  wrapper function copies the system call number into a specific CPU
  register (%eax).

Then, what conclusion can I draw upon the utility of EAX register in system calls?

When the kernel comes across a system call the it copies the system call number to the EAX register, for which the value in the register is replaced by the return value of the system call at the time of return from the system call. Is this conclusion correct?

答:
X86 Assembly/Interfacing with Linux

Making a syscall

For making a syscall using an interrupt, you have to pass all required
  information to the kernel by copying them into general purpose
  registers.

Each syscall has a fixed number (note: the numbers differ between int
  $0x80 and syscall!). You specify the syscall by writing the number
  into the eax/rax register.

Most syscalls take parameters to perform their task. Those parameters
  are passed by writing them in the appropriate registers before making
  the actual call. Each parameter index has a specific register. See the
  tables in the subsections as the mapping differs between int $0x80
  and syscall. Parameters are passed in the order they appear in the
  function signature of the corresponding C wrapper function. You may
  find syscall functions and their signatures in every Linux API
  documentation, like the reference manual (type man 2 open to see the
  signature of the open syscall).

After everything is set up correctly, you call the interrupt using
  int $0x80 or syscall and the kernel performs the task.

The return / error value of a syscall is written to eax/rax.

The kernel uses its own stack to perform the actions. The user stack
  is not touched in any way.

So to sum up:

In user space:

prepare the syscall by writing the parameters into specified registers

put the syscall number into eax

call the interrupt by int $0x80 or syscall

In kernel space:

the kernel reads the syscall number from eax

reads the parameters from the specific registers

performs the task (on it's own stack)

writes the result in eax

returns to control to user space

In user space again:

you can find the result of the interrupt in the eax register


问:
How to use own method on ArrayList in Java?
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

```<code>public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}
</code>```

And subclass which extends Employee:

```<code>public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}
</code>```

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

```<code>public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}
</code>```

Why can't I do this like that?

答:
What's happening is that you are calling the method hire directly into the ArrayList object, instead of that, create an object called Company, then, once it's created, call the method of hire in the Company, as the Company already has the property of ArrayList in it.

```<code>public static void main(String[]args) {
    Company company = new Company();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    company.hire(e1);
}
</code>```

Hope it helps!

Body:
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}

And subclass which extends Employee:

public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}

Why can't I do this like that?

Body:
What's happening is that you are calling the method hire directly into the ArrayList object, instead of that, create an object called Company, then, once it's created, call the method of hire in the Company, as the Company already has the property of ArrayList in it.

public static void main(String[]args) {
    Company company = new Company();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    company.hire(e1);
}

Hope it helps!


问:
How to do arithmetic operation in group values using javascript
How to do arithmetic operation in group values using javascript for example

```<code>var a = "5(8)+109/100";
</code>```

I have used javascript eval() function to solve this,

Output :

```<code>var output = eval(a); //41.09
</code>```

But eval() is not correct solution. Is there anything alternate solution to solve this task

答:
Try following:

var a = "5(8)+109/100";
var res = ( new Function( 'return ' + a.split('(').join('*(') ) )();
console.log(res);

Body:
How to do arithmetic operation in group values using javascript for example

var a = "5(8)+109/100";

I have used javascript eval() function to solve this,

Output :

var output = eval(a); //41.09

But eval() is not correct solution. Is there anything alternate solution to solve this task


问:
Unable to add volume to image via docker-compose
I'm trying to add a volume to the mattermost/mattermost-preview docker image. The Dockerfile for this image (not controlled by me) is:

```<code># Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
# See License.txt for license information.
FROM mysql:5.7

# Install ca-certificates to support TLS of Mattermost v3.5
RUN apt-get update && apt-get install -y ca-certificates

#
# Configure SQL
#

ENV MYSQL_ROOT_PASSWORD=mostest
ENV MYSQL_USER=mmuser
ENV MYSQL_PASSWORD=mostest
ENV MYSQL_DATABASE=mattermost_test

#
# Configure Mattermost
#
WORKDIR /mm

# Copy over files
ADD https://releases.mattermost.com/4.4.4/mattermost-team-4.4.4-linux-amd64.tar.gz .
RUN tar -zxvf ./mattermost-team-4.4.4-linux-amd64.tar.gz
ADD config_docker.json ./mattermost/config/config_docker.json
ADD docker-entry.sh .

RUN chmod +x ./docker-entry.sh
ENTRYPOINT ./docker-entry.sh

# Create default storage directory
RUN mkdir ./mattermost-data
VOLUME ./mattermost-data

# Ports
EXPOSE 8065
</code>```

I want to add a volume to this image, and a custom entrypoint so that I can add some test data to the mysql database before my container starts up. I'm trying to use docker-compose to do this:

```<code>version: '3'
services:
  mattermost:
    ports:
     - "8065:8065"
    image: mattermost/mattermost-preview
    volumes:
      - ./end_to_end/mattermost/mock-mount:/mm/mock-mount
    entrypoint: /mm/mock-mount/docker-entry.sh
</code>```

But I'm unfortunately not able to get this to start, when I try running docker-compose up, I get the error

```<code>ERROR: for mattermost  Cannot create container for service mattermost: invalid bind mount spec "39742853c03b3b2747f11c942a4a76e4cd138ad41d54f70f71d7aa9ccc36dcca:mattermost-data:rw": invalid volume specification: '39742853c03b3b2747f11c942a4a76e4cd138ad41d54f70f71d7aa9ccc36dcca:mattermost-data:rw': invalid mount config for type "volume": invalid mount path: 'mattermost-data' mount path must be absolute
ERROR: Encountered errors while bringing up the project.
</code>```

The weird thing is - if I take out the volumes and entrypoint sections from my docker-compose.yml file, then the container starts up no problem, even though it seems to me that the error is with the original image. Is there a way to do what I want here?

答:
You cannot use a relative path when declaring a volume in a Dockerfile to be used with docker-compose:

```<code>VOLUME ./mattermost-data
</code>```

As mentioned here, the question would be relative to what? Is it relative to some workdir of the container? Is it relative to the local filesystem while you're building the layer?

Usual practice is to create the volume with absolute paths, such as just /mattermost-data (so this mount point will be at the root level of the container).

In the compose file, a relative path is OK for the source path, but it is interpreted relative to the compose file itself ... so you have to be careful not to think that it is relative to some container path. Relative paths are still disallowed for the destination paths.

More details:

As reported here, relative paths for a VOLUME in a Dockerfile won't cause the Dockerfile to break necessarily, it's just that they are always treated relative to / and don't care about any intermediate WORKDIR or the temporary layers involved with creating the image, etc.

Basically, creating a relative VOLUME is going to create it at the top level if you manually perform docker build. For docker-compose though, it will not work at all, and throws the error that you are seeing.

You might want to file a bug report with the authors of that Dockerfile, since the usage of VOLUME ./mattermost-data hamstrings anyone downstream who wants to use that image drectly with docker-compose.

Body:
I'm trying to add a volume to the mattermost/mattermost-preview docker image. The Dockerfile for this image (not controlled by me) is:

# Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
# See License.txt for license information.
FROM mysql:5.7

# Install ca-certificates to support TLS of Mattermost v3.5
RUN apt-get update && apt-get install -y ca-certificates

#
# Configure SQL
#

ENV MYSQL_ROOT_PASSWORD=mostest
ENV MYSQL_USER=mmuser
ENV MYSQL_PASSWORD=mostest
ENV MYSQL_DATABASE=mattermost_test

#
# Configure Mattermost
#
WORKDIR /mm

# Copy over files
ADD https://releases.mattermost.com/4.4.4/mattermost-team-4.4.4-linux-amd64.tar.gz .
RUN tar -zxvf ./mattermost-team-4.4.4-linux-amd64.tar.gz
ADD config_docker.json ./mattermost/config/config_docker.json
ADD docker-entry.sh .

RUN chmod +x ./docker-entry.sh
ENTRYPOINT ./docker-entry.sh

# Create default storage directory
RUN mkdir ./mattermost-data
VOLUME ./mattermost-data

# Ports
EXPOSE 8065

I want to add a volume to this image, and a custom entrypoint so that I can add some test data to the mysql database before my container starts up. I'm trying to use docker-compose to do this:

version: '3'
services:
  mattermost:
    ports:
     - "8065:8065"
    image: mattermost/mattermost-preview
    volumes:
      - ./end_to_end/mattermost/mock-mount:/mm/mock-mount
    entrypoint: /mm/mock-mount/docker-entry.sh

But I'm unfortunately not able to get this to start, when I try running docker-compose up, I get the error

ERROR: for mattermost  Cannot create container for service mattermost: invalid bind mount spec "39742853c03b3b2747f11c942a4a76e4cd138ad41d54f70f71d7aa9ccc36dcca:mattermost-data:rw": invalid volume specification: '39742853c03b3b2747f11c942a4a76e4cd138ad41d54f70f71d7aa9ccc36dcca:mattermost-data:rw': invalid mount config for type "volume": invalid mount path: 'mattermost-data' mount path must be absolute
ERROR: Encountered errors while bringing up the project.

The weird thing is - if I take out the volumes and entrypoint sections from my docker-compose.yml file, then the container starts up no problem, even though it seems to me that the error is with the original image. Is there a way to do what I want here?

Body:
You cannot use a relative path when declaring a volume in a Dockerfile to be used with docker-compose:

VOLUME ./mattermost-data

As mentioned here, the question would be relative to what? Is it relative to some workdir of the container? Is it relative to the local filesystem while you're building the layer?

Usual practice is to create the volume with absolute paths, such as just /mattermost-data (so this mount point will be at the root level of the container).

In the compose file, a relative path is OK for the source path, but it is interpreted relative to the compose file itself ... so you have to be careful not to think that it is relative to some container path. Relative paths are still disallowed for the destination paths.

More details:

As reported here, relative paths for a VOLUME in a Dockerfile won't cause the Dockerfile to break necessarily, it's just that they are always treated relative to / and don't care about any intermediate WORKDIR or the temporary layers involved with creating the image, etc.

Basically, creating a relative VOLUME is going to create it at the top level if you manually perform docker build. For docker-compose though, it will not work at all, and throws the error that you are seeing.

You might want to file a bug report with the authors of that Dockerfile, since the usage of VOLUME ./mattermost-data hamstrings anyone downstream who wants to use that image drectly with docker-compose.


问:
What are the standard naming conventions for global objects in Javascript?
In Javascript, objects 'window' and 'document' start with a small letter, but global object 'Math' starts with a capital object.

Do these objects follow a standardised naming convention?

答: These are all built-in JS objects. So we have to follow the conventions.</p>


问:
Ruby: Access member variable with string (Reflection)
I have a Ruby object User, which has a :first_name member variable. I would like to be able to access that variable with a string.

So if I have a user called u:

u.'first_name' should be equivalent to u.first_name

How could I use reflection to get u.first_name through the string, which is passed in as a variable?

答:
I think what you mean with "member variable", is that you have a model that has an attribute called first_name. If so, then you can access that attribute as you'd do in a "plain" ("plain" because the question is focused to Rails) Ruby class:

```<code>class Foo
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end

foo = Foo.new('bar')
p foo.instance_variables             # [:@name]
p foo.instance_variable_get('@name') # "bar"
</code>```

The most idiomatic way to get dynamically an instance variable is using instance_variable_get, but you can also use send, or better using __send__, or even better in your case using public_send:

```<code>foo = Foo.new('bar')
p foo.instance_variables             # [:@name]
p foo.instance_variable_get('@name') # "bar"
p foo.send('name')                   # "bar"
p foo.public_send('name')            # "bar"
</code>```

The way Rails handles your models and attributes is almost the same (NOTE: opened to edition). By instantiating one of your models, you can get the attribute you need:

```<code>user = User.first
user.email                # email@mail.com
user.public_send('email') # email@mail.com
</code>```

Body:
I think what you mean with "member variable", is that you have a model that has an attribute called first_name. If so, then you can access that attribute as you'd do in a "plain" ("plain" because the question is focused to Rails) Ruby class:

class Foo
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end

foo = Foo.new('bar')
p foo.instance_variables             # [:@name]
p foo.instance_variable_get('@name') # "bar"

The most idiomatic way to get dynamically an instance variable is using instance_variable_get, but you can also use send, or better using __send__, or even better in your case using public_send:

foo = Foo.new('bar')
p foo.instance_variables             # [:@name]
p foo.instance_variable_get('@name') # "bar"
p foo.send('name')                   # "bar"
p foo.public_send('name')            # "bar"

The way Rails handles your models and attributes is almost the same (NOTE: opened to edition). By instantiating one of your models, you can get the attribute you need:

user = User.first
user.email                # email@mail.com
user.public_send('email') # email@mail.com


问:
Timer interrupt and scheduling
I'm having a hard time understanding the way that timer interrupts relate to the system scheduler and the role of DPC (deferred procedure calls) in all of this. Here's what I understood (Correct me if i'm wrong):

1) At every clock interval an interrupt is made, Causing the current process to pause and the clock interrupt handler starts running after a context switch.

2) The handler runs the scheduler which checks if a certain process ran out of running time or stopped executing because of an IO operation etc...

So my first question is: does the scheduler actually run on every interval?

My second question is: What is the role of DPC here and is it related to the scheduler?

(I tried to understand from Wikipedia but didn't quite understand what's the "dispatching" that's mentioned there)

thanks.

答: Timer interruption is a technique that is closely related to preemption. when a process gets the CPU, a timer may be set to a specified interval. If the process is still using the CPU at the end of the interval, then it is preempted.</p>

Title: Timer interrupt and scheduling


问:
JavaScript delete elements in array by a criteria
I have an array, and I want to delete elements that have status equal to true (as seen in this part of code)

```<code>listArray.forEach((element, index) => {
        if (element.status === true) {
            listArray.splice(index, 1);
        }
    });
</code>```

The problem is that, if, for example, the first, second and third elements have status true, than the second element will not be deleted

答:
try this:</p>

```<code>listArray = listArray.filter(element => !element.status);
</code>```

Body:
I have an array, and I want to delete elements that have status equal to true (as seen in this part of code)

listArray.forEach((element, index) => {
        if (element.status === true) {
            listArray.splice(index, 1);
        }
    });

The problem is that, if, for example, the first, second and third elements have status true, than the second element will not be deleted

Body:
try this:

listArray = listArray.filter(element => !element.status);


问:
Three.js Draw where mouse clicks, but entirely parallel to camera orientation
I"m not exactly sure how I can do this. I read a lot about raycasting and that seems to be good for finding points that intersect with something, but in this case I just want it to interpolate the 2d mouse coordinates to the 3d point exactly where the mouse clicks, regardless of scale, rotation, whether or not there's an object there, etc.

One method I've thought of but not approached would be making an invisible plane that is parallel to the camera, always oriented upright and always intersecting the y axis. Then use a raycaster to hit the plane, draw as needed, then delete the plane. Seems like a silly way to do this though.

At the moment I have a method that works pretty well but it has some issues when the line gets further away from the origin, or the camera gets zoomed

In this photo I drew two lines from two different perspectives. The vertical line what it looks like when the camera is level with the x and z axis, and I draw a straight line down the y axis, while the horizontal line is what happens when i scribble with the camera facing down.
https://i.imgur.com/f8qw5xV.png

As you can see, it seems to use the distance to the camera to make this calculation, so the further the distance from the camera, the more distortion is in the calculation. How can get rid of this distortion?

source: https://github.com/AskAlice/mandala-3d-threejs
live demo: https://askalice.me/mandala/

Here is the relevant code:

js/content.js@112

```<code>function get3dPointZAxis(event)
{
    camPos = camera.position;
    var mv = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY/window.innerHeight) * 2 + 1, 1).unproject(camera);
    var m2 = new THREE.Vector3(0,0,0);
    var pos = camPos.clone();
    pos.add(mv.sub(camPos).normalize().multiplyScalar(m2.distanceTo(camPos)));
    return pos;
}
</code>```

I used information from two stackoverflow posts to come up with this, and it has the issues I've described.

firstly, this post shows how to draw and convert it to the z axis. It is flat. But I had a lot of trouble trying to make that work in three dimensions.

How to draw a line segment at run time using three.js

and then i used information in the below post to at least get it parallel to the camera on the x-z axis like such: https://i.imgur.com/E9AQNpH.png

Moving objects parallel to projection plane in three.js

答:
That option with THREE.Plane() and THREE.Raycaster().ray.intersectPlane():

```<code>var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var plane = new THREE.Plane();
var planeNormal = new THREE.Vector3();
var point = new THREE.Vector3();

function getPoint(event){
  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  planeNormal.copy(camera.position).normalize();
  plane.setFromNormalAndCoplanarPoint(planeNormal, scene.position);
  raycaster.setFromCamera(mouse, camera);
  raycaster.ray.intersectPlane(plane, point);
}
</code>```

Run the code snippet, click the "draw" checkbox to set it as checked, move your mouse randomly (without mouse down), click the checkbox again, rotate the scene with mousedown. All points are on the same plane.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var plane = new THREE.Plane();
var planeNormal = new THREE.Vector3();
var point = new THREE.Vector3();

document.addEventListener("mousedown", onMouseDown, false);
document.addEventListener("mousemove", onMouseMove, false);

function getPoint(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  planeNormal.copy(camera.position).normalize();
  plane.setFromNormalAndCoplanarPoint(planeNormal, scene.position);
  raycaster.setFromCamera(mouse, camera);
  raycaster.ray.intersectPlane(plane, point);
}

function setPoint() {
  var sphere = new THREE.Mesh(new THREE.SphereBufferGeometry(.125, 4, 2), new THREE.MeshBasicMaterial({
    color: "yellow",
    wireframe: true
  }));
  sphere.position.copy(point);
  scene.add(sphere);
}

function onMouseDown(event) {
  getPoint(event);
  if (draw.checked) setPoint();
}

function onMouseMove(event) {
  getPoint(event);
  if (draw.checked) setPoint();
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

  <input id="draw" type="checkbox">
  draw

```

Body:
I"m not exactly sure how I can do this. I read a lot about raycasting and that seems to be good for finding points that intersect with something, but in this case I just want it to interpolate the 2d mouse coordinates to the 3d point exactly where the mouse clicks, regardless of scale, rotation, whether or not there's an object there, etc.

One method I've thought of but not approached would be making an invisible plane that is parallel to the camera, always oriented upright and always intersecting the y axis. Then use a raycaster to hit the plane, draw as needed, then delete the plane. Seems like a silly way to do this though.

At the moment I have a method that works pretty well but it has some issues when the line gets further away from the origin, or the camera gets zoomed

In this photo I drew two lines from two different perspectives. The vertical line what it looks like when the camera is level with the x and z axis, and I draw a straight line down the y axis, while the horizontal line is what happens when i scribble with the camera facing down.
https://i.imgur.com/f8qw5xV.png

As you can see, it seems to use the distance to the camera to make this calculation, so the further the distance from the camera, the more distortion is in the calculation. How can get rid of this distortion?

source: https://github.com/AskAlice/mandala-3d-threejs
live demo: https://askalice.me/mandala/

Here is the relevant code:

js/content.js@112

function get3dPointZAxis(event)
{
    camPos = camera.position;
    var mv = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY/window.innerHeight) * 2 + 1, 1).unproject(camera);
    var m2 = new THREE.Vector3(0,0,0);
    var pos = camPos.clone();
    pos.add(mv.sub(camPos).normalize().multiplyScalar(m2.distanceTo(camPos)));
    return pos;
}

I used information from two stackoverflow posts to come up with this, and it has the issues I've described.

firstly, this post shows how to draw and convert it to the z axis. It is flat. But I had a lot of trouble trying to make that work in three dimensions.

How to draw a line segment at run time using three.js

and then i used information in the below post to at least get it parallel to the camera on the x-z axis like such: https://i.imgur.com/E9AQNpH.png

Moving objects parallel to projection plane in three.js

Body:
That option with THREE.Plane() and THREE.Raycaster().ray.intersectPlane():

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var plane = new THREE.Plane();
var planeNormal = new THREE.Vector3();
var point = new THREE.Vector3();

function getPoint(event){
  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  planeNormal.copy(camera.position).normalize();
  plane.setFromNormalAndCoplanarPoint(planeNormal, scene.position);
  raycaster.setFromCamera(mouse, camera);
  raycaster.ray.intersectPlane(plane, point);
}

Run the code snippet, click the "draw" checkbox to set it as checked, move your mouse randomly (without mouse down), click the checkbox again, rotate the scene with mousedown. All points are on the same plane.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var plane = new THREE.Plane();
var planeNormal = new THREE.Vector3();
var point = new THREE.Vector3();

document.addEventListener("mousedown", onMouseDown, false);
document.addEventListener("mousemove", onMouseMove, false);

function getPoint(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  planeNormal.copy(camera.position).normalize();
  plane.setFromNormalAndCoplanarPoint(planeNormal, scene.position);
  raycaster.setFromCamera(mouse, camera);
  raycaster.ray.intersectPlane(plane, point);
}

function setPoint() {
  var sphere = new THREE.Mesh(new THREE.SphereBufferGeometry(.125, 4, 2), new THREE.MeshBasicMaterial({
    color: "yellow",
    wireframe: true
  }));
  sphere.position.copy(point);
  scene.add(sphere);
}

function onMouseDown(event) {
  getPoint(event);
  if (draw.checked) setPoint();
}

function onMouseMove(event) {
  getPoint(event);
  if (draw.checked) setPoint();
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div style="position:absolute;">
  <input id="draw" type="checkbox">
  <label for="draw" style="color: white;">draw</label>
</div>


问:
How do I drag and drop a row in a JTable?
How do you setup a JTable to be able to drag a row to a different index in the table.  For example if I have 5 rows and I want to drag the 4th row to the 2nd position?</p>

答:
The following allows JTable re-ordering of a single dragged row:

```<code>  table.setDragEnabled(true);
  table.setDropMode(DropMode.INSERT_ROWS);
  table.setTransferHandler(new TableRowTransferHandler(table));
</code>```

Your TableModel should implement the following to allow for re-ordering:

```<code>public interface Reorderable {
   public void reorder(int fromIndex, int toIndex);
}
</code>```

This TransferHandler class handles the drag & drop, and calls reorder() on your TableModel when the gesture is completed.

```<code>/**
 * Handles drag & drop row reordering
 */
public class TableRowTransferHandler extends TransferHandler {
   private final DataFlavor localObjectFlavor = new ActivationDataFlavor(Integer.class, "application/x-java-Integer;class=java.lang.Integer", "Integer Row Index");
   private JTable           table             = null;

   public TableRowTransferHandler(JTable table) {
      this.table = table;
   }

   @Override
   protected Transferable createTransferable(JComponent c) {
      assert (c == table);
      return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
   }

   @Override
   public boolean canImport(TransferHandler.TransferSupport info) {
      boolean b = info.getComponent() == table && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
      table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
      return b;
   }

   @Override
   public int getSourceActions(JComponent c) {
      return TransferHandler.COPY_OR_MOVE;
   }

   @Override
   public boolean importData(TransferHandler.TransferSupport info) {
      JTable target = (JTable) info.getComponent();
      JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
      int index = dl.getRow();
      int max = table.getModel().getRowCount();
      if (index < 0 || index > max)
         index = max;
      target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      try {
         Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
         if (rowFrom != -1 && rowFrom != index) {
            ((Reorderable)table.getModel()).reorder(rowFrom, index);
            if (index > rowFrom)
               index--;
            target.getSelectionModel().addSelectionInterval(index, index);
            return true;
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return false;
   }

   @Override
   protected void exportDone(JComponent c, Transferable t, int act) {
      if ((act == TransferHandler.MOVE) || (act == TransferHandler.NONE)) {
         table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      }
   }

}
</code>```

OwnerDisplayName: ShawnD

LastEditorDisplayName: Bob Cross

Body:
The following allows JTable re-ordering of a single dragged row:

  table.setDragEnabled(true);
  table.setDropMode(DropMode.INSERT_ROWS);
  table.setTransferHandler(new TableRowTransferHandler(table));

Your TableModel should implement the following to allow for re-ordering:

public interface Reorderable {
   public void reorder(int fromIndex, int toIndex);
}

This TransferHandler class handles the drag & drop, and calls reorder() on your TableModel when the gesture is completed.

/**
 * Handles drag & drop row reordering
 */
public class TableRowTransferHandler extends TransferHandler {
   private final DataFlavor localObjectFlavor = new ActivationDataFlavor(Integer.class, "application/x-java-Integer;class=java.lang.Integer", "Integer Row Index");
   private JTable           table             = null;

   public TableRowTransferHandler(JTable table) {
      this.table = table;
   }

   @Override
   protected Transferable createTransferable(JComponent c) {
      assert (c == table);
      return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
   }

   @Override
   public boolean canImport(TransferHandler.TransferSupport info) {
      boolean b = info.getComponent() == table && info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
      table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
      return b;
   }

   @Override
   public int getSourceActions(JComponent c) {
      return TransferHandler.COPY_OR_MOVE;
   }

   @Override
   public boolean importData(TransferHandler.TransferSupport info) {
      JTable target = (JTable) info.getComponent();
      JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
      int index = dl.getRow();
      int max = table.getModel().getRowCount();
      if (index < 0 || index > max)
         index = max;
      target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      try {
         Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
         if (rowFrom != -1 && rowFrom != index) {
            ((Reorderable)table.getModel()).reorder(rowFrom, index);
            if (index > rowFrom)
               index--;
            target.getSelectionModel().addSelectionInterval(index, index);
            return true;
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return false;
   }

   @Override
   protected void exportDone(JComponent c, Transferable t, int act) {
      if ((act == TransferHandler.MOVE) || (act == TransferHandler.NONE)) {
         table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      }
   }

}


问:
matlab how to call a class method that changes prop from another class method
If I call a method (receiving and returning obj) it changes my property.

But if I call that method from another method it fails. I tried all kinds of ways but still failing.

```<code> classdef AClass
  properties
    A;
  end
  methods
    function obj = ChangeA(obj, v)
      obj.A = v;
    end
    function obj = CallChangeA(obj)
      obj.ChangeA(4);
      %obj = obj.ChangeA(4);
      %ChangeA(obj, 4);
      %obj = ChangeA(obj, 4);
      % none of these works
    end
  end
end

% ------ script:
a1 = AClass;
a1.A = 1;
a1.ChangeA(2); % a1.A = 2

a2 = AClass;
a2.A = 3;
a2.CallChangeA(); % a2.A = 3 !!!  not four
</code>```

How do I write the code so calling from 1 method to the other updates the property?

答:
Other than the obvious typos in your example code, as I commented above, I would highly suggest taking a look at the difference between MATLAB's Handle and Value classes. By default, MATLAB classes are value classes, so each time the object is passed to a function an independent copy is created. If you're making changes to this object then you need to return it as an output:

```<code>classdef AClass
    properties
        A;
    end
    methods
        function obj = ChangeA(obj, a)
            obj.A = a;
        end

        function obj = CallChangeA(obj)
            obj = obj.ChangeA(4);
        end
    end
end
</code>```

Which functions as expected:

```<code>>> a1 = AClass;
>> a1.A = 1

a1 =

  AClass with properties:

    A: 1

>> a1 = a1.CallChangeA()

a1 =

  AClass with properties:

    A: 4
</code>```

Handle classes, on the other hand, are references to a single underlying object, allowing for (among other things) in place modification of the object:

```<code>classdef AClass < handle
    properties
        A;
    end
    methods
        function ChangeA(obj, a)
            obj.A = a;
        end

        function CallChangeA(obj)
            obj.ChangeA(4);
        end
    end
end
</code>```

Which also functions as expected:

```<code>>> a1 = AClass;
>> a1.A = 1;
>> a1.A

ans =

     1

>> a1.CallChangeA()
>> a1.A

ans =

     4
</code>```

Body:
If I call a method (receiving and returning obj) it changes my property.

But if I call that method from another method it fails. I tried all kinds of ways but still failing.

 classdef AClass
  properties
    A;
  end
  methods
    function obj = ChangeA(obj, v)
      obj.A = v;
    end
    function obj = CallChangeA(obj)
      obj.ChangeA(4);
      %obj = obj.ChangeA(4);
      %ChangeA(obj, 4);
      %obj = ChangeA(obj, 4);
      % none of these works
    end
  end
end

% ------ script:
a1 = AClass;
a1.A = 1;
a1.ChangeA(2); % a1.A = 2

a2 = AClass;
a2.A = 3;
a2.CallChangeA(); % a2.A = 3 !!!  not four

How do I write the code so calling from 1 method to the other updates the property?

Body:
Other than the obvious typos in your example code, as I commented above, I would highly suggest taking a look at the difference between MATLAB's Handle and Value classes. By default, MATLAB classes are value classes, so each time the object is passed to a function an independent copy is created. If you're making changes to this object then you need to return it as an output:

classdef AClass
    properties
        A;
    end
    methods
        function obj = ChangeA(obj, a)
            obj.A = a;
        end

        function obj = CallChangeA(obj)
            obj = obj.ChangeA(4);
        end
    end
end

Which functions as expected:

>> a1 = AClass;
>> a1.A = 1

a1 =

  AClass with properties:

    A: 1

>> a1 = a1.CallChangeA()

a1 =

  AClass with properties:

    A: 4

Handle classes, on the other hand, are references to a single underlying object, allowing for (among other things) in place modification of the object:

classdef AClass < handle
    properties
        A;
    end
    methods
        function ChangeA(obj, a)
            obj.A = a;
        end

        function CallChangeA(obj)
            obj.ChangeA(4);
        end
    end
end

Which also functions as expected:

>> a1 = AClass;
>> a1.A = 1;
>> a1.A

ans =

     1

>> a1.CallChangeA()
>> a1.A

ans =

     4


答:
Your main method should be like:

```<code>public static void main(String[]args) {

    Company company = new Company();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    company.hire(e1);
}
</code>```

As you have already written method hire() in class Company which adds the Employee in the ArrayList <Employee> alist.

There is NO way you can create your own method in Java ArrayList class.

Title: How to use own method on ArrayList in Java?

Body:
Your main method should be like:

public static void main(String[]args) {

    Company company = new Company();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    company.hire(e1);
}

As you have already written method hire() in class Company which adds the Employee in the ArrayList <Employee> alist.

There is NO way you can create your own method in Java ArrayList class.


答:
Try this:

```<code>listArray.filter(element => element.status === false)
</code>```

You can also do:

```<code>listArray.filter(element => !element.status)
</code>```

Title: JavaScript delete elements in array by a criteria

Body:
Try this:

listArray.filter(element => element.status === false)

You can also do:

listArray.filter(element => !element.status)