问:
Fail to write model history to a json file in the end of 2nd epoch of a keras fit_generator training
I am using a customized callback to save model history parameters (loss, acc, etc.) to a json file on_epoch_end. I used a keras fit_generator to train the data. In the end of 1st epoch, everything works fine and i can get the json file with parameters. However, after 2nd epoch, i always encounter an long error ending with "TypeError: Object of type 'float32' is not JSON serializable". I am very confused, because the model history is a dictionary.

I have tried:
1) change json.dumps to json.dump. But the same error in the end of 2nd epoch
2) I have commented out json file portion, and add a code "print(self.H)" in my callback class. It works. By every end of epoch, the model history dictionary can be printed out and my training can be completed without error.
3) I use lr decay. One observation is that there is no "lr" parameter in the model history dictionary for the 1st epoch, and a "lr" parameter will be added since 2nd epoch onwards for the history dictionary.

```<code>class TrainingMonitor(BaseLogger):
    def __init__(self, figPath, jsonPath=None, startAt=0):
        # store the output path for the figure, the path to the JSON
        # serialized file, and the starting epoch
        super(TrainingMonitor, self).__init__()
        self.figPath = figPath
        self.jsonPath = jsonPath
        self.startAt = startAt

    def on_train_begin(self, logs={}):
        # initialize the history dictionary
        self.H = {}

    def on_epoch_end(self, epoch, logs={}):
        # loop over the logs and update the loss, accuracy, etc.
        # for the entire training process
        for (k, v) in logs.items():
            l = self.H.get(k, [])
            l.append(v)
            self.H[k] = l

        # check to see if the training history should be serialized to the file
        if self.jsonPath is not None:
            f = open(self.jsonPath, "w")
            f.write(json.dumps(self.H))
            f.close()
</code>```

答:
problem solved by changing "l.append(v)" to "l.append(float(v))". The error is because that data type of "lr" is numpy.float32 and json's encoder might not be able to encode it. Below shows data type has been changed to native Python float type then no problem to be written into json.</p>

```<code>acc <class 'numpy.float64'>

acc <class 'float'>

lr <class 'numpy.float32'>

lr <class 'float'>
</code>```

Body:
I am using a customized callback to save model history parameters (loss, acc, etc.) to a json file on_epoch_end. I used a keras fit_generator to train the data. In the end of 1st epoch, everything works fine and i can get the json file with parameters. However, after 2nd epoch, i always encounter an long error ending with "TypeError: Object of type 'float32' is not JSON serializable". I am very confused, because the model history is a dictionary.

I have tried:
1) change json.dumps to json.dump. But the same error in the end of 2nd epoch
2) I have commented out json file portion, and add a code "print(self.H)" in my callback class. It works. By every end of epoch, the model history dictionary can be printed out and my training can be completed without error.
3) I use lr decay. One observation is that there is no "lr" parameter in the model history dictionary for the 1st epoch, and a "lr" parameter will be added since 2nd epoch onwards for the history dictionary.

class TrainingMonitor(BaseLogger):
    def __init__(self, figPath, jsonPath=None, startAt=0):
        # store the output path for the figure, the path to the JSON
        # serialized file, and the starting epoch
        super(TrainingMonitor, self).__init__()
        self.figPath = figPath
        self.jsonPath = jsonPath
        self.startAt = startAt

    def on_train_begin(self, logs={}):
        # initialize the history dictionary
        self.H = {}

    def on_epoch_end(self, epoch, logs={}):
        # loop over the logs and update the loss, accuracy, etc.
        # for the entire training process
        for (k, v) in logs.items():
            l = self.H.get(k, [])
            l.append(v)
            self.H[k] = l

        # check to see if the training history should be serialized to the file
        if self.jsonPath is not None:
            f = open(self.jsonPath, "w")
            f.write(json.dumps(self.H))
            f.close()

Body:
problem solved by changing "l.append(v)" to "l.append(float(v))". The error is because that data type of "lr" is numpy.float32 and json's encoder might not be able to encode it. Below shows data type has been changed to native Python float type then no problem to be written into json.

acc <class 'numpy.float64'>

acc <class 'float'>

lr <class 'numpy.float32'>

lr <class 'float'>


来源: stackexchange

问:
PHP $-SESSION variables disappear on new page and return empty
I'm having an issue with the Sessions Variables. Ever since i switched from mysqli to PDO. It worked fine with mysqli, but ever since i switched to PDO, this issue has now come forward.

I'm trying to login and i have an area, where i want to make sure that the user can only see, if the user is logged in. The login works fine, but as soon as i get referred to my index file, i don't see anything, because of the logged in function. I can see the $_SESSION Variable gets filled, but as soon as i redirect to another file, the $_SESSION Variables disappear and i get an empty Array:

Array
(
)
```

<p>process_login.php</p>

<pre class="lang-php prettyprint-override"><code>require_once('../inc/user.inc.php'); // here i have all my functions

  $user = new User(); // New Instance of my User Class

  $user -> sec_session(); // selfmade session function. I use start_session() in this function

  if (isset($_POST['email'], $_POST['p'])) {
      $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
      $password = filter_var ($_POST['p'], FILTER_SANITIZE_STRING);

      $login = $user -> login_user($email, $password);

      if ($login) {
          // Login sucessful
          //print("```".print_r($_SESSION,true)."```"); //Here i get my $_SESSION variable printed out and it works. I see it is filled.
          header('Location: ../index.php');
          exit();
      }
</code>```

index.php

<?php
    $title = 'Index';
    $currentPage = 'Dashboard';
    include('php/head.php');
    require_once('../inc/user.inc.php');
    $user = new User();

    $user -> sec_session(); // here i call my session function again. Note: session_start() is included in this function
    print("```".print_r($_SESSION,true)."```"); //Now The Array is empty?!?
?>
```

<p>user.inc.php - sec_session function</p>

<pre class="lang-php prettyprint-override"><code>protected function sec_session() {
            $session_name = 'sec_session_id';
            $secure = SECURE;
            $httponly = true;
            if (ini_set('session.use_only_cookies', 1) === FALSE) {
            header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
            }

            $cookieParams = session_get_cookie_params();
            session_set_cookie_params($cookieParams["lifetime"],
                $cookieParams["path"],
                $cookieParams["domain"],
                $secure,
                $httponly);

            session_name($session_name);
            session_start();
            session_regenerate_id();
        }
</code>```

Whilst logging in, i set the Session to the following in my login function:

if ($db_password == $password) {
                $user_browser = $_SERVER['HTTP_USER_AGENT'];
                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                $_SESSION['user_id'] = $user_id;
                $username = preg_replace("/[^a-zA-Z0-9_\-]+/",
                                                            "",
                                                            $username);
                $_SESSION['username'] = $username;
                $_SESSION['login_string'] = hash('sha512',
                          $password . $user_browser);
                return true;
              }
```

This above works all fine, but only disappears, when i land in my index.php and i know there is something worng, but i have no idea what it is.

答:
Are you using http or https to access your local site? If you are using secure cookies PHP won't read them under http instead it starts a new session with a new cookie, switching to https solves this problem.

It looks from your sec_session function that you are using secure cookies ($secure = SECURE;) so is your browser session using HTTPS? If you are using HTTP with secure cookies you will start a new session on each page and won't have access to existing session variables.

The best solution is to access your local site with https just like you would for your live site but if you switch off the secure cookie setting for your local site that will work too.

ContentLicense: CC BY-SA 4.0

Body:
I'm having an issue with the Sessions Variables. Ever since i switched from mysqli to PDO. It worked fine with mysqli, but ever since i switched to PDO, this issue has now come forward.

I'm trying to login and i have an area, where i want to make sure that the user can only see, if the user is logged in. The login works fine, but as soon as i get referred to my index file, i don't see anything, because of the logged in function. I can see the $_SESSION Variable gets filled, but as soon as i redirect to another file, the $_SESSION Variables disappear and i get an empty Array:

Array
(
)

process_login.php

require_once('../inc/user.inc.php'); // here i have all my functions

  $user = new User(); // New Instance of my User Class

  $user -> sec_session(); // selfmade session function. I use start_session() in this function

  if (isset($_POST['email'], $_POST['p'])) {
      $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
      $password = filter_var ($_POST['p'], FILTER_SANITIZE_STRING);

      $login = $user -> login_user($email, $password);

      if ($login) {
          // Login sucessful
          //print("
".print_r($_SESSION,true)."
"); //Here i get my $_SESSION variable printed out and it works. I see it is filled.
          header('Location: ../index.php');
          exit();
      }

index.php

<?php
    $title = 'Index';
    $currentPage = 'Dashboard';
    include('php/head.php');
    require_once('../inc/user.inc.php');
    $user = new User();

    $user -> sec_session(); // here i call my session function again. Note: session_start() is included in this function
    print("
".print_r($_SESSION,true)."
"); //Now The Array is empty?!?
?>

user.inc.php - sec_session function

protected function sec_session() {
            $session_name = 'sec_session_id';
            $secure = SECURE;
            $httponly = true;
            if (ini_set('session.use_only_cookies', 1) === FALSE) {
            header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
            }

            $cookieParams = session_get_cookie_params();
            session_set_cookie_params($cookieParams["lifetime"],
                $cookieParams["path"],
                $cookieParams["domain"],
                $secure,
                $httponly);

            session_name($session_name);
            session_start();
            session_regenerate_id();
        }

Whilst logging in, i set the Session to the following in my login function:

if ($db_password == $password) {
                $user_browser = $_SERVER['HTTP_USER_AGENT'];
                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                $_SESSION['user_id'] = $user_id;
                $username = preg_replace("/[^a-zA-Z0-9_\-]+/",
                                                            "",
                                                            $username);
                $_SESSION['username'] = $username;
                $_SESSION['login_string'] = hash('sha512',
                          $password . $user_browser);
                return true;
              }

This above works all fine, but only disappears, when i land in my index.php and i know there is something worng, but i have no idea what it is.


问:
Single selection is not working in UITableview
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

```<code>
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

