问:
Unexpected token < in JSON at position 0
If I do curl, the server returns an array of posts objects, like this:

```<code>curl http://localhost/api/posts/
[
    {
        "id": 7,
        "target": {
            "body": "This is the body",
            "title": "Airbnb raising a reported $850M at a $30B valuation",
            "user": {
                "first_name": "ben",
                "last_name": "jamin"
            }
        }
    },
    {
        "id": 11,
        "target": {
            "body": "This is the body",
            "title": "Browsing the APISSS",
            "user": {
                "first_name": "user",
                "last_name": "two"
            }
        }
    }
]
</code>```

I tried getting this using the fetch api:

```<code>fromServer() {
    console.log('fromServer')
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    let a = fetch('http://test.com/api/posts/', headers)
        .then(function(response) {
                if (response.status !== 200) {
                    console.log('There was a problem. Status Code: ' +  response.status);
                    return;
                }

                response.json().then(function(data) {
                    console.log(data);
                });
            }
        )
        .catch(function(err) {
            console.log('Fetch Error :-S', err);
        });
}
</code>```

But I am getting this error:

Unexpected token < in JSON at position 0

SyntaxError: Unexpected token < in JSON at position 0

How can I solve this problem? Could you please help me. Thank you.

答: You can try adding the dataType property,just like dataType: 'html' or dataType: 'text'

Body:
If I do curl, the server returns an array of posts objects, like this:

curl http://localhost/api/posts/
[
    {
        "id": 7,
        "target": {
            "body": "This is the body",
            "title": "Airbnb raising a reported $850M at a $30B valuation",
            "user": {
                "first_name": "ben",
                "last_name": "jamin"
            }
        }
    },
    {
        "id": 11,
        "target": {
            "body": "This is the body",
            "title": "Browsing the APISSS",
            "user": {
                "first_name": "user",
                "last_name": "two"
            }
        }
    }
]

I tried getting this using the fetch api:

fromServer() {
    console.log('fromServer')
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    let a = fetch('http://test.com/api/posts/', headers)
        .then(function(response) {
                if (response.status !== 200) {
                    console.log('There was a problem. Status Code: ' +  response.status);
                    return;
                }

                response.json().then(function(data) {
                    console.log(data);
                });
            }
        )
        .catch(function(err) {
            console.log('Fetch Error :-S', err);
        });
}

But I am getting this error:

Unexpected token < in JSON at position 0

SyntaxError: Unexpected token < in JSON at position 0

How can I solve this problem? Could you please help me. Thank you.


来源: stackexchange

问:
Meteor not loading external CSS and JS files
I am trying to load my stylesheets and js files in Meteor. I have an index.html file. This is what I was doing at first:

```<code><link href="assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>
</code>```

There were lots of stylesheet files and script files. This was working fine but if i wrote a url like: 'localhost:3000/manage-user/add', everything stopped working. I have read loads of answers where they have mentioned that I need to make a lib folder and in that folder, I need to make a css and a js folder, but it's not picking up my files, especially my 'style.css' file which overrides styles of bootstrap and all.

答:
URL can be absolute and relative.

Absolute should starts from protocol value(http://, https://, ftp:// etc) and then domain name, port, path and query part.
Relative can be started either from slash or any other character.

If URL is started from slash it's assumed its value is relative to domain's root.

If URL is started from any other character it's assumed it's value is relative to current URL(or value in  tag).

Anyway value localhost:3000/manage-user/add means for browser:
"take current page's URL and append this value to its end".
So your files are tried to be fetched from something like http://localhost:3000/localhost:3000/manage-user/add

ContentLicense: CC BY-SA 3.0

Body:
I am trying to load my stylesheets and js files in Meteor. I have an index.html file. This is what I was doing at first:

<link href="assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
<link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css"/>

There were lots of stylesheet files and script files. This was working fine but if i wrote a url like: 'localhost:3000/manage-user/add', everything stopped working. I have read loads of answers where they have mentioned that I need to make a lib folder and in that folder, I need to make a css and a js folder, but it's not picking up my files, especially my 'style.css' file which overrides styles of bootstrap and all.


问:
No Module Named AppKit
I am trying to run an audio file in Python:

```<code>from playsound import playsound

def main():
    playsound('audio.mp3')

main()
</code>```

However, I keep getting the following error:

```<code>File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/playsound.py", line 55, in _playsoundOSX
from AppKit     import NSSound
ImportError: No module named 'AppKit'
</code>```

I am using Python 3.5.4 on macOS 10.12.6. I have tried installing it via pip but I am returned this error:

```<code>Using cached AppKit-0.2.8.tar.gz
Requirement already satisfied: flask in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from appkit)
Collecting pygobject (from appkit)
Could not find a version that satisfies the requirement pygobject (from appkit) (from versions: )
No matching distribution found for pygobject (from appkit)
</code>```

答:
If you want to use AppKit you have to install PyObjC:

```<code>pip3 install -U PyObjC
</code>```

or

```<code>pip install -U PyObjC
</code>```

ContentLicense: CC BY-SA 4.0

Title: No Module Named AppKit

Body:
I am trying to run an audio file in Python:

from playsound import playsound

def main():
    playsound('audio.mp3')

main()

However, I keep getting the following error:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/playsound.py", line 55, in _playsoundOSX
from AppKit     import NSSound
ImportError: No module named 'AppKit'

I am using Python 3.5.4 on macOS 10.12.6. I have tried installing it via pip but I am returned this error:

Using cached AppKit-0.2.8.tar.gz
Requirement already satisfied: flask in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from appkit)
Collecting pygobject (from appkit)
Could not find a version that satisfies the requirement pygobject (from appkit) (from versions: )
No matching distribution found for pygobject (from appkit)

Body:
If you want to use AppKit you have to install PyObjC:

pip3 install -U PyObjC

or

pip install -U PyObjC


问:
javascript - convert font element to span element using regex
I want to convert  element to  element like this using regex:

Input:

```<code>[some strings...]<span [something]></span><font ...>[sometext]</font>[some strings...]
</code>```

Output:

```<code>[some strings...]<span [something]>[sometext]</span>[some strings...]
</code>```

Note: The input/output is a string.

In shortly, I want to remove the  element and move the contents of that into  element keeping the attributes of the  element.

I've tried this:

```<code>const rx = /<span(.*?)><\/span>([^<\\s]+?|\\s*)<font(?:\\s+[^>]*)?>(.*?)<\/font>/gi;

inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });
</code>```

However it doesn't work.

Can anyone help me?

答:
I also agree with @skyboyer, this is not the best way, but if you can use regexp only or if this is a one-time task, you can use a class group specifing to take all chars that are not ">", in this way you can take all the params of the tag span and use it in the font:

```<code>var text = 'Some text... <span style="color:red"></span><font style="margin:10px">Hi there!</font> other text <span style="color:blu"></span><font style="margin:10px">doh!</font> final text';
console.log(text.replace(/<span([^>]*)><\/span><font[^>]*>(.+?)<\/font>/gi,'<span$1>$2</span>'));
</code>```

edited in order to match other tags inside  (except other s, obviously)

Body:
I want to convert  element to  element like this using regex:

Input:

[some strings...][sometext][some strings...]

Output:

[some strings...][sometext][some strings...]

Note: The input/output is a string.

In shortly, I want to remove the  element and move the contents of that into  element keeping the attributes of the  element.

I've tried this:

const rx = /<\/span>([^<\\s]+?|\\s*)]*)?>(.*?)<\/font>/gi;

inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });

However it doesn't work.

Can anyone help me?

Body:
I also agree with @skyboyer, this is not the best way, but if you can use regexp only or if this is a one-time task, you can use a class group specifing to take all chars that are not ">", in this way you can take all the params of the tag span and use it in the font:

var text = 'Some text... <span style="color:red"></span><font style="margin:10px">Hi there!</font> other text <span style="color:blu"></span><font style="margin:10px">doh!</font> final text';
console.log(text.replace(/<span([^>]*)><\/span><font[^>]*>(.+?)<\/font>/gi,'<span$1>$2</span>'));

edited in order to match other tags inside  (except other s, obviously)


问:
unable to get component variable value in angular 2 in frontend
Am unable to display mapLoc value in front end... any help?

Here is my component.ts file

```<code>export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}
</code>```

this is mycomponent.html file

```<code><ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">
                        <div *ngIf="marker.display">
                        {{mapLoc}}
                        </div>
                    </info-window>
            </ngui-map>
</code>```

答:
The value of this can be different inside the callback (To check this, try console.log("this", this) inside the callback.). Try using a big arrow function instead to keep reference to your component.

```<code>    geocoder.geocode({ 'latLng': latlng }, (results, status) => {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    this.mapLoc = results[1].formatted_address;
                }
            }
        });
</code>```

or cache a reference and use it in the old way:

```<code>    let component = this;
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    console.log(results[1].formatted_address); //able to console
                    component.mapLoc = results[1].formatted_address;
                }
            }
        });
</code>```

Body:
Am unable to display mapLoc value in front end... any help?

Here is my component.ts file

export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}

this is mycomponent.html file

<ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">

                        {{mapLoc}}

                    </info-window>
            </ngui-map>

Body:
The value of this can be different inside the callback (To check this, try console.log("this", this) inside the callback.). Try using a big arrow function instead to keep reference to your component.

    geocoder.geocode({ 'latLng': latlng }, (results, status) => {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    this.mapLoc = results[1].formatted_address;
                }
            }
        });

or cache a reference and use it in the old way:

    let component = this;
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    console.log(results[1].formatted_address); //able to console
                    component.mapLoc = results[1].formatted_address;
                }
            }
        });


问:
How to query complex range in postgreSql
I have two columns in my one postgreSQL Table.

The name of columns are: TO, FROM
which denotes a range. Let say 100 - 200 (so here 100 will save in TO and 200 will get saved in FROM)

Now, the main problem is any number in this range will be never be used again. i.e we can't save (100,101,102...200 according to the example mentioned above).

I have to create a query in which I have to take data from the request and check whether the requested range is in the database or not.

