问:
Convert float64 column to datetime pandas
I have the following pandas DataFrame column dfA['TradeDate']:

```<code>0     20100329.0
1     20100328.0
2     20100329.0
...
</code>```

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')
</code>```

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')
</code>```

It returns: must be a Str and not Series.

答:
In your first attempt you tried to convert it to string and then pass to strptime, which resulted in ValueError. This happens because dfA['TradeDate'].astype('int').to_string() creates a single string containing all dates as well as their row numbers. You can change this to

```<code>dates = dfA['TradeDate'].astype('int').to_string(index=False).split()
dates
[u'20100329.0', u'20100328.0', u'20100329.0']
</code>```

to get a list of dates. Then use python list comprehension to convert each element to datetime:

```<code>dfA['TradeDate'] = [datetime.strptime(x, '%Y%m%d.0') for x in dates]
</code>```

Body:
I have the following pandas DataFrame column dfA['TradeDate']:

0     20100329.0
1     20100328.0
2     20100329.0
...

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')

It returns: must be a Str and not Series.

Body:
In your first attempt you tried to convert it to string and then pass to strptime, which resulted in ValueError. This happens because dfA['TradeDate'].astype('int').to_string() creates a single string containing all dates as well as their row numbers. You can change this to

dates = dfA['TradeDate'].astype('int').to_string(index=False).split()
dates
[u'20100329.0', u'20100328.0', u'20100329.0']

to get a list of dates. Then use python list comprehension to convert each element to datetime:

dfA['TradeDate'] = [datetime.strptime(x, '%Y%m%d.0') for x in dates]


来源: stackexchange

问:
How to filter array using same key value of(preview_url and countries code) and return higher amount of array and unmatch array data will be same
I have this array i want sorting using same preview_url and same countries code and want result which array have higher amount of value and unmatch array data remain same.
I want result i have add in comment please provide sollution for same i have stuck on this issue from couple of days

Thanks in advance

```<code>Array
(
    [id] => 377556
    [amount] => 1.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                    [regions] => Array
                        (
                        )
                )
        )
)
Array
(
    [id] => 377557
    [amount] => 2.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                )
            [UK] => Array
                (
                    [id] => 841
                    [code] => UK
                    [name] => united kingdom
                )
        )
)
</code>```

答:
You have to use multisort

```<code>$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);
$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);
</code>```

now my array will

```<code>array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this array i want sorting using same preview_url and same countries code and want result which array have higher amount of value and unmatch array data remain same.
I want result i have add in comment please provide sollution for same i have stuck on this issue from couple of days

Thanks in advance

Array
(
    [id] => 377556
    [amount] => 1.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                    [regions] => Array
                        (
                        )
                )
        )
)
Array
(
    [id] => 377557
    [amount] => 2.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                )
            [UK] => Array
                (
                    [id] => 841
                    [code] => UK
                    [name] => united kingdom
                )
        )
)

Body:
You have to use multisort

$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);
$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);

now my array will

array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)


问:
UINavigationBar failing to change color
I'm trying to change the background color / bar tint color of my nav bars programatically.

I have tried several examples, but some required writing code in every view controller which doesn't make the most sense to me, as I would like to have it subclassed to reduce repeated code.

I created a subclass of UINavigationBar (as I also wanted to change the height).

I have successfully changed the height and it works in my application. However, when changing the color, it doesn't appear to work.

```<code>class Navbars: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    //self.backgroundColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    //self.barTintColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    self.backgroundColor = UIColor.blue
    self.barTintColor = UIColor.blue
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func draw(_ rect: CGRect) {

}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 205)
}
}
</code>```

The height changes, so I presumed having the code to change it's color in the init function would work, but it doesn't, and I'm not sure why.

I even then tried to subclass UINavigationController and still nothing happens.

```<code>class NavControllers: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationBar.barTintColor = UIColor.brown

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

If anyone knows where I am going wrong, that would be much appreciated. Thank you!

答:
Trying the following in a playground works fine for me…

```<code>class NavController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.barTintColor = .red
    }
}

let viewController = UIViewController()
viewController.view.backgroundColor = .white

let navController = NavController(rootViewController: viewController)
</code>```

Title: UINavigationBar failing to change color

Body:
I'm trying to change the background color / bar tint color of my nav bars programatically.

I have tried several examples, but some required writing code in every view controller which doesn't make the most sense to me, as I would like to have it subclassed to reduce repeated code.

I created a subclass of UINavigationBar (as I also wanted to change the height).

I have successfully changed the height and it works in my application. However, when changing the color, it doesn't appear to work.

class Navbars: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    //self.backgroundColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    //self.barTintColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    self.backgroundColor = UIColor.blue
    self.barTintColor = UIColor.blue
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func draw(_ rect: CGRect) {

}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 205)
}
}

The height changes, so I presumed having the code to change it's color in the init function would work, but it doesn't, and I'm not sure why.

I even then tried to subclass UINavigationController and still nothing happens.

class NavControllers: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationBar.barTintColor = UIColor.brown

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

If anyone knows where I am going wrong, that would be much appreciated. Thank you!

Body:
Trying the following in a playground works fine for me…

class NavController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.barTintColor = .red
    }
}

let viewController = UIViewController()
viewController.view.backgroundColor = .white

let navController = NavController(rootViewController: viewController)


问:
Android: Find API calls requiring permissions
I'm making changes to existing code to make it compliant with the new permissions model in Android M. The app declares the READ_PHONE_STATE permission in its manifest which will require me to prompt the user to grant it at runtime. How can I locate all API calls which require this permission so I can prompt the user? I tried commenting out the permission from the manifest but the app built without errors in Android Studio 1.5.1. I also ran the lint tool while making sure that permission checking is turned on as described here but found no errors.</p>

答:
Maybe a bit late, just found the following threads, hopefully still can help.
How to find required Android Marshmallow runtime permissions in code? and How to find out which permission an android application needs</p>


问:
How to detect input field value change in ng-repeat
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/></code>```

答:
The question you linked in your question is not about Angular (it uses jQuery). Where is the Angular way to do it (considering you are showing inputs with ng-repeat):

```<code><div ng-repeat="i in items">
    <input ng-model="i" ng-change="update(i)"/>
</div>
</code>```

With this code, whenever you will update i (eg: when you will change the input value), the update(i) method will be triggered.

Here is a tiny example of what I'm explaining:

function MyCtrl($scope) {
    $scope.items = ['1', '2', '3', '4', '5'];

    $scope.update = function(item) {
        alert(item + ' has been changed!');
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
    <div ng-repeat="i in items">
        <input type="text" ng-model="i" ng-change="update(i)"  />
    </div>
</div></code>```

Body:
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}

//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/>

Body:
The question you linked in your question is not about Angular (it uses jQuery). Where is the Angular way to do it (considering you are showing inputs with ng-repeat):

<div ng-repeat="i in items">
    <input ng-model="i" ng-change="update(i)"/>
</div>

With this code, whenever you will update i (eg: when you will change the input value), the update(i) method will be triggered.

Here is a tiny example of what I'm explaining:

