问:
!=null or !=undefined not working
I'm trying to create a personalized welcome message on the homepage, that basically says "welcome [username]" providing the user has registered and their username goes into localStorage. That works fine, but I only want the message to display the username if the user has actually registered, (otherwise it says "welcome Null". So I'm trying to use the following code to do that:

```<code>// Stores username inputted on registration page inside Local Storage//
function storeUsrName() {
   var regName= document.getElementById("regName");
   localStorage.setItem("usrName", regName.value);
   alert("Thanks for registering!");
 };

// Display welcome message //
$(document).ready(function() {
  var usrName = localStorage.getItem("usrName");

  if (usrName !="null" || usrName !="undefined") {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome " + usrName + "! ");
  } else {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome! ");
  }
});
</code>```

If a user registers and usrName is assigned a value, the welcome message works fine. But I expect the welcome message to say "Welcome!" if its the users first time visiting the site, and they have yet to register, and usrName has no value (null, or undefined).

Instead, if usrName has no value, the if/else statement doesn't work correctly, and the welcome message displays "welcome null!", despite the fact that I only want usrName to be displayed in the welcome message IF the value is NOT null or undefined.

Is there some correct way of doing this?

答:
usrName !="null" is comparing with string null, change if (usrName !="null" || usrName !="undefined") { to

```<code>if (usrName !== null || usrName !==undefined) {.. rest of code}
</code>```

Title: !=null or !=undefined not working

Body:
I'm trying to create a personalized welcome message on the homepage, that basically says "welcome [username]" providing the user has registered and their username goes into localStorage. That works fine, but I only want the message to display the username if the user has actually registered, (otherwise it says "welcome Null". So I'm trying to use the following code to do that:

// Stores username inputted on registration page inside Local Storage//
function storeUsrName() {
   var regName= document.getElementById("regName");
   localStorage.setItem("usrName", regName.value);
   alert("Thanks for registering!");
 };

// Display welcome message //
$(document).ready(function() {
  var usrName = localStorage.getItem("usrName");

  if (usrName !="null" || usrName !="undefined") {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome " + usrName + "! ");
  } else {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome! ");
  }
});

If a user registers and usrName is assigned a value, the welcome message works fine. But I expect the welcome message to say "Welcome!" if its the users first time visiting the site, and they have yet to register, and usrName has no value (null, or undefined).

Instead, if usrName has no value, the if/else statement doesn't work correctly, and the welcome message displays "welcome null!", despite the fact that I only want usrName to be displayed in the welcome message IF the value is NOT null or undefined.

Is there some correct way of doing this?

Body:
usrName !="null" is comparing with string null, change if (usrName !="null" || usrName !="undefined") { to

if (usrName !== null || usrName !==undefined) {.. rest of code}


来源: stackexchange

问:
How to converted dataTable from request Spring Boot
i'm learning programming and want use DataTables and i have a problem. I don't know how to converted records...

I have code in spring boot

```<code>@RequestMapping(path="/seriess", method=RequestMethod.GET)
public Page<SeriesDao> showSeries(@RequestParam(defaultValue="0") int page)
{
    Page<SeriesDao> sss = seriesRepository.findAll(new PageRequest(page, 20));

    return sss;
}
@RequestMapping("/showSeries")
public ModelAndView model(){
    ModelAndView model = new ModelAndView("showSeries");
    return model;
}
</code>```

Next I have json when i go to localhost:8080/seriess, i didn't copy all result (20)

{"content":[{"id":41,"name":"Average Weekly Earnings of All Employees: Total Private in Corpus Christi, TX (MSA)","file":"SMU48185800500000011.csv","cassid":"1d2e556b-031e-4c6f-aec4-981c4e907324","categoryid":3,"datefrom":"2006-12-31","dateto":"2016-09-30","frequency":5,"markers":null,"unit":"$ per Week","feed":"Macroeconomic_And_Major_Markets","createdate":1476567529000,"changedate":1483919401000}........and next 19 records ]
  "last":false,"totalPages":25,"totalElements":488,"size":20,"number":0,"sort":null,"first":true,"numberOfElements":20}

This is my java script code. I have to correct convert this data from url, but i don't know how...

```<code>$(document).ready( function () {
$('#dataTable').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "seriess",
        "dataSrc" : ""
         }
    },
        "columns": [
            { "data": "id"},
            { "data": "name" },
            { "data": "file" },
            { "data": "cassid" },
            { "data": "categoryid" },
            { "data": "datefrom" },
            { "data": "dateto" },
            { "data": "frequency" },
            { "data": "markers" },
            { "data": "unit" },
            { "data": "feed" },
            { "data": "createdate" },
            { "data": "changedate" }
        ]
 })});
</code>```

答:
Change

```<code>"ajax": {
        "url": "seriess",
        "dataSrc" : ""
         }
    }
</code>```

to

```<code>"ajax": {
        "url": "/seriess",
        "dataSrc" : "content"
         }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'm learning programming and want use DataTables and i have a problem. I don't know how to converted records...

I have code in spring boot

@RequestMapping(path="/seriess", method=RequestMethod.GET)
public Page<SeriesDao> showSeries(@RequestParam(defaultValue="0") int page)
{
    Page<SeriesDao> sss = seriesRepository.findAll(new PageRequest(page, 20));

    return sss;
}
@RequestMapping("/showSeries")
public ModelAndView model(){
    ModelAndView model = new ModelAndView("showSeries");
    return model;
}

Next I have json when i go to localhost:8080/seriess, i didn't copy all result (20)

{"content":[{"id":41,"name":"Average Weekly Earnings of All Employees: Total Private in Corpus Christi, TX (MSA)","file":"SMU48185800500000011.csv","cassid":"1d2e556b-031e-4c6f-aec4-981c4e907324","categoryid":3,"datefrom":"2006-12-31","dateto":"2016-09-30","frequency":5,"markers":null,"unit":"$ per Week","feed":"Macroeconomic_And_Major_Markets","createdate":1476567529000,"changedate":1483919401000}........and next 19 records ]
  "last":false,"totalPages":25,"totalElements":488,"size":20,"number":0,"sort":null,"first":true,"numberOfElements":20}

This is my java script code. I have to correct convert this data from url, but i don't know how...

$(document).ready( function () {
$('#dataTable').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "seriess",
        "dataSrc" : ""
         }
    },
        "columns": [
            { "data": "id"},
            { "data": "name" },
            { "data": "file" },
            { "data": "cassid" },
            { "data": "categoryid" },
            { "data": "datefrom" },
            { "data": "dateto" },
            { "data": "frequency" },
            { "data": "markers" },
            { "data": "unit" },
            { "data": "feed" },
            { "data": "createdate" },
            { "data": "changedate" }
        ]
 })});

Body:
Change

"ajax": {
        "url": "seriess",
        "dataSrc" : ""
         }
    }

to

"ajax": {
        "url": "/seriess",
        "dataSrc" : "content"
         }
    }


问:
How can I use Angular interpolation to insert a dynamic URL into an elements style?
I am trying to use interpolation to generate background images for my element using variables from the ngFor.

Here's what I currently have, which renders perfectly:

```<code>  <ion-item-group *ngFor="let game of games">
  <ion-card padding style="background: url('./assets/imgs/Body Harvest (USA).png')">
    <h2>{{game.name}}</h2>
  </ion-card>
  </ion-item-group>
</code>```

game object looks like this:

```<code>  {
    "Id": 30,
    "name": "Body Harvest",
    "genres": "Action/Adventure/3D shooter",
    "date": "30-Sep-98",
    "images": "Body Harvest (USA).png",
    "developer": "DMA Design",
    "publisher": "Midway",
    "description": "A video game released for the Nintendo 64.",
    "players": 1
  },
</code>```

I am looking for a way to inject the URL using something like this:

```<code><ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/{{games.images}}')">
   <h2>{{game.name}}</h2>
</ion-card>
</ion-item-group>
</code>```

I think part of the issue is that 'game.images' is returned with double quotes.

答:
You will need to sanitize the url after you receive your data</p>

```<code>// component.ts
import { DomSanitizer } from '@angular/platform-browser'

@Component(...)
export class MyComponent {
    games;

    constructor(private sanitizer: DomSanitizer){}

    ngOnInit(){
        this.service.getData().subscribe(res => {
            res.forEach(item => {
                item.backgroundImage = this.sanitizer.bypassSecurityTrustStyle('url("./assets/imgs/' + item.images + '")');
            });
        });
    }
}

// component.html
<ion-item-group *ngFor="let game of games">
    <ion-card padding [style.background-image]="game.backgroundImage">
        <h2>{{game.name}}</h2>
    </ion-card>
</ion-item-group>
</code>```

Body:
I am trying to use interpolation to generate background images for my element using variables from the ngFor.

Here's what I currently have, which renders perfectly:

  <ion-item-group *ngFor="let game of games">
  <ion-card padding style="background: url('./assets/imgs/Body Harvest (USA).png')">

{{game.name}}

  </ion-card>
  </ion-item-group>

game object looks like this:

  {
    "Id": 30,
    "name": "Body Harvest",
    "genres": "Action/Adventure/3D shooter",
    "date": "30-Sep-98",
    "images": "Body Harvest (USA).png",
    "developer": "DMA Design",
    "publisher": "Midway",
    "description": "A video game released for the Nintendo 64.",
    "players": 1
  },

I am looking for a way to inject the URL using something like this:

<ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/{{games.images}}')">

{{game.name}}

</ion-card>
</ion-item-group>

I think part of the issue is that 'game.images' is returned with double quotes.

Body:
You will need to sanitize the url after you receive your data

// component.ts
import { DomSanitizer } from '@angular/platform-browser'

@Component(...)
export class MyComponent {
    games;

    constructor(private sanitizer: DomSanitizer){}

    ngOnInit(){
        this.service.getData().subscribe(res => {
            res.forEach(item => {
                item.backgroundImage = this.sanitizer.bypassSecurityTrustStyle('url("./assets/imgs/' + item.images + '")');
            });
        });
    }
}

// component.html
<ion-item-group *ngFor="let game of games">
    <ion-card padding [style.background-image]="game.backgroundImage">
        <h2>{{game.name}}</h2>
    </ion-card>
</ion-item-group>


问:
How should you end a Spark job inside an if statement?
What is the recommended way to end a spark job inside a conditional statement?

I am doing validation on my data, and if false, I want to end the spark job gracefully.

Right now I have:

```<code>if (isValid(data)) {
    sparkSession.sparkContext.stop()
}
</code>```

However, I get the following error:

```<code>Exception in thread "main" java.lang.IllegalStateException: SparkContext has been shutdown
</code>```

Then it shows a stacktrace.

Is sparkContext.stop() not the proper way to end a spark job gracefully?

答:
Once you stop the SparkSession means, your SparkContext is killed on the JVM. sc is no longer active now.

So You can't call any sparkContext related objects/functions for creating RDD/Dataframe or anything else.
If you call the same sparksession again in the flow of program.. you should find the above Exception.
For example.

```<code>`    val rdd=sc.parallelize(Seq(Row("RAMA","DAS","25"),Row("smritu","ranjan","26")))
    val df=spark.createDataFrame(rdd,schema)
    df.show()   //It works fine
    if(df.select("fname").collect()(0).getAs[String]("fname")=="MAA"){
    println("continue")
    }
    else{
    spark.stop()   //stopping sparkSession
    println("inside Stopiing condition")
    }
    println("code continues")
    val rdd1=sc.parallelize(Seq(Row("afdaf","DAS","56"),Row("sadfeafe","adsadaf","27")))
    //Throws Exception...
    val df1=spark.createDataFrame(rdd1,schema)
    df1.show()
`
</code>```

Body:
What is the recommended way to end a spark job inside a conditional statement?

I am doing validation on my data, and if false, I want to end the spark job gracefully.

Right now I have:

if (isValid(data)) {
    sparkSession.sparkContext.stop()
}

However, I get the following error:

Exception in thread "main" java.lang.IllegalStateException: SparkContext has been shutdown

Then it shows a stacktrace.

Is sparkContext.stop() not the proper way to end a spark job gracefully?

Body:
Once you stop the SparkSession means, your SparkContext is killed on the JVM. sc is no longer active now.

So You can't call any sparkContext related objects/functions for creating RDD/Dataframe or anything else.
If you call the same sparksession again in the flow of program.. you should find the above Exception.
For example.

`    val rdd=sc.parallelize(Seq(Row("RAMA","DAS","25"),Row("smritu","ranjan","26")))
    val df=spark.createDataFrame(rdd,schema)
    df.show()   //It works fine
    if(df.select("fname").collect()(0).getAs[String]("fname")=="MAA"){
    println("continue")
    }
    else{
    spark.stop()   //stopping sparkSession
    println("inside Stopiing condition")
    }
    println("code continues")
    val rdd1=sc.parallelize(Seq(Row("afdaf","DAS","56"),Row("sadfeafe","adsadaf","27")))
    //Throws Exception...
    val df1=spark.createDataFrame(rdd1,schema)
    df1.show()
`


问:
Symfony 4.0 doesn't work
To the point:

- I created new project on symfony 4.0: composer create-project symfony/skeleton sf4

- Welcome page is working

- I wanted to create my first page with https://symfony.com/doc/current/page_creation.html
and I did exactly what they say: create controller and route

- Welcome page changed status to: No route found for "GET /"  <-Solved

- new page path can't find file - Error 404

What am I doing wrong? That is silly

~src/Controller/SecurityController.php

```<code><?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class SecurityController {
    public function logowanie() {
        return new Response(
            '<html><body>Logowanie</body></html>'
        );
    }
}
</code>```

~config/routes.yaml

```<code>index:
    path: /
    controller: App\Controller\MainController::index

logowanie:
    path: /logowanie
    controller: App\Controller\SecurityController::logowanie
</code>```

EDIT:

Home page works - thanks @Cerad

答:
I had the same problem. Homepage was working, but any other urls generate a 404, served by apache, and not logged in symfony.

My mistake was the missconfiguration of the virtualhost. As there is no longer .htaccess in the public directory, you have to configure redirection & rewrite in your virtualhost.
Here is the documentation: https://symfony.com/doc/master/setup/web_server_configuration.html

Title: Symfony 4.0 doesn't work

Body:
To the point:

- I created new project on symfony 4.0: composer create-project symfony/skeleton sf4

- Welcome page is working

- I wanted to create my first page with https://symfony.com/doc/current/page_creation.html
and I did exactly what they say: create controller and route

- Welcome page changed status to: No route found for "GET /"  <-Solved

- new page path can't find file - Error 404

What am I doing wrong? That is silly

~src/Controller/SecurityController.php

<?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class SecurityController {
    public function logowanie() {
        return new Response(
            'Logowanie'
        );
    }
}

~config/routes.yaml

index:
    path: /
    controller: App\Controller\MainController::index

logowanie:
    path: /logowanie
    controller: App\Controller\SecurityController::logowanie

EDIT:

Home page works - thanks @Cerad


问:
How to send two JSON values from view to controller using EF
This is my script:

```<code>$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function btnadHocSave() {
    debugger
    var lv_header = $("#Header").serializeObject(); // this is header <fieldset> tag
    var lv_detail = $("#SubmitMachine").serializeObject(); // this is detail <fieldset> tag
    $.ajax({
        type: "POST",
        url: '@Url.Action("UpdateMachine")',
        contentType: "application/json",
        dataType: "JSON",
        data: {
            myheader: lv_header,
            mydetail: lv_detail
        },
        cache: false,
        success: function (data) {
            alert("Success!..");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    })
}
</code>```

This is my action code. PMAllotmentEntry and PMAllotmentDetailEntry are models:

```<code>public ActionResult UpdateMachine(PMAllotmentEntry myheader, PMAllotmentDetailEntry mydetail)
{
    return View();
}
</code>```

Now my problem I'm not able get the values from view to controller.
I tried JSON.stringify also but there is no use.

It is working If I pass single JSON value.

I tried out all the possibilities. Did as you said also but no use. Finally I did the following. I got two JSON values but still facing a issues because JSON second values first field value coming with first JSON values.

```<code>       function btnadHocSave() {
            debugger

            var lv_header = $("#Header").serialize(); // this is header <fieldset>
            var lv_detail = $("#SubmitMachine").serialize();
            $.ajax(
                {
                    type: "GET",
                    url: '/PMAllotments/UpdateMachine',
                    contentType: "application/json",
                    dataType: "JSON",
                    data: lv_header + ',' + lv_detail,
                    success: function (data) {
                        alert("Success!..");
                        debugger
                        $("#adHocAdd40").modal("hide");
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    }
                })
        }
</code>```

答:
Now I'm removed JQuery from cshtml file and simply used post method

```<code>[HttpPost]
public ActionResult UpdateMachine(PMAllotmentEntry m)
{
    //complete the task
    return View();
}
</code>```

replaced foreach loop in .cshtml file with for loop

FOR loop is highly important foreach loop never return your child model data.

```<code>@for (int a = 0; a < Model.PMAllotmentDetail.Count; a++)
{
     @* table rows here *@
}
</code>```

My Model as following

```<code>[NotMapped]
public class PMAllotmentEntry
{
    [Key]
    public Int64 PMAllotmentId { get; set; }

    [Required (ErrorMessage ="Add atleast one machine!")]
    public List<PMAllotmentDetailEntry> PMAllotmentDetail { get; set; }

}

[NotMapped]
public class PMAllotmentDetailEntry
{

    [Key]
    public Int64 PMAllotmentDetailId { get; set; }

    [ForeignKey("PMAllotmentId")]
    public Int64 PMAllotmentId { get; set; }

}
</code>```

Body:
This is my script:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function btnadHocSave() {
    debugger
    var lv_header = $("#Header").serializeObject(); // this is header <fieldset> tag
    var lv_detail = $("#SubmitMachine").serializeObject(); // this is detail <fieldset> tag
    $.ajax({
        type: "POST",
        url: '@Url.Action("UpdateMachine")',
        contentType: "application/json",
        dataType: "JSON",
        data: {
            myheader: lv_header,
            mydetail: lv_detail
        },
        cache: false,
        success: function (data) {
            alert("Success!..");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    })
}

This is my action code. PMAllotmentEntry and PMAllotmentDetailEntry are models:

public ActionResult UpdateMachine(PMAllotmentEntry myheader, PMAllotmentDetailEntry mydetail)
{
    return View();
}

Now my problem I'm not able get the values from view to controller.
I tried JSON.stringify also but there is no use.

It is working If I pass single JSON value.

I tried out all the possibilities. Did as you said also but no use. Finally I did the following. I got two JSON values but still facing a issues because JSON second values first field value coming with first JSON values.

       function btnadHocSave() {
            debugger

            var lv_header = $("#Header").serialize(); // this is header <fieldset>
            var lv_detail = $("#SubmitMachine").serialize();
            $.ajax(
                {
                    type: "GET",
                    url: '/PMAllotments/UpdateMachine',
                    contentType: "application/json",
                    dataType: "JSON",
                    data: lv_header + ',' + lv_detail,
                    success: function (data) {
                        alert("Success!..");
                        debugger
                        $("#adHocAdd40").modal("hide");
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    }
                })
        }

Body:
Now I'm removed JQuery from cshtml file and simply used post method

[HttpPost]
public ActionResult UpdateMachine(PMAllotmentEntry m)
{
    //complete the task
    return View();
}

replaced foreach loop in .cshtml file with for loop

FOR loop is highly important foreach loop never return your child model data.

@for (int a = 0; a < Model.PMAllotmentDetail.Count; a++)
{
     @* table rows here *@
}

My Model as following

[NotMapped]
public class PMAllotmentEntry
{
    [Key]
    public Int64 PMAllotmentId { get; set; }

    [Required (ErrorMessage ="Add atleast one machine!")]
    public List<PMAllotmentDetailEntry> PMAllotmentDetail { get; set; }

}

[NotMapped]
public class PMAllotmentDetailEntry
{

    [Key]
    public Int64 PMAllotmentDetailId { get; set; }

    [ForeignKey("PMAllotmentId")]
    public Int64 PMAllotmentId { get; set; }

}


问:
JavaScript, getting value of a td with id name
Originally I was using input with an id and grabbing it's value with getElementById. Currently, I'm playing with s. How can I grab the values of the ?

Originally I used:

```<code><input id="hello">
document.getElementById("hello").value;
</code>```

Now I want to get value of , but I don't know how;

```<code><td id="test">Chicken</td>
<td>Cow</td>
</code>```

Edit: What's the difference between textContent, innerHTML, and innerText?

答:
if i click table name its shown all fields about table. i did table field to show. but i need to know click function.

My Code:

```<code>$sql = "SHOW tables from database_name where tables_in_databasename not like '%tablename' and tables_in_databasename not like '%tablename%'";

$result=mysqli_query($cons,$sql);

$count = 0;

$array = array();

while ($row = mysqli_fetch_assoc($result)) {

    $count++;

    $tbody_txt .= '<tr>';

    foreach ($row as $key => $value) {
        if($count  == '1') {
            $thead_txt .='<td>'.$key.'</td>';
        }
        $tbody_txt .='<td>'.$value.'</td>';

        $array[$key][] = $value;
    }
}?>
</code>```

Body:
Originally I was using input with an id and grabbing it's value with getElementById. Currently, I'm playing with s. How can I grab the values of the ?

Originally I used:

<input id="hello">
document.getElementById("hello").value;

Now I want to get value of , but I don't know how;

Chicken
Cow

Edit: What's the difference between textContent, innerHTML, and innerText?

Body:
if i click table name its shown all fields about table. i did table field to show. but i need to know click function.

My Code:

$sql = "SHOW tables from database_name where tables_in_databasename not like '%tablename' and tables_in_databasename not like '%tablename%'";

$result=mysqli_query($cons,$sql);

$count = 0;

$array = array();

while ($row = mysqli_fetch_assoc($result)) {

    $count++;

    $tbody_txt .= '<tr>';

    foreach ($row as $key => $value) {
        if($count  == '1') {
            $thead_txt .='<td>'.$key.'</td>';
        }
        $tbody_txt .='<td>'.$value.'</td>';

        $array[$key][] = $value;
    }
}?>


问:
How to initialize a EditText when the Fragment's method is called from activity?
i work on a NotePad application, because i wanted to try SQLite and i don't have a correct NotePad app on my smartphone.

Screenshot of the app

So my app is composed of a Activity which contains a Viewpager and a menu for save the Note, create a new Note or delete the current note, and a Fragment where is a simple EditText.

I create a custom object Note which is compose of a String title, a String content and a Integer id for save the data on SQLite.

So my problem is for the functionnality of saving the Note on my database.

Its start with the menu in the Action Bar of the Activity, so when i click on the button for Saving (the second which look like a SD card), i called a method from my Fragment for edit the Note on the database like this :

```<code>private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}
</code>```

The arraylist contains the title of every note (i use him for create the TabLayout) and i pass him for get the title of the note.

So there is the code of my Fragment :

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = (ViewGroup) inflater.inflate(R.layout.fragment_tab, container, false);
    editText1 = rootview.findViewById(R.id.editText1);

    manager = new NoteManager(getActivity());
    manager.open();

    Bundle args = getArguments();
    position = args.getInt("0");
    arrayListContent = args.getStringArrayList("1");

    editText1.setText(arrayListContent.get(position));
    return rootview;
}

public void editNote(ArrayList<String> arrayListTitle) {
    title_edit = arrayListTitle.get(position);
    content_edit = editText1.getText().toString();
    Note note = manager.getNote(position + 1);

    note.setTitle(title_edit);
    note.setContent(content_edit);
    manager.modNote(note);
}
</code>```

When i go in the editNote method i receive the error :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: fr.pensebete, PID: 24165
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at fr.pensebete.TabFragment.editNote(TabFragment.java:50)
                  at fr.pensebete.MainActivity.save(MainActivity.java:130)
                  at fr.pensebete.MainActivity.onOptionsItemSelected(MainActivity.java:101)
                  at android.app.Activity.onMenuItemSelected(Activity.java:3369)
                  at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
                  at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:65)
                  at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:202)
                  at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
                  at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
                  at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
                  at android.view.View.performClick(View.java:6213)
                  at android.widget.TextView.performClick(TextView.java:11074)
                  at android.view.View$PerformClick.run(View.java:23645)
                  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:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