Example: 100 -200 are already saved in database and I am getting request of following:
1) 100 -200
2) 150-250
3) 20 -150
4) 50 -280
e.t.c...
All the above cases are false because at least one number is already saved in db

I am new to SQL can you please help in querying? I am using postgreSQL.

答:
```<code>SELECT * FROM TABLE_NAME WHERE
(dateFrom <= Req.from AND dateTo >= Req.from)OR
(dateFrom <= Req.to AND dateTo >= Req.to) OR
(dateFrom >= Req.from AND dateTo <= Req.to)
</code>```

I didn't find better then this

Body:
SELECT * FROM TABLE_NAME WHERE
(dateFrom <= Req.from AND dateTo >= Req.from)OR
(dateFrom <= Req.to AND dateTo >= Req.to) OR
(dateFrom >= Req.from AND dateTo <= Req.to)

I didn't find better then this


问:
Unable to make RDP connection to AWS windows instance
I have created windows 12 R2 Base EC2 instance with VPC in AWS. But I am unable to do RDP to that instance.
I have checked the following things :  </p>

```<code>1. Instance has elastic IP with IPv4 public Ip
2 .Security group : Inbound: Type :RDS ,Protocol:TCP, Port range: 3389 , Source :0.0.0.0/0 .Outbound : All traffic, destination:0.0.0.0/0.
3. Route Table : Destination 0.0.0.0/0 Target **************** Status Active Propagated No
</code>```

<p>But still I am not able do RDS connection. Any suggestions would be very much helpful to me. </p>

答:
Are the EC2 instances in a public subnet? You can check to see this in the route table of your subnet - you must have an Internet Gateway configured for the subnet to be public. Where you have Target ****************, is this the Internet Gateway (something like igw-ab7ff6b1)? If it's not an Internet Gateway, then you won't be able to RDP to those instances. Create an Internet Gateway, attach it to the VPC and then create a rule in the route table for Destination 0.0.0.0/0 to the Internet Gateway.

Once you have an Internet Gateway, you'll need to also ensure that your Network ACLs are allowing RDP access in and out of the subnet.

Body:
I have created windows 12 R2 Base EC2 instance with VPC in AWS. But I am unable to do RDP to that instance.
I have checked the following things :

1. Instance has elastic IP with IPv4 public Ip
2 .Security group : Inbound: Type :RDS ,Protocol:TCP, Port range: 3389 , Source :0.0.0.0/0 .Outbound : All traffic, destination:0.0.0.0/0.
3. Route Table : Destination 0.0.0.0/0 Target **************** Status Active Propagated No

But still I am not able do RDS connection. Any suggestions would be very much helpful to me.


问:
Accessing the associated string of a stringstream object
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :

```<code>  stringstream HTMLss;   // string stream of HTML document

  // ... (load up HTMLss with HTML)

  const string & HTMLstr = HTMLss.str();   // grab reference to associated string
  string::const_iterator begin,end;
  begin = HTMLstr.begin();                 // grab iterators to that string as well
  end = HTMLstr.end();
  boost::match_results<std::string::const_iterator> matches;

  // do some processing, updating the iterators along the way
  while( boost::regex_search(begin, end, matches, metaexp) )
    {
      string key( matches[1].first, matches[1].second );
      string raw_val( matches[2].first, matches[2].second );

      // ... some processing which does NOT manipulate HTMLss stringstream in any way

      begin = matches[2].second;   // updating the iterator
    }
</code>```

My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?

答:
This returns a temporary which is lifetime-extended to HTMLstr's scope:

```<code>const string & HTMLstr = HTMLss.str();
</code>```

Because this is a copy of HTMLss's buffer, any later changes made to HTMLss won't be reflected, but it's perfectly find to keep and use iterators to HTMLstr for as long as HTMLstr is in scope.

However, you might as well make HTMLstr a non-reference, but you can keep the const (or drop it) as you like:

```<code>const string HTMLstr = HTMLss.str();
</code>```

Keeping the const does reduce the ways you can invalidate the iterators, but you didn't have a problem with that in the original code either.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :

  stringstream HTMLss;   // string stream of HTML document

  // ... (load up HTMLss with HTML)

  const string & HTMLstr = HTMLss.str();   // grab reference to associated string
  string::const_iterator begin,end;
  begin = HTMLstr.begin();                 // grab iterators to that string as well
  end = HTMLstr.end();
  boost::match_results<std::string::const_iterator> matches;

  // do some processing, updating the iterators along the way
  while( boost::regex_search(begin, end, matches, metaexp) )
    {
      string key( matches[1].first, matches[1].second );
      string raw_val( matches[2].first, matches[2].second );

      // ... some processing which does NOT manipulate HTMLss stringstream in any way

      begin = matches[2].second;   // updating the iterator
    }

My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?

Body:
This returns a temporary which is lifetime-extended to HTMLstr's scope:

const string & HTMLstr = HTMLss.str();

Because this is a copy of HTMLss's buffer, any later changes made to HTMLss won't be reflected, but it's perfectly find to keep and use iterators to HTMLstr for as long as HTMLstr is in scope.

However, you might as well make HTMLstr a non-reference, but you can keep the const (or drop it) as you like:

const string HTMLstr = HTMLss.str();

Keeping the const does reduce the ways you can invalidate the iterators, but you didn't have a problem with that in the original code either.


问:
Cannot update data in MySQL Database using mysqli
Hello can someone assist me im failing to update the data in my mysql database</p>

```<code><?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."<br>".$conn->error;
    }

    $conn->close();

    ?>
</code>```

答:
There are a couple of things wring with your code, aside from the quite obvious SQL Injection risk.

Remove the ) bracket from your query,

```<code>$mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description =
'$item_description',item_unit_price = '$item_unit_price' where
item_name='$item_name')";
                    //^ remove the bracket
//execute the query
$result = mysqli_query($conn,$mysql_query);

//Executing the query again?
if($conn->query($mysql_query) ===TRUE){
</code>```

you are executing your query twice. Remove one of the these lines:

```<code>$result = mysqli_query($conn,$mysql_query);
</code>```

Or:

```<code>if($conn->query($mysql_query) ===TRUE)
</code>```

Warning

If those variables are inputs from the user, please use prepared statement, instead, to counter the SQL Injection. Like:

```<code>$mysql_query = "UPDATE Stock SET item_code = ?, item_description =?, item_unit_price = ? where item_name=?";
$stmt = $mysqli->prepare($mysql_query);
$stmt->bind_param("isds", $item_code, $item_description, $item_unit_price, $item_name);
$stmt->execute();
</code>```

Body:
Hello can someone assist me im failing to update the data in my mysql database

<?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."
".$conn->error;
    }

    $conn->close();

    ?>

Body:
There are a couple of things wring with your code, aside from the quite obvious SQL Injection risk.

Remove the ) bracket from your query,

$mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description =
'$item_description',item_unit_price = '$item_unit_price' where
item_name='$item_name')";
                    //^ remove the bracket
//execute the query
$result = mysqli_query($conn,$mysql_query);