function MyCtrl($scope) {
    $scope.items = ['1', '2', '3', '4', '5'];

    $scope.update = function(item) {
        alert(item + ' has been changed!');
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
    <div ng-repeat="i in items">
        <input type="text" ng-model="i" ng-change="update(i)"  />
    </div>
</div>


问:
Form is submitted even after using e.preventDefault()
I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.

```<code>$('#corporate-signup').on('submit',function(e){

    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
           e.preventDefault(e);
       }

       else{
           $('#corporate-signup').submit()
           }

    });

});
</code>```

I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.

答:
I think that because you use an async function and don't return false, it goes ahead and submits before waiting for an answer - it doesn't know to wait for the callback.

Since you manually submit inside the async callback, try to add e.preventDefault(e); after the $.get:

```<code>var shouldSubmit = false;
$('#corporate-signup').on('submit',function(e){
    if (!shouldSubmit) {
        // First time entering, this won't submit due to line below
        e.preventDefault(e);
        var ifsc_code = $('#ifsc-code').val();
        var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
        $.get(api_url, function(data, status){

           if (data.status === "failure") {
               $('.bank-details').addClass('no-ifsc').text(data.message);
           }

           else{
               shouldSubmit = true;
               $('#corporate-signup').submit()
           }

        });
    }
});
</code>```

Edit: added shouldSubmit boolean, since otherwise it would keep hitting e.preventDefault(e) and never submitting. Upon a successful result from the async request, you can set it to true and resubmit.

Body:
I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.

$('#corporate-signup').on('submit',function(e){

    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
           e.preventDefault(e);
       }

       else{
           $('#corporate-signup').submit()
           }

    });

});

I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.

Body:
I think that because you use an async function and don't return false, it goes ahead and submits before waiting for an answer - it doesn't know to wait for the callback.

Since you manually submit inside the async callback, try to add e.preventDefault(e); after the $.get:

var shouldSubmit = false;
$('#corporate-signup').on('submit',function(e){
    if (!shouldSubmit) {
        // First time entering, this won't submit due to line below
        e.preventDefault(e);
        var ifsc_code = $('#ifsc-code').val();
        var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
        $.get(api_url, function(data, status){

           if (data.status === "failure") {
               $('.bank-details').addClass('no-ifsc').text(data.message);
           }

           else{
               shouldSubmit = true;
               $('#corporate-signup').submit()
           }

        });
    }
});

Edit: added shouldSubmit boolean, since otherwise it would keep hitting e.preventDefault(e) and never submitting. Upon a successful result from the async request, you can set it to true and resubmit.


问:
How do I deserialize Drupal JSON Services strings in Android?
I am using Drupal Services along with the JSON Services module as a data source.

I am using the DrupalCloud library, https://github.com/skyred/DrupalCloud/wiki, and am wondering how to best process the results that I receive from a userLogin() call.

If the call itself fails we get:

```<code>{
  "#error": true,
  "#message": "Some message"
}
</code>```

If the call succeeds but the login credentials are wrong:

```<code>{
  "#error": false,
  "#data": {
    "#error": true,
    "#message": "Some message"
  }
}
</code>```

If the call success and the login credentials are correct, it returns:

```<code>{
  "#error": false,
  "#data": {
    "sessid": "foo",
    "user": {
      "uid": "69",
      "name": "Russell Jones",
      "pass": "bar",
      "mail": "russell@test.net",
      "roles": {
        "2": "authenticated user",
        "5": "Student"
      },
    }
  }
}
</code>```

How do I go about using this data meaningfully?  Or rather, how do I test to see if the call worked, and if the login was successful or not.

答:
Have you searched older posts? Like this post, from 2 hours ago:
how to convert json object into class object
or: JSON Parsing in Android

Or just search for yourself: Search: Android+Json
Should give you a good idea..

ContentLicense: CC BY-SA 2.5

Body:
I am using Drupal Services along with the JSON Services module as a data source.

I am using the DrupalCloud library, https://github.com/skyred/DrupalCloud/wiki, and am wondering how to best process the results that I receive from a userLogin() call.

If the call itself fails we get:

{
  "#error": true,
  "#message": "Some message"
}

If the call succeeds but the login credentials are wrong:

{
  "#error": false,
  "#data": {
    "#error": true,
    "#message": "Some message"
  }
}

If the call success and the login credentials are correct, it returns:

{
  "#error": false,
  "#data": {
    "sessid": "foo",
    "user": {
      "uid": "69",
      "name": "Russell Jones",
      "pass": "bar",
      "mail": "russell@test.net",
      "roles": {
        "2": "authenticated user",
        "5": "Student"
      },
    }
  }
}

How do I go about using this data meaningfully?  Or rather, how do I test to see if the call worked, and if the login was successful or not.


问:
How to remove Accept-char header from HTTP post request
I am using rest template for creating HTTP post request . But request contain by default added Accept-char header with huge Content . Please suggest how to exclude addition of that header. Below is the code i am using:

```<code>HttpHeader header= new HttpHeader();
RestTemplate template = new RestTemplate();

header.setContentType("application/xml");

String body=" content of body ";

HttpEntity<string>  request=new HttpEntity<string> (body,header);

template.postForObject(URL,request,String.class);
</code>```

答:
This should remove 'Accept-Charset' header:</p>

```<code>StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
stringHttpMessageConverter.setWriteAcceptCharset(false);
restTemplate.getMessageConverters().add(0, stringHttpMessageConverter);
</code>```

Body:
I am using rest template for creating HTTP post request . But request contain by default added Accept-char header with huge Content . Please suggest how to exclude addition of that header. Below is the code i am using:

HttpHeader header= new HttpHeader();
RestTemplate template = new RestTemplate();

header.setContentType("application/xml");

String body=" content of body ";

HttpEntity<string>  request=new HttpEntity<string> (body,header);

template.postForObject(URL,request,String.class);

Body:
This should remove 'Accept-Charset' header:

StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
stringHttpMessageConverter.setWriteAcceptCharset(false);
restTemplate.getMessageConverters().add(0, stringHttpMessageConverter);


问:
How can I deploy my Angular 2 + Typescript + Webpack app
I am actually learning Angular 2 with Typescript and developed a little app by based on the angular-seed project (angular-seed). I have built the app for production purposes and got dist folder ready to be deployed containing my bundle files like this:

```<code>dist/
  main.bundle.js
  main.map
  polyfills.bundle.js
  polyfills.map
  vendor.bundle.js
  vendor.map
</code>```

However, as a fresher, I have no idea how to deploy it now on my EC2 server. I read that I have to config Nginx server to serve my static file but do I have to config it particularly to work with my bundle files?

Excuse my mistakes if any. Thanks a lot in advance!

答:
A quicker way to deploy is as below:

1. Install nginx as mentioned by Herman.