</code>```

I just want to change image on cell click with a single selection

答:
Replace

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
</code>```

with

```<code>guard let cell = tableView.cellForRow(at:indexPath) as? PaymentCell else { return }
</code>```

but the better is to change your model to the new image at that indexPath and then reload the tableView to avoid dequeuing problems

Body:
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

I just want to change image on cell click with a single selection

Body:
Replace

let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell

with

guard let cell = tableView.cellForRow(at:indexPath) as? PaymentCell else { return }

but the better is to change your model to the new image at that indexPath and then reload the tableView to avoid dequeuing problems


问:
Bootstrap Table Column width not getting
More table column not getting width with table-responsive

I Need this column Well Type width 200px

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

              Problem
              Inactive Category
              Action

              Validation
              Endorsed

              Well No
              String
              Well Type
              Reservoir
              Downtime Start/Rig Release
              Downtime (in days)
              Code
              Description
              Code
              Description
              Code
              Description
              Planned Date
              Expected Rate
              Status
              Remarks
              Status
              Remarks
              Action Category
              Project
              Case
              Attachments
              Remarks

              Well No
              String
              Well Type
              Reservoir
              Downtime Start/Rig Release
              Downtime (in days)
              Code
              Description
              Code
              Description
              Code
              Description
              Planned Date
              Expected Rate
              Status
              Remarks
              Status
              Remarks
              Action Category
              Project
              Case
              Attachments
              Remarks

                Edit
                Cancel

```

答:
The solution is setting the min-width instead of width like I did in the example below.

Note that the width Attribute of  you've used is not supported in HTML5 and should not be used anymore.

Back to topic: According to the table-layout documentation most Browsers are using an automatic table layout algorithm. I think that's why your CSS gets overwritten if the table gets too wide.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

              Problem
              Inactive Category
              Action

              Validation
              Endorsed

              Well No
              String
              Well Type
              Reservoir
              Downtime Start/Rig Release
              Downtime (in days)
              Code
              Description
              Code
              Description
              Code
              Description
              Planned Date
              Expected Rate
              Status
              Remarks
              Status
              Remarks
              Action Category
              Project
              Case
              Attachments
              Remarks

              Well No
              String
              Well Type
              Reservoir
              Downtime Start/Rig Release
              Downtime (in days)
              Code
              Description
              Code
              Description
              Code
              Description
              Planned Date
              Expected Rate
              Status
              Remarks
              Status
              Remarks
              Action Category
              Project
              Case
              Attachments
              Remarks

                Edit
                Cancel

```

Body:
The solution is setting the min-width instead of width like I did in the example below.

Note that the width Attribute of <th> you've used is not supported in HTML5 and should not be used anymore.

Back to topic: According to the table-layout documentation most Browsers are using an automatic table layout algorithm. I think that's why your CSS gets overwritten if the table gets too wide.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="table-responsive">
        <table class="table table-bordered">
          <tbody>
            <tr>
              <th></th>
              <th></th>
              <th style="min-width: 200px;"></th>
              <th></th>
              <th></th>
              <th></th>
              <th class="text-center" colspan="2">Problem</th>
              <th class="text-center" colspan="2">Inactive Category</th>
              <th class="text-center" colspan="3">Action</th>
              <th></th>
              <th class="text-center" colspan="2">Validation</th>
              <th class="text-center" colspan="2">Endorsed</th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
            <tr>
              <th>Well No</th>
              <th>String</th>
              <th>Well Type</th>
              <th>Reservoir</th>
              <th>Downtime Start/Rig Release</th>
              <th>Downtime (in days)</th>
              <th>Code</th>
              <th>Description</th>
              <th>Code</th>
              <th>Description</th>
              <th>Code</th>
              <th>Description</th>
              <th>Planned Date</th>
              <th>Expected Rate</th>
              <th>Status</th>
              <th>Remarks</th>
              <th>Status</th>
              <th>Remarks</th>
              <th>Action Category</th>
              <th>Project</th>
              <th>Case</th>
              <th>Attachments</th>
              <th>Remarks</th>
              <th></th>
            </tr>
          </tbody>
          <tbody>
            <tr>
              <td>Well No</td>
              <td>String</td>
              <td>Well Type</td>
              <td>Reservoir</td>
              <td>Downtime Start/Rig Release</td>
              <td>Downtime (in days)</td>
              <td>Code</td>
              <td>Description</td>
              <td>Code</td>
              <td>Description</td>
              <td>Code</td>
              <td>Description</td>
              <td>Planned Date</td>
              <td>Expected Rate</td>
              <td>Status</td>
              <td>Remarks</td>
              <td>Status</td>
              <td>Remarks</td>
              <td>Action Category</td>
              <td>Project</td>
              <td>Case</td>
              <td>Attachments</td>
              <td>Remarks</td>
              <td>
                <a href="#">Edit</a>
                <a href="#">Cancel</a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>


问:
vertical centering of list items
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

```<code><div id = "main">
    <ul>
        <li>
            <img src="test.jpg" alt="#" />
            <p>Lorem ipsum</p>
        </li>
    </ul>
</div>

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}
</code>```

答:
Not exactly sure what you're trying to do but here is a possible solution. The trick to this is the line-height.

EDIT: This should do it...

http://jsfiddle.net/cxmsr/4/

```<code>
#main
{
    margin-left: auto;
    margin-right: auto;
    position: relative;
    left: 0px;
    top: 0px;
    height: 400px;
    background-color: #999999;
    display: table;
}
#main UL
{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
#main LI
{
    display: inline-block;
    background-color: #CCC;
    margin: 2px 2px 6px;
    height: 100px;
}
</code>```

You can change the #main width to 100% or whatever you need.

ContentLicense: CC BY-SA 3.0

Title: vertical centering of list items

Body:
I have read many articles about vertical centering but I’m afraid not many of them are intuitive, hence unable to apply it to my problem. Basically, I have a main div and in there, I’ve got unordered list which has an image and paragraph tag within it and are displayed using inline-block. This aspect of the work is fine.

The problem or what I am trying to achieve is to have the list centered in the middle of the screen. So for instance, if I have got just one item in the list, it should be in the middle and then move upwards as more items are entered in the list.

Lorem ipsum

#main {
    margin: 60px auto;
    height: 400px;
}
#main ul li {
    display: inline-block;
    vertical-align: top;
    margin: 0 13px 72px 22px;
    height: 100px;
}

#main ul {
    text-align: center;
}

Body:
Not exactly sure what you're trying to do but here is a possible solution. The trick to this is the line-height.

EDIT: This should do it...

http://jsfiddle.net/cxmsr/4/