//Executing the query again?
if($conn->query($mysql_query) ===TRUE){

you are executing your query twice. Remove one of the these lines:

$result = mysqli_query($conn,$mysql_query);

Or:

if($conn->query($mysql_query) ===TRUE)

Warning

If those variables are inputs from the user, please use prepared statement, instead, to counter the SQL Injection. Like:

$mysql_query = "UPDATE Stock SET item_code = ?, item_description =?, item_unit_price = ? where item_name=?";
$stmt = $mysqli->prepare($mysql_query);
$stmt->bind_param("isds", $item_code, $item_description, $item_unit_price, $item_name);
$stmt->execute();


问:
Get OneSignal UserID after subscribe
I'm using OneSignal to get notifications, so according to docs I made my SDK code like this:

```<code><script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "myappID",
      safari_web_id: "myID",
      autoRegister: false,
      promptOptions: {
            /* My prompt options */
       },
       welcomeNotification: {
            //my options
       },
       notifyButton: {
        enable: true,
        showCredit: false,
        prenotify: true,
        position: 'bottom-left',
        text: {
            /*My text options */
        },
        colors: { // My custom colors
        }
      }
    }]);

    OneSignal.push(function(){
        OneSignal.showHttpPrompt();

        OneSignal.getUserId().then(function(userId){
            console.log("OneSignal User ID:", userId);
        });
    });
</script>
</code>```

It works great showing slideshow prompt message, but after subscribe I need to refresh the website to get UserID in console. How can I modify this code function to get userID in console immediately after subscribe?

答:
You need to add a listener for the subscription change event. Otherwise the getUserId call will trigger before the user has accepted the subscription. This is working for me:</p>

```<code>var OneSignal = window.OneSignal || [];

OneSignal.push(function() {
  OneSignal.on('subscriptionChange', function (isSubscribed) {
    console.log("The user's subscription state is now:",isSubscribed);
      OneSignal.push(function() {
        OneSignal.getUserId(function(userId) {
          console.log("OneSignal User ID:", userId);
        });
      });
    });
  });

  OneSignal.push(["init", {
    appId: "myappID",
    safari_web_id: "myID",
    autoRegister: false,
    promptOptions: {
        /* My prompt options */
    },
    welcomeNotification: {
        //my options
    },
    notifyButton: {
      enable: true,
      showCredit: false,
      prenotify: true,
      position: 'bottom-left',
      text: {
        /*My text options */
     },
     colors: { // My custom colors
     }
   }
}]);
</code>```

Title: Get OneSignal UserID after subscribe

Body:
I'm using OneSignal to get notifications, so according to docs I made my SDK code like this:

It works great showing slideshow prompt message, but after subscribe I need to refresh the website to get UserID in console. How can I modify this code function to get userID in console immediately after subscribe?

Body:
You need to add a listener for the subscription change event. Otherwise the getUserId call will trigger before the user has accepted the subscription. This is working for me:

var OneSignal = window.OneSignal || [];

OneSignal.push(function() {
  OneSignal.on('subscriptionChange', function (isSubscribed) {
    console.log("The user's subscription state is now:",isSubscribed);
      OneSignal.push(function() {
        OneSignal.getUserId(function(userId) {
          console.log("OneSignal User ID:", userId);
        });
      });
    });
  });

  OneSignal.push(["init", {
    appId: "myappID",
    safari_web_id: "myID",
    autoRegister: false,
    promptOptions: {
        /* My prompt options */
    },
    welcomeNotification: {
        //my options
    },
    notifyButton: {
      enable: true,
      showCredit: false,
      prenotify: true,
      position: 'bottom-left',
      text: {
        /*My text options */
     },
     colors: { // My custom colors
     }
   }
}]);


问:
Can't figured why header location is not working for this case (php)
So I'm building a website where the user registers and when logged in, he/she is able to do somethings such as unflagging quotations (adding back) that where flagged (removed from the public view) by users not registered. However, I'm having problems figuring out why my header('location: index.php') on my controller file won't redirect the page to the index.php page.I already tried to comment out all instances of echo("something") in my controller to see if that's why it's not working, but it didn't work either. I have no clues left of why  header('location: index.php') is not working.

Here is my controller file where I redirect the user after successful registration:

```<code><?php

session_start();
include "DataBaseAdaptor.php";

function GetQuotes($theDBA) {
    $array = $theDBA->getQuotesAsArray();
    $quotes = [];
    //$quotes[] = [];

    $i = 0;
    $j = 0;
    $id = "";
    if(count($array)>0){
    foreach($array as $item) {
        $quotes[$i][$j] = $item['quote'];
        $quotes[$i][$j+1] = $item['author'];
        $quotes[$i][$j+2] = $item['rating'];
        $quotes[$i][$j+3] = $item['id'];
        $i++;
    }}
    return $quotes;
}
$quotes = GetQuotes($theDBA);                         //This to display the quotes initially

// This part is for registering the user
if(isset($_GET['user']) && isset($_GET['pass'])) {
    $username = $_GET['user'];
    $password = $_GET['pass'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // If false, then username already exists
    if (!$theDBA->register($username,  $hashed_password )) {
       //echo("Username already exists");
    }
    else {          //The control does come to this block and the else is evaluated to true. However it won't redirect
        $_SESSION['user'] = $username;
        header('Location: index.php');

    }
}
// Register ends here----------------------------------------------------------------------------------

//This part is for adding quote
if(isset($_GET['quote']) && isset($_GET['author'])) {
    $quote = $_GET['quote'];
    $quote = str_replace("'", "", $quote);

    $author = $_GET['author'];
    $theDBA->addQuote($quote, $author);
    $quotes = GetQuotes($theDBA);
    header( 'Location: index.php' );
}

// This is for logging in
$quotes = GetQuotes($theDBA);
$user = "";
$pass = "";
if(isset($_GET['p']) && isset($_GET['q'])) {
     $user = isset($_GET['p']);
     $pass = isset($_GET['q']);

}
for ($i = 0; $i < count($quotes); $i++){
    if($user === $quotes[$i][0]) {
        $_SESSION['user'] = 'Rick';
        header('Location: index.php');
    }
}

echo json_encode($quotes);
?>
</code>```

I don't know if you need my model.php (DataBaseAdaptor.php in my case), but here is. Everything related to the database, like all sql operations are working. but in case you need it, find it bellow. Feel free to send edit suggestions to my post if you find model.php not to be necessary( but please, do it only if you are sure it's not necessary). Thanks!

Here is model.php

```<code><?php

//
// Author: Rick Mercer.   File name: model.php
//

class DatabaseAdaptor {
// The instance variable used in every one of the functions in class
DatbaseAdaptor
private $DB;

// Make a connection to an existing data based named 'first' that has table
customer
public function __construct() {
$db = 'mysql:dbname=quotes; charset=utf8; host=127.0.0.1';
$user = 'root';
$password = '';

try {
  $this->DB = new PDO ( $db, $user, $password );
  $this->DB->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo ('Error establishing Connection');
  exit ();
}
}

// Return all records as an associative array.
public function getQuotesAsArray() {
$query = "SELECT * FROM quotations WHERE flagged = 0 ORDER BY rating DESC";

$stmt = $this->DB->prepare($query);
$stmt->execute ();
// fetchall returns all records in the set as an array
return $stmt->fetchAll ( PDO::FETCH_ASSOC );
}

   // Checks if a user exists, if not register the new user
  public function register($username, $password) {
  $query = "SELECT * from users";
  $stmt = $this->DB->prepare($query);
  $stmt->execute ();

// fetchall returns all records in the set as an array
$array = $stmt->fetchAll ( PDO::FETCH_ASSOC );

// If there are no registered users, just register the new user
if(count($array) == 0) {
    $query = "INSERT INTO users (username, hash) VALUES ('$username',
'$password')";
    $stmt = $this->DB->prepare($query);
    $stmt->execute ();
    return true;
 // header( 'Location: index.php' );
}

foreach($array as $item) {
    if($username == $item['username']) {
        return false;
    }
}
    $query = "INSERT INTO users (username, hash) VALUES ('$username', '$password')";
    $stmt = $this->DB->prepare($query);
    $stmt->execute ();
    return true;
   //header( 'Location: index.php' );
 }

 public function addQuote($quote, $author) {
 $query = "INSERT INTO quotations (added, quote, author, rating, flagged)
 VALUES(now(), '$quote', '$author', 0, 0)";
 $stmt = $this->DB->prepare($query);
 $stmt->execute ();
 }

 } // End class DatabaseAdaptor

$theDBA = new DatabaseAdaptor();
?>

Any help is appreciated. Thanks!
</code>```

答:
Replace header(); with echo 'redirecting...'; and see if your code reaches header part or no.

If you could see "redirecting..." then something prevents header from running. For example, there might be a warning or something  that comes before header. In that case, try to solve that warning or (not a good idea) try ob_start and ob_end_clean to prevent flushing anything to output.

Body:
So I'm building a website where the user registers and when logged in, he/she is able to do somethings such as unflagging quotations (adding back) that where flagged (removed from the public view) by users not registered. However, I'm having problems figuring out why my header('location: index.php') on my controller file won't redirect the page to the index.php page.I already tried to comment out all instances of echo("something") in my controller to see if that's why it's not working, but it didn't work either. I have no clues left of why  header('location: index.php') is not working.

Here is my controller file where I redirect the user after successful registration:

<?php

session_start();
include "DataBaseAdaptor.php";

function GetQuotes($theDBA) {
    $array = $theDBA->getQuotesAsArray();
    $quotes = [];
    //$quotes[] = [];

    $i = 0;
    $j = 0;
    $id = "";
    if(count($array)>0){
    foreach($array as $item) {
        $quotes[$i][$j] = $item['quote'];
        $quotes[$i][$j+1] = $item['author'];
        $quotes[$i][$j+2] = $item['rating'];
        $quotes[$i][$j+3] = $item['id'];
        $i++;
    }}
    return $quotes;
}
$quotes = GetQuotes($theDBA);                         //This to display the quotes initially

// This part is for registering the user
if(isset($_GET['user']) && isset($_GET['pass'])) {
    $username = $_GET['user'];
    $password = $_GET['pass'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // If false, then username already exists
    if (!$theDBA->register($username,  $hashed_password )) {
       //echo("Username already exists");
    }
    else {          //The control does come to this block and the else is evaluated to true. However it won't redirect
        $_SESSION['user'] = $username;
        header('Location: index.php');

    }
}
// Register ends here----------------------------------------------------------------------------------

//This part is for adding quote
if(isset($_GET['quote']) && isset($_GET['author'])) {
    $quote = $_GET['quote'];
    $quote = str_replace("'", "", $quote);

    $author = $_GET['author'];
    $theDBA->addQuote($quote, $author);
    $quotes = GetQuotes($theDBA);
    header( 'Location: index.php' );
}

// This is for logging in
$quotes = GetQuotes($theDBA);
$user = "";
$pass = "";
if(isset($_GET['p']) && isset($_GET['q'])) {
     $user = isset($_GET['p']);
     $pass = isset($_GET['q']);

}
for ($i = 0; $i < count($quotes); $i++){
    if($user === $quotes[$i][0]) {
        $_SESSION['user'] = 'Rick';
        header('Location: index.php');
    }
}

echo json_encode($quotes);
?>

I don't know if you need my model.php (DataBaseAdaptor.php in my case), but here is. Everything related to the database, like all sql operations are working. but in case you need it, find it bellow. Feel free to send edit suggestions to my post if you find model.php not to be necessary( but please, do it only if you are sure it's not necessary). Thanks!

Here is model.php

<?php

//
// Author: Rick Mercer.   File name: model.php
//

class DatabaseAdaptor {
// The instance variable used in every one of the functions in class
DatbaseAdaptor
private $DB;

// Make a connection to an existing data based named 'first' that has table
customer
public function __construct() {
$db = 'mysql:dbname=quotes; charset=utf8; host=127.0.0.1';
$user = 'root';
$password = '';

try {
  $this->DB = new PDO ( $db, $user, $password );
  $this->DB->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo ('Error establishing Connection');
  exit ();
}
}

// Return all records as an associative array.
public function getQuotesAsArray() {
$query = "SELECT * FROM quotations WHERE flagged = 0 ORDER BY rating DESC";

$stmt = $this->DB->prepare($query);
$stmt->execute ();
// fetchall returns all records in the set as an array
return $stmt->fetchAll ( PDO::FETCH_ASSOC );
}

   // Checks if a user exists, if not register the new user
  public function register($username, $password) {
  $query = "SELECT * from users";
  $stmt = $this->DB->prepare($query);
  $stmt->execute ();

// fetchall returns all records in the set as an array
$array = $stmt->fetchAll ( PDO::FETCH_ASSOC );

// If there are no registered users, just register the new user
if(count($array) == 0) {
    $query = "INSERT INTO users (username, hash) VALUES ('$username',
'$password')";
    $stmt = $this->DB->prepare($query);
    $stmt->execute ();
    return true;
 // header( 'Location: index.php' );
}

foreach($array as $item) {
    if($username == $item['username']) {
        return false;
    }
}
    $query = "INSERT INTO users (username, hash) VALUES ('$username', '$password')";
    $stmt = $this->DB->prepare($query);
    $stmt->execute ();
    return true;
   //header( 'Location: index.php' );
 }

 public function addQuote($quote, $author) {
 $query = "INSERT INTO quotations (added, quote, author, rating, flagged)
 VALUES(now(), '$quote', '$author', 0, 0)";
 $stmt = $this->DB->prepare($query);
 $stmt->execute ();
 }

 } // End class DatabaseAdaptor