I know its because the EditText is not initialize because i called the editNote() method only and the OnCreateView is not called.

How can i call the EditNote() method from the Activity and make the EditText and the variable position initialize correctly (like in the OnCreateView method)? Can you help me because i search since 3 hours without a solution to make it works.

Thanks for your time and your help, and sorry for my bad english.

Edit : During i write this question i realize its maybe because i do a new TabFragment in my Activity's method :

```<code>private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}
</code>```

Maybe i must receive or find the current fragment already created, but i don't know how to do that. HELP !

答:
For example refer this

https://github.com/codepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter

In Activity Class

```<code>public class MainActivity extends AppCompatActivity {

Adapter adapterViewPager; //Replace with your adapter
ViewPager vpPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new ViewPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);
}

private void save() {
  TabFragment fragment = vPager.getItem(0) //position to which fragment
  fragment.editNote(arrayListTitle);
}
}
</code>```

Hope it helps.!

Body:
i work on a NotePad application, because i wanted to try SQLite and i don't have a correct NotePad app on my smartphone.

Screenshot of the app

So my app is composed of a Activity which contains a Viewpager and a menu for save the Note, create a new Note or delete the current note, and a Fragment where is a simple EditText.

I create a custom object Note which is compose of a String title, a String content and a Integer id for save the data on SQLite.