#main
{
    margin-left: auto;
    margin-right: auto;
    position: relative;
    left: 0px;
    top: 0px;
    height: 400px;
    background-color: #999999;
    display: table;
}
#main UL
{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
#main LI
{
    display: inline-block;
    background-color: #CCC;
    margin: 2px 2px 6px;
    height: 100px;
}

You can change the #main width to 100% or whatever you need.


问:
is there any way to cancel a dart Future?
In a Dart UI, I have a button submit to launch a long async request. The submit handler returns a Future. Next, the button submit is replaced by a button cancel to allow the cancellation of the whole operation. In the cancel handler, I would like to cancel the long operation. How can I cancel the Future returned by the submit handler? I found no method to do that.

答:
For those, who are trying to achieve this in Flutter, here is the simple example for the same. </p>

```<code>class MyPage extends StatelessWidget {
  final CancelableCompleter<bool> _completer = CancelableCompleter(onCancel: () => false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Future")),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("Submit"),
            onPressed: () async {
              // it is true only if the future got completed
              bool _isFutureCompleted = await _submit();
            },
          ),
          RaisedButton(child: Text("Cancel"), onPressed: _cancel),
        ],
      ),
    );
  }

  Future<bool> _submit() async {
    _completer.complete(Future.value(_solve()));
    return _completer.operation.value;
  }

  // This is just a simple method that will finish the future in 5 seconds
  Future<bool> _solve() async {
    return await Future.delayed(Duration(seconds: 5), () => true);
  }

  void _cancel() async {
    var value = await _completer.operation.cancel();
    // if we stopped the future, we get false
    assert(value == false);
  }
}
</code>```

Body:
For those, who are trying to achieve this in Flutter, here is the simple example for the same.

class MyPage extends StatelessWidget {
  final CancelableCompleter<bool> _completer = CancelableCompleter(onCancel: () => false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Future")),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("Submit"),
            onPressed: () async {
              // it is true only if the future got completed
              bool _isFutureCompleted = await _submit();
            },
          ),
          RaisedButton(child: Text("Cancel"), onPressed: _cancel),
        ],
      ),
    );
  }

  Future<bool> _submit() async {
    _completer.complete(Future.value(_solve()));
    return _completer.operation.value;
  }

  // This is just a simple method that will finish the future in 5 seconds
  Future<bool> _solve() async {
    return await Future.delayed(Duration(seconds: 5), () => true);
  }

  void _cancel() async {
    var value = await _completer.operation.cancel();
    // if we stopped the future, we get false
    assert(value == false);
  }
}


问:
How to implement flowcharts in Typora with markdown?
Is it possible to create diagrams and flowcharts like this?

I'm using Typora markdown editor.

答:
Reading this as a question about typora rather than markdown,
the typora support site has an article on diagrams.

This article refers to Mermaid which may be what you are looking for.

Mermaid also has a Live Editor in which you can experiment.


问:
Performance Penalty in DynamoDB Because Of Conditional Put
We're trying to decide if Conditional Put is the right choice for one of our high throughput use cases.

Its enough for us to be able to say "Insert an item only if no other item exists for same Partition Key and Sort Key values".

We're trying to see how much performance penalty this would have over unconditional puts. Does anyone know if Conditional Puts are slower than Unconditional Puts? If they are, by how much?

答:
The best way to find out is always to measure for your specific use case.

Having said that it’s most likely not appreciably slower than a regular PUT. All of the data needed for a conditional PUT exists on the exact node(s) where the data will end up being stored, and the conditions available are very basic so I doubt there would ever be a significant performance difference.


问:
Call TypeScript function in HTML without a click event
I know how to call a TypeScript when clicking a button, but how do you call a function without that type of event? I would like to call a function when I have an array called chartData populated. This is what I have:

```<code>        <div *ngIf="chartData.length">
            chartMethod();
        </div>
</code>```

But instead of chartMethod() being called, it just prints 'chartMethod()' on the html page.

I've also tried:

```<code>            <script>
                chartTest();
            </script>
</code>```

but the function was still not called.

答:
In your component.ts put his after constructor

```<code>ngAfterViewInit(){
    this.getUser();//Put here your function or what you need
  }
</code>```

ngAfterViewInit() is called after a component's view, and its children's views, are created.
Its a lifecycle hook that is called after a component's view has been fully initialized.

Body:
I know how to call a TypeScript when clicking a button, but how do you call a function without that type of event? I would like to call a function when I have an array called chartData populated. This is what I have:

            chartMethod();

But instead of chartMethod() being called, it just prints 'chartMethod()' on the html page.

I've also tried:

but the function was still not called.

Body:
In your component.ts put his after constructor

ngAfterViewInit(){
    this.getUser();//Put here your function or what you need
  }

ngAfterViewInit() is called after a component's view, and its children's views, are created.
Its a lifecycle hook that is called after a component's view has been fully initialized.


问:
SQL Agent Run SSIS package as Administrator
I'm trying to run a SQL Agent Job with a step that is a SSIS File, and I need this step to be run as administrator.

My Package uses a Script task to download a file, as a Browser i Use WATIN.

I'm using a thread to start this browser because this browser control requires the thread to be set as Single-Threaded Apartment.

This browser control is requiring to be run as administrator.

I've already created a Credential for a user that is Windows Admin, a Proxy SSIS account. (SQL Agent user is not windows admin).

But the SSIS package is not run as administrator yet.
I'm suspecting this is related to UAC.

Some details:

SQL Agent Account is not Windows Administrator

Using Windows Server 2008 R2

My Package is run from the File System.