$theDBA = new DatabaseAdaptor();
?>

Any help is appreciated. Thanks!


问:
How to convert Excel to semicolon or pipe delimited file using script?
I am trying to automate task of converting an Excel workbook to a CSV file. The resulting file should be semicolon and pipe delimited. However I am getting comma separated files only. I tried playing with SaveAs parameters, but no help.

Can somebody suggest a way to do this in VBScript.

Here is my code that is able to convert workbook to CSV. I even tried to replace comma with pipe or semicolon, but that was super buggy resulting in incorrect data.

```<code>Dim strExcelFileName
Dim strCSVFileName
strDelimiter = "|"

strExcelFileName = "file_temp" '

Set fso = CreateObject ("Scripting.FileSystemObject")
strScript = WScript.ScriptFullName
strScriptPath = fso.GetAbsolutePathName(strScript & "\..")
WScript.Echo strScriptPath

'If the Input file is NOT qualified with a path, default the current path
LPosition = InStrRev(strExcelFileName, "\")
If LPosition = 0 Then 'no folder path
    strExcelFileName = strScriptPath & "\file\" & strExcelFileName
    strScriptPath = strScriptPath & "\"
Else 'there is a folder path, use it for the output folder path also
    strScriptPath = Mid(strExcelFileName, 1, LPosition)
End If
'MsgBox LPosition & " - " & strExcelFileName & " - " & strScriptPath  ' use this for debugging

Set objXL = CreateObject("Excel.Application")
Set objWorkBook = objXL.Workbooks.Open(strExcelFileName)
objXL.DisplayAlerts = False

'loop over worksheets
For Each sheet In objWorkBook.Sheets
    'only saveAS sheets that are NOT empty
    If objXL.Application.WorksheetFunction.CountA(sheet.Cells) <> 0 Then
        sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case sheet.Name
        Case "Sales"
            sheet.SaveAs strScriptPath & "abc_sales.csv", 23, local=true 'CSV
        Case "Goals"
            sheet.SaveAs strScriptPath & "abc_file_goals.csv", 6 'CSV
        Case "Commissions"
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        Case Else
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        End Select
    End If
Next

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
Set fso = Nothing
</code>```

Edit I have tried below code to force local setting and windows csv format. but it is stil generating comma separated file. Local setting is set as pipe.

```<code>sheet.SaveAs strScriptPath & "abc.csv", 23, local=true
</code>```

答:
test it:  UPDATED (Field local it is  position 10! )

--for VBScript--

, , , , , , , , , , True
  last position is 'local'

(ty @Lankymart)

--for VBA--

FileFormat := xlCSVWindows, Local := True

then delimiter from regional settings

Default is

Local := False (Default)

Always ','

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-saveas-method-excel

Workbook.SaveAs Method (Excel)

Syntax

expression . SaveAs( FileName , FileFormat , Password , WriteResPassword , ReadOnlyRecommended , CreateBackup , AccessMode , ConflictResolution , AddToMru , TextCodepage , TextVisualLayout , Local )

Local Optional Variant

True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).

BUT in column Description for TextVisualLayout and TextCodepage write:

Ignored for all languages in Microsoft Excel.

IMHO therefore the number of arguments in the function is reduced from 12 to 10

And set format of the file to 23:

XlFileFormat Enumeration (Excel)

Name  Value  Description

xlCSV  6  CSV

xlCSVMac  22  Macintosh CSV

xlCSVMSDOS  24  MSDOS CSV

xlCSVWindows  23  Windows CSV

Now here’s where the interesting part happens… Excel by default will use a comma as the delimiter, but if you open up Control Panel –> Region and Language, and then click the Additional settings button on the bottom…

Now look very closely at the “List separator” item, which normally has a comma in the field, but for the purposes of illustration I’ve switched it to a Pipe character.

List separator Change

I hope this helps!

End solution in short example: for VBScript
(place in file *.vbs)

```<code>Set objXL = CreateObject("Excel.Application")
Path = Replace(WScript.ScriptFullName,WScript.ScriptName, "")
Set objWorkBook = objXL.Workbooks.Open(Path & "file_temp")

objXL.DisplayAlerts = False

'eight comma
objWorkBook.WorkSheets("Sales").SaveAs Path & "abc_sales", 23 , , , , , , , , True

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
</code>```

Script make file abc_sales (type of CSV) in folder of script and with file file_temp (type of Excel with 1 sheet "Sales").

Delimiter set in field List Separatorabove

<img src="https://i.stack.imgur.com/lVHSC.png" alt="Delimiter set in field List Separator">

or Full automatic variant:

```<code>strDelimiter = "|"
strDelimiterPath = "HKCU\Control Panel\International\sList"

Set WshShell = WScript.CreateObject("WScript.Shell")
strOldDelimiter = WshShell.RegRead(strDelimiterPath)
WshShell.RegWrite strDelimiterPath, strDelimiter, "REG_SZ"

Set objXL = CreateObject("Excel.Application")
strPath = Replace(WScript.ScriptFullName,WScript.ScriptName, "")
Set objWorkBook = objXL.Workbooks.Open(strPath & "file_temp")

objXL.DisplayAlerts = False

'eight comma
objWorkBook.WorkSheets("Sales").SaveAs Path & "abc_sales", 23 , , , , , , , , True

'clean up
WshShell.RegWrite strDelimiterPath, strOldDelimiter, "REG_SZ"
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
</code>```

End solution in short example: for VBА
(place in module of file_temp.xlsm)

```<code>Attribute VB_Name = "Module1"
Sub Sheets2CSV()
Set awb = ActiveWorkbook
Sheets.Copy
For Each Sheet In ActiveWorkbook.Sheets
    'only saveAS sheets that are NOT empty
    If Sheet.Application.WorksheetFunction.CountA(Sheet.Cells) <> 0 Then
        Sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case Sheet.Name
        Case "Sales"
            Sheet.SaveAs awb.Path & "\abc_sales", xlCSVWindows, local:=True
        Case "Goals"
            Sheet.SaveAs awb.Path & "\abc_file_goals", xlCSVWindows, local:=True
        Case "Commissions"
            Sheet.SaveAs awb.Path & "\abc_file_coms", xlCSVWindows, local:=True
        Case Else
            Sheet.SaveAs awb.Path & "\abc_file_sheet_" & Sheet.Name, xlCSVWindows, local:=True
        End Select
    End If
Next
ActiveWorkbook.Close 0
End Sub
</code>```

Body:
I am trying to automate task of converting an Excel workbook to a CSV file. The resulting file should be semicolon and pipe delimited. However I am getting comma separated files only. I tried playing with SaveAs parameters, but no help.

Can somebody suggest a way to do this in VBScript.

Here is my code that is able to convert workbook to CSV. I even tried to replace comma with pipe or semicolon, but that was super buggy resulting in incorrect data.

Dim strExcelFileName
Dim strCSVFileName
strDelimiter = "|"

strExcelFileName = "file_temp" '

Set fso = CreateObject ("Scripting.FileSystemObject")
strScript = WScript.ScriptFullName
strScriptPath = fso.GetAbsolutePathName(strScript & "\..")
WScript.Echo strScriptPath

'If the Input file is NOT qualified with a path, default the current path
LPosition = InStrRev(strExcelFileName, "\")
If LPosition = 0 Then 'no folder path
    strExcelFileName = strScriptPath & "\file\" & strExcelFileName
    strScriptPath = strScriptPath & "\"
Else 'there is a folder path, use it for the output folder path also
    strScriptPath = Mid(strExcelFileName, 1, LPosition)
End If
'MsgBox LPosition & " - " & strExcelFileName & " - " & strScriptPath  ' use this for debugging

Set objXL = CreateObject("Excel.Application")
Set objWorkBook = objXL.Workbooks.Open(strExcelFileName)
objXL.DisplayAlerts = False

'loop over worksheets
For Each sheet In objWorkBook.Sheets
    'only saveAS sheets that are NOT empty
    If objXL.Application.WorksheetFunction.CountA(sheet.Cells) <> 0 Then
        sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case sheet.Name
        Case "Sales"
            sheet.SaveAs strScriptPath & "abc_sales.csv", 23, local=true 'CSV
        Case "Goals"
            sheet.SaveAs strScriptPath & "abc_file_goals.csv", 6 'CSV
        Case "Commissions"
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        Case Else
            sheet.SaveAs strScriptPath & "abc_file_coms.csv", 6 'CSV
        End Select
    End If
Next

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing
Set fso = Nothing

Edit I have tried below code to force local setting and windows csv format. but it is stil generating comma separated file. Local setting is set as pipe.

sheet.SaveAs strScriptPath & "abc.csv", 23, local=true

Body:
test it:  UPDATED (Field local it is  position 10! )

--for VBScript--

, , , , , , , , , , True
  last position is 'local'

(ty @Lankymart)

--for VBA--

FileFormat := xlCSVWindows, Local := True

then delimiter from regional settings

Default is

Local := False (Default)

Always ','

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-saveas-method-excel

Workbook.SaveAs Method (Excel)

Syntax

expression . SaveAs( FileName , FileFormat , Password , WriteResPassword , ReadOnlyRecommended , CreateBackup , AccessMode , ConflictResolution , AddToMru , TextCodepage , TextVisualLayout , Local )

Local Optional Variant

True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).

BUT in column Description for TextVisualLayout and TextCodepage write:

Ignored for all languages in Microsoft Excel.

IMHO therefore the number of arguments in the function is reduced from 12 to 10

And set format of the file to 23:

XlFileFormat Enumeration (Excel)

Name  Value  Description

xlCSV  6  CSV

xlCSVMac  22  Macintosh CSV

xlCSVMSDOS  24  MSDOS CSV

xlCSVWindows  23  Windows CSV

Now here’s where the interesting part happens… Excel by default will use a comma as the delimiter, but if you open up Control Panel –> Region and Language, and then click the Additional settings button on the bottom…

Now look very closely at the “List separator” item, which normally has a comma in the field, but for the purposes of illustration I’ve switched it to a Pipe character.

List separator Change

I hope this helps!

End solution in short example: for VBScript
(place in file *.vbs)

Set objXL = CreateObject("Excel.Application")
Path = Replace(WScript.ScriptFullName,WScript.ScriptName, "")
Set objWorkBook = objXL.Workbooks.Open(Path & "file_temp")

objXL.DisplayAlerts = False

'eight comma
objWorkBook.WorkSheets("Sales").SaveAs Path & "abc_sales", 23 , , , , , , , , True

'clean up
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing

Script make file abc_sales (type of CSV) in folder of script and with file file_temp (type of Excel with 1 sheet "Sales").

Delimiter set in field List Separatorabove

or Full automatic variant:

strDelimiter = "|"
strDelimiterPath = "HKCU\Control Panel\International\sList"

Set WshShell = WScript.CreateObject("WScript.Shell")
strOldDelimiter = WshShell.RegRead(strDelimiterPath)
WshShell.RegWrite strDelimiterPath, strDelimiter, "REG_SZ"

Set objXL = CreateObject("Excel.Application")
strPath = Replace(WScript.ScriptFullName,WScript.ScriptName, "")
Set objWorkBook = objXL.Workbooks.Open(strPath & "file_temp")

objXL.DisplayAlerts = False

'eight comma
objWorkBook.WorkSheets("Sales").SaveAs Path & "abc_sales", 23 , , , , , , , , True

'clean up
WshShell.RegWrite strDelimiterPath, strOldDelimiter, "REG_SZ"
objWorkBook.Close
objXL.Quit
Set objXL = Nothing
Set objWorkBook = Nothing

End solution in short example: for VBА
(place in module of file_temp.xlsm)

Attribute VB_Name = "Module1"
Sub Sheets2CSV()
Set awb = ActiveWorkbook
Sheets.Copy
For Each Sheet In ActiveWorkbook.Sheets
    'only saveAS sheets that are NOT empty
    If Sheet.Application.WorksheetFunction.CountA(Sheet.Cells) <> 0 Then
        Sheet.Rows(1).Delete  ' this will remove Row 1 or the header Row
        Select Case Sheet.Name
        Case "Sales"
            Sheet.SaveAs awb.Path & "\abc_sales", xlCSVWindows, local:=True
        Case "Goals"
            Sheet.SaveAs awb.Path & "\abc_file_goals", xlCSVWindows, local:=True
        Case "Commissions"
            Sheet.SaveAs awb.Path & "\abc_file_coms", xlCSVWindows, local:=True
        Case Else
            Sheet.SaveAs awb.Path & "\abc_file_sheet_" & Sheet.Name, xlCSVWindows, local:=True
        End Select
    End If
Next
ActiveWorkbook.Close 0
End Sub


问:
How to make click reveal in css/js?
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

```<code><button type="button" class="btn btn-primary">Phone</button>
<span>+971235051</span>
</code>```

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

答:
here it is, just take advantage of the onclick event handler in JS, attach a custom function to execute n it and in the function do the text change ;)

function myFunction()
{
document.getElementById("toClick").innerHTML = "+971235051";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()" id="toClick">Phone</button></code>```

Title: How to make click reveal in css/js?

Body:
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

<button type="button" class="btn btn-primary">Phone</button>
+971235051

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

Body:
here it is, just take advantage of the onclick event handler in JS, attach a custom function to execute n it and in the function do the text change ;)

function myFunction()
{
document.getElementById("toClick").innerHTML = "+971235051";
}

<button onclick="myFunction()" id="toClick">Phone</button>


问:
Rest response issue || arraylist inside list
I am new to restresponse

My api returns response as:

```<code>{"response":"{}{}{}{}","status":"OK","statusMsg":"Successful"}
</code>```

My js could not read this response.

I want response as below:

```<code>{"response":["{},{},{},{}"],"status":"OK","statusMsg":"Successful"}
</code>```

Below is my code snippet:

```<code>public static Response buildRestResponse(List object, HashMap<Long,HashMap<String,String>> newCol, String headerName, String headerValue) throws JSONException
  {

    RestResponse resp = new RestResponse();
    resp.setStatus(Response.Status.OK);
    ArrayList rows = new ArrayList<>();
    List<Map<String, Object>> rows1 = new ArrayList<>();
    // loop through the obect reveived as parameter
    for (int i=0;i<object.size();i++){
       classA res = (classA) object.get(i);
        try{
            //loop through the new columns
            Iterator it = newCol.entrySet().iterator();
            //JSONObject row = new JSONObject()
            Map<String, Object> row = new HashMap<>();
            row.put("id", res.getId());row.put("name", res.getName());row.put("status",res.getStatus());

            while (it.hasNext()){
                Map.Entry pair = (Map.Entry) it.next();
                if ((Long)pair.getKey() == res.getId()){
                    HashMap<String,String> value =
                                 (HashMap<String,String>)pair.getValue();
                    Iterator iter = value.entrySet().iterator();
                    while(iter.hasNext()){
                        Map.Entry values = (Map.Entry) iter.next();
                        String proValue = (String)values.getKey();
                        row.put(proValue, (String)values.getValue());
                    }

                }
            }

            rows1.add(row);
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }
    rows.add(rows1);
    resp.setResponse(rows);

    resp.setStatusMsg("Successful");

    Response.ResponseBuilder responseBuilder = Response.status((Response.Status)Response.Status.OK).entity((Object)resp);
        responseBuilder.header(headerName, (Object)headerValue);
        return responseBuilder.build();
  }
</code>```

When in my Javascript I try to get results.response returns nothing

答:
Please tell what is being set in   resp.setResponse(rows);
Inside this method, there is a problem.</p>

Body:
I am new to restresponse

My api returns response as:

{"response":"{}{}{}{}","status":"OK","statusMsg":"Successful"}

My js could not read this response.

I want response as below:

{"response":["{},{},{},{}"],"status":"OK","statusMsg":"Successful"}

Below is my code snippet:

public static Response buildRestResponse(List object, HashMap<Long,HashMap<String,String>> newCol, String headerName, String headerValue) throws JSONException
  {

    RestResponse resp = new RestResponse();
    resp.setStatus(Response.Status.OK);
    ArrayList rows = new ArrayList<>();
    List<Map<String, Object>> rows1 = new ArrayList<>();
    // loop through the obect reveived as parameter
    for (int i=0;i<object.size();i++){
       classA res = (classA) object.get(i);
        try{
            //loop through the new columns
            Iterator it = newCol.entrySet().iterator();
            //JSONObject row = new JSONObject()
            Map<String, Object> row = new HashMap<>();
            row.put("id", res.getId());row.put("name", res.getName());row.put("status",res.getStatus());

            while (it.hasNext()){
                Map.Entry pair = (Map.Entry) it.next();
                if ((Long)pair.getKey() == res.getId()){
                    HashMap<String,String> value =
                                 (HashMap<String,String>)pair.getValue();
                    Iterator iter = value.entrySet().iterator();
                    while(iter.hasNext()){
                        Map.Entry values = (Map.Entry) iter.next();
                        String proValue = (String)values.getKey();
                        row.put(proValue, (String)values.getValue());
                    }

                }
            }

            rows1.add(row);
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }
    rows.add(rows1);
    resp.setResponse(rows);

    resp.setStatusMsg("Successful");

    Response.ResponseBuilder responseBuilder = Response.status((Response.Status)Response.Status.OK).entity((Object)resp);
        responseBuilder.header(headerName, (Object)headerValue);
        return responseBuilder.build();
  }

When in my Javascript I try to get results.response returns nothing


问:
throw exception with root cause error in my spring crud operation project
Error: (throw exception with root cause error in my spring crud operation project)

```<code>Error: Nov 14, 2017 12:43:12 PM org.apache.catalina.core.StandardWrapperValve invoke

SEVERE: Servlet.service() for servlet [spring] in context with path

[/Spring4MVCAngularJSExampleLatest] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.websystique.springmvc.service.UserServiceImpl.saveUser(UserServiceImpl.java:56)
    at
com.websystique.springmvc.controller.HelloWorldRestController.createUser(HelloWorldRestController.java:69)
</code>```

(The money was paid in a lump sum at the end of the engagement. My kind master, at my request, granted me a lump sum in place of my annuity. I propose to pay a lump sum on condition that you withdraw the suit at once. This appropriation is not in a lump sum but by allotments or funds.)

Code:

```<code>JavaService Impl:

public void saveUser(User user)
{

System.out.println(user.getAddress()+""+user.getId());//printing successfully

        // user.setId(1);
        ((UserDaoImpl) users).saveOrUpdate(user);// i got error here
         //ud.saveOrUpdate(user);
    }
</code>```

=================================================

UserService.java This is service class

```<code>public interface UserService {

    User findById(long id);

    User findByName(String name);

    void saveUser(User user);

    void updateUser(User user);

    void deleteUserById(long id);

    List<User> findAllUsers();

    void deleteAllUsers();

    public boolean isUserExist(User user);

}
</code>```

========================================================

UserDaoImpl.java:(This is repository impl class)

```<code>public List<User> list() {
        String sql = "SELECT * FROM user12";
        List<User> listContact = jdbcTemplate.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User aContact = new User();

                aContact.setId(rs.getInt("id"));
                aContact.setUsername(rs.getString("username"));
                aContact.setEmail(rs.getString("email"));
                aContact.setAddress(rs.getString("address"));

                System.out.println("ASADADADAS" + rs.getString("username"));
                return aContact;
            }

        });
</code>```

=================================

HelloWorldRestController.java(This is controller class)

```<code>  @RequestMapping(value = "/user/", method = RequestMethod.GET)

    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
       /* if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }*/
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
</code>```

=============================

UserDao.java (this is repository class)

```<code>public interface UserDao {

    public void saveOrUpdate(User user);

    public void delete(int id);

    public User get(long id);

    public List<User> list();

}
</code>```

答:
In the service the ((UserDaoImpl) users) is null. It means it was not injected properly.

The UserDaoImpl must be annotated with @Repository (or @Component) to be a spring bean. Also it should be in component scan package to let Spring find it and create a bean.

Body:
Error: (throw exception with root cause error in my spring crud operation project)

Error: Nov 14, 2017 12:43:12 PM org.apache.catalina.core.StandardWrapperValve invoke

SEVERE: Servlet.service() for servlet [spring] in context with path

[/Spring4MVCAngularJSExampleLatest] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.websystique.springmvc.service.UserServiceImpl.saveUser(UserServiceImpl.java:56)
    at
com.websystique.springmvc.controller.HelloWorldRestController.createUser(HelloWorldRestController.java:69)

(The money was paid in a lump sum at the end of the engagement. My kind master, at my request, granted me a lump sum in place of my annuity. I propose to pay a lump sum on condition that you withdraw the suit at once. This appropriation is not in a lump sum but by allotments or funds.)

Code:

JavaService Impl:

public void saveUser(User user)
{

System.out.println(user.getAddress()+""+user.getId());//printing successfully

        // user.setId(1);
        ((UserDaoImpl) users).saveOrUpdate(user);// i got error here
         //ud.saveOrUpdate(user);
    }

=================================================

UserService.java This is service class

public interface UserService {

    User findById(long id);

    User findByName(String name);

    void saveUser(User user);

    void updateUser(User user);

    void deleteUserById(long id);

    List<User> findAllUsers();

    void deleteAllUsers();

    public boolean isUserExist(User user);

}

========================================================

UserDaoImpl.java:(This is repository impl class)

public List<User> list() {
        String sql = "SELECT * FROM user12";
        List<User> listContact = jdbcTemplate.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User aContact = new User();

                aContact.setId(rs.getInt("id"));
                aContact.setUsername(rs.getString("username"));
                aContact.setEmail(rs.getString("email"));
                aContact.setAddress(rs.getString("address"));

                System.out.println("ASADADADAS" + rs.getString("username"));
                return aContact;
            }

        });