So my problem is for the functionnality of saving the Note on my database.

Its start with the menu in the Action Bar of the Activity, so when i click on the button for Saving (the second which look like a SD card), i called a method from my Fragment for edit the Note on the database like this :

private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}

The arraylist contains the title of every note (i use him for create the TabLayout) and i pass him for get the title of the note.

So there is the code of my Fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = (ViewGroup) inflater.inflate(R.layout.fragment_tab, container, false);
    editText1 = rootview.findViewById(R.id.editText1);

    manager = new NoteManager(getActivity());
    manager.open();

    Bundle args = getArguments();
    position = args.getInt("0");
    arrayListContent = args.getStringArrayList("1");

    editText1.setText(arrayListContent.get(position));
    return rootview;
}

public void editNote(ArrayList<String> arrayListTitle) {
    title_edit = arrayListTitle.get(position);
    content_edit = editText1.getText().toString();
    Note note = manager.getNote(position + 1);

    note.setTitle(title_edit);
    note.setContent(content_edit);
    manager.modNote(note);
}

When i go in the editNote method i receive the error :

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: fr.pensebete, PID: 24165
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at fr.pensebete.TabFragment.editNote(TabFragment.java:50)
                  at fr.pensebete.MainActivity.save(MainActivity.java:130)
                  at fr.pensebete.MainActivity.onOptionsItemSelected(MainActivity.java:101)
                  at android.app.Activity.onMenuItemSelected(Activity.java:3369)
                  at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
                  at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:65)
                  at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:202)
                  at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
                  at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
                  at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
                  at android.view.View.performClick(View.java:6213)
                  at android.widget.TextView.performClick(TextView.java:11074)
                  at android.view.View$PerformClick.run(View.java:23645)
                  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:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