The Package only works on BIDS if I run it as an Administrator (if not admin doesn't work)

The Proxy account the job step is configured to run is windows admin.

Any help is appreciated!

答: Take a look at SSIS runs in BIDS but not with SQL Agent for some ideas</p>


问:
ActiveRecord Fuzzy Search
I'm looking to perform a search to find an object similar to this:

Object(id: 1, example: "abc")

by using a search like this:

```<code>params[:search] = "abcdef"
Object.where("example LIKE ?", "#{params[:search]%")
</code>```

but am only able to use the above example if my search has less characters than my object, not more.

答:
Note: the fuzzily gem does not work with Rails 6. This solution has been deprecated.

The fuzzily gem allows you to do fuzzy searching of ActiveRecord models that you've instrumented appropriately.

Fuzzily finds misspelled, prefix, or partial needles in a haystack of strings. It's a fast, trigram-based, database-backed fuzzy string search/match engine for Rails.

Once you've installed the gem, you can instrument your model as follows:

class MyStuff < ActiveRecord::Base
  # assuming my_stuffs has a 'name' attribute
  fuzzily_searchable :name
end
```

<p>You can then perform fuzzy searches as follows:</p>

<pre class="lang-rb prettyprint-override"><code>MyStuff.find_by_fuzzy_name('Some Name', :limit => 10)
# => records
</code>```

Title: ActiveRecord Fuzzy Search

Body:
I'm looking to perform a search to find an object similar to this:

Object(id: 1, example: "abc")

by using a search like this:

params[:search] = "abcdef"
Object.where("example LIKE ?", "#{params[:search]%")

but am only able to use the above example if my search has less characters than my object, not more.

Body:
Note: the fuzzily gem does not work with Rails 6. This solution has been deprecated.

The fuzzily gem allows you to do fuzzy searching of ActiveRecord models that you've instrumented appropriately.

Fuzzily finds misspelled, prefix, or partial needles in a haystack of strings. It's a fast, trigram-based, database-backed fuzzy string search/match engine for Rails.

Once you've installed the gem, you can instrument your model as follows:

class MyStuff < ActiveRecord::Base
  # assuming my_stuffs has a 'name' attribute
  fuzzily_searchable :name
end

You can then perform fuzzy searches as follows:

MyStuff.find_by_fuzzy_name('Some Name', :limit => 10)
# => records


问:
LocalDateTime to specific timezone
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

```<code>LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
</code>```

答:
In Java 8, you can use ZonedDateTime to convert LocalDateTime with respect to a specific ZoneId. Considering your example, the conversion could be implemented as follows:

ZoneId istZoneId = ZoneId.of("Asia/Kolkata");
LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
ZonedDateTime zonedDateTimeOfAfterFiveDays = dateTimeOfAfterFiveDays.atZone(istZoneId);
```

Hope it helps!

Title: LocalDateTime to specific timezone

Body:
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

Body:
In Java 8, you can use ZonedDateTime to convert LocalDateTime with respect to a specific ZoneId. Considering your example, the conversion could be implemented as follows:

ZoneId istZoneId = ZoneId.of("Asia/Kolkata");
LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
ZonedDateTime zonedDateTimeOfAfterFiveDays = dateTimeOfAfterFiveDays.atZone(istZoneId);

Hope it helps!


问:
How to get() multiple updated values only once in Firebase Real Time Database (Angular)
I am updating all data for each user in Firebase - Real Time Database at fixed periods of time and I am using:

```<code>this.db.list('/' + this.user.uid + '/data).valueChanges()
.subscribe(items=>{
    console.log(items)
});
</code>```

to retrieve the update. But because multiple values are updated(even though all at once) I receive in the web application one update at a time.
Is this normal? Is there any way to update all and receive the update only once?

答: If you make multiple independent updates at the location of a listener, the listener could trigger as many times as there are updates.  This system is going to try to synchronize all the changes as fast as it can.  You can't change this behavior.  If you want only one update, then you should make only one change at that location.</p>

Body:
I am updating all data for each user in Firebase - Real Time Database at fixed periods of time and I am using:

this.db.list('/' + this.user.uid + '/data).valueChanges()
.subscribe(items=>{
    console.log(items)
});

to retrieve the update. But because multiple values are updated(even though all at once) I receive in the web application one update at a time.
Is this normal? Is there any way to update all and receive the update only once?


问:
Why no call fstab64 after read? And can this be a problem?
I want to create a new dynamic library instead of another, the source code of which is lost. I have created a library with exported functions, but the program does not load it. Conclusion Strace is almost the same, the only difference is that in the case of loading my library after the call to read() there is no call to fstat64().

strace original library:

```<code>open("/usr/local/lpr/li2/libSA.so", O_RDONLY) = 12
read(12, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3409\0"...,     1024) = 1024
fstat64(12, {st_mode=S_IFREG|0644, st_size=46166, ...}) = 0
old_mmap(NULL, 40256, PROT_READ|PROT_EXEC, MAP_PRIVATE, 12, 0) = 0x40150000
mprotect(0x40159000, 3392, PROT_NONE)   = 0
old_mmap(0x40159000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 12, 0x8000) = 0x40159000
close(12)                               = 0
</code>```

my library:

```<code>open("/usr/local/lpr/li2/libSA.so", O_RDONLY) = 12
read(12, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0`\210\0\0"...,     1024) = 1024
close(12)                               = 0
time(NULL)
</code>```

答:
You're trying to load a 64-bit shared object into a 32-bit process.

The ELF header read by these two read() calls:

```<code>read(12, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3409\0"...,     1024) = 1024
</code>```

and

```<code>read(12, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0`\210\0\0"...,     1024) = 1024
</code>```

differ.  Note that the fifth byte in the first read() is 1.  That's the successful load of a 32-bit shared object.

That fifth byte is 2 on the unsuccessful attempt - and that 2 means that the shared object is a 64-bit shared object.

You likely need to compile and link with the -m32 option.

Body:
I want to create a new dynamic library instead of another, the source code of which is lost. I have created a library with exported functions, but the program does not load it. Conclusion Strace is almost the same, the only difference is that in the case of loading my library after the call to read() there is no call to fstat64().

strace original library:

open("/usr/local/lpr/li2/libSA.so", O_RDONLY) = 12
read(12, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3409\0"...,     1024) = 1024
fstat64(12, {st_mode=S_IFREG|0644, st_size=46166, ...}) = 0
old_mmap(NULL, 40256, PROT_READ|PROT_EXEC, MAP_PRIVATE, 12, 0) = 0x40150000
mprotect(0x40159000, 3392, PROT_NONE)   = 0
old_mmap(0x40159000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 12, 0x8000) = 0x40159000
close(12)                               = 0

my library:

open("/usr/local/lpr/li2/libSA.so", O_RDONLY) = 12
read(12, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0`\210\0\0"...,     1024) = 1024
close(12)                               = 0
time(NULL)

Body:
You're trying to load a 64-bit shared object into a 32-bit process.

The ELF header read by these two read() calls:

read(12, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3409\0"...,     1024) = 1024

and

read(12, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0`\210\0\0"...,     1024) = 1024

differ.  Note that the fifth byte in the first read() is 1.  That's the successful load of a 32-bit shared object.

That fifth byte is 2 on the unsuccessful attempt - and that 2 means that the shared object is a 64-bit shared object.

You likely need to compile and link with the -m32 option.


问:
How to find List<Object> sorted by Date
I'm trying to build simple REST for purchases
I need 2 methods.
Firstone should show all purchases sorted by date
Secondone removes all purchases for specified date
I made a method to add and to get all purchases.
Now i'm stucked.

```<code>@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

 @Column(name = "name")
 private String name;

 @CreationTimestamp
 @Temporal(TemporalType.DATE)
 @Column(name="createat")
    private Date created;

 @Column(name="price")
 private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long> {
}

@Service
public class PurchaseService {

    @Autowired
    private PurchaseRepository purchaseRepository;

    public void addPurchase(Purchase purchase) {
        purchaseRepository.save(purchase);
    }

    public List<Purchase> getAllPurchase() {

        List<Purchase> purchase = new ArrayList<>();
        purchaseRepository.findAll().forEach(purchase::add);
        return purchase;
    }
}

@RestController
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @PostMapping("/purchase")
    public void addPurchase(@RequestBody Purchase purchase) {
        purchaseService.addPurchase(purchase);
    }

    @RequestMapping("/purchase")
    public List<Purchase> getAllTopics() {
        return purchaseService.getAllPurchase();
    }
}
</code>```

Can't find the solution and implementation for:
I expect 1 method to sort my List sorted by date
2 method that removes all purchases for specified date

答:
Assuming you're using Spring as your annotations show, also assuming you're using SpringData as abstraction layer for database communication. You shouldn't extend JPARepository instead you should extend CrudRepository. There you could define Queries by a special naming convention or by HQL.

For Example:

```<code>@Repository
public interface PurchaseRepository extends CrudRepository<Purchase, Long> {
    List<Purchase> findAllOrderByDate();

    long deleteByDate(Date date);
}
</code>```

The deleteByDate function will return the count of deleted rows.

As you can see you can define Queries by their name. For more information on this: https://docs.spring.io/spring-data/data-commons/docs/2.1.8.RELEASE/reference/html/

Update: The Implementation is just an example, you can not Copy & Paste it and use it as it is. As in the mentioned documentation explained, you can define a Query by a special naming convention which allows you two define Queries in a semantic way by using the property names from your entity. In your case this would be findAllOrderByCreatedAsc or findAllOrderByCreatedDesc same applies for delete.

Title: How to find List<Object> sorted by Date

Body:
I'm trying to build simple REST for purchases
I need 2 methods.
Firstone should show all purchases sorted by date
Secondone removes all purchases for specified date
I made a method to add and to get all purchases.
Now i'm stucked.

@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

 @Column(name = "name")
 private String name;

 @CreationTimestamp
 @Temporal(TemporalType.DATE)
 @Column(name="createat")
    private Date created;

 @Column(name="price")
 private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long> {
}

@Service
public class PurchaseService {

    @Autowired
    private PurchaseRepository purchaseRepository;

    public void addPurchase(Purchase purchase) {
        purchaseRepository.save(purchase);
    }

    public List<Purchase> getAllPurchase() {

        List<Purchase> purchase = new ArrayList<>();
        purchaseRepository.findAll().forEach(purchase::add);
        return purchase;
    }
}

@RestController
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @PostMapping("/purchase")
    public void addPurchase(@RequestBody Purchase purchase) {
        purchaseService.addPurchase(purchase);
    }

    @RequestMapping("/purchase")
    public List<Purchase> getAllTopics() {
        return purchaseService.getAllPurchase();
    }
}

Can't find the solution and implementation for:
I expect 1 method to sort my List sorted by date
2 method that removes all purchases for specified date

Body:
Assuming you're using Spring as your annotations show, also assuming you're using SpringData as abstraction layer for database communication. You shouldn't extend JPARepository instead you should extend CrudRepository. There you could define Queries by a special naming convention or by HQL.

For Example:

@Repository
public interface PurchaseRepository extends CrudRepository<Purchase, Long> {
    List<Purchase> findAllOrderByDate();

    long deleteByDate(Date date);
}

The deleteByDate function will return the count of deleted rows.

As you can see you can define Queries by their name. For more information on this: https://docs.spring.io/spring-data/data-commons/docs/2.1.8.RELEASE/reference/html/

Update: The Implementation is just an example, you can not Copy & Paste it and use it as it is. As in the mentioned documentation explained, you can define a Query by a special naming convention which allows you two define Queries in a semantic way by using the property names from your entity. In your case this would be findAllOrderByCreatedAsc or findAllOrderByCreatedDesc same applies for delete.


问:
How to find the maximum element and its index in the matrix using the max function?
The program does not correctly count the maximum

```<code>clc
A = [   13 54 21 ;
        16 69 13 ;
        22 23 32];

[r,c,v] = find(A == max(A(:)));

disp(['max ',num2str(v)])
disp(['index ',num2str([r,c])])
</code>```

The program does not correctly count the maximum, but the indices are correct

max 1 - false,  must be 69 ||
index 2  2 - true

答:
```<code>%For r2018b and later
[val,idx] = max(A,[],'all');
%For earlier versions
[val,idx] = max(A(:));
</code>```

Maximum element value is val, val == A(idx). For given syntax, val and idx are guaranteed to be numbers, not vectors or matrices.
If you want row and column subscripts, use ind2sub function

```<code>[r,c] = ind2sub(size(A), idx);
</code>```

Body:
The program does not correctly count the maximum

clc
A = [   13 54 21 ;
        16 69 13 ;
        22 23 32];

[r,c,v] = find(A == max(A(:)));

disp(['max ',num2str(v)])
disp(['index ',num2str([r,c])])

The program does not correctly count the maximum, but the indices are correct

max 1 - false,  must be 69 ||
index 2  2 - true

Body:
%For r2018b and later
[val,idx] = max(A,[],'all');
%For earlier versions
[val,idx] = max(A(:));

Maximum element value is val, val == A(idx). For given syntax, val and idx are guaranteed to be numbers, not vectors or matrices.
If you want row and column subscripts, use ind2sub function

[r,c] = ind2sub(size(A), idx);


问:
How to drop a specific Django table which uses PostgreSQL?
I want to delete a Django UserModel table and then recreate it.

Or delete user field and recreate it with a new user by python manage.py createsuperuser

[NOTE]:

My DB is PostgreSQL on a docker container.

答:
Are you trying to delete a development database (e.g., during local development?).

In that case, I usually like to just unapply and reapply migrations, making any changes to migrations I need before reapplying them.

E.g.,:

```<code>$ python manage.py migrate auth zero
$ python manage.py migrate auth
</code>```

This would destroy the auth tables (Permission, Group, and User) and recreate them without any data.

If you have other migrations that depend on auth, they will have been rolled back too. In that case you can just migrate the whole app back with:

$ python manage.py migrate
```

Body:
Are you trying to delete a development database (e.g., during local development?).

In that case, I usually like to just unapply and reapply migrations, making any changes to migrations I need before reapplying them.

E.g.,:

$ python manage.py migrate auth zero
$ python manage.py migrate auth

This would destroy the auth tables (Permission, Group, and User) and recreate them without any data.

If you have other migrations that depend on auth, they will have been rolled back too. In that case you can just migrate the whole app back with:

$ python manage.py migrate


问:
Can I compare to folders contents and return non-duplicate files?
I have a directory with a number of files. I have another directory with identical files, only now all the files are named the same but are within a folder that's named the same as the file names in the other directory.

Example:

First Directory XYZ.txt, ABC.txt, LMN.txt

Second Directory:XYZ/text.txt, ABC/text.txt, LMN/text.txt

I am looking to find out what files are present only in the second directory and not in the first.

How can i do this using the command line?

I've used the find command in both folders. The ABC.txt folder contains 870 files.

```<code>find . -name '*.txt' | egrep -f "*.txt"
</code>```

While the second folder contains 109 Folders

```<code>find . -name 'text.txt' | egrep -c 'text.txt'
</code>```

So I am expecting to find that maybe 80/90 of the 109 files are within the folder with 870 files.

I'm looking to find out which files are present in both directories and have them listed.

答:
Assuming no newlines in your file or directory names you could do something like:

```<code>diff \
    <(find first_dir -name '*.txt' -printf '%p\n' | sort) \
    <(find second_dir -name 'text.txt' | sed 's:.*/\([^/]*\)/[^/]*$:\1.txt:' | sort)
</code>```

You might want to use comm instead of diff, idk.

Body:
I have a directory with a number of files. I have another directory with identical files, only now all the files are named the same but are within a folder that's named the same as the file names in the other directory.

Example:

First Directory XYZ.txt, ABC.txt, LMN.txt

Second Directory:XYZ/text.txt, ABC/text.txt, LMN/text.txt

I am looking to find out what files are present only in the second directory and not in the first.

How can i do this using the command line?

I've used the find command in both folders. The ABC.txt folder contains 870 files.

find . -name '*.txt' | egrep -f "*.txt"

While the second folder contains 109 Folders

find . -name 'text.txt' | egrep -c 'text.txt'

So I am expecting to find that maybe 80/90 of the 109 files are within the folder with 870 files.

I'm looking to find out which files are present in both directories and have them listed.

Body:
Assuming no newlines in your file or directory names you could do something like:

diff \
    <(find first_dir -name '*.txt' -printf '%p\n' | sort) \
    <(find second_dir -name 'text.txt' | sed 's:.*/\([^/]*\)/[^/]*$:\1.txt:' | sort)

You might want to use comm instead of diff, idk.


问:
Excel VlookUp function with conditon ''or''
I Have two excel files:

First file :

```<code>Store name   ID distributor 1    ID distributor 2     ID distributor 3
 Apple         ID10               ID200               ID5000
 Nokia         ID30               ID400               ID6000
</code>```

Second File is a list of mix ID from different distributors

```<code>Distributor ID code      Strore Name
1- ID10                      ?
2- ID400                     ?
3- ID5000                    ?
</code>```

Is it possible to make a VLOOKUP function which will try to find a match in ID distributor 1 and IF no match, look up in ID distributor 2 and IF no match, look up in ID distributor 3. I have about 7 columns of different IDs for the same store name.

For each ID then, it will return the store name in my column 'Store Name' in sheet 2.

答:
Use Index/Aggregate:

```<code>=IFERROR(INDEX(Sheet1!A:A,AGGREGATE(15,7,ROW(Sheet1!$B$1:$D$100)/(Sheet1!$B$1:$D$100=A1),1)),"")
</code>```

Body:
I Have two excel files:

First file :

Store name   ID distributor 1    ID distributor 2     ID distributor 3
 Apple         ID10               ID200               ID5000
 Nokia         ID30               ID400               ID6000

Second File is a list of mix ID from different distributors

Distributor ID code      Strore Name
1- ID10                      ?
2- ID400                     ?
3- ID5000                    ?

Is it possible to make a VLOOKUP function which will try to find a match in ID distributor 1 and IF no match, look up in ID distributor 2 and IF no match, look up in ID distributor 3. I have about 7 columns of different IDs for the same store name.

For each ID then, it will return the store name in my column 'Store Name' in sheet 2.

Body:
Use Index/Aggregate:

=IFERROR(INDEX(Sheet1!A:A,AGGREGATE(15,7,ROW(Sheet1!$B$1:$D$100)/(Sheet1!$B$1:$D$100=A1),1)),"")


问:
Need help about nextjs dynamic url
I am having this problem that whenever i try to visit the page localhost:3000/blog/test directly it returns a 404 error. But whenever i try to visit it using <Link> component it works fine.

This is my code <Link href={{ pathname: '/blog', query: {slug: 'test'} }} as="/blog/test">Blog</Link>

and i have a file blog.js in my pages folder.

答:
You'll have to use now.json to set up your routes. Also it is important to note that it's now that builds the route so visiting it on the client side wont work if you are using localhost. Build your project with now and it should work.

Also the "as" parameter would be as={{ pathname:/user/manage/${variable}}}

Title: Need help about nextjs dynamic url


问:
Why do my app crashes when trying to use DataOutputStream
Im trying create a app that post information to a web page using  DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
But it crashes if i try to do just that.

My app/src/main/AndroidManifest.xml look something like this:

```<code><uses-permission android:name="com.symbol.emdk.permission.EMDK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
<uses-permission android:name="android.permission.BIND_CARRIER_MESSAGING_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <uses-library android:name="com.symbol.emdk"/>

class AsyncT extends AsyncTask<Void,Void,Void>
{
    public String info="";
    public String info2="";
    @Override
    protected Void doInBackground(Void... voids) {

        try {
            URL url = new URL("http://mypage.nu/info.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            //httpURLConnection.connect();
            try {
                    DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());//Something goes wrong
            }catch(IOException e){
                 e.printStackTrace();
            }
            String json="{'name':'test'}";
            out.writeBytes("x="+json);
            httpURLConnection.disconnect();
        }...
</code>```

I expect That i can retrieve $obj = json_decode($_POST["x"], false);

But it dies when trying to create DataOutputStream out = new DataOutputStream

答:
You have to tell the connection that you want an output stream.

```<code>httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
</code>```

See UrlConnection chapter:
Java

Body:
Im trying create a app that post information to a web page using  DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
But it crashes if i try to do just that.

My app/src/main/AndroidManifest.xml look something like this:

<uses-permission android:name="com.symbol.emdk.permission.EMDK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
<uses-permission android:name="android.permission.BIND_CARRIER_MESSAGING_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <uses-library android:name="com.symbol.emdk"/>

class AsyncT extends AsyncTask<Void,Void,Void>
{
    public String info="";
    public String info2="";
    @Override
    protected Void doInBackground(Void... voids) {

        try {
            URL url = new URL("http://mypage.nu/info.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            //httpURLConnection.connect();
            try {
                    DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());//Something goes wrong
            }catch(IOException e){
                 e.printStackTrace();
            }
            String json="{'name':'test'}";
            out.writeBytes("x="+json);
            httpURLConnection.disconnect();
        }...

I expect That i can retrieve $obj = json_decode($_POST["x"], false);

But it dies when trying to create DataOutputStream out = new DataOutputStream

Body:
You have to tell the connection that you want an output stream.

httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);

See UrlConnection chapter:
Java


问:
php artisan queue not showing anything
I'm using laravel 5.0 and trying to set a queue for sending an email, I have created it and wrote code like.
Queue::pushOn('emails', new SendEmail($user));

It's adding a row in the jobs table, then I'm running the following command

$ php artisan queue:listen

But it is not showing anything and not sending emails too.

答:
Be sure to try to:

```<code>config:clear
cache:clear
config:cache
</code>```

And then:

```<code>php artisan queue:listen emails
</code>```

Will listen for jobs in the emails queue.

Title: php artisan queue not showing anything

Body:
Be sure to try to:

config:clear
cache:clear
config:cache

And then:

php artisan queue:listen emails

Will listen for jobs in the emails queue.


问:
Single selection is not working in UITableview
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

```<code>
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

</code>```

I just want to change image on cell click with a single selection

答:
You could handle the button selection in your PaymentCell:

```<code>override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // get image according to cell selection
    let image = selected ? UIImage(named: "CheckTerm") : UIImage(named: "uncheckTerm")
    // update button image
    btnCheckUnCheck.setImage(image, for: .normal)
}

</code>```

Body:
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

I just want to change image on cell click with a single selection

Body:
You could handle the button selection in your PaymentCell:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // get image according to cell selection
    let image = selected ? UIImage(named: "CheckTerm") : UIImage(named: "uncheckTerm")
    // update button image
    btnCheckUnCheck.setImage(image, for: .normal)
}


问:
How to make cell bigger for few seconds?
I have a UICollection with some cells, I want that cell after cell each one will be "chosen" - change size to be bigger and change the background color and stay like this for a few seconds before it get back to normal. I could not find something like that in the web.</p>

答:
You can try this code on the CollectionView's delegate:</p>

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let scale: CGFloat = 1.2
    let animationDuration = 0.5
    let delay = 4.0
    UIView.animate(withDuration: animationDuration, animations: {
        collectionView.cellForItem(at: indexPath)?.transform = CGAffineTransform(scaleX: scale, y: scale)
    }) { (c) in
        UIView.animate(withDuration: animationDuration, delay: delay, options: .curveLinear, animations: {
            collectionView.cellForItem(at: indexPath)?.transform = .identity
        })
    }
}
</code>```

Body:
You can try this code on the CollectionView's delegate:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let scale: CGFloat = 1.2
    let animationDuration = 0.5
    let delay = 4.0
    UIView.animate(withDuration: animationDuration, animations: {
        collectionView.cellForItem(at: indexPath)?.transform = CGAffineTransform(scaleX: scale, y: scale)
    }) { (c) in
        UIView.animate(withDuration: animationDuration, delay: delay, options: .curveLinear, animations: {
            collectionView.cellForItem(at: indexPath)?.transform = .identity
        })
    }
}


问:
Does HTML Encoding a mailto tag stop spammers
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

```<code><a href="mailto:newbi...">email me</a>
</code>```

Also, are there any other techniques that I've left out?  Which is the best method?

答: For my personal home page, I give the email address in a graphic.  Then I apologize for not making it a link.</p>

OwnerDisplayName: bendewey

Body:
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

email me

Also, are there any other techniques that I've left out?  Which is the best method?

LastEditorDisplayName: bendewey

OwnerDisplayName: Mark Ransom

ContentLicense: CC BY-SA 2.5


问:
Write to specific objects in json. Python
I want to create a program that loads a json file, reads it and then adds a
object to a list.

```<code>import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

with open("json.json", "w") as f:
    json.dump(newo, f)
</code>```

This is the python file I have been using.

```<code>{
    "cointiply": [
        {
            "balance" : "242537",
            "time": "28.05.2019"
        },
        {
            "balance": "246362",
            "time": "29.05.2019"
        }
    ]
}
</code>```

And that's the json file.

I now want the newo list to be inserted into the json list "cointiply".

Any idea how that could be done?
Because right now the "newo" list is deleting every think in the json file and then just inserted like the file would have been empty.

答:
Use list.append

Ex:

```<code>import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

data["cointiply"].append(newo)  #Append newo

with open("json.json", "w") as f:
    json.dump(data, f)
</code>```

Body:
I want to create a program that loads a json file, reads it and then adds a
object to a list.

import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

with open("json.json", "w") as f:
    json.dump(newo, f)

This is the python file I have been using.

{
    "cointiply": [
        {
            "balance" : "242537",
            "time": "28.05.2019"
        },
        {
            "balance": "246362",
            "time": "29.05.2019"
        }
    ]
}

And that's the json file.

I now want the newo list to be inserted into the json list "cointiply".

Any idea how that could be done?
Because right now the "newo" list is deleting every think in the json file and then just inserted like the file would have been empty.

Body:
Use list.append

Ex:

import json

newo = {
    "balance": "1234",
    "time": "forever"
}

with open("json.json", "r") as f:
    data = json.load(f)

data["cointiply"].append(newo)  #Append newo

with open("json.json", "w") as f:
    json.dump(data, f)


问:
UitextFiled with first letter must 0 and format will be like (0) 1234 56789
I am using phone number texfield, now i am using this format for texfield (#) #### #####, now issue is that i want first character 0 as compulsary, like this (0) 1234 56789, so user enter whatever first character must be typed 0, its not duplicate quesion number format is different

here is my code but its not working

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 15 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
        let sIndex = String.Index(encodedOffset: $0)
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}
</code>```

答:
In this format <code>(#) #### #####</code> only two spaces are used. So you can insert space at a particular index without a for loop like this </p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 14 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    if oldText.count > 3 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 3))
    }
    if oldText.count > 8 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 8))
    }
    textField.text = oldText
    return false
}
</code>```

Body:
I am using phone number texfield, now i am using this format for texfield (#) #### #####, now issue is that i want first character 0 as compulsary, like this (0) 1234 56789, so user enter whatever first character must be typed 0, its not duplicate quesion number format is different

here is my code but its not working

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 15 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
        let sIndex = String.Index(encodedOffset: $0)
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

Body:
In this format (#) #### ##### only two spaces are used. So you can insert space at a particular index without a for loop like this

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 14 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    if oldText.count > 3 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 3))
    }
    if oldText.count > 8 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 8))
    }
    textField.text = oldText
    return false
}


问:
error while trying to pass location cordinate from a list view to a map activity
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

```<code>listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}
</code>```

```<code>class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
</code>```

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

答:
<blockquote>
```<code>   include code inside onCreate() also check if it contain the extra
</code>```
</blockquote>

```<code>oncreate(){
if(getIntent.hasExtra("long")){
var long:String = intent.getStringExtra("long")
}
if(getIntent.hasExtra("late")){
var late:String = intent.getStringExtra("late")
}
}
</code>```

Body:
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}

class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

Body:
   include code inside onCreate() also check if it contain the extra

oncreate(){
if(getIntent.hasExtra("long")){
var long:String = intent.getStringExtra("long")
}
if(getIntent.hasExtra("late")){
var late:String = intent.getStringExtra("late")
}
}


问:
jquerytools & $.maskedinput conflict
I need some help about a wierd problem.

I'm using jQueryTools and i'm very hapy with that but i think maskedinput plug in's $.mask() method conficts with jQueryTools's .mask() property. When I used both of them together console says "object doesnt have a method such as load()". If ı remove the masket input js from document everything is ok with overlays.

$.maskedInputs

```<code>$("#Phone1, #Phone2, #Gsm").mask("(999) 999 9999");
</code>```

jQueryTools .mas()

```<code>var dialogsOverlay = $(".dialogs").overlay({
    mask: {
        color: '#fff',
        loadSpeed: 200,
        opacity: 0.8
    },
    closeOnClick: false,
    close: ".closeDialog"
});
</code>```

Do you have any exprience somethink like that?

Thanks

答:
Just rename the mask function in maskedinput to something else.  I renamed it to maskMyI.  You can basically just do a find and replace in maskedinput with your new name.  Then use the new name when calling the function on your page.

```<code>$("#Phone1, #Phone2, #Gsm").mask("(999) 999 9999");
</code>```

becomes

```<code>$("#Phone1, #Phone2, #Gsm").maskMyI("(999) 999 9999");
</code>```

in my case. Use your own function name.

Title: jquerytools & $.maskedinput conflict

Body:
I need some help about a wierd problem.

I'm using jQueryTools and i'm very hapy with that but i think maskedinput plug in's $.mask() method conficts with jQueryTools's .mask() property. When I used both of them together console says "object doesnt have a method such as load()". If ı remove the masket input js from document everything is ok with overlays.

$.maskedInputs

$("#Phone1, #Phone2, #Gsm").mask("(999) 999 9999");

jQueryTools .mas()

var dialogsOverlay = $(".dialogs").overlay({
    mask: {
        color: '#fff',
        loadSpeed: 200,
        opacity: 0.8
    },
    closeOnClick: false,
    close: ".closeDialog"
});

Do you have any exprience somethink like that?

Thanks

Body:
Just rename the mask function in maskedinput to something else.  I renamed it to maskMyI.  You can basically just do a find and replace in maskedinput with your new name.  Then use the new name when calling the function on your page.

$("#Phone1, #Phone2, #Gsm").mask("(999) 999 9999");

becomes

$("#Phone1, #Phone2, #Gsm").maskMyI("(999) 999 9999");

in my case. Use your own function name.


问:
SED search and replace more than 1 pattern if matched line
How to search and replace multiple patterns for a matched section in a file?
I tried this

```<code>sed '/pattern1,pattern2/s/string1/replace1/g;s/string2/replace2/g' file
</code>```

But it will ignore the pattern1,pattern2 section and do search and replace for the whole file for my second search and replace.

答:
Curlies.

For the record, this is for GNU sed, which you appear to be using. For other versions/portability, replace the semicolons with newlines.

Also /pattern1,pattern2/ is only searching for literally "pattern1,pattern2" as a single string.

If I read this right, you want to do some substitutions on lines that have both pattern1 and pattern2, though not necessarily in any relative placement. In that case:

```<code>sed '
  /pattern1/ {
    /pattern2/ {
      s/string1/replace1/g;
      s/string2/replace2/g;
    }
  }