=================================

HelloWorldRestController.java(This is controller class)

  @RequestMapping(value = "/user/", method = RequestMethod.GET)

    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
       /* if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }*/
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

=============================

UserDao.java (this is repository class)

public interface UserDao {

    public void saveOrUpdate(User user);

    public void delete(int id);

    public User get(long id);

    public List<User> list();

}


问:
Any queries to the api.linkedin.com/v2/ return "Not enough permissions to access ..."

I got the Access Token (with scope: r_basicprofile rw_company_admin w_share) using the Client ID, Client Secret at following URLs:

https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/oauth/v2/accessToken

Make request to the https://api.linkedin.com/v2/me endpoint

```<code>curl -H "Authorization: Bearer ACCESS_TOKEN"
    -H "Accept: application/json"
    -H "Content-Type: application/json"
    -H "X-Restli-Protocol-Version: 2.0.0" https://api.linkedin.com/v2/me
</code>```

Get response:

```<code>{
    "serviceErrorCode": 100,
    "message": "Not enough permissions to access /me GET ",
    "status": 403
}
</code>```

Similar erroneous responses are returned to any requests for https://api.linkedin.com/v2/

In official documentation there is difference requirements to headers:

X-Rest**l**i-Protocol-Version

X-Rest**L**i-Protocol-Version

But I tried both, and nothing worked.

Requests to the https://api.linkedin.com/v1/ (using the same token) successfully return data.

Please, tell me what I'm doing wrong.

答:
You need to request permissions from LinkedIn.

Now all requests to api.linkedin.com/v2/ successfully pass to me!

We received permissions (r_ad_campaigns and rw_organization) after request offer by address https://business.linkedin.com/marketing-solutions/marketing-partners/become-a-partner/marketing-developer-program

Leave a request at the address below and LinkedIn will answer you.

Good luck!

Body:
I got the Access Token (with scope: r_basicprofile rw_company_admin w_share) using the Client ID, Client Secret at following URLs:

https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/oauth/v2/accessToken

Make request to the https://api.linkedin.com/v2/me endpoint

curl -H "Authorization: Bearer ACCESS_TOKEN"
    -H "Accept: application/json"
    -H "Content-Type: application/json"
    -H "X-Restli-Protocol-Version: 2.0.0" https://api.linkedin.com/v2/me

Get response:

{
    "serviceErrorCode": 100,
    "message": "Not enough permissions to access /me GET ",
    "status": 403
}

Similar erroneous responses are returned to any requests for https://api.linkedin.com/v2/

In official documentation there is difference requirements to headers:

X-Rest**l**i-Protocol-Version

X-Rest**L**i-Protocol-Version

But I tried both, and nothing worked.

Requests to the https://api.linkedin.com/v1/ (using the same token) successfully return data.

Please, tell me what I'm doing wrong.


问:
Create certificate for SHA-3
I am trying to create a certificate for SHA-3. Which tool can I use to create it?

Currently, I am using SHA-256. Will OpenSSL work in this case? If yes then how?

答:
This is generally not considered a good idea. The idea of using a certificate is to allow other people to verify the identity of whatever you are serving. SHA-3 is still relatively new and support for legacy devices is a problem. This Answer explains more about that in detail.

Further, the post you linked explains how to use a SHA-256 hash for your certificate. SHA-256 belongs to the SHA-2 family, not the SHA-3 family.

Title: Create certificate for SHA-3


问:
Lua os.time does not do not work
I have programed Lua script to a game with function os.clock() and os.time(). Its worked correctly, but after upgrade of this game I have observed fail message : attempt to call global 'os' (a nil value)... ? I thought that os.clock() and os.time() are native function of Lua.

答:
From the Lua reference manual:

Except for the basic and the package libraries, each library provides
  all its functions as fields of a global table or as methods of its
  objects.

To have access to these libraries, the C host program should call the
  luaL_openlibs function, which opens all standard libraries.
  Alternatively, the host program can open them individually by using ... luaopen_os (for the operating system library)...

As you see adding the standard libraries in a host program is optional. Many applications restrict access to standard libraries. Especially os and io.

As the os librarie has not been added to the scripting environment of your game the global table os is nil.

So obviously the developers of your game decided that their users should survive without the os functions. Sometimes they just don't want you to do things, sometimes it just doesn't make sense. It is the simplest way to prevent you from interacting with the operatinig system from inside a game.
Usually they also prevent you from loading external code by removing the necessary functions.

Title: Lua os.time does not do not work


问:
how to iterate throught an array of objects and concate the contents
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

```<code>[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]
</code>```

obj1:

```<code>var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}
</code>```

my attempts:
    //this code was added outside the scope of obj1

```<code>Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});
</code>```

update_1

I added the following lines to obj1:

```<code>getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;
</code>```

and I call it as follows:

```<code>console.log(obj1.getPlaysIn());
</code>```

but the results i get is

```<code>undefined
</code>```

答:
Just iterate the favoritePlayers array

var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ]
}
obj1.favoritePlayers.forEach(function(item) {
  console.log(item.name + ' plays ' + item.club)
})```
</div>
</div>
</p>

<p>If you want to use prototype</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ]
}
Array.prototype.customForEach = function() {
  for (let i = 0; i < this.length; i++) {
    console.log(this[i].name + ' plays ' + this[i].club);

  }
}
obj1.favoritePlayers.customForEach();</code>```

Body:
I have the object (obj1) that is posted below. As shown  in it, it contains an array of objects called "favoritePlayers".

what I am trying to do is, to create a function or add an array prototype so that I can iterate through each element in the array separately and get the following output:

"messi plays in barcelona"
"totti plays in roma"

I tried to solve it as shown below but what I get is

[ 'undefinedplays in[object Object]',
'undefinedplays in[object Object]' ]

obj1:

var obj1 = {
score: [10, 22, 30, 55, 70, 90],
lettersOfMyName: ["a", "m", "r"],
avgScore: null,
favoritePlayers: [
    {
        name: "messi",
        club: "barcelona"
    },

    {
        name: "totti",
        club: "roma"
    }
],

calcAvgScore: function () {
    var sumOfScores = this.score.reduce(function (prev, cur, index, array)
{

        return prev + cur;

    })

    return (sumOfScores / this.score.length);
},

myFavoritePlayersInfo: function () {
    console.log(this.favoritePlayers.join());
},

}

my attempts:
    //this code was added outside the scope of obj1

Array.prototype.concat1 = ( (array) => {
var tempArray = [];

for (var i = 0; i < array.length; i++) {

tempArray[i] = array.slice(i, i+1).name + "plays in" + array.slice(i,
i+1);

}

return tempArray;

});

update_1

I added the following lines to obj1:

getPlaysIn:function() {
    this.favoritePlayers.forEach( (favoritePlayer)=> {
        return favoritePlayer.name + " plays in " + favoritePlayer.club;

and I call it as follows:

console.log(obj1.getPlaysIn());

but the results i get is

undefined

Body:
Just iterate the favoritePlayers array

var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ]
}
obj1.favoritePlayers.forEach(function(item) {
  console.log(item.name + ' plays ' + item.club)
})

If you want to use prototype

var obj1 = {
  score: [10, 22, 30, 55, 70, 90],
  lettersOfMyName: ["a", "m", "r"],
  avgScore: null,
  favoritePlayers: [{
      name: "messi",
      club: "barcelona"
    },

    {
      name: "totti",
      club: "roma"
    }
  ]
}
Array.prototype.customForEach = function() {
  for (let i = 0; i < this.length; i++) {
    console.log(this[i].name + ' plays ' + this[i].club);

  }
}
obj1.favoritePlayers.customForEach();


问:
panel.border in ggplot2 ploting thicker lines in bottom and right side of the plot in CairoPDF device

I am using Cairo setting as

```<code>CairoPDF(file = "test2.pdf", width = 8.3, height = 11.7)
</code>```

and theme setting is like this:

```<code>mytheme<-theme_bw() +
         theme(plot.title = element_text(lineheight=.8, face="bold"),
               text=element_text(size=11, family="Times New Roman"))+
         theme(panel.border = element_rect(linetype = "dashed",
                                           colour = "black"))+
         theme(plot.margin = unit(c(1,1.5,1,1.5), "inches"))
</code>```

I guess, this is a problem with my theme setting for ggplot. please give advice to fix it.
Thanks.

答:
I have the same problem with bottom and right panel borders becoming thicker when sending the above ggplot example code to svg, pdf, cairo_pdf etc.

Here's a workaround that I use in Inkscape which might give some insight to someone with better understanding of R and pdf/svg rendering:

In Inkscape:

select the panel border

object > ungroup (do this twice)

or keyboard shortcut shift+ctrl+G (x2)

So it seems the panel border is grouped with the panel background. Surprisingly rather than the bottom and right becoming thinner, the top and left become thicker. So actually it looks like OP question should be rephrased to "plotting thinner lines in top and left side of plot".

Body:
I am using Cairo setting as

CairoPDF(file = "test2.pdf", width = 8.3, height = 11.7)

and theme setting is like this:

mytheme<-theme_bw() +
         theme(plot.title = element_text(lineheight=.8, face="bold"),
               text=element_text(size=11, family="Times New Roman"))+
         theme(panel.border = element_rect(linetype = "dashed",
                                           colour = "black"))+
         theme(plot.margin = unit(c(1,1.5,1,1.5), "inches"))

I guess, this is a problem with my theme setting for ggplot. please give advice to fix it.
Thanks.


问:
How to mock a function call while initializing a variable in @Tested testObject in junit
I have a class A which has a private integer member b. Here is the structure of the class:

```<code>public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}
</code>```

I am testing some method of this class using jmockit with junit4 `

```<code>public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}
</code>```

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.

答:
First of all the way you are doing this is not very good since you are not able to control values that are returned from class C. But if you want to keep your code like this, you can extract

C.getValue(anyString)

to new protected function in your class

```<code>public class A {

   private int b= Integer.parseInt(getValue(anyString));

   public int getB() {
      return b;
   }

   public void setB(int b) {
      this.b= b;
   }

   protected String getValue(String anyString) {
      return C.getValue(anyString);
   }
}
</code>```

After that you can in your test clas can create new private class that extends  class A and then override its

getValue(String anyString)

function.

In test class:

```<code>public class ATest extends A {

    @Override protected String getValue(String anyString) {
      return "return 1 or any other string reperesentation of number";
   }
}
</code>```

Function getValue(String anyString) in that, let's call it AText class, then can return value of your choice. This way you'll have controlled environment and you can test this new ATest class.

Body:
I have a class A which has a private integer member b. Here is the structure of the class:

public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}

I am testing some method of this class using jmockit with junit4 `

public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.

Body:
First of all the way you are doing this is not very good since you are not able to control values that are returned from class C. But if you want to keep your code like this, you can extract

C.getValue(anyString)

to new protected function in your class

public class A {

   private int b= Integer.parseInt(getValue(anyString));

   public int getB() {
      return b;
   }

   public void setB(int b) {
      this.b= b;
   }

   protected String getValue(String anyString) {
      return C.getValue(anyString);
   }
}

After that you can in your test clas can create new private class that extends  class A and then override its

getValue(String anyString)

function.

In test class:

public class ATest extends A {

    @Override protected String getValue(String anyString) {
      return "return 1 or any other string reperesentation of number";
   }
}

Function getValue(String anyString) in that, let's call it AText class, then can return value of your choice. This way you'll have controlled environment and you can test this new ATest class.


问:
resolving promise from another function
How does promise chaining inside a function works?
In the following code:

```<code>     promiseA() {
            return anotherPromise().then( res => {
                   // resolution of promise A
             })
     };

      promiseB() {
             promiseA().then( res => {
                     // resolution of promise B
              })
      }
</code>```

I tested this code and I get that resolution of B is always done after A is resolved. However, I can't find any documentation. Will resolution of promise B always happens after resolution of Promise A done, or is my test just one case of race condition?

答:
You have invoked the Promise A inside Promise B, so by logic Promise A should be resolved before Promise B.</p>

```<code>Promise.then( // resolved first )
       .then( // resolved second )
</code>```

Title: resolving promise from another function

Body:
How does promise chaining inside a function works?
In the following code:

     promiseA() {
            return anotherPromise().then( res => {
                   // resolution of promise A
             })
     };

      promiseB() {
             promiseA().then( res => {
                     // resolution of promise B
              })
      }

I tested this code and I get that resolution of B is always done after A is resolved. However, I can't find any documentation. Will resolution of promise B always happens after resolution of Promise A done, or is my test just one case of race condition?

Body:
You have invoked the Promise A inside Promise B, so by logic Promise A should be resolved before Promise B.