I know its because the EditText is not initialize because i called the editNote() method only and the OnCreateView is not called.

How can i call the EditNote() method from the Activity and make the EditText and the variable position initialize correctly (like in the OnCreateView method)? Can you help me because i search since 3 hours without a solution to make it works.

Thanks for your time and your help, and sorry for my bad english.

Edit : During i write this question i realize its maybe because i do a new TabFragment in my Activity's method :

private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}

Maybe i must receive or find the current fragment already created, but i don't know how to do that. HELP !

Body:
For example refer this

https://github.com/codepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter

In Activity Class

public class MainActivity extends AppCompatActivity {

Adapter adapterViewPager; //Replace with your adapter
ViewPager vpPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new ViewPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);
}

private void save() {
  TabFragment fragment = vPager.getItem(0) //position to which fragment
  fragment.editNote(arrayListTitle);
}
}

Hope it helps.!


问:
How do I check which SSL Certificate my SIM800 module has by default using ATCommands? How do I enable to use HTTPS GET using ATCommands?
I want to get information from a particular web-page using HTTPS GET via GPRS connection using SIM800 Module connected to my Arduino Uno.
For using HTTPS, I read somewhere that I need to have the right SSL certificate. I wanted to know is there any way using which I can view the SSL certificate which is there by default in SIM800 Module using AT Commands?
Also, how do I enable it to use HTTPS GET, because I get ERROR message when I used AT+HTTPSSL and AT+CIPSSL. </p>

答:
You can use secured connection on arduino if you have GSM module which supports secured connections. Unlike the other answer said you CAN use arduino to make secured connections. These are the commands I use in SIM800 series module.

For https connection use  " AT+HTTPSSL=1  "

For secured  tcp connection use  " AT+CIPSSL=1 "

ContentLicense: CC BY-SA 4.0


问:
Would a DBMS be part of a database layer or DAL in an n-tier software architecture?
I have database layer, Data Access Layer then Business Logic Layer and so on, so I would like to know where the DBMS fits into this. Which layer would I put it in? And also, if someone could give an example of what I could put inside the business logic layer. Like what an example of a component?</p>

答:
The purpose of the DAL (Data Access Layer) is to decouple the higher-level tiers, such as the business later logic, from the DBMS, so that whenever you want to switch to a different database (i.e. different DBMS), only the DAL needs to be touched and nothing else. Therefore, the DBMS is not part of the DAL. Rather, the DAL depends on the DBMS.

For example, consider an e-commerce application. There is logic that decides whether some item or some user is eligible for free shipping. This shall be implemented in a module that belongs in the business logic layer. Internally, this check requires to fetch data about the item or the user from the database. This will be done by calling the DAL, which shall invoke the DBMS.


问:
Google map Android API v2 - InfoWindow on polyline?
I am drawing polyline on my map,I need to show some data to user now.

How I can draw text or InfoWindow on each polyline ?

I add polyline like :

```<code>ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();

// Traversing through all the routes
for(int i=0;i<result.size();i++){
    points = new ArrayList<LatLng>();
    lineOptions = new PolylineOptions();
    String color = colors[i % colors.length];
    // Fetching i-th route
    List<HashMap<String, String>> path = result.get(i);

    // Fetching all the points in i-th route
    for(int j=0;j<path.size();j++){
        HashMap<String,String> point = path.get(j);

        double lat = Double.parseDouble(point.get("lat"));
        double lng = Double.parseDouble(point.get("lng"));
        LatLng position = new LatLng(lat, lng);

        points.add(position);
    }

    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    lineOptions.width(5);
    lineOptions.color(Color.parseColor(color));

    // Drawing polyline in the Google Map for the i-th route
    mMap.addPolyline(lineOptions);
}
</code>```

For example I need to this :

答:
Use Google Direction API to get the route and draw the polyline

Add OnPolylineClickListener in Map and get the reference using getTag

```<code>mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
    @Override
    public void onPolylineClick(Polyline polyline) {
        Log.e("Polyline position", " -- " + polyline.getTag());
        onButtonShowPopupWindowClick("  " + polyline.getTag());
    }
});
</code>```

Set any reference in polyline using setTag method

```<code>            Polyline line = mMap.addPolyline(lineOptions);
            line.setTag("" + i);
            line.setClickable(true);
</code>```

Open PopupWindow in polyline click

public void onButtonShowPopupWindowClick(String count) {

```<code>String[] timeDistance = count.split(",");

// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout)
        findViewById(R.id.whole_layout);

// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
        getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.polyline_window, null);

((TextView) popupView.findViewById(R.id.time)).setText("30 mins");
((TextView) popupView.findViewById(R.id.distance)).setText("20 km");

// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

// show the popup window
popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);

// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        popupWindow.dismiss();
        return true;
    }
});
</code>```

}

Body:
I am drawing polyline on my map,I need to show some data to user now.

How I can draw text or InfoWindow on each polyline ?

I add polyline like :

ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();

// Traversing through all the routes
for(int i=0;i<result.size();i++){
    points = new ArrayList<LatLng>();
    lineOptions = new PolylineOptions();
    String color = colors[i % colors.length];
    // Fetching i-th route
    List<HashMap<String, String>> path = result.get(i);

    // Fetching all the points in i-th route
    for(int j=0;j<path.size();j++){
        HashMap<String,String> point = path.get(j);

        double lat = Double.parseDouble(point.get("lat"));
        double lng = Double.parseDouble(point.get("lng"));
        LatLng position = new LatLng(lat, lng);

        points.add(position);
    }

    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    lineOptions.width(5);
    lineOptions.color(Color.parseColor(color));

    // Drawing polyline in the Google Map for the i-th route
    mMap.addPolyline(lineOptions);
}

For example I need to this :

Body:
Use Google Direction API to get the route and draw the polyline

Add OnPolylineClickListener in Map and get the reference using getTag

mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
    @Override
    public void onPolylineClick(Polyline polyline) {
        Log.e("Polyline position", " -- " + polyline.getTag());
        onButtonShowPopupWindowClick("  " + polyline.getTag());
    }
});