' file
</code>```

I spaced it out for readability, but you could smash it all back into one line if you really wanted to.

If you know pattern1 is always before pattern2 then you could use

```<code>sed '/pattern1.*pattern2/ {
  s/string1/replace1/g; s/string2/replace2/g;
}' file
</code>```

But if they could be in reversed order, use the first sed.

Also...maybe we could get a sample file to test against? These are just typed off the cuff, but if you had provided example data I would actually use it to test them first before submitting something that might have a typo or a logic flaw. Just a suggestion. People will be more likely to be thorough if you don't make them genberate all the pieces, lol

Body:
How to search and replace multiple patterns for a matched section in a file?
I tried this

sed '/pattern1,pattern2/s/string1/replace1/g;s/string2/replace2/g' file

But it will ignore the pattern1,pattern2 section and do search and replace for the whole file for my second search and replace.

Body:
Curlies.

For the record, this is for GNU sed, which you appear to be using. For other versions/portability, replace the semicolons with newlines.

Also /pattern1,pattern2/ is only searching for literally "pattern1,pattern2" as a single string.

If I read this right, you want to do some substitutions on lines that have both pattern1 and pattern2, though not necessarily in any relative placement. In that case:

sed '
  /pattern1/ {
    /pattern2/ {
      s/string1/replace1/g;
      s/string2/replace2/g;
    }
  }
' file

I spaced it out for readability, but you could smash it all back into one line if you really wanted to.

If you know pattern1 is always before pattern2 then you could use

sed '/pattern1.*pattern2/ {
  s/string1/replace1/g; s/string2/replace2/g;
}' file

But if they could be in reversed order, use the first sed.

Also...maybe we could get a sample file to test against? These are just typed off the cuff, but if you had provided example data I would actually use it to test them first before submitting something that might have a typo or a logic flaw. Just a suggestion. People will be more likely to be thorough if you don't make them genberate all the pieces, lol


问:
Divide data into bins with inf Python
I'm having a problem with qcut function in python. My upper bounds and lower bounds are -Inf and Inf, but when I apply qcut with these bounds, Python return this error "cannot convert float infinity to integer".

My friends told me that I should change the Inf into 1e100 (a very large number represents ) so qcut could use. However, another error occur: "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

Example:

a1 = [-Inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
a2 = [-1e100, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]

cut_range = [-Inf, 27.0, 33.0, 40.0, Inf] #For a1

cut_range = [-1e+100, 27.0, 33.0, 40.0, 1e+100] #For a2

b = pd.qcut(a, cut_range, duplicates = 'drop')
```