2. Copy your dist/* files to /var/www/html/ without disturbing /etc/nginx/sites-available/default.

    sudo cp /your/path/to/dist/* /var/www/html/

3. Restart nginx:

    sudo systemctl restart nginx

Body:
I am actually learning Angular 2 with Typescript and developed a little app by based on the angular-seed project (angular-seed). I have built the app for production purposes and got dist folder ready to be deployed containing my bundle files like this:

dist/
  main.bundle.js
  main.map
  polyfills.bundle.js
  polyfills.map
  vendor.bundle.js
  vendor.map

However, as a fresher, I have no idea how to deploy it now on my EC2 server. I read that I have to config Nginx server to serve my static file but do I have to config it particularly to work with my bundle files?

Excuse my mistakes if any. Thanks a lot in advance!


问:
C++ - Method/Member access
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

```<code>class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

        return(EXIT_SUCCESS);
}
</code>```

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?

答:
Once you've fiddled around with the machine code, you're no longer compiling C++, but you're programming directly in machine code.

Your question is therefore somewhat moot.

You can regard the access specifiers as being essentially compile time directives, but note that the compiler can make optimisation choices based on them. In other words, it could be either. The C++ standard doesn't have to say anything about this either.

Title: C++ - Method/Member access

Body:
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

        return(EXIT_SUCCESS);
}

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?


问:
Tags not found in neovim, but work in vim
I have a tags file which is being generated and placed in my project's directory and set tags=./tags,tags;/ placed in my init.vim (edit: this was to ensure that the configuration is the same across both editors)

The crazy thing is that, when looking for tags in neovim (v0.1.7), nothing is found, however tagbar (majutsushi/tagbar) seems to find these tags correctly. Furthermore, I have set tags to point directly to the tag file (set tags=/home/<me/project/>tags) with no change in outcome. When I perform the same steps in vim (v8.0, 2016 Sep 12) these tags are found correctly.

Does neovim handle ctags in a different way from vim or am I missing something simple?

Thanks

EDIT:

@Justin M. Keyes is correct in the behavior of vim and neovim. I failed to ask the vague question of "why is my system broken" since there was not a whole lot to go on, but the answer to this, for me, was found here:

Why can't vim see the tags file, despite being in the same directory? - Vi and Vim Exchange (beta)

In my case the vim-scripts/gitignore plugin was adding patterns to my wildignore variable which obscured my editor from finding my tags file.

答:
set tags=./tags,tags;/ is an unsual choice. As mentioned at :help 'tags', the default in nvim is:

```<code>'tags' 'tag'            string  (default "./tags;,tags")
</code>```

Try not setting the 'tags' option, use the default instead.

when looking for tags in neovim (v0.1.7), nothing is found, however tagbar (majutsushi/tagbar) seems to find these tags correctly

It's not unlikely that tagbar looks in places other than what is specified by the 'tags' option.

Does neovim handle ctags in a different way from vim

No, only the default changed.

Body:
set tags=./tags,tags;/ is an unsual choice. As mentioned at :help 'tags', the default in nvim is:

'tags' 'tag'            string  (default "./tags;,tags")

Try not setting the 'tags' option, use the default instead.

when looking for tags in neovim (v0.1.7), nothing is found, however tagbar (majutsushi/tagbar) seems to find these tags correctly

It's not unlikely that tagbar looks in places other than what is specified by the 'tags' option.

Does neovim handle ctags in a different way from vim

No, only the default changed.


问:
How to set object property (of object property of..) given its string name in JavaScript?

Suppose we are only given

var obj = {};
var propName = "foo.bar.foobar";
```

<p>How can we set the property <code>obj.foo.bar.foobar</code> to a certain value (say "hello world")?
So I want to achieve this, while we only have the property name in a string:</p>

<pre class="lang-js prettyprint-override"><code>obj.foo.bar.foobar = "hello world";
</code>```

答:
You could split the path and make a check if the following element exist. If not assign an object to the new property.

Return then the value of the property.

At the end assign the value.

function setValue(object, path, value) {
    var fullPath = path.split('.'),
        way = fullPath.slice(),
        last = way.pop();

    way.reduce(function (r, a) {
        return r[a] = r[a] || {};
    }, object)[last] = value;
}

var object = {},
    propName = 'foo.bar.foobar',
    value = 'hello world';

setValue(object, propName, value);
console.log(object);```

Body:
Suppose we are only given

var obj = {};
var propName = "foo.bar.foobar";

How can we set the property obj.foo.bar.foobar to a certain value (say "hello world")?
So I want to achieve this, while we only have the property name in a string:

obj.foo.bar.foobar = "hello world";


问:
How to format an OID Subject Alt Name entry in a openssl.cnf file
I need to add the following SAN to a certifacate:

```<code>oid:1.2.3.4.5.5
</code>```

My normal certificate creation process is to generate an openssl.cnf file, then using this file generate a csr (certificate signing request), and then generate a certificate from the csr using my own CA.

The .cnf file is a plain text file which contains a section describing all the SANs that I would like included in the csr and eventually the crt. That section looks like this:

```<code>...
[san]
DNS.1 = foo.bar
DNS.2 = baz.foobar
IP.1 = 1.1.1.1
IP.2 = 2.2.2.2
...
</code>```

I have tried inserting the OID entry 3 different ways:

```<code>attempt 1) OID.1 = 1.2.3.4.5.5
attempt 2) DNS.3 = 1.2.3.4.5.5
attempt 3) IP.3 = 1.2.3.4.5.5
</code>```

With 1) I get an error when trying to generate the certificate, indicating that the prefix OID is unrecognized. With 2) and 3) I am able to generate the crt, but when I put it in place the SAN oid:1.2.3.4.5.5 is not supported.

So, I am wondering what the correct syntax would be for adding such and entry to the Subject Alternative Names section of an openssl.cnf file.

Cheers!

答:
Based on Steffen Ullrich's answer, this version correctly specifies the OID identifier in a complete example:

```<code>subjectAltName=@san
[san]
DNS.1=foo.example.com
DNS.2=bar.example.com
RID.1=1.2.3.4.5.5
</code>```

Alternatively, do it on one line:

```<code>subjectAltName=DNS:foo.example.com,DNS:bar.example.com,RID:1.2.3.4.5.5
</code>```

This is particularly useful when combined with https://security.stackexchange.com/a/91556 to pass -config options to the CLI without using a .cnf file.

Body:
I need to add the following SAN to a certifacate:

oid:1.2.3.4.5.5

My normal certificate creation process is to generate an openssl.cnf file, then using this file generate a csr (certificate signing request), and then generate a certificate from the csr using my own CA.

The .cnf file is a plain text file which contains a section describing all the SANs that I would like included in the csr and eventually the crt. That section looks like this:

...
[san]
DNS.1 = foo.bar
DNS.2 = baz.foobar
IP.1 = 1.1.1.1
IP.2 = 2.2.2.2
...

I have tried inserting the OID entry 3 different ways:

attempt 1) OID.1 = 1.2.3.4.5.5
attempt 2) DNS.3 = 1.2.3.4.5.5
attempt 3) IP.3 = 1.2.3.4.5.5

With 1) I get an error when trying to generate the certificate, indicating that the prefix OID is unrecognized. With 2) and 3) I am able to generate the crt, but when I put it in place the SAN oid:1.2.3.4.5.5 is not supported.

So, I am wondering what the correct syntax would be for adding such and entry to the Subject Alternative Names section of an openssl.cnf file.

Cheers!

Body:
Based on Steffen Ullrich's answer, this version correctly specifies the OID identifier in a complete example:

subjectAltName=@san
[san]
DNS.1=foo.example.com
DNS.2=bar.example.com
RID.1=1.2.3.4.5.5

Alternatively, do it on one line:

subjectAltName=DNS:foo.example.com,DNS:bar.example.com,RID:1.2.3.4.5.5

This is particularly useful when combined with https://security.stackexchange.com/a/91556 to pass -config options to the CLI without using a .cnf file.


问:
How socket send data?
I got a snippet from internet for send data through a socket .

Here is the code .

```<code>u32_t nLength = 0;
u32_t nOffset = 0;

do {
    nLength = nFullLength - nOffset;
    status = Socket->Send(((u8_t*) buff) + nOffset, &nLength);
    if (status != ERROR_SUCCESS) {
        break;
    }
    nOffset += nLength;
} while (nOffset < nFullLength);
</code>```

My doubts are :

When send(sock_fd, buf+bytes, buflen-bytes, flags); function running , it will send the entire data ?

Let's assume i have a buff with 45 byte length . So it will send like

```<code>send(buf+0, 45-0) = send(buf+0, 45);
</code>```

So it will send complete  data with length 45 ? what is the use of length here ? initially it will 45 . Isn't ?

答:
Well, no. There's no guarantee that it will send all the data you ask it to send, that's why the code looks the way it does.

The manual page for send() states this pretty clearly:

Return Value

On success, these calls return the number of characters sent. On error, -1
  is returned, and errno is set appropriately.

The same is true for e.g. a regular write() to a local file, by the way. It might never happen, but the way the interface is designed you're supposed to handle partial sends (and writes) if they do happen.

Title: How socket send data?

Body:
I got a snippet from internet for send data through a socket .

Here is the code .

u32_t nLength = 0;
u32_t nOffset = 0;

do {
    nLength = nFullLength - nOffset;
    status = Socket->Send(((u8_t*) buff) + nOffset, &nLength);
    if (status != ERROR_SUCCESS) {
        break;
    }
    nOffset += nLength;
} while (nOffset < nFullLength);

My doubts are :

When send(sock_fd, buf+bytes, buflen-bytes, flags); function running , it will send the entire data ?

Let's assume i have a buff with 45 byte length . So it will send like

send(buf+0, 45-0) = send(buf+0, 45);

So it will send complete  data with length 45 ? what is the use of length here ? initially it will 45 . Isn't ?


问:
Is possible to use multiple retrofit API
I am using retrofit 2. I need to use 2 different Rest API, because they have different base URL, headers and cookies.

```<code>public class RestClient {

private static IRestApi REST_CLIENT;

static {
    setupRestClient();
}

public static IRestApi get() {
    return REST_CLIENT;
}

private static void setupRestClient() {

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
      //add some cookies & headers
        }
    };

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(GenericConstants.READ_TIMEOUT, TimeUnit.SECONDS)
            .connectTimeout(GenericConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(GenericConstants.BASE_ENDPOINT_INSTAGRAM)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    REST_CLIENT = retrofit.create(IRestApi.class);
    }
}
</code>```

I am using it like so:

```<code>Call<Obj> call = RestClient.get().myMethod(params);
</code>```

I want to create 2 clases like this, because I have 2 types of requests, 1 with headers and cookies and one plain, is this possible?

答:
you can create method of retrofit url like

```<code>public Retrofit getAdapter(String url){
      Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

      return retrofit;
}
</code>```

Use this adapter wherever you want.

Body:
I am using retrofit 2. I need to use 2 different Rest API, because they have different base URL, headers and cookies.

public class RestClient {

private static IRestApi REST_CLIENT;

static {
    setupRestClient();
}

public static IRestApi get() {
    return REST_CLIENT;
}

private static void setupRestClient() {

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
      //add some cookies & headers
        }
    };

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(GenericConstants.READ_TIMEOUT, TimeUnit.SECONDS)
            .connectTimeout(GenericConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(GenericConstants.BASE_ENDPOINT_INSTAGRAM)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    REST_CLIENT = retrofit.create(IRestApi.class);
    }
}

I am using it like so:

Call<Obj> call = RestClient.get().myMethod(params);

I want to create 2 clases like this, because I have 2 types of requests, 1 with headers and cookies and one plain, is this possible?

Body:
you can create method of retrofit url like

public Retrofit getAdapter(String url){
      Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

      return retrofit;
}

Use this adapter wherever you want.


问:
Configure UICollectionViewCells having same cell type but different UI styles
I have a UICollectionView that has the same cell type, but every cell has different UI properties like background color, textColor ...

I could configure them inside collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell as below:

```<code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let item = indexPath.item
    switch item {
    case 1:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.text = xxx
        cell.ScoreName.textColor = xxx
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.....

        return cell
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as BCollectionViewCell
        cell.title.text = "xxx xxx"
        cell.score.isHidden = true
        return cell
    default:

        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as DCollectionViewCell
        cell.title.text = "xxx"
        cell.score.text = "xx"
        cell.score.backgroundColor = .green
        cell....
        return cell
    }
}
</code>```

As you can see from case 1 to 5 same cell type with different UI properties, it is not appealing at all also it is not scalable so what is the best approach to deal with such configuration ?

答: background color, textColor, etc. should be added as variables in the object you use to populate that collection view. Each object will have its own variables which will be used to customize the cell.</p>

Body:
I have a UICollectionView that has the same cell type, but every cell has different UI properties like background color, textColor ...

I could configure them inside collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell as below:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let item = indexPath.item
    switch item {
    case 1:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
        cell.ScoreName.text = xxx
        cell.ScoreName.textColor = xxx
        cell.score.text = xxx
        cell.score.backgroundColor = xxx
        cell.....

        return cell
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as BCollectionViewCell
        cell.title.text = "xxx xxx"
        cell.score.isHidden = true
        return cell
    default:

        let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as DCollectionViewCell
        cell.title.text = "xxx"
        cell.score.text = "xx"
        cell.score.backgroundColor = .green
        cell....
        return cell
    }
}

As you can see from case 1 to 5 same cell type with different UI properties, it is not appealing at all also it is not scalable so what is the best approach to deal with such configuration ?


问:
Retrofit enqueue doesn't work but execute work
I'm using com.squareup.retrofit2:retrofit:2.2.0

```<code>    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)
</code>```

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

```<code>  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });
</code>```

答:
You can try this full Answer Link

Here is the shortest code snippest.

```<code>    private void emailLoginRequest() {
    LoginService loginService = ApiFactory.createService(LoginService.class);
    Call<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            hideProgressDialog();
            if (response.isSuccessful()) {
                LOGD(TAG, "onResponse 0: " + response.body().toString());
                LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class);

                System.out.println("+++ get message >> " + loginResponse.getMessage());
                int status = loginResponse.getStatus();

            }else {
                LOGD(TAG, "response fail 0: " + response.body());
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            hideProgressDialog();
            LOGD(TAG, "onFailure: " + t.getMessage());
        }
    });
}
</code>```

Body:
I'm using com.squareup.retrofit2:retrofit:2.2.0

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });

Body:
You can try this full Answer Link

Here is the shortest code snippest.

    private void emailLoginRequest() {
    LoginService loginService = ApiFactory.createService(LoginService.class);
    Call<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            hideProgressDialog();
            if (response.isSuccessful()) {
                LOGD(TAG, "onResponse 0: " + response.body().toString());
                LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class);

                System.out.println("+++ get message >> " + loginResponse.getMessage());
                int status = loginResponse.getStatus();

            }else {
                LOGD(TAG, "response fail 0: " + response.body());
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            hideProgressDialog();
            LOGD(TAG, "onFailure: " + t.getMessage());
        }
    });
}


问:
How do I test Rails block helpers with rSpec
In my views I use a helper that takes arbitrary HTML as a block:

```<code><% some_block_helper do %>
  Some arbitrary HTML and ERB variables here.
  More HTML here.
<% end %>
</code>```

My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.

答:
Here's another example that expands on Cameron's answer</p>

```<code>describe SomeHelper do
  it 'should do something' do
    content = lambda { "blah" }
    result  = helper.some_block_helper(&content)

    result.should include("blah")
    result.should XXX
  end
end
</code>```

OwnerDisplayName: ismaSan

Body:
In my views I use a helper that takes arbitrary HTML as a block:

<% some_block_helper do %>
  Some arbitrary HTML and ERB variables here.
  More HTML here.
<% end %>

My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.

Body:
Here's another example that expands on Cameron's answer

describe SomeHelper do
  it 'should do something' do
    content = lambda { "blah" }
    result  = helper.some_block_helper(&content)

    result.should include("blah")
    result.should XXX
  end
end


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib / Image not found
I am running my app from xcode to my iOS device and I get this and black screen on iOS device.

Console text:

```<code>dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/10DB2FE8-EF09-4857-B4AC-0DB2E4419D6F/App-Name.app/App-Name
Reason: image not found
(lldb)
</code>```

答:
Oh yes. I've faced with that problem spending hours on solution.
You may try to set "Always Embed Swift Standard Libraries" to "Yes" under your Build Settings > Build Options

(don't forget to shift+cmd+K your project after)

Body:
I am running my app from xcode to my iOS device and I get this and black screen on iOS device.

Console text:

dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/10DB2FE8-EF09-4857-B4AC-0DB2E4419D6F/App-Name.app/App-Name
Reason: image not found
(lldb)


问:
How to setup timer resolution to 0.5 ms?
I want to set a machine timer resolution to 0.5ms.

Sysinternal utility reports that the min clock resolution is 0.5ms so it can be done.

P.S. I know how to set it to 1ms.

P.P.S. I changed it from C# to more general question (thanks to Hans)

System timer resolution

答:
If you use python, I wrote a library named wres, which calls NtSetTimerResolution internally.

pip install wres

import wres

# Set resolution to 0.5 ms (in 100-ns units)
# Automatically restore previous resolution when exit with statement
with wres.set_resolution(5000):
    pass
```


问:
Java Reading Strings to a 2D Boolean Array
I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.

With the help of similar posts i got together a code, although they were reading integers to an array.

My code is:

```<code>public static void main(String[] args) {
    String x;
    String y;
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    x = fileName.nextLine();
    y = fileName.nextLine();

    boolean[][] cells = new boolean[x][y];

    String finalX = fileName.nextLine();
    String finalY = fileName.nextLine();
    cells[finalX][finalY] = true;

    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells[i].length; j++) {
            if (cells[i][j])
                System.out.print("#");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}
</code>```

In my code where I have written boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

At what point is my issue? If I parse to an Int, then it can't read the # correct?

答:
It says the [x] and [y] requires an int, but found a string. The same
  issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an
  error: Exception in thread "main" java.lang.NumberFormatException: For
  input string: "#####################"

One approach you could do is first read the entire file.

Example:

```<code>List<String> tempList = new ArrayList<>();

while (fileName.hasNextLine()) {
     String line = fileName.nextLine();
     tempList.add(line);
}
</code>```

then you can do this:

```<code>boolean[][] cells = new boolean[tempList.size()][tempList.get(0).length()];
</code>```

note - this solution assumes the length() of each line is the same and the columns of each line is the same.

Also, why do you need to perform this outside the loop?

```<code>cells[finalX][finalY] = true;
</code>```

you should remove that line and let the loop do all the work to determine what's # or ' '. Also, your if condition doesn't seem to be doing the correct operation. Consider implementing this approach and then go on from there.

Body:
I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.

With the help of similar posts i got together a code, although they were reading integers to an array.

My code is:

public static void main(String[] args) {
    String x;
    String y;
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    x = fileName.nextLine();
    y = fileName.nextLine();

    boolean[][] cells = new boolean[x][y];

    String finalX = fileName.nextLine();
    String finalY = fileName.nextLine();
    cells[finalX][finalY] = true;

    for (int i = 0; i < cells.length; i++) {
        for (int j = 0; j < cells[i].length; j++) {
            if (cells[i][j])
                System.out.print("#");
            else
                System.out.print(" ");
        }
        System.out.println();
    }

}

In my code where I have written boolean[][] cells = new boolean[x][y];

It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"

At what point is my issue? If I parse to an Int, then it can't read the # correct?

Body:
It says the [x] and [y] requires an int, but found a string. The same
  issue is for cells[finalX][finalY] = true;

I tried parsing i.e. Integer.parseInt(x) however this gets me an
  error: Exception in thread "main" java.lang.NumberFormatException: For
  input string: "#####################"

One approach you could do is first read the entire file.

Example:

List<String> tempList = new ArrayList<>();

while (fileName.hasNextLine()) {
     String line = fileName.nextLine();
     tempList.add(line);
}

then you can do this:

boolean[][] cells = new boolean[tempList.size()][tempList.get(0).length()];

note - this solution assumes the length() of each line is the same and the columns of each line is the same.

Also, why do you need to perform this outside the loop?

cells[finalX][finalY] = true;

you should remove that line and let the loop do all the work to determine what's # or ' '. Also, your if condition doesn't seem to be doing the correct operation. Consider implementing this approach and then go on from there.


问:
Track database inserts with specific data
I'm maintaining ASP.NET MVC application, which talks to MS SQL database via Entity Framework.

For some time we are observing cases when entities are updated or inserted into the database with specific field null.

This field may be null, but we strongly suspect, that most of these situations should not happen. I'd like to hook some debug code to log all instances of such attempts.

The problem is that I have no idea, where should I do it.

Entity is inserted and updated in a lot of places in code;

I might override Insert and Update methods of its DBSet descendent, but I won't catch changes caused indirectly (for instance by retrieving the entity from the database, changing it and calling SaveChanges() ).

Where can I put the code, which will be able to access all write modifications to the database on a specific entity?

答:
I believe you're looking for the ChangeTracking property of your DbContext.

I use a similar method to build history on entities, by capturing what has been changed/added/deleted.

To do this, you can, within your DbContext, override the SaveChanges() method and then intercept the entries that are changing.

Be sure to call base.SaveChanges(); at the end of your override to actually save any changes.

Here for example, lets say your DbContext is called MyAppDbContext

```<code>public partial class MyAppDbContext : DbContext
{
    public override int SaveChanges()
    {
         ChangeTracker.Entries().ToList().ForEach(entry =>
        {

            // entry, here, is DbEntityEntry.
            // it will allow you to see original and new values,
            // such as entry.OriginalValues
            // and entry.CurrentValues
            // You can also find its type
            // entry.Entity.GetType()

            switch (entry.State)
            {
                case EntityState.Detached:
                    break;
                case EntityState.Unchanged:
                    break;
                case EntityState.Added:
                    break;
                case EntityState.Deleted:
                    break;
                case EntityState.Modified:
                    break;
            }
        });

       // call the base.SaveChanges();
       base.SaveChanges();
    }

}
</code>```

Body:
I believe you're looking for the ChangeTracking property of your DbContext.

I use a similar method to build history on entities, by capturing what has been changed/added/deleted.

To do this, you can, within your DbContext, override the SaveChanges() method and then intercept the entries that are changing.

Be sure to call base.SaveChanges(); at the end of your override to actually save any changes.

Here for example, lets say your DbContext is called MyAppDbContext

public partial class MyAppDbContext : DbContext
{
    public override int SaveChanges()
    {
         ChangeTracker.Entries().ToList().ForEach(entry =>
        {

            // entry, here, is DbEntityEntry.
            // it will allow you to see original and new values,
            // such as entry.OriginalValues
            // and entry.CurrentValues
            // You can also find its type
            // entry.Entity.GetType()

            switch (entry.State)
            {
                case EntityState.Detached:
                    break;
                case EntityState.Unchanged:
                    break;
                case EntityState.Added:
                    break;
                case EntityState.Deleted:
                    break;
                case EntityState.Modified:
                    break;
            }
        });

       // call the base.SaveChanges();
       base.SaveChanges();
    }

}


问:
Get columns from MySQL and display in PHP
I`ve created table where i want to store some page content

```<code>CREATE TABLE `option` (
  `id` int(11) NOT NULL,
  `parametr` text COLLATE utf8_unicode_ci NOT NULL,
  `value` text COLLATE utf8_unicode_ci NOT NULL,
  `status` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

For example filled with this parametrs

```<code>id  parametr      value                    status
1   title         test                     active
2   subtitle      subtest                  active
3   category      machine                  active
4   description   detailed_description     active
</code>```

Then i want to display only choosen id in different parts of page.
Currently i'm doing this as below, however it`s not allowed me to display multiple parametrs in different places without starting placing the same code in new place where i want it ( test,subtest,detailed_description and somewhere machine)

```<code><div class="title-section">
    <?php
     $sel_option = "SELECT value FROM option WHERE status = 'active' AND id = '1' ";
     $run_option = mysqli_query($connect,$sel_option);
     while ($rows = mysqli_fetch_assoc($run_option)) {
     echo '<h3>'.$rows['value'].'</h3>';}
     ?>
</code>```

How to do it with different way ?

答:
I am not pretty sure what you need exactly, but if I understood well, you don't want to run the query every time you need to show a title, subtitle, category or description, right?

Try it:

```<code><html>
    <body>
        <p><h3 id="title">Ronaldo</h3></p>
        <p><h3 id="subtitle">The Brazilian Soccer Player Legend</h3></p>
        <p><h3 id="category">Soccer</h3></p>
        <p><h3 id="description">Ronaldo Luís Nazário de Lima commonly known as Ronaldo.</h3></p>

        <script type="text/javascript">
    <?php
        $sel_option = "SELECT parametr, value FROM option WHERE status = 'active'";
        $run_option = mysqli_query($connect,$sel_option);
        while ($rows = mysqli_fetch_assoc($run_option)) {
            echo 'var a = document.getElementById("'.$rows['parametr'].'");';
            echo 'a.innerHTML = "'.$rows['value'].'";';
        }
    ?>
        </script>
    </body>
</html>
</code>```

Body:
I`ve created table where i want to store some page content

CREATE TABLE `option` (
  `id` int(11) NOT NULL,
  `parametr` text COLLATE utf8_unicode_ci NOT NULL,
  `value` text COLLATE utf8_unicode_ci NOT NULL,
  `status` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

For example filled with this parametrs

id  parametr      value                    status
1   title         test                     active
2   subtitle      subtest                  active
3   category      machine                  active
4   description   detailed_description     active

Then i want to display only choosen id in different parts of page.
Currently i'm doing this as below, however it`s not allowed me to display multiple parametrs in different places without starting placing the same code in new place where i want it ( test,subtest,detailed_description and somewhere machine)

    <?php
     $sel_option = "SELECT value FROM option WHERE status = 'active' AND id = '1' ";
     $run_option = mysqli_query($connect,$sel_option);
     while ($rows = mysqli_fetch_assoc($run_option)) {
     echo '
'.$rows['value'].'
';}
     ?>

How to do it with different way ?

Body:
I am not pretty sure what you need exactly, but if I understood well, you don't want to run the query every time you need to show a title, subtitle, category or description, right?

Try it:

<html>
    <body>
        <p><h3 id="title">Ronaldo</h3></p>
        <p><h3 id="subtitle">The Brazilian Soccer Player Legend</h3></p>
        <p><h3 id="category">Soccer</h3></p>
        <p><h3 id="description">Ronaldo Luís Nazário de Lima commonly known as Ronaldo.</h3></p>

        <script type="text/javascript">
    <?php
        $sel_option = "SELECT parametr, value FROM option WHERE status = 'active'";
        $run_option = mysqli_query($connect,$sel_option);
        while ($rows = mysqli_fetch_assoc($run_option)) {
            echo 'var a = document.getElementById("'.$rows['parametr'].'");';
            echo 'a.innerHTML = "'.$rows['value'].'";';
        }
    ?>
        </script>
    </body>
</html>


问:
How to pass container ip as ENV to other container in docker-compose file
this is my docker-compose file:

```<code>version: '3.0'
services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: $(APP_DB_IP)
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db

 app-db:
  build: ./db
  expose:
   - "5432"

  volumes:
   - /var/lib/postgresql/data
</code>```

I want to pass to app-web the ip of app-db (Postgresql in this case) as ENV var so it can connect to the DB smoothly... any idea on how to achieve it?

答:
You can use app-db as name instead of ip, docker will automatically determine what the right ip. As stated in the Docker docs: A container can always discover other containers on the same stack using just the container name as hostname.

So in your example you can use:

```<code>environment:
    PG_HOST: app-db
</code>```

Source:https://docs.docker.com/docker-cloud/apps/service-links/#discovering-containers-on-the-same-service-or-stack

Body:
this is my docker-compose file:

version: '3.0'
services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: $(APP_DB_IP)
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db

 app-db:
  build: ./db
  expose:
   - "5432"

  volumes:
   - /var/lib/postgresql/data

I want to pass to app-web the ip of app-db (Postgresql in this case) as ENV var so it can connect to the DB smoothly... any idea on how to achieve it?

Body:
You can use app-db as name instead of ip, docker will automatically determine what the right ip. As stated in the Docker docs: A container can always discover other containers on the same stack using just the container name as hostname.

So in your example you can use:

environment:
    PG_HOST: app-db

Source:https://docs.docker.com/docker-cloud/apps/service-links/#discovering-containers-on-the-same-service-or-stack


问:
Passing data from a class to same instance of a viewcontroller
When a specific event happens(in my case when a tab bar is changed) I want to create a new link from an Array. I have gotten this to work but the problem I am not facing is when i try to pass the generated link to the same viewcontroller i get an error

fatal error: unexpectedly found nil while unwrapping an Optional value

This happens when I try to change the UILabel movietitle and imageview. I think this is because every time it sends the link it creates a new ViewController instead of using the existing one. Might also be that i have missed an unwrapped value somewhere. Hope someone here can help me!

StringBuilder:

```<code>import UIKit

class StringBuilder: NSObject {

let urlString = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acb9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=12"

let urlStringMultipleGenres = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbf5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=28,12,10749"
var currentGenreArray: Array<Int> = []

//This will be run after the user has selected or deselected genres in the genreControllerView
func updateGenres(genreArrayIn: Array<Int>){
    print("update genres input: ")
    print(genreArrayIn)

    //If new array input is the same as old arrayinput, do nothing
    if genreArrayIn == currentGenreArray{
        return
    }
    else{
        let returnedLink = generateString(genreID: genreArrayIn)
        print("Returned link after generate string" + returnedLink)
        sendLink(link: returnedLink)
    }

}
//After the updated genres have been put into an Array, this function will generate the whole string which
//will be the main String the getMovieRequest follows
func generateString(genreID: Array<Int>) -> String{

    let filteredGenreArray = filterZeroes(unfilteredArray: genreID)

    currentGenreArray = genreID
    print("current genre array: ")
    print(currentGenreArray)

    let baseString = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbfed4ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres="
    var generatedString = baseString

    for id in filteredGenreArray{
        let k = String(id)
        generatedString += k + ","
    }
    print("Generated Link from Strinbuilder: ")
    print(generatedString)

    return generatedString
}
func filterZeroes(unfilteredArray: Array<Int>) -> Array<Int>{

    let filteredGenreArray = unfilteredArray.filter {$0 > 0}
    print("filtered array: ")
    print(filteredGenreArray)
    return filteredGenreArray
}

func sendLink(link: String){
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let movieVC = storyBoard.instantiateViewController(withIdentifier: "movieView") as! ViewController

    movieVC.getMovieData(activeGenreLink: link)
    print("new link sent from sendlink()")
}
</code>```

}

ViewController:

```<code>import UIKit
import Alamofire
import AlamofireImage

class ViewController: UIViewController{

static let sharedInstance = ViewController()

var movieIndex = 0
var movieArray:[Movie] = []
var downloadGrp = DispatchGroup()

@IBOutlet var uiMovieTitle: UILabel!

@IBOutlet var uiMoviePoster: UIImageView!

@IBOutlet var posterLoading: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let firstTimeLink = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acb9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=35,18"

    getMovieData(activeGenreLink: firstTimeLink)

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    uiMoviePoster.isUserInteractionEnabled = true
    uiMoviePoster.addGestureRecognizer(tapGestureRecognizer)
    print("settings Sucessful")
}

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){

     performSegue(withIdentifier: "detailsSegue", sender: self)
    }

@IBAction func yesBtn(_ sender: UIButton) {
    movieIndex += 1
    updateUI()
}

@IBAction func seenBtn(_ sender: UIButton) {
    movieIndex += 1
}

@IBAction func noBtn(_ sender: UIButton) {
    movieIndex += 1
}

//Get movie data

func getMovieData(activeGenreLink: String){

    //self.posterLoading.startAnimating()

    movieIndex = 0
    self.downloadGrp.enter()
        Alamofire.request(activeGenreLink).responseJSON { response in
            //print(response.request)  // original URL request
            //print(response.response) // HTTP URL response
            //print(response.data)     // server data
            //print(response.result)   // result of response serialization

            self.movieArray = []

            print(self.movieArray)
            if let json = response.result.value as? Dictionary<String,AnyObject> {
                if let movies = json["results"] as? [AnyObject]{
                    for movie in movies{
                        let movieObject: Movie = Movie()

                        let title = movie["title"] as! String
                        let releaseDate = movie["release_date"] as! String
                        let posterPath = movie["poster_path"] as! String
                        let overView = movie["overview"] as! String
                        let movieId = movie["id"] as! Int
                        let genre_ids = movie["genre_ids"] as! [AnyObject]

                        movieObject.title = title
                        movieObject.movieRelease = releaseDate
                        movieObject.posterPath = posterPath
                        movieObject.overView = overView
                        movieObject.movieId = movieId

                        for genre in genre_ids{//Genre ids, fix this
                            movieObject.movieGenre.append(genre as! Int)
                        }

                        Alamofire.request("http://image.tmdb.org/t/p/w1920" + posterPath).responseImage {
                            response in
                            //print(response.request)
                            //print(response.response)
                            //debugPrint(response.result)

                            if var image = response.result.value {
                                image = UIImage(data: response.data!)!

                                movieObject.poster = image
                            }
                        }

                        self.movieArray.append(movieObject)

                    }//End of for each movie
                }
                else{
                    print("error while making results anyobject")
                }
            }
            else{
            print("error while trying to make NSDictionary")}
     self.downloadGrp.leave()
    }//End of Json request

    downloadGrp.notify( queue: .main){
        print("all downloads finished")

        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
            print(self.movieArray[0].title!)
            self.updateUI()
            print("updatedUI")
        }

    }

}//End of getmoviedata

override func prepare(for segue: UIStoryboardSegue,sender: Any?){

    // Create a variable that you want to send
    let currentMovie = self.movieArray[movieIndex]

    if let destinationVC = segue.destination as? DetailsViewController{
        destinationVC.currentMovie = currentMovie
    }

}

func updateUI(){
    //self.posterLoading.stopAnimating()
    if uiMoviePoster == nil{
    print(uiMovieTitle.debugDescription)
    }
    else{
        print("first time debugID: " + uiMovieTitle.debugDescription)
    uiMovieTitle.text = self.movieArray[movieIndex].title
    uiMoviePoster.image = self.movieArray[movieIndex].poster
    }

}

}
</code>```

答:
You want to grab a sharedInstance not instantiate from a storyboard

```<code>let movieVC = ViewController.sharedInstance()
</code>```

but I still do not understand why do you need to do it like this

Body:
When a specific event happens(in my case when a tab bar is changed) I want to create a new link from an Array. I have gotten this to work but the problem I am not facing is when i try to pass the generated link to the same viewcontroller i get an error

fatal error: unexpectedly found nil while unwrapping an Optional value

This happens when I try to change the UILabel movietitle and imageview. I think this is because every time it sends the link it creates a new ViewController instead of using the existing one. Might also be that i have missed an unwrapped value somewhere. Hope someone here can help me!

StringBuilder:

import UIKit

class StringBuilder: NSObject {

let urlString = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acb9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=12"

let urlStringMultipleGenres = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbf5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=28,12,10749"
var currentGenreArray: Array<Int> = []

//This will be run after the user has selected or deselected genres in the genreControllerView
func updateGenres(genreArrayIn: Array<Int>){
    print("update genres input: ")
    print(genreArrayIn)

    //If new array input is the same as old arrayinput, do nothing
    if genreArrayIn == currentGenreArray{
        return
    }
    else{
        let returnedLink = generateString(genreID: genreArrayIn)
        print("Returned link after generate string" + returnedLink)
        sendLink(link: returnedLink)
    }

}
//After the updated genres have been put into an Array, this function will generate the whole string which
//will be the main String the getMovieRequest follows
func generateString(genreID: Array<Int>) -> String{

    let filteredGenreArray = filterZeroes(unfilteredArray: genreID)

    currentGenreArray = genreID
    print("current genre array: ")
    print(currentGenreArray)

    let baseString = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acbfed4ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres="
    var generatedString = baseString

    for id in filteredGenreArray{
        let k = String(id)
        generatedString += k + ","
    }
    print("Generated Link from Strinbuilder: ")
    print(generatedString)

    return generatedString
}
func filterZeroes(unfilteredArray: Array<Int>) -> Array<Int>{

    let filteredGenreArray = unfilteredArray.filter {$0 > 0}
    print("filtered array: ")
    print(filteredGenreArray)
    return filteredGenreArray
}

func sendLink(link: String){
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let movieVC = storyBoard.instantiateViewController(withIdentifier: "movieView") as! ViewController

    movieVC.getMovieData(activeGenreLink: link)
    print("new link sent from sendlink()")
}

}

ViewController:

import UIKit
import Alamofire
import AlamofireImage

class ViewController: UIViewController{

static let sharedInstance = ViewController()

var movieIndex = 0
var movieArray:[Movie] = []
var downloadGrp = DispatchGroup()

@IBOutlet var uiMovieTitle: UILabel!

@IBOutlet var uiMoviePoster: UIImageView!

@IBOutlet var posterLoading: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let firstTimeLink = "https://api.themoviedb.org/3/discover/movie?api_key=935f539acb9e5534ddeed3fb57e&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=35,18"

    getMovieData(activeGenreLink: firstTimeLink)

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    uiMoviePoster.isUserInteractionEnabled = true
    uiMoviePoster.addGestureRecognizer(tapGestureRecognizer)
    print("settings Sucessful")
}

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){

     performSegue(withIdentifier: "detailsSegue", sender: self)
    }

@IBAction func yesBtn(_ sender: UIButton) {
    movieIndex += 1
    updateUI()
}

@IBAction func seenBtn(_ sender: UIButton) {
    movieIndex += 1
}

@IBAction func noBtn(_ sender: UIButton) {
    movieIndex += 1
}

//Get movie data

func getMovieData(activeGenreLink: String){

    //self.posterLoading.startAnimating()

    movieIndex = 0
    self.downloadGrp.enter()
        Alamofire.request(activeGenreLink).responseJSON { response in
            //print(response.request)  // original URL request
            //print(response.response) // HTTP URL response
            //print(response.data)     // server data
            //print(response.result)   // result of response serialization

            self.movieArray = []

            print(self.movieArray)
            if let json = response.result.value as? Dictionary<String,AnyObject> {
                if let movies = json["results"] as? [AnyObject]{
                    for movie in movies{
                        let movieObject: Movie = Movie()

                        let title = movie["title"] as! String
                        let releaseDate = movie["release_date"] as! String
                        let posterPath = movie["poster_path"] as! String
                        let overView = movie["overview"] as! String
                        let movieId = movie["id"] as! Int
                        let genre_ids = movie["genre_ids"] as! [AnyObject]

                        movieObject.title = title
                        movieObject.movieRelease = releaseDate
                        movieObject.posterPath = posterPath
                        movieObject.overView = overView
                        movieObject.movieId = movieId

                        for genre in genre_ids{//Genre ids, fix this
                            movieObject.movieGenre.append(genre as! Int)
                        }

                        Alamofire.request("http://image.tmdb.org/t/p/w1920" + posterPath).responseImage {
                            response in
                            //print(response.request)
                            //print(response.response)
                            //debugPrint(response.result)

                            if var image = response.result.value {
                                image = UIImage(data: response.data!)!

                                movieObject.poster = image
                            }
                        }

                        self.movieArray.append(movieObject)

                    }//End of for each movie
                }
                else{
                    print("error while making results anyobject")
                }
            }
            else{
            print("error while trying to make NSDictionary")}
     self.downloadGrp.leave()
    }//End of Json request

    downloadGrp.notify( queue: .main){
        print("all downloads finished")

        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
            print(self.movieArray[0].title!)
            self.updateUI()
            print("updatedUI")
        }

    }

}//End of getmoviedata

override func prepare(for segue: UIStoryboardSegue,sender: Any?){

    // Create a variable that you want to send
    let currentMovie = self.movieArray[movieIndex]

    if let destinationVC = segue.destination as? DetailsViewController{
        destinationVC.currentMovie = currentMovie
    }

}

func updateUI(){
    //self.posterLoading.stopAnimating()
    if uiMoviePoster == nil{
    print(uiMovieTitle.debugDescription)
    }
    else{
        print("first time debugID: " + uiMovieTitle.debugDescription)
    uiMovieTitle.text = self.movieArray[movieIndex].title
    uiMoviePoster.image = self.movieArray[movieIndex].poster
    }

}

}

Body:
You want to grab a sharedInstance not instantiate from a storyboard

let movieVC = ViewController.sharedInstance()

but I still do not understand why do you need to do it like this


问:
Service worker not run in offline mode using nodejs server
i've been create new project PWA.
when i develop not using node js for (socket.io running) just running in offline like i expected and needed.

but when integration with nodejs server. when go online the app running well not get any problem. but when i change to offline mode my service work not run but show offline browser.

this my code node js server:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cors = require('cors');

app.use(cors());
app.use(express.static(__dirname + '/'));

app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

io.on('connection', function(socket) {
  console.log('new connection');

  socket.on('afterBid', function(data) {
    io.emit('bcCurrentBid', {
      current_bidding: data.auction_current_bidding,
      user_id_dominated: data.user_id_dominated
    });
  });

});

server.listen(9991, function() {
  console.log('server up and running at 2205 port');
});```
</div>
</div>
</p>

<p>and this is my service register in index js</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>if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

   window.addEventListener('load', function() {
   navigator.serviceWorker
             .register('./service-worker.js')
             .then(function() { console.log('Service Worker Registered'); });
   });
 }</code>```

and this is my service-worker.js file:

var cacheName = 'Auction-v2';
var filesToCache = [
  'index.html',
  'server.js',
  '/',
  './app/app.js',
  './app/listAuctionController.js',
  './app/auctionDetailController.js',
  './app/service/auctionDataService.js',
  './media/frontend/images/auction_logo_white.png',
  // './media/frontend/',
  // './media/catalog/',
  // './view/',
  './lib/css/materialize.min.css',
  './lib/css/owl.carousel.min.css',
  './lib/css/jquery.countdown.css',
  './lib/css/owl.theme.default.min.css',
  './lib/css/materialize-icon.css',
  './lib/js/jquery.min.js',
  './lib/js/jquery.lazyLoad.js',
  './lib/js/jquery.maskMoney.js',
  './lib/js/jquery.countdown.min.js',
  './lib/js/materialize.min.js',
  './lib/js/owl.carousel.min.js',
  './lib/js/angular/angular.min.js',
  './lib/js/angular/angular-route.min.js',
  './lib/js/angular/angular-sanitize.min.js',
  './lib/js/angular/angular-locale_id-id.js',
  './lib/js/angular/angular-animate.min.js',
];

var dataCacheName = 'Auction-Data-v1';

// SW Install
self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('fetch', function(e) {
  // console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = '/backendFrame/public/api/v1/';
  var dataUrl2 = '/view/';
  if (e.request.url.indexOf(dataUrl) > -1 || e.request.url.indexOf(dataUrl2)) {
    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          // console.log('url to cache =' + e.request.url);
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

// SW Activate
self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName  && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  return self.clients.claim();
});```

thanks maybe someone can give me solution

答:
The service worker is just a javascript file served from your webserver. It doesn't matter if it's node.js or not.

Have you checked the 'application' tab in the chrome debugging tools to see if the service worker is loaded? If it is, please share the code of your 'service-worker.js' file.
You can also add a 'catch' part when registering the service worker. That may show you what is going on if the service worker can't be loaded.

window.addEventListener('load', function() {
  navigator.serviceWorker
    .register('./service-worker.js')
    .then(function() { console.log('Service Worker Registered'); })

    .catch(function (err) {
            console.log('ServiceWorker registration failed: ', err);
    });

});```

Body:
i've been create new project PWA.
when i develop not using node js for (socket.io running) just running in offline like i expected and needed.

but when integration with nodejs server. when go online the app running well not get any problem. but when i change to offline mode my service work not run but show offline browser.

this my code node js server:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cors = require('cors');

app.use(cors());
app.use(express.static(__dirname + '/'));

app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

io.on('connection', function(socket) {
  console.log('new connection');

  socket.on('afterBid', function(data) {
    io.emit('bcCurrentBid', {
      current_bidding: data.auction_current_bidding,
      user_id_dominated: data.user_id_dominated
    });
  });

});

server.listen(9991, function() {
  console.log('server up and running at 2205 port');
});

and this is my service register in index js

if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

   window.addEventListener('load', function() {
   navigator.serviceWorker
             .register('./service-worker.js')
             .then(function() { console.log('Service Worker Registered'); });
   });
 }

and this is my service-worker.js file:

var cacheName = 'Auction-v2';
var filesToCache = [
  'index.html',
  'server.js',
  '/',
  './app/app.js',
  './app/listAuctionController.js',
  './app/auctionDetailController.js',
  './app/service/auctionDataService.js',
  './media/frontend/images/auction_logo_white.png',
  // './media/frontend/',
  // './media/catalog/',
  // './view/',
  './lib/css/materialize.min.css',
  './lib/css/owl.carousel.min.css',
  './lib/css/jquery.countdown.css',
  './lib/css/owl.theme.default.min.css',
  './lib/css/materialize-icon.css',
  './lib/js/jquery.min.js',
  './lib/js/jquery.lazyLoad.js',
  './lib/js/jquery.maskMoney.js',
  './lib/js/jquery.countdown.min.js',
  './lib/js/materialize.min.js',
  './lib/js/owl.carousel.min.js',
  './lib/js/angular/angular.min.js',
  './lib/js/angular/angular-route.min.js',
  './lib/js/angular/angular-sanitize.min.js',
  './lib/js/angular/angular-locale_id-id.js',
  './lib/js/angular/angular-animate.min.js',
];

var dataCacheName = 'Auction-Data-v1';

// SW Install
self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('fetch', function(e) {
  // console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = '/backendFrame/public/api/v1/';
  var dataUrl2 = '/view/';
  if (e.request.url.indexOf(dataUrl) > -1 || e.request.url.indexOf(dataUrl2)) {
    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          // console.log('url to cache =' + e.request.url);
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

// SW Activate
self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName  && key !== dataCacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  return self.clients.claim();
});

thanks maybe someone can give me solution