Set any reference in polyline using setTag method

            Polyline line = mMap.addPolyline(lineOptions);
            line.setTag("" + i);
            line.setClickable(true);

Open PopupWindow in polyline click

public void onButtonShowPopupWindowClick(String count) {

String[] timeDistance = count.split(",");

// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout)
        findViewById(R.id.whole_layout);

// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
        getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.polyline_window, null);

((TextView) popupView.findViewById(R.id.time)).setText("30 mins");
((TextView) popupView.findViewById(R.id.distance)).setText("20 km");

// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

// show the popup window
popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);

// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        popupWindow.dismiss();
        return true;
    }
});

}


问:
propensity score matching in MatchIt package in linux
Actually, I have some difficulty to do propensity score matching in MatchIt package in Linux:

I do not know how to load the MatchIt package after I install it in R in Vnc Viewer,if I input "R" then press "ENTER" first in the home directory, then I input >library(MatchIt) >q(), then press "ENTER" last ,is it the right way to load the MatchIt package?

Alternatively, I typed "R -e 'library("MatchIt")'", then "ENTER" directly in the home directory, it can load successfully?

how could I write a script to run to do propensity score matching after loading MatchIt?

I typed "Rscripts xxx.R", but things seem to be not working, so what should I do correctly?

答: In the console, type R and you should be taken to an R session. This is an interactive session which is not ideal for writing scripts. My suggestion would be to write your script (library(), import of data...) into a text file and source that, e.g. Rscript sourcefile.R. Or, use an IDE which will enable you to write code, run it and a few other trinkets. There are a few options out there, RStudio appears to be quite popular and comes in a desktop and server versions.


问:
SharePoint - CustomAction isn't showing on toolbar for a content type
I've created a feature with a content type:

```<code><ContentType ID="0x01007C963A8770A24bbfBDBCE157B96EE769"
             Name="Send" Group="Demo" Version="1">
</ContentType>
</code>```

I want to create custom actions for this content type.