<p>I want to have a final result like this:</p>

<pre class="lang-py prettyprint-override"><code>b = ['[-Inf,27]','(33,40]','(33,40],'(40, Inf]','(40, Inf]','(40, Inf]']
or with 1e100:
b = ['[-1e100,27]','(33,40]','(33,40],'(40, 1e100]','(40, 1e100]','(40, 1e100]']
</code>```

And someone could help me to explained how Inf works in Python and in R. They are both Infinite but how are they behave so different.

In R I tried function with Inf and it worked:

```<code>as.character(cut(a1,cut_range, include.lowest = TRUE))
</code>```

答:
You actually need pd.cut. It's because you're binning/labeling your data based on ranges:

```<code>a1 = [-np.inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
cut_range = [-np.inf, 27.0, 33.0, 40.0, np.inf]
pd.cut(a1, bins = cut_range, include_lowest=True)
>> [(-inf, 27.0], (-inf, 27.0], (33.0, 40.0], (33.0, 40.0], (40.0, inf], (40.0, inf], (40.0, inf]]
</code>```

Also note that qcut labels data based on quantiles, so if you have [0, 0.25, 0.5, 0.75, 1] as your cut_range then the data will be divided into 4 quantiles. The first quantile will belong to values from the minimum to the 25th percentile(0-0.25). When you add in -np.inf, there can't be a negative percentile value, and hence you got the error.

Title: Divide data into bins with inf Python

Body:
I'm having a problem with qcut function in python. My upper bounds and lower bounds are -Inf and Inf, but when I apply qcut with these bounds, Python return this error "cannot convert float infinity to integer".

My friends told me that I should change the Inf into 1e100 (a very large number represents ) so qcut could use. However, another error occur: "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

Example:

a1 = [-Inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
a2 = [-1e100, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]

cut_range = [-Inf, 27.0, 33.0, 40.0, Inf] #For a1

cut_range = [-1e+100, 27.0, 33.0, 40.0, 1e+100] #For a2

b = pd.qcut(a, cut_range, duplicates = 'drop')

I want to have a final result like this:

b = ['[-Inf,27]','(33,40]','(33,40],'(40, Inf]','(40, Inf]','(40, Inf]']
or with 1e100:
b = ['[-1e100,27]','(33,40]','(33,40],'(40, 1e100]','(40, 1e100]','(40, 1e100]']

And someone could help me to explained how Inf works in Python and in R. They are both Infinite but how are they behave so different.

In R I tried function with Inf and it worked:

as.character(cut(a1,cut_range, include.lowest = TRUE))

Body:
You actually need pd.cut. It's because you're binning/labeling your data based on ranges:

a1 = [-np.inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
cut_range = [-np.inf, 27.0, 33.0, 40.0, np.inf]
pd.cut(a1, bins = cut_range, include_lowest=True)
>> [(-inf, 27.0], (-inf, 27.0], (33.0, 40.0], (33.0, 40.0], (40.0, inf], (40.0, inf], (40.0, inf]]

Also note that qcut labels data based on quantiles, so if you have [0, 0.25, 0.5, 0.75, 1] as your cut_range then the data will be divided into 4 quantiles. The first quantile will belong to values from the minimum to the 25th percentile(0-0.25). When you add in -np.inf, there can't be a negative percentile value, and hence you got the error.


问:
How do I display the contents of local Storage after button click without refreshing the page?
I want the contents of the local Storage to be displayed when the submit button is clicked without having to refresh the page. I don't see the changes made until I manually refresh the page

This function handles the page load. When a button is clicked it shows wrong data. The correct data is only shown when the page is manually refreshed.

```<code>const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage());
</code>```

This is the event listener that handles saving:

```<code>notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const save = (sid, spost, sdate) => {
    const obj = { id: sid, post: spost, date: sdate };
    localStorage.setItem(`${sid}`, JSON.stringify(obj));
  };
  save(generateId(), post.value, dateFormat());
  loadData();
});
</code>```

答:
The loadData function is only adding an event listener. It is not displaying the data in localStorage.

Try replacing the loadData() call in the submit callback with displayStorage().

Body:
I want the contents of the local Storage to be displayed when the submit button is clicked without having to refresh the page. I don't see the changes made until I manually refresh the page

This function handles the page load. When a button is clicked it shows wrong data. The correct data is only shown when the page is manually refreshed.

const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage());

This is the event listener that handles saving:

notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const save = (sid, spost, sdate) => {
    const obj = { id: sid, post: spost, date: sdate };
    localStorage.setItem(`${sid}`, JSON.stringify(obj));
  };
  save(generateId(), post.value, dateFormat());
  loadData();
});


Title: Write to specific objects in json. Python

Body:
You can try:

>>> demo = {
...     "cointiply": [
...         {
...             "balance" : "242537",
...             "time": "28.05.2019"
...         },
...         {
...             "balance": "246362",
...             "time": "29.05.2019"
...         }
...     ]
... }
>>> newo = {
...     "balance": "1234",
...     "time": "forever"
... }
>>> demo["cointiply"].append(newo)
>>> demo
{'cointiply': [{'balance': '242537', 'time': '28.05.2019'}, {'balance': '246362', 'time': '29.05.2019'}, {'balance': '1234', 'time': 'forever'}]}


问:
AJAX Post request sending repeated requests
I'm sending an AJAX POST request for a login form. If I put the wrong combination or I put the right combination, the ajax sends that request plus all the others

Incorrect login:

```<code>function incorrect() {
    $('#loginModal .modal-dialog').addClass('shake');
    $('.error').addClass('alert alert-danger').html("Username ou password incorretos!");
    $('input[type="password"]').val('');
    setTimeout(function () {
        $('#loginModal .modal-dialog').removeClass('shake');
    }, 1000);
}
</code>```

Correct login:

```<code>function correct() {
    $('#loginModal .modal-dialog');
    $('.error').removeClass('alert alert-danger');
    $('.error').addClass('alert alert-success').html("Logado com sucesso!");
    $("#reglogin").toggle();
    $("#conta").toggle();
}
</code>```

Ajax call:

```<code>function loginAjax() {
    $("form").on("submit", function (x) {
        x.preventDefault();

        var form = $(this);

        $.ajax({
            type: 'POST',
            url: '/Login/Login',
            traditional: true,
            data: form.serialize(),
            success: function (data) {
                if (data === false) {
                    incorrect();
                } else if (data === true) {
                    correct();
                }
            }
        });
    });
}
</code>```

Controller:

```<code>SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ToString());
        SqlCommand cmd = new SqlCommand();
        public ActionResult Login(string username, string password)
        {
            conn.Open();
            string passstr = Encrypt(password);
            SqlDataReader reader;

            cmd.Connection = conn;
            cmd.CommandText = string.Format("select * from Cliente where Username='{0}' and Password='{1}'", username, passstr);

            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                Session["Username"] = username;
                string valueFromSession = Session["Username"].ToString();

                conn.Close();
                return Json(data: true);
            } else
            {
                conn.Close();
                return Json(data: false);
            }

        }