Promise.then( // resolved first )
       .then( // resolved second )


答:
Try this with jquery

$('#btn').on('click', function() {
    if($('#btn').text() != 'Phone') {
        $('#btn').text('Phone');
    } else {
        $('#btn').text('+971235051');
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button type="button" id="btn" class="btn btn-primary">Phone</button></code>```

This with javascript

function fns() {
  var elem = document.getElementById("btn");
  if (elem.innerHTML == "Phone") {
    elem.innerHTML = "+971235051";
  } else {
    elem.innerHTML = "Phone";
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" id="btn" onclick="fns()" class="btn btn-primary">Phone</button></code>```

Title: How to make click reveal in css/js?

Body:
Try this with jquery

$('#btn').on('click', function() {
    if($('#btn').text() != 'Phone') {
        $('#btn').text('Phone');
    } else {
        $('#btn').text('+971235051');
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button type="button" id="btn" class="btn btn-primary">Phone</button>

This with javascript

function fns() {
  var elem = document.getElementById("btn");
  if (elem.innerHTML == "Phone") {
    elem.innerHTML = "+971235051";
  } else {
    elem.innerHTML = "Phone";
  }

}

<button type="button" id="btn" onclick="fns()" class="btn btn-primary">Phone</button>


答:
I think that there is a problem in the code:

```<code>if(isset($_GET['p']) && isset($_GET['q'])) {
     $user = isset($_GET['p']);
     $pass = isset($_GET['q']);

}
</code>```

$user and $pass will always get the value 0 or 1 and therefore the next part of your code

```<code>for ($i = 0; $i < count($quotes); $i++){
    if($user === $quotes[$i][0]) {
        $_SESSION['user'] = 'Rick';
        header('Location: index.php');
    }
}
</code>```

will be unlikely to evaluate to true (unless the $quotes array has the values 0 or 1) and the header redirection will not fire.

Looks to me like the user and password should be set as follows:

```<code>if(isset($_GET['p']) && isset($_GET['q'])) {
     $user =$_GET['p'];
     $pass = $_GET['q'];
}
</code>```

Hopefully this is the problem.

Title: Can't figured why header location is not working for this case (php)

Body:
I think that there is a problem in the code:

if(isset($_GET['p']) && isset($_GET['q'])) {
     $user = isset($_GET['p']);
     $pass = isset($_GET['q']);

}

$user and $pass will always get the value 0 or 1 and therefore the next part of your code

for ($i = 0; $i < count($quotes); $i++){
    if($user === $quotes[$i][0]) {
        $_SESSION['user'] = 'Rick';
        header('Location: index.php');
    }
}

will be unlikely to evaluate to true (unless the $quotes array has the values 0 or 1) and the header redirection will not fire.

Looks to me like the user and password should be set as follows:

if(isset($_GET['p']) && isset($_GET['q'])) {
     $user =$_GET['p'];
     $pass = $_GET['q'];
}

Hopefully this is the problem.


问:
keystroke generation
I have a scenario where i need to generate all possible keystrokes using numbers 2 to 9. The possible keystrokes should generate 2-git, 3-digit etc upto 32-digit numbers. can anybody tell me what is the best way to solve this problem.

Thanks,
Pdit

答: Start with some simple analysis to consider feasibility.  One digit has 8 possible values.  Two digits have 8 x 8.  Etc.  Now grab your calculator and compute 8 ^ 32.</p>

OwnerDisplayName: Pdit

Title: keystroke generation

OwnerDisplayName: nobugz


问:
angular4 local variable issue for *ngFor
I have a requirement where I have load multiple items using item list. Whenever you upload a file, upload file input has to hide and details of that file has to show like filename and other button.

I implemented the scenario by using a localvariable, it works fine with one item, but when we have multiple items, its not working.
Assume if I have 3 itemList, if we click on 1st item fileupload button and upload a file, it loads filename and validate button, but if we do same process for 2nd item (after 1st process), after fileupload, 1st filename will be modified.

View:

```<code><div id="userItemList" *ngFor="let item of itemList; let i=index">
    <div>
        <span>{{item.Id}}</span>
        <span>{{item.Name}}</span>
        <span>{{item.Count}}</span>
    </div>
    <div>
        <input type="file" name="UploadFile" id="fileInput" #fileInput (change)="txtUploadFile($event,i)">
        <div class="validate-file-div" #validateContent style="display:none">
            <div class="file-name" #fileName></div>
            <span id="validate-csv-button" data-program-id="0" class="button">Validate</span>
        </div>
    </div>
</div>
</code>```

My component look like:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-programs-manager',
  templateUrl: './ProgramsManager.component.html',
  styleUrls: ['./ProgramsManager.component.css'],
})

export class ProgramsManagerComponent implements OnInit {

    itemList = [{"Id":1,"Name":"Item1","Count":2},{"Id":2,"Name":"Item2","Count":2},{"Id":3,"Name":"Item3","Count":3}];
    @ViewChild("fileInput") fileInput;
    @ViewChild("validateContent") validateContent;
    @ViewChild("fileName") fileName;

    constructor() { }

    ngOnInit() {
    }

    txtUploadFile(event,index) {
        this.fileInput.nativeElement.style.display = "none";
        this.validateContent.nativeElement.style.display = "block";
        this.fileInput.nativeElement.innerHTML = event.target.files[0].name;
    }
}
</code>```

I feel local variable is giving problem,but don't know how to fix it. can anyone help me.
Thanks in advance

答:
All you need to do is use @ViewChildren instead of @ViewChild

```<code>@ViewChildren("fileInput") fileInput : QueryList<any>;
@ViewChildren("validateContent") validateContent : QueryList<any>;
@ViewChildren("fileName") fileName : QueryList<any>;
</code>```

And change function txtUploadFile to

```<code>txtUploadFile(event,index) {
    var fileInputs = this.fileInput.toArray();
    var validateContents = this.validateContent.toArray();

    fileInputs[index].nativeElement.style.display = "none";
    validateContents[index].nativeElement.style.display = "block";
    fileInputs[index].nativeElement.innerHTML = event.target.files[0].name;
}
</code>```

Here is the link of working example :

https://stackblitz.com/edit/angular-view-children

Extra Notes :

@ViewChild:

You can use ViewChild to get the first element or the directive
  matching the selector from the view DOM. If the view DOM changes, and
  a new child matches the selector, the property will be updated.

@ViewChildren:

You can use ViewChildren to get the QueryList of elements or
  directives from the view DOM. Any time a child element is added,
  removed, or moved, the query list will be updated, and the changes
  observable of the query list will emit a new value.

Body:
I have a requirement where I have load multiple items using item list. Whenever you upload a file, upload file input has to hide and details of that file has to show like filename and other button.

I implemented the scenario by using a localvariable, it works fine with one item, but when we have multiple items, its not working.
Assume if I have 3 itemList, if we click on 1st item fileupload button and upload a file, it loads filename and validate button, but if we do same process for 2nd item (after 1st process), after fileupload, 1st filename will be modified.

View:

        {{item.Id}}
        {{item.Name}}
        {{item.Count}}

        <input type="file" name="UploadFile" id="fileInput" #fileInput (change)="txtUploadFile($event,i)">

            Validate

My component look like:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-programs-manager',
  templateUrl: './ProgramsManager.component.html',
  styleUrls: ['./ProgramsManager.component.css'],
})

export class ProgramsManagerComponent implements OnInit {

    itemList = [{"Id":1,"Name":"Item1","Count":2},{"Id":2,"Name":"Item2","Count":2},{"Id":3,"Name":"Item3","Count":3}];
    @ViewChild("fileInput") fileInput;
    @ViewChild("validateContent") validateContent;
    @ViewChild("fileName") fileName;

    constructor() { }

    ngOnInit() {
    }

    txtUploadFile(event,index) {
        this.fileInput.nativeElement.style.display = "none";
        this.validateContent.nativeElement.style.display = "block";
        this.fileInput.nativeElement.innerHTML = event.target.files[0].name;
    }
}

I feel local variable is giving problem,but don't know how to fix it. can anyone help me.
Thanks in advance

Body:
All you need to do is use @ViewChildren instead of @ViewChild

@ViewChildren("fileInput") fileInput : QueryList<any>;
@ViewChildren("validateContent") validateContent : QueryList<any>;
@ViewChildren("fileName") fileName : QueryList<any>;

And change function txtUploadFile to

txtUploadFile(event,index) {
    var fileInputs = this.fileInput.toArray();
    var validateContents = this.validateContent.toArray();

    fileInputs[index].nativeElement.style.display = "none";
    validateContents[index].nativeElement.style.display = "block";
    fileInputs[index].nativeElement.innerHTML = event.target.files[0].name;
}

Here is the link of working example :

https://stackblitz.com/edit/angular-view-children

Extra Notes :

@ViewChild:

You can use ViewChild to get the first element or the directive
  matching the selector from the view DOM. If the view DOM changes, and
  a new child matches the selector, the property will be updated.

@ViewChildren:

You can use ViewChildren to get the QueryList of elements or
  directives from the view DOM. Any time a child element is added,
  removed, or moved, the query list will be updated, and the changes
  observable of the query list will emit a new value.


问:
Angular 4 hide button
When i click the 1st button how i can show 2nd button and hide 1st button, and want to click 2nd button and then show 1st button and hide 2nd button</p>

```<code><button class="btn" type="button" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" name="button" (click)="followed()">followed</button>
</code>```

答:
If I understand the question correctly, I think it's more of making the two buttons visible/hidden as supposed to enabling/disabling them. </p>

<p>This is probably what I would do. </p>

```<code><button class="btn" type="button" *ngIf="isVisible" name="button" (click)="toggle()">follow</button>
<button class="btn" type="button" *ngIf="!isVisible" name="button" (click)="toggle()">followed</button>

export class AppComponent {
    public isVisible: boolean = true;
    toggle() {
        this.isVisible = !this.isVisible;
    }
}
</code>```

Title: Angular 4 hide button

Body:
When i click the 1st button how i can show 2nd button and hide 1st button, and want to click 2nd button and then show 1st button and hide 2nd button

<button class="btn" type="button" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" name="button" (click)="followed()">followed</button>

Body:
If I understand the question correctly, I think it's more of making the two buttons visible/hidden as supposed to enabling/disabling them.

This is probably what I would do.

<button class="btn" type="button" *ngIf="isVisible" name="button" (click)="toggle()">follow</button>
<button class="btn" type="button" *ngIf="!isVisible" name="button" (click)="toggle()">followed</button>

export class AppComponent {
    public isVisible: boolean = true;
    toggle() {
        this.isVisible = !this.isVisible;
    }
}


问:
Cannot set "ExternalId" because only strings can be used as values to set XmlNode properties
I am trying to convert a .CSV file into a .XML file using PowerShell.

Here is my code:

```<code>[xml]$xml = "
<Cv>
<Owner>
    <ExternalId></ExternalId>
    <Name></Name>
</Owner>
<Content>
   <Educations>
   </Educations>
</Content>
</Cv>"

$basePath= "C:\Users\test\source\CERTSUMMARY.CSV"
$targetBase = "C:\Users\test\source\target"

$sert = Import-CSV $basePath -Delimiter ';'

foreach ($person in $sert) {
    $xml2 = $xml.Clone()
    $xml2.Cv.Owner.ExternalId = $person.Användarnamn
    $xml2.Cv.Owner.Name = $person.Namn
</code>```

I've looked here for an answer and tried the suggestions that other developers has said. I've tried to put [string]$person.Användarnamn, I've tried $xml2.Cv.Owner.ExternalId.ToString() and I have also tried to change the values inside the CSV file, but without any result.

The error message is as the topic says:

"Cannot set "ExternalId" because only strings can be used as values to set XmlNode properties."

答:
Most likely you have an encoding issue there. Your column title contains a special character (ä) that isn't defined in ASCII (the encoding Import-Csv uses by default), so the property most likely shows up as Anv?ndarnamn (you can verify by echoing $sert[0]). In that case the imported objects have no property Användarnamn. Since PowerShell expands non-existent properties to $null the statement

```<code>$xml2.Cv.Owner.ExternalId = $person.Användarnamn
</code>```

would try to assign $null to the XML node, which doesn't work.

Try importing the file with the Default encoding:

```<code>$sert = Import-Csv $basePath -Delimiter ';' -Encoding Default
</code>```

If that doesn't help you probably need to save the CSV in a format that does support special characters (e.g. UTF8).

Body:
I am trying to convert a .CSV file into a .XML file using PowerShell.

Here is my code:

[xml]$xml = "
<Cv>
<Owner>
    <ExternalId></ExternalId>
    <Name></Name>
</Owner>
<Content>
   <Educations>
   </Educations>
</Content>
</Cv>"

$basePath= "C:\Users\test\source\CERTSUMMARY.CSV"
$targetBase = "C:\Users\test\source\target"

$sert = Import-CSV $basePath -Delimiter ';'

foreach ($person in $sert) {
    $xml2 = $xml.Clone()
    $xml2.Cv.Owner.ExternalId = $person.Användarnamn
    $xml2.Cv.Owner.Name = $person.Namn

I've looked here for an answer and tried the suggestions that other developers has said. I've tried to put [string]$person.Användarnamn, I've tried $xml2.Cv.Owner.ExternalId.ToString() and I have also tried to change the values inside the CSV file, but without any result.

The error message is as the topic says:

"Cannot set "ExternalId" because only strings can be used as values to set XmlNode properties."

Body:
Most likely you have an encoding issue there. Your column title contains a special character (ä) that isn't defined in ASCII (the encoding Import-Csv uses by default), so the property most likely shows up as Anv?ndarnamn (you can verify by echoing $sert[0]). In that case the imported objects have no property Användarnamn. Since PowerShell expands non-existent properties to $null the statement

$xml2.Cv.Owner.ExternalId = $person.Användarnamn

would try to assign $null to the XML node, which doesn't work.

Try importing the file with the Default encoding:

$sert = Import-Csv $basePath -Delimiter ';' -Encoding Default

If that doesn't help you probably need to save the CSV in a format that does support special characters (e.g. UTF8).


问:
Pyspark dataframe operator "IS NOT IN"
I would like to rewrite this from R to Pyspark, any nice looking suggestions?</p>

```<code>array <- c(1,2,3)
dataset <- filter(!(column %in% array))
</code>```

答:
slightly different syntax and a "date" data set:</p>

```<code>toGetDates={'2017-11-09', '2017-11-11', '2017-11-12'}
df= df.filter(df['DATE'].isin(toGetDates) == False)
</code>```

Title: Pyspark dataframe operator "IS NOT IN"

Body:
I would like to rewrite this from R to Pyspark, any nice looking suggestions?

array <- c(1,2,3)
dataset <- filter(!(column %in% array))

Body:
slightly different syntax and a "date" data set:

toGetDates={'2017-11-09', '2017-11-11', '2017-11-12'}
df= df.filter(df['DATE'].isin(toGetDates) == False)