This works on the ECB (the popup menu of every item's title):

```<code><CustomAction
    Id="Demo.Send.PopupMenu"
    Title="Send"
    Location="EditControlBlock"
    Description="Hold"
    RegistrationType="ContentType"
    RegistrationId="0x01007C963A8770A24bbfBDBCE157B96EE769">
      <UrlAction Url="http://www.google.com/search?q={ItemId} Cookies"/>
</CustomAction>
</code>```

However, I can't get it to work on forms' toolbars (edit or display):

```<code><CustomAction
    Id="Demo.Send.DisplayFormToolbar"
    Title="Send"
    Location="DisplayFormToolbar"
    Description="Send"
    RegistrationType="ContentType"
    RegistrationId="0x01007C963A8770A24bbfBDBCE157B96EE769"
    Sequence="108">
       <UrlAction Url="http://www.google.com/search?q={ItemId} Cookies"/>
</CustomAction>
</code>```

I don't get any error message, I just can't see the button.

It is working if I change the RegistrationId to 0x01, but then I see it on all content types (all items, really).

Any idea what's wrong with this code?

答:
I seem to remember there being issues with content types when they didn't have all capitals in the identifier, both for the definition and when using.

Try

```<code>RegistrationId="0x01007C963A8770A24BBFBDBCE157B96EE769"
</code>```

But completely remove the everything that refers to the content type. (or try a new one)

ContentLicense: CC BY-SA 2.5

Body:
I've created a feature with a content type:

<ContentType ID="0x01007C963A8770A24bbfBDBCE157B96EE769"
             Name="Send" Group="Demo" Version="1">
</ContentType>

I want to create custom actions for this content type.

This works on the ECB (the popup menu of every item's title):

<CustomAction
    Id="Demo.Send.PopupMenu"
    Title="Send"
    Location="EditControlBlock"
    Description="Hold"
    RegistrationType="ContentType"
    RegistrationId="0x01007C963A8770A24bbfBDBCE157B96EE769">
      <UrlAction Url="http://www.google.com/search?q={ItemId} Cookies"/>
</CustomAction>

However, I can't get it to work on forms' toolbars (edit or display):

<CustomAction
    Id="Demo.Send.DisplayFormToolbar"
    Title="Send"
    Location="DisplayFormToolbar"
    Description="Send"
    RegistrationType="ContentType"
    RegistrationId="0x01007C963A8770A24bbfBDBCE157B96EE769"
    Sequence="108">
       <UrlAction Url="http://www.google.com/search?q={ItemId} Cookies"/>
</CustomAction>

I don't get any error message, I just can't see the button.

It is working if I change the RegistrationId to 0x01, but then I see it on all content types (all items, really).

Any idea what's wrong with this code?

Body:
I seem to remember there being issues with content types when they didn't have all capitals in the identifier, both for the definition and when using.

Try

RegistrationId="0x01007C963A8770A24BBFBDBCE157B96EE769"

But completely remove the everything that refers to the content type. (or try a new one)


问:
How to stop an audio from playing based on condition in Python?
I am playing an audio, and simultaneously taking an input from keyboard. I have used threading to achieve this. I created a new thread to run the audio, and listening to the input from main thread. But I want to stop the audio from playing, based on a certain input from keyboard.

Since I can't "kill" a thread from another thread, and I can't make the audio thread listen to the main thread unless it has stopped playing the audio, how do I achieve this?

EDIT:
I have this code written:

```<code>from multiprocessing import Process
import os

p = Process(target=os.system, args=("aplay path/to/audio/file",))
p.start()
print("started")
while p.is_alive():
    print("inside loop")
    inp = input("give input")
    if inp is not None:
        p.terminate()
        print(p.is_alive())     # Returns True for the first time, False for the second time
        print("terminated")
</code>```

This is the output:

```<code>started
inside loop
give input2
True
terminated
inside loop
give input4
False
terminated
</code>```

Why is this happening? Also, even after the second loop iteration, the process terminates (p.is_alive() returns false) but the audio keeps playing. The audio doesn't stop.

答:
The solution to this problem is to the have a common variable/flag between both the threads. The variable will signal the audio playing thread to end or wait for it to be changed.

Here is an example of the same.

In this case the thread will exit on getting the signal.

```<code>import time
import winsound
import threading

class Player():
    def __init__(self, **kwargs):
        # Shared Variable.
        self.status = {}
        self.play = True
        self.thread_kill = False
    def start_sound(self):
        while True and not self.thread_kill:
            # Do somthing only if flag is true
            if self.play == True:
                #Code to do continue doing what you want.

    def stop_sound(self):
        # Update the variable to stop the sound
        self.play = False
        # Code to keep track of saving current status

    #Function to run your start_alarm on a different thread
    def start_thread(self):
        #Set Alarm_Status to true so that the thread plays the sound
        self.play = True
        t1 = threading.Thread(target=self.start_sound)
        t1.start()

    def run(self):
        while True:
            user_in = str(raw_input('q: to quit,p: to play,s: to Stop\n'))
            if user_in == "q":
                #Signal the thread to end. Else we ll be stuck in for infinite time.
                self.thread_kill = True
                break
            elif user_in == "p":
                self.start_thread()
            elif user_in == "s":
                self.stop_sound()
            else:
                print("Incorrect Key")

if __name__ == '__main__':
    Player().run()
</code>```

Body:
I am playing an audio, and simultaneously taking an input from keyboard. I have used threading to achieve this. I created a new thread to run the audio, and listening to the input from main thread. But I want to stop the audio from playing, based on a certain input from keyboard.

Since I can't "kill" a thread from another thread, and I can't make the audio thread listen to the main thread unless it has stopped playing the audio, how do I achieve this?

EDIT:
I have this code written:

from multiprocessing import Process
import os

p = Process(target=os.system, args=("aplay path/to/audio/file",))
p.start()
print("started")
while p.is_alive():
    print("inside loop")
    inp = input("give input")
    if inp is not None:
        p.terminate()
        print(p.is_alive())     # Returns True for the first time, False for the second time
        print("terminated")

This is the output:

started
inside loop
give input2
True
terminated
inside loop
give input4
False
terminated

Why is this happening? Also, even after the second loop iteration, the process terminates (p.is_alive() returns false) but the audio keeps playing. The audio doesn't stop.

Body:
The solution to this problem is to the have a common variable/flag between both the threads. The variable will signal the audio playing thread to end or wait for it to be changed.

Here is an example of the same.

In this case the thread will exit on getting the signal.

import time
import winsound
import threading

class Player():
    def __init__(self, **kwargs):
        # Shared Variable.
        self.status = {}
        self.play = True
        self.thread_kill = False
    def start_sound(self):
        while True and not self.thread_kill:
            # Do somthing only if flag is true
            if self.play == True:
                #Code to do continue doing what you want.

    def stop_sound(self):
        # Update the variable to stop the sound
        self.play = False
        # Code to keep track of saving current status

    #Function to run your start_alarm on a different thread
    def start_thread(self):
        #Set Alarm_Status to true so that the thread plays the sound
        self.play = True
        t1 = threading.Thread(target=self.start_sound)
        t1.start()

    def run(self):
        while True:
            user_in = str(raw_input('q: to quit,p: to play,s: to Stop\n'))
            if user_in == "q":
                #Signal the thread to end. Else we ll be stuck in for infinite time.
                self.thread_kill = True
                break
            elif user_in == "p":
                self.start_thread()
            elif user_in == "s":
                self.stop_sound()
            else:
                print("Incorrect Key")

if __name__ == '__main__':
    Player().run()


问:
Android sdk option missing on android studio 3.0.1
I have just downloaded the android studio from here.
I couldn't find the Android sdk option with this setup file. Can anyone help me with this problem?

答: Android sdk is already included when you install Android Studio, then if you want to download more sdk version, build tools,.. just use SDK Manager tool</p>


答:
null and undefined are constant values, not strings. You need to omit the "" part from them. Also you can combine the null and undefined checking inside a single check like this

```<code>if(userName) {
   // ...your code
}
</code>```

Because null and undefined are falsy values, you can try to evaluate userName in the if statement without checking for each case.

Title: !=null or !=undefined not working

Body:
I'm trying to create a personalized welcome message on the homepage, that basically says "welcome [username]" providing the user has registered and their username goes into localStorage. That works fine, but I only want the message to display the username if the user has actually registered, (otherwise it says "welcome Null". So I'm trying to use the following code to do that:

// Stores username inputted on registration page inside Local Storage//
function storeUsrName() {
   var regName= document.getElementById("regName");
   localStorage.setItem("usrName", regName.value);
   alert("Thanks for registering!");
 };

// Display welcome message //
$(document).ready(function() {
  var usrName = localStorage.getItem("usrName");

  if (usrName !="null" || usrName !="undefined") {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome " + usrName + "! ");
  } else {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome! ");
  }
});

If a user registers and usrName is assigned a value, the welcome message works fine. But I expect the welcome message to say "Welcome!" if its the users first time visiting the site, and they have yet to register, and usrName has no value (null, or undefined).

Instead, if usrName has no value, the if/else statement doesn't work correctly, and the welcome message displays "welcome null!", despite the fact that I only want usrName to be displayed in the welcome message IF the value is NOT null or undefined.

Is there some correct way of doing this?

Body:
null and undefined are constant values, not strings. You need to omit the "" part from them. Also you can combine the null and undefined checking inside a single check like this

if(userName) {
   // ...your code
}

Because null and undefined are falsy values, you can try to evaluate userName in the if statement without checking for each case.


问:
Using Python's ctypes to call functions involving custom types
I am currently trying to use Python 3.6's ctypes module to call functions from a library written in C++.

Suppose I used ctypes to create a shared library object called myLibrary:

```<code># Python code
myLibrary = ctypes.CDLL(mylib.dylib)
</code>```

The library I'm trying to make calls from uses C++ classes, and it is impossible with ctypes to make Python calls of the form myLibrary.class()->method() (see here).

I am therefore first writing some intermediate C++ code which "wraps" the C++ class methods in a non-class form. For example, suppose Math is one of the classes, and Add() is one of its methods. My intermediate wrapper would look like this:

```<code>// C++ intermediate code
int Add(int num1, int num2){                // no reference to a class
    return Math()->Add(num1, num2);         // reference to a class
}
</code>```

I then plan on compiling this C++ into a shared library (a dylib file) on which I can make calls in Python using ctypes. For example:

```<code># Python code
def add(num1, num2):
    myLibrary.add(num1, num2)
</code>```

That's the plan.

Unfortunately, many methods in the library have exotic argument and value types. Some are simply variant type names created with the typedef keyword, but others are exotic structs. Further, there is a bit of enumeration in the original C++ code.

My question is: How does one deal with custom argument and value types (and enumeration) when using ctypes?

Looking at the ctypes documentation, I know that you must specify restypes and argtypes for the methods you're trying to call, but how to do this when the original C++ functions involve exotic types and structs?

I thought the ctypes documentation might shed light on this, in section 15.17.1.6. ("Calling functions with your own custom data types"), but it just talks about the reverse scenario where you want to pass your own object types into the C++ functions.

Similar questions that were helpful, but not totally:

How to use C++ classes with ctypes?

Obtaining address of custom data-type in C from Python using ctypes

答:
Note that the ctypes is designed to call C code, not C++.

Since you're already writing wrappers, you only need to change one thing - specify that these wrapper functions have C linkage:

```<code>// C++ intermediate code
extern "C" int Add(int num1, int num2) {    // no reference to a class
    return Math()->Add(num1, num2);         // reference to a class
}
</code>```

As for the structures and so on, you should define a proper C language interface for those. It will not be that difficult to come up with the ctypes wrapper for that.

Body:
I am currently trying to use Python 3.6's ctypes module to call functions from a library written in C++.

Suppose I used ctypes to create a shared library object called myLibrary:

# Python code
myLibrary = ctypes.CDLL(mylib.dylib)

The library I'm trying to make calls from uses C++ classes, and it is impossible with ctypes to make Python calls of the form myLibrary.class()->method() (see here).

I am therefore first writing some intermediate C++ code which "wraps" the C++ class methods in a non-class form. For example, suppose Math is one of the classes, and Add() is one of its methods. My intermediate wrapper would look like this:

// C++ intermediate code
int Add(int num1, int num2){                // no reference to a class
    return Math()->Add(num1, num2);         // reference to a class
}

I then plan on compiling this C++ into a shared library (a dylib file) on which I can make calls in Python using ctypes. For example:

# Python code
def add(num1, num2):
    myLibrary.add(num1, num2)

That's the plan.

Unfortunately, many methods in the library have exotic argument and value types. Some are simply variant type names created with the typedef keyword, but others are exotic structs. Further, there is a bit of enumeration in the original C++ code.

My question is: How does one deal with custom argument and value types (and enumeration) when using ctypes?

Looking at the ctypes documentation, I know that you must specify restypes and argtypes for the methods you're trying to call, but how to do this when the original C++ functions involve exotic types and structs?

I thought the ctypes documentation might shed light on this, in section 15.17.1.6. ("Calling functions with your own custom data types"), but it just talks about the reverse scenario where you want to pass your own object types into the C++ functions.

Similar questions that were helpful, but not totally:

How to use C++ classes with ctypes?

Obtaining address of custom data-type in C from Python using ctypes

Body:
Note that the ctypes is designed to call C code, not C++.

Since you're already writing wrappers, you only need to change one thing - specify that these wrapper functions have C linkage:

// C++ intermediate code
extern "C" int Add(int num1, int num2) {    // no reference to a class
    return Math()->Add(num1, num2);         // reference to a class
}

As for the structures and so on, you should define a proper C language interface for those. It will not be that difficult to come up with the ctypes wrapper for that.


问:
jQuery toggle function not called after creation of dynamic list
created a dynamic li list field which is having a toggle functionality. but toggle is working only for first field not the rest dynamically created lists

```<code><html>
  <head>
    <title>add / remove textbox</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style type="text/css">
      div{
        padding:8px;
      }
    </style>

    <style>
      #toggle-view {
        list-style: none;
        font-family: arial;
        font-size: 11px;
        margin: 0;
        padding: 0;
        width: 300px;
      }

      #toggle-view li {
        margin: 10px;
        border:1px solid #ccc;
        padding:4px 3px;
        position: relative;
        cursor: pointer;
      }

      #toggle-view h3 {
        margin: 0;
        font-size: 14px;
      }

      #toggle-view span{
        position: absolute;
        right: 5px;
        top: 0;
        color: #ccc;
        font-size: 13px;
      }
      #toggle-view dd {
        margin: 5px 0;
        display: none;
      }
    </style>
  </head>
  <body>
    <script type="text/javascript">
      window.onload = $(function() {
        var counter = 2;
        $("#addButton").click(function () {
          var newTextBoxDiv = $(document.createElement('li'))
            .attr("id", 'TextBoxDiv' + counter);

          newTextBoxDiv.after().html('<h3>Page No#'+counter+'</h3><dd>' +
          '<input type="text" name="textbox' + counter +
          '" id="textbox' + counter + '" value=""  /></dd>');

          newTextBoxDiv.appendTo("#toggle-view");
          counter++;
        });

        $("#removeButton").click(function () {
          if(counter==1){
            alert("No more textbox to remove");
            return false;
          }

          counter--;
          $("#TextBoxDiv" + counter).remove();
        });

  var parent = $('#toggle-view'), // storing main ul for use below
  delay = 200; // storing delay for easier configuration

// bind the click to all headers 'li h3', parent
$('#toggle-view li').on( 'click', function( event ) {

    //console.log( 'clicked', $( this ).text() );

    // get the li that this header belongs to
    var li = $(this).closest('li');

    // check to see if this li is not already being displayed
    if (!$('dd', li).is(':visible'))
    {
        // loop on all the li elements
        $('li', parent).each(function() {
           //alert();
            // slide up the element and set it's marker to '+'
            $('dd', $(this)).slideUp(delay);
            //$('dd', $(this)).text('+');
        });

        // display the current li with a '-' marker
        $('dd', li).slideDown(delay);
        //$('dd', li).text('-');
    }
});
  //}
    //setTimeout(togg, 100);

  });

</script>
</head><body>

<div id='TextBoxesGroup'>
  <ul id="toggle-view">

    <li id="TextBoxDiv1" >
        <h3>Page No#1</h3>
        <dd><input type='textbox' id='textbox1' ></dd>
    </li>

    </ul>

</div>
<input type='button' value='Add Page' id='addButton'>
<input type='button' value='Remove Page' id='removeButton'>

</body>
</html>
</code>```

答:
Use jQuery delegation to bind event handlers to elements that do not yet exist in the dom</p>

```<code>$('#toggle-view').on( 'click', 'li', function( event ) {
</code>```

Body:
created a dynamic li list field which is having a toggle functionality. but toggle is working only for first field not the rest dynamically created lists

    <title>add / remove textbox</title>

Page No#1

<input type='textbox' id='textbox1' >

<input type='button' value='Add Page' id='addButton'>
<input type='button' value='Remove Page' id='removeButton'>

Body:
Use jQuery delegation to bind event handlers to elements that do not yet exist in the dom

$('#toggle-view').on( 'click', 'li', function( event ) {


问:
NHibernate elt field
Does anyone know why NHibernate generates a field named 'elt' of type int for a many to many mapping?
I'm wondering why I need it.
Thanks</p>

答:
Thanks, yes you are right with a little more playing I found that if I
don't explicitly name the column it defaults to elt.

```<code><bag name="equipment" table="tb_room_equipment" lazy="false">
  <key column="roomID"/>
  <many-to-many class="Equipment" column="equipmentID"/>
</bag>
</code>```

Like here, I have now named the column equipmentID; If I don't it will be named elt.

Title: NHibernate elt field

LastEditorDisplayName: Cade Roux

Body:
Thanks, yes you are right with a little more playing I found that if I
don't explicitly name the column it defaults to elt.

<bag name="equipment" table="tb_room_equipment" lazy="false">
  <key column="roomID"/>
  <many-to-many class="Equipment" column="equipmentID"/>
</bag>

Like here, I have now named the column equipmentID; If I don't it will be named elt.


问:
onkeyup and onkeydown not catching anything
Can someone tell me whats going on? My console isn't throwing any exceptions.

```<code>    function onKeyDown(){
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = true;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = true;
                    }

                    if (e==83 /*s*/){
                        down = true;
                    }

                    if (e==68 /*d*/){
                        right = true;
                    }
                }

                function onKeyUp(){
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = false;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = false;
                    }

                    if (e==83 /*s*/){
                        down = false;
                    }

                    if (e==68 /*d*/){
                        right = false;
                    }
                }

Okay, so that was the javascript, and this is the html:

    <body>
            <input id="ss" type="button" value="start/stop" />
            <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
                <canvas id="canvas" width="480" height="320"  onkeyup="onKeyUp();" onkeydown="onKeydown();">
                    Canvas not displaying.
                </canvas>
            </div>
        </body>

Edit: current code:
</code>```

window.onload = function(){
                init();
            };

```<code>function init(){
                initSettings();
                initImages();

                document.getElementById('canvas').onkeydown = function(event) {
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = true;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = true;
                    }

                    if (e==83 /*s*/){
                        down = true;
                    }

                    if (e==68 /*d*/){
                        right = true;
                    }
                }
</code>```

答:
You should be doing something like this:

```<code>document.onkeydown = function(event) {
    ...
}
document.onkeyup = function(event) {
    ...
}
</code>```

And get rid of:

```<code>onkeyup="onKeyUp();" onkeydown="onKeydown();"
</code>```

The quick test page I made which works:

```<code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">
document.onkeydown = function(event) {
 event = event || window.event;

 var e = event.keyCode;

 //if (e==87 /*w*/){
  up = true;
  throw('up');
 //}

 if (e==65 /*a*/){
  left = true;
 }

 if (e==83 /*s*/){
  down = true;
 }

 if (e==68 /*d*/){
  right = true;
 }
}

document.onkeyup=function(event) {
 event = event || window.event;

 var e = event.keyCode;

 //if (e==87 /*w*/){
  up = false;
  throw('up');
 //}

 if (e==65 /*a*/){
  left = false;
 }

 if (e==83 /*s*/){
  down = false;
 }

 if (e==68 /*d*/){
  right = false;
 }
}
</script>
</head>

<body>
    <input id="ss" type="button" value="start/stop" />
    <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
        <canvas id="canvas" width="480" height="320">
            Canvas not displaying.
        </canvas>
    </div>
</body>

</html>
</code>```

Body:
Can someone tell me whats going on? My console isn't throwing any exceptions.

    function onKeyDown(){
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = true;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = true;
                    }

                    if (e==83 /*s*/){
                        down = true;
                    }

                    if (e==68 /*d*/){
                        right = true;
                    }
                }

                function onKeyUp(){
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = false;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = false;
                    }

                    if (e==83 /*s*/){
                        down = false;
                    }

                    if (e==68 /*d*/){
                        right = false;
                    }
                }

Okay, so that was the javascript, and this is the html:

            <input id="ss" type="button" value="start/stop" />

                <canvas id="canvas" width="480" height="320"  onkeyup="onKeyUp();" onkeydown="onKeydown();">
                    Canvas not displaying.
                </canvas>

Edit: current code:

window.onload = function(){
                init();
            };

function init(){
                initSettings();
                initImages();

                document.getElementById('canvas').onkeydown = function(event) {
                    var e = event.keyCode;

                    //if (e==87 /*w*/){
                        up = true;
                        throw('up');
                    //}

                    if (e==65 /*a*/){
                        left = true;
                    }

                    if (e==83 /*s*/){
                        down = true;
                    }

                    if (e==68 /*d*/){
                        right = true;
                    }
                }

Body:
You should be doing something like this:

document.onkeydown = function(event) {
    ...
}
document.onkeyup = function(event) {
    ...
}

And get rid of:

onkeyup="onKeyUp();" onkeydown="onKeydown();"

The quick test page I made which works:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">
document.onkeydown = function(event) {
 event = event || window.event;

 var e = event.keyCode;

 //if (e==87 /*w*/){
  up = true;
  throw('up');
 //}

 if (e==65 /*a*/){
  left = true;
 }

 if (e==83 /*s*/){
  down = true;
 }

 if (e==68 /*d*/){
  right = true;
 }
}

document.onkeyup=function(event) {
 event = event || window.event;

 var e = event.keyCode;

 //if (e==87 /*w*/){
  up = false;
  throw('up');
 //}

 if (e==65 /*a*/){
  left = false;
 }

 if (e==83 /*s*/){
  down = false;
 }

 if (e==68 /*d*/){
  right = false;
 }
}
</script>
</head>

<body>
    <input id="ss" type="button" value="start/stop" />
    <div id="container" style="border:1px solid; cursor:none; width:480px; height:320px;">
        <canvas id="canvas" width="480" height="320">
            Canvas not displaying.
        </canvas>
    </div>
</body>

</html>


问:
Remove duplicates Objects from List in Java
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

```<code>dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));
</code>```

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

```<code>class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }
</code>```

step 2) method to remove duplicates

```<code>public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }
</code>```

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

```<code>public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}
</code>```

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

```<code>    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }
</code>```

Thank you very much

答:
With your code

```<code>    linkedList.remove();
</code>```

Each time it removes an item from linkedList, the indexes of all following items are decremented.  That is going to mess up your iteration loop.

Body:
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }

step 2) method to remove duplicates