</code>```

I want to send only one request every time I submit the form

Thank You!

答: I changed the $("form").on("submit", function (x) to $("form").off("submit").on("submit", function (x) and it worked

Body:
I'm sending an AJAX POST request for a login form. If I put the wrong combination or I put the right combination, the ajax sends that request plus all the others

Incorrect login:

function incorrect() {
    $('#loginModal .modal-dialog').addClass('shake');
    $('.error').addClass('alert alert-danger').html("Username ou password incorretos!");
    $('input[type="password"]').val('');
    setTimeout(function () {
        $('#loginModal .modal-dialog').removeClass('shake');
    }, 1000);
}

Correct login:

function correct() {
    $('#loginModal .modal-dialog');
    $('.error').removeClass('alert alert-danger');
    $('.error').addClass('alert alert-success').html("Logado com sucesso!");
    $("#reglogin").toggle();
    $("#conta").toggle();
}

Ajax call:

function loginAjax() {
    $("form").on("submit", function (x) {
        x.preventDefault();

        var form = $(this);

        $.ajax({
            type: 'POST',
            url: '/Login/Login',
            traditional: true,
            data: form.serialize(),
            success: function (data) {
                if (data === false) {
                    incorrect();
                } else if (data === true) {
                    correct();
                }
            }
        });
    });
}

Controller:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ToString());
        SqlCommand cmd = new SqlCommand();
        public ActionResult Login(string username, string password)
        {
            conn.Open();
            string passstr = Encrypt(password);
            SqlDataReader reader;

            cmd.Connection = conn;
            cmd.CommandText = string.Format("select * from Cliente where Username='{0}' and Password='{1}'", username, passstr);

            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                Session["Username"] = username;
                string valueFromSession = Session["Username"].ToString();

                conn.Close();
                return Json(data: true);
            } else
            {
                conn.Close();
                return Json(data: false);
            }

        }

I want to send only one request every time I submit the form

Thank You!


问:
Export to EXCEL from SQL Server 2017 Reporting Services using command line
Using command line to export report from SQL Server Reporting Services (RDL) to Excel format.

I tried using the RS.exe utility - but it's not working with RDL files. I have a report on SQL Server 2017 Reporting Services; when exporting to Excel using the button on the page, all is working fine.

I am trying to create a script that will export this report every 3 hours.

Any ideas are welcome.

答:
You can make a subscription for the report and set the frequency to your needs.

Go to SSRS report page and click on the ... for that report, then click Subscribe, fill out the information and save.


问:
How to fire vue lifecycle-events for every instance of a component?
I have a vue-component consisting of multiple instances of the same child-component. Some of these child-components are displayed under condition only. My problem is, that when the if-condition turns to false, both the destroyed-methods as well as the beforeDestroy-methods are only called once (for the last child-component which is to be destroyed) but not for every of the mounted child components. Is there any way to change this behaviour and achieve that the destroyed-method is called for every destroyed instance?

I created a fiddle for better understanding: When switching from "Precondition 1" to "Precondition 2 " I would expect that the destroy-method for both, "instance 1" as well as "instance 2" gets fired. But the console shows only conducting the method for instance 2.
When switching back to "Precondition 1" there is no destroy-event bubbling up at all, but I would expect it to be called for instance 3.

```<code>Here is the fiddle:
https://jsfiddle.net/5chq02zs/2/
</code>```

I also tried changing "destroyed" with "beforeDestroy" or "deactivated", but the outcome remains the same. Can anyone point me in the right direction? Thank you.

答:
Add key="id" to elements.

```<code>
    <my-component v-if="picked == 'true'" id="1" :key="1">
      instance 1
    </my-component>
    <my-component v-if="picked == 'true'" id="2" :key="2">
      instance 2
    </my-component>
    <my-component v-if="picked == 'false'" id="3" :key="3">
      instance 3
    </my-component>
</code>```

Body:
I have a vue-component consisting of multiple instances of the same child-component. Some of these child-components are displayed under condition only. My problem is, that when the if-condition turns to false, both the destroyed-methods as well as the beforeDestroy-methods are only called once (for the last child-component which is to be destroyed) but not for every of the mounted child components. Is there any way to change this behaviour and achieve that the destroyed-method is called for every destroyed instance?

I created a fiddle for better understanding: When switching from "Precondition 1" to "Precondition 2 " I would expect that the destroy-method for both, "instance 1" as well as "instance 2" gets fired. But the console shows only conducting the method for instance 2.
When switching back to "Precondition 1" there is no destroy-event bubbling up at all, but I would expect it to be called for instance 3.

Here is the fiddle:
https://jsfiddle.net/5chq02zs/2/

I also tried changing "destroyed" with "beforeDestroy" or "deactivated", but the outcome remains the same. Can anyone point me in the right direction? Thank you.

Body:
Add key="id" to elements.

    <my-component v-if="picked == 'true'" id="1" :key="1">
      instance 1
    </my-component>
    <my-component v-if="picked == 'true'" id="2" :key="2">
      instance 2
    </my-component>
    <my-component v-if="picked == 'false'" id="3" :key="3">
      instance 3
    </my-component>