public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }

Thank you very much

Body:
With your code

    linkedList.remove();

Each time it removes an item from linkedList, the indexes of all following items are decremented.  That is going to mess up your iteration loop.


问:
!=null or !=undefined not working
I'm trying to create a personalized welcome message on the homepage, that basically says "welcome [username]" providing the user has registered and their username goes into localStorage. That works fine, but I only want the message to display the username if the user has actually registered, (otherwise it says "welcome Null". So I'm trying to use the following code to do that:

```<code>// Stores username inputted on registration page inside Local Storage//
function storeUsrName() {
   var regName= document.getElementById("regName");
   localStorage.setItem("usrName", regName.value);
   alert("Thanks for registering!");
 };

// Display welcome message //
$(document).ready(function() {
  var usrName = localStorage.getItem("usrName");

  if (usrName !="null" || usrName !="undefined") {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome " + usrName + "! ");
  } else {
    document.getElementById("welcomeMessage").innerHTML = ("Welcome! ");
  }
});
</code>```

If a user registers and usrName is assigned a value, the welcome message works fine. But I expect the welcome message to say "Welcome!" if its the users first time visiting the site, and they have yet to register, and usrName has no value (null, or undefined).

Instead, if usrName has no value, the if/else statement doesn't work correctly, and the welcome message displays "welcome null!", despite the fact that I only want usrName to be displayed in the welcome message IF the value is NOT null or undefined.

Is there some correct way of doing this?

答:
May be null is not string so that "null" this is not valid for null you can also write like following

usrName != "".(care that only double quotes no space between them!)
I haven't idea for undefined sorry for this.

Title: !=null or !=undefined not working


问:
How to get number of index's a element is away from a certain element in jQuery?
Suppose I have the following HTML code:

// post the jquery code here...```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="perspectiveSlider__main">
  <div class="perspectiveSlider__slidesContainer">
    <div class="perspectiveSlider__item item-left-faded">
      <img src="img/slide-1.jpg" alt="">
    </div>
    <div class="perspectiveSlider__item item-left">
      <img src="img/slide-2.png" alt="">
    </div>
    <div class="perspectiveSlider__item item-center">
      <img src="img/slide-3.png" alt="">
    </div>
    <div class="perspectiveSlider__item item-right">
      <img src="img/slide-5.jpg" alt="">
    </div>
    <div class="perspectiveSlider__item item-right-faded">
      <img src="img/slide-6.jpg" alt="">
    </div>
  </div>
</div></code>```

As you can see perspectiveSlider__item are 5 siblings of each other and each also has a unique class, now how do I find the number of index's .item-left-faded is away from item-center ?

I know jQuery provides a next() and prev() functions and also index() function but is there something that I can create that will work like a ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement() ?

In the above case .item-left-faded is away from item-center by 2 index's , How do i achieve this functionality ?

答:
Store your elements to an array with index and find your required classes and subtract indexes between them

here are code snippet to perform my thought

```<code>$(document).ready(function(){

  var allItems = [];

  $('.perspectiveSlider__item').each(function(){
    allItems.push({ index: $(this).index(), className:$(this).attr('class').replace('perspectiveSlider__item ','') })
  })

  function ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement(fromClass,toClass){
    var fromIndex = allItems.filter(function(item){
      if(item.className == fromClass){
        return item.index;
      }
    });

    var toIndex = allItems.filter(function(item){
      if(item.className == toClass){
        return item.index;
      }
    });

    return fromIndex[0].index - toIndex[0].index;

  }
  console.log(ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement('item-left-faded','item-center'));

})
</code>```

Please let me know your issue is solve?

Body:
Suppose I have the following HTML code:

// post the jquery code here...

As you can see perspectiveSlider__item are 5 siblings of each other and each also has a unique class, now how do I find the number of index's .item-left-faded is away from item-center ?

I know jQuery provides a next() and prev() functions and also index() function but is there something that I can create that will work like a ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement() ?

In the above case .item-left-faded is away from item-center by 2 index's , How do i achieve this functionality ?

Body:
Store your elements to an array with index and find your required classes and subtract indexes between them

here are code snippet to perform my thought

$(document).ready(function(){

  var allItems = [];

  $('.perspectiveSlider__item').each(function(){
    allItems.push({ index: $(this).index(), className:$(this).attr('class').replace('perspectiveSlider__item ','') })
  })

  function ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement(fromClass,toClass){
    var fromIndex = allItems.filter(function(item){
      if(item.className == fromClass){
        return item.index;
      }
    });

    var toIndex = allItems.filter(function(item){
      if(item.className == toClass){
        return item.index;
      }
    });

    return fromIndex[0].index - toIndex[0].index;

  }
  console.log(ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement('item-left-faded','item-center'));

})

Please let me know your issue is solve?


问:
Can't connect JS script Chrome extension

Hello there! I have a problem while adding socket.io.js to Chrome extension, it doesn't go well! I have tried like this

```<code>var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
</code>```

But it doesn't work, it is only attaching on HTML (I saw in Dev tools networking), but console still says Uncaught ReferenceError: io is not defined. What can I do?

Code:
manifest.json

```<code>{
  "name": "Test",
  "version": "0.0.1",
  "description": "Test app",
  "permissions": [ "background", "tts", "storage" ],

  "background": { "scripts": ["my.js"] },

  "browser_action": {
    "default_popup": "my.html"
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["socket.io.js", "my.js"]
    }
  ],
  "manifest_version": 2
}
</code>```

my.js

```<code>console.log("hey");

var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
script2.src = 'smart.js';
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);
</code>```

smart.js

```<code>var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
  console.log('Client connected');
});
</code>```

my.html

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="my.js"></script>
  </head>
  <body>

  </body>
</html>
</code>```

How to get it work?

P.S. sockets.io.js is located in the same directory as all of this scripts

答:
You need to wait for the first script to be loaded.

my.js:

```<code>(function(d, s, id){
  if (d.getElementById(id)){ return; } // exec only once
  var js1 = d.createElement(s);
  js1.id = id;
  js1.onload = function(){
    console.log("js1 is ready");
    var js2 = document.createElement(s);
    js2.src = 'smart.js';
    document.getElementsByTagName('head')[0].appendChild(js2);
  };
  console.log("loading js1");
  js1.src = "socket.io.js";
  document.getElementsByTagName('head')[0].appendChild(js1);
}(document, 'script', 'some unique id'));
</code>```

Body:
Hello there! I have a problem while adding socket.io.js to Chrome extension, it doesn't go well! I have tried like this

var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

But it doesn't work, it is only attaching on HTML (I saw in Dev tools networking), but console still says Uncaught ReferenceError: io is not defined. What can I do?

Code:
manifest.json

{
  "name": "Test",
  "version": "0.0.1",
  "description": "Test app",
  "permissions": [ "background", "tts", "storage" ],

  "background": { "scripts": ["my.js"] },

  "browser_action": {
    "default_popup": "my.html"
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["socket.io.js", "my.js"]
    }
  ],
  "manifest_version": 2
}

my.js

console.log("hey");

var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
script2.src = 'smart.js';
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);

smart.js

var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
  console.log('Client connected');
});

my.html

<!DOCTYPE html>

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

How to get it work?

P.S. sockets.io.js is located in the same directory as all of this scripts

Body:
You need to wait for the first script to be loaded.

my.js:

(function(d, s, id){
  if (d.getElementById(id)){ return; } // exec only once
  var js1 = d.createElement(s);
  js1.id = id;
  js1.onload = function(){
    console.log("js1 is ready");
    var js2 = document.createElement(s);
    js2.src = 'smart.js';
    document.getElementsByTagName('head')[0].appendChild(js2);
  };
  console.log("loading js1");
  js1.src = "socket.io.js";
  document.getElementsByTagName('head')[0].appendChild(js1);
}(document, 'script', 'some unique id'));