问:
Cannot read property 'prototype' of undefined in angular
i installed a package via npm in angular(last version) that uses some libs like "fs,stream,.."

when i run ng serve it shows many errors like:

```<code>Can't resolve 'crypto' in '\node_modules\..'
Can't resolve 'fs' in '\node_modules\..'
Can't resolve 'stream' in '\node_modules\..'
</code>```

to resolve the errors i added this code to pckage.json:

```<code>"browser": {
"fs": false,
"path": false,
"os": false,
"crypto" : false,
"stream" : false,
"http" : false,
"tls" : false,
"zlib" : false,
"https" : false,
"net" : false
}
</code>```

after that i see these two errors:

```<code>global is not defined
process is not defined
</code>```

to resolve these two i add this part of code to my polyfills.ts:

```<code>(window as any).global = window;
(window as any).process = {
 env: { DEBUG: undefined },
};
</code>```

and errors gone away but now i have this error in console:

```<code>TypeError: Cannot read property 'prototype' of undefined
at Object.inherits (inherits_browser.js:5)
at Object../node_modules/sshpk/lib/ed-compat.js (ed-compat.js:25)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/private-key.js (private-key.js:17)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/fingerprint.js (fingerprint.js:11)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/key.js (key.js:8)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/index.js (index.js:3)
</code>```

i have no idea What should i do!

thanks for any help!

for more info:

the package tested in react and worked fine

package url :https://www.npmjs.com/package/podchat

and the angular componet

```<code>import { Component, OnInit  } from '@angular/core';
import * as Chat from 'podchat';

@Component({
  selector: 'app-c2',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  flag: boolean;
  params = {
    socketAddress: "wss://chat-sandbox.pod.land/ws", // {**REQUIRED**} Socket Address
    ssoHost: "https://accounts.pod.land", // {**REQUIRED**} Socket Address
    platformHost: "https://sandbox.pod.land:8043/srv/basic-platform", // {**REQUIRED**} Platform Core Address
    fileServer: "https://sandbox.pod.land:8443", // {**REQUIRED**} File Server Address
    serverName: "chat-server", // {**REQUIRED**} Server to to register on
    grantDeviceIdFromSSO: false,
    enableCache: true, // Enable Client side caching
    token: "80fdb34b3086438e91061d0902f33c7b", // {**REQUIRED**} SSO Token
    wsConnectionWaitTime: 500, // Time out to wait for socket to get ready after open
    connectionRetryInterval: 5000, // Time interval to retry registering device or registering server
    connectionCheckTimeout: 10000, // Socket connection live time on server
    messageTtl: 86400000, // Message time to live
    reconnectOnClose: true, // auto connect to socket after socket close
    asyncLogging: {
        onFunction: true, // log main actions on console
        onMessageReceive: true, // log received messages on console
        onMessageSend: true, // log sent messaged on console
        actualTiming: true // log actual functions running time
    }
};
  constructor() {
  }

  ngOnInit() {
    const chat = new Chat(this.params);
  }
}
</code>```

答:
This library depends of the fs package, which is a node.js package to create/read/modify files in your file system. Since you cannot do that in a browser, you will never need those packages. You can remove them.

According to the github page, there is a client part of podchat, you should include that instead:

```<code>import { Component, OnInit  } from '@angular/core';
import * as Chat from 'podchat/src/chat-browser';
</code>```

I'm not sure about the correct syntax to import, but I hope you get the idea.

Body:
i installed a package via npm in angular(last version) that uses some libs like "fs,stream,.."

when i run ng serve it shows many errors like:

Can't resolve 'crypto' in '\node_modules\..'
Can't resolve 'fs' in '\node_modules\..'
Can't resolve 'stream' in '\node_modules\..'

to resolve the errors i added this code to pckage.json:

"browser": {
"fs": false,
"path": false,
"os": false,
"crypto" : false,
"stream" : false,
"http" : false,
"tls" : false,
"zlib" : false,
"https" : false,
"net" : false
}

after that i see these two errors:

global is not defined
process is not defined

to resolve these two i add this part of code to my polyfills.ts:

(window as any).global = window;
(window as any).process = {
 env: { DEBUG: undefined },
};

and errors gone away but now i have this error in console:

TypeError: Cannot read property 'prototype' of undefined
at Object.inherits (inherits_browser.js:5)
at Object../node_modules/sshpk/lib/ed-compat.js (ed-compat.js:25)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/private-key.js (private-key.js:17)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/fingerprint.js (fingerprint.js:11)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/key.js (key.js:8)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/sshpk/lib/index.js (index.js:3)

i have no idea What should i do!

thanks for any help!

for more info:

the package tested in react and worked fine

package url :https://www.npmjs.com/package/podchat

and the angular componet

import { Component, OnInit  } from '@angular/core';
import * as Chat from 'podchat';

@Component({
  selector: 'app-c2',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  flag: boolean;
  params = {
    socketAddress: "wss://chat-sandbox.pod.land/ws", // {**REQUIRED**} Socket Address
    ssoHost: "https://accounts.pod.land", // {**REQUIRED**} Socket Address
    platformHost: "https://sandbox.pod.land:8043/srv/basic-platform", // {**REQUIRED**} Platform Core Address
    fileServer: "https://sandbox.pod.land:8443", // {**REQUIRED**} File Server Address
    serverName: "chat-server", // {**REQUIRED**} Server to to register on
    grantDeviceIdFromSSO: false,
    enableCache: true, // Enable Client side caching
    token: "80fdb34b3086438e91061d0902f33c7b", // {**REQUIRED**} SSO Token
    wsConnectionWaitTime: 500, // Time out to wait for socket to get ready after open
    connectionRetryInterval: 5000, // Time interval to retry registering device or registering server
    connectionCheckTimeout: 10000, // Socket connection live time on server
    messageTtl: 86400000, // Message time to live
    reconnectOnClose: true, // auto connect to socket after socket close
    asyncLogging: {
        onFunction: true, // log main actions on console
        onMessageReceive: true, // log received messages on console
        onMessageSend: true, // log sent messaged on console
        actualTiming: true // log actual functions running time
    }
};
  constructor() {
  }

  ngOnInit() {
    const chat = new Chat(this.params);
  }
}

Body:
This library depends of the fs package, which is a node.js package to create/read/modify files in your file system. Since you cannot do that in a browser, you will never need those packages. You can remove them.

According to the github page, there is a client part of podchat, you should include that instead:

import { Component, OnInit  } from '@angular/core';
import * as Chat from 'podchat/src/chat-browser';

I'm not sure about the correct syntax to import, but I hope you get the idea.


来源: stackexchange

问:
encoding - displaying EURO symbol and more - UTF-8 charset
this is driving me bonkers. I have a column in my table with all currency symbols and am trying to display them but to no avail.

my page is set as utf8

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

I have tried mb_convert_encoding, utf8_encode but cant seem to s=get it to display correctly.

At the moment I have

```<code>function isUTF8($str) {
    if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
        return true;
    } else {
        return false;
    }
}
echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
</code>```

which also doesn't work.

any help is much appreciated.

EDIT

```<code>function get_currency_symbol( $code ) {
$con = Database::getInstance();
    $re = $con->query("SELECT * FROM `countryinfo` WHERE currency_code = '$code'");
    if( $re->num_rows == 0 ) {
        return '£';
    }
    $ar = $re->fetch_assoc();
    echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
    //return iconv( mb_detect_encoding( $ar['currrency_symbol'] ), 'UTF-8//TRANSLIT', $ar['currrency_symbol'] );
}
</code>```

///

```<code>abstract class Database {
    private static $instance = NULL;
    private function __clone() {}
    public function __construct() {}
    public static function getInstance() {
        if ( NULL === self::$instance ) {
            self::$instance = new MySQLi( DBSERVER, DBUSER, DBPASS, DBNAME );
        }
        self::$instance->query("SET NAMES 'utf8'");
        return self::$instance;
    }
    public function kill_con() {
        self::$instance->close();
    }
}
</code>```

答:
Do you use PDO for your database connection? If yes, try using:

```<code>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
</code>```

As a an option when creating the connection.

See: http://www.php.net/manual/de/pdo.construct.php -> $driver_options

ContentLicense: CC BY-SA 3.0

Body:
this is driving me bonkers. I have a column in my table with all currency symbols and am trying to display them but to no avail.

my page is set as utf8

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

I have tried mb_convert_encoding, utf8_encode but cant seem to s=get it to display correctly.

At the moment I have

function isUTF8($str) {
    if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
        return true;
    } else {
        return false;
    }
}
echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );

which also doesn't work.

any help is much appreciated.

EDIT

function get_currency_symbol( $code ) {
$con = Database::getInstance();
    $re = $con->query("SELECT * FROM `countryinfo` WHERE currency_code = '$code'");
    if( $re->num_rows == 0 ) {
        return '£';
    }
    $ar = $re->fetch_assoc();
    echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
    //return iconv( mb_detect_encoding( $ar['currrency_symbol'] ), 'UTF-8//TRANSLIT', $ar['currrency_symbol'] );
}

///

abstract class Database {
    private static $instance = NULL;
    private function __clone() {}
    public function __construct() {}
    public static function getInstance() {
        if ( NULL === self::$instance ) {
            self::$instance = new MySQLi( DBSERVER, DBUSER, DBPASS, DBNAME );
        }
        self::$instance->query("SET NAMES 'utf8'");
        return self::$instance;
    }
    public function kill_con() {
        self::$instance->close();
    }
}

Body:
Do you use PDO for your database connection? If yes, try using:

PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'

As a an option when creating the connection.

See: http://www.php.net/manual/de/pdo.construct.php -> $driver_options


问:
Simple mapping of integer values to another integer
This is a very simple problem but I have not found an easy way to solve it. Consider the following sets of integers (these are not actual Python sets since they contain an infinite number of members):

```<code>set1 = (0, 3, 6, 9,  ...) --> 0
set2 = (1, 4, 7, 10, ...) --> 2
set3 = (2, 5, 8, 11, ...) --> 4
</code>```

This is: assuming I receive a random positive integer as input, I need to map those that belong to set1 to the integer 0, those in set2 to 2 and those in set3 to 4.

Is there an "easy" way to do this in Python?

答:
def map_to_set(i):
    return 2*(i%3)
```

ContentLicense: CC BY-SA 4.0

Body:
This is a very simple problem but I have not found an easy way to solve it. Consider the following sets of integers (these are not actual Python sets since they contain an infinite number of members):

set1 = (0, 3, 6, 9,  ...) --> 0
set2 = (1, 4, 7, 10, ...) --> 2
set3 = (2, 5, 8, 11, ...) --> 4

This is: assuming I receive a random positive integer as input, I need to map those that belong to set1 to the integer 0, those in set2 to 2 and those in set3 to 4.

Is there an "easy" way to do this in Python?

Body:
def map_to_set(i):
    return 2*(i%3)


问:
ASP.NET, two Web.Config
I have a .NET application with all the aspx pages and the main web.config in the root folder but I now have a situation where I need a portal like section for other users. I have created a new folder with it's own unique aspx pages and a second web.config.

I especially need a second web.config to have the <authentication> with a <forms loginUrl="" defaultUrl="> for this portal section and a <authentication> too.

I have implemeted this second web.config in the way I created the first and I am getting this error message:

```<code>    It is an error to use a section registered as allowDefintion='MachineToApplication'
    beyond application level. This error can be caused by a virtual directory not being
    configured as an application in IIS.
</code>```

Now I think the main web.config file is conflicting with the this second webconfig in it's folder. I'm not sure how to fix this, I have seen theories on how this works but no solid code.

Thank you for any suggestions and your time, it is much appreciated.

答: In IIS, create a virtual directory, under your main application. The local web.config will overide stuff in your main web.config, but still use you main web.config for everything else (i.e. ConnectionStrings, encoding, etc.).</p>

Title: ASP.NET, two Web.Config

Body:
I have a .NET application with all the aspx pages and the main web.config in the root folder but I now have a situation where I need a portal like section for other users. I have created a new folder with it's own unique aspx pages and a second web.config.

I especially need a second web.config to have the <authentication> with a <forms loginUrl="" defaultUrl="> for this portal section and a <authentication> too.

I have implemeted this second web.config in the way I created the first and I am getting this error message:

    It is an error to use a section registered as allowDefintion='MachineToApplication'
    beyond application level. This error can be caused by a virtual directory not being
    configured as an application in IIS.

Now I think the main web.config file is conflicting with the this second webconfig in it's folder. I'm not sure how to fix this, I have seen theories on how this works but no solid code.

Thank you for any suggestions and your time, it is much appreciated.


问:
Find all duplicate ids and add unique key
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

```<code><input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
</code>```

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

```<code><input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
</code>```

JS

```<code> $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });
</code>```

Any ideas? Thank you all.

答:
Try like this.

 var allId = [];
 var data = [];
 $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(allId.indexOf(this.id) < 0){
    data[this.id] = 1;
    allId.push(this.id);
  } else {
    data[this.id]++;
  }
  $(this).attr('id', $(this).attr('id') + data[this.id]);
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" /></code>```

Body:
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />

JS

 $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });

Any ideas? Thank you all.

Body:
Try like this.

 var allId = [];
 var data = [];
 $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(allId.indexOf(this.id) < 0){
    data[this.id] = 1;
    allId.push(this.id);
  } else {
    data[this.id]++;
  }
  $(this).attr('id', $(this).attr('id') + data[this.id]);
 });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />


问:
How does the country path drupal module work?
I want my Drupal site to be divided:

```<code>/uk/en
/uk/fr
/us/en
/us/es
</code>```

Based on this advice, I was told to use this. The problem is, the module has no configuration page, nor does it have a README. I have scanned the code and it's not immediately apparent how to use it with the Domain Module.

Anybody been able to use this and get it working as described above?

答:
Country Path module extends domain access module. You do not have to configure anything except checking 'country path' in 'configuration->languages->detection and selection'. The country suffix will be added automatically based on the country domain selected in your domain record.
Example: I had created three domain records for india australia and singapore with the same URL and was able to access all the three by prefixing /in /au  and /sg respectively

Body:
I want my Drupal site to be divided:

/uk/en
/uk/fr
/us/en
/us/es

Based on this advice, I was told to use this. The problem is, the module has no configuration page, nor does it have a README. I have scanned the code and it's not immediately apparent how to use it with the Domain Module.

Anybody been able to use this and get it working as described above?


问:
How to change className?
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

```<code>    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [
            <div
              id="firstDiv"
              key={1}
              className={"first"}
              onClick={this.changeClass}
            />
          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return <div>{this.state.myDiv.map(div => div)}</div>;
      }
    }

    export default App;
</code>```

答:
there's a simpler option try this:</p>

```<code>import React, { Component } from "react";
import "./styles/style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      className: "first"
    };
  }

  changeClass = () => {
    this.setState({className: "second"});
  };

  render() {
    return <div
             id="firstDiv"
             className={this.state.className}
             onClick={this.changeClass}>
           </div>;
   }
}

export default App;
</code>```

Title: How to change className?

Body:
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [

          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return
{this.state.myDiv.map(div => div)}
;
      }
    }

    export default App;

Body:
there's a simpler option try this:

import React, { Component } from "react";
import "./styles/style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      className: "first"
    };
  }

  changeClass = () => {
    this.setState({className: "second"});
  };

  render() {
    return <div
             id="firstDiv"
             className={this.state.className}
             onClick={this.changeClass}>
           </div>;
   }
}

export default App;


问:
setTimeOut() solution on Twitter
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

```<code>var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);
</code>```

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

```<code>var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});
</code>```

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.

答:
@ Question 1:

I read your related link and I think the answer to your question is if ( didScroll ) {. This query prevents that your code will be executed all time, even if it is not necessary. But I'm not sure to 100%.

Title: setTimeOut() solution on Twitter

Body:
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.


答:
No need for jQuery:

const ids = {}

document.querySelectorAll('[id]').forEach(node => {
  if (ids[node.id] !== undefined) {
    ids[node.id] += 1
  } else {
    ids[node.id] = 1
  }
  node.id = `${node.id}${ids[node.id]}`

})

document.querySelectorAll('[id]').forEach(node => console.log(node))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" /></code>```

Title: Find all duplicate ids and add unique key

Body:
No need for jQuery:

const ids = {}

document.querySelectorAll('[id]').forEach(node => {
  if (ids[node.id] !== undefined) {
    ids[node.id] += 1
  } else {
    ids[node.id] = 1
  }
  node.id = `${node.id}${ids[node.id]}`

})

document.querySelectorAll('[id]').forEach(node => console.log(node))

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />


问:
Convert html url into uri module ansible
I am looking to convert the html url into ansible uri module, when i load the url in browser it gives results, but from uri module i am getting errors

My URL:-
https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName = test1)&fetch=true

Ansible uri module:-

```<code>      uri:
        url: https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName = "test1")&fetch=true
        user: myusername
        password: mypass
        force_basic_auth: yes
        follow_redirects: all
        return_content: yes
        method: GET
      register: get_data
    - debug: var=get_data
</code>```

I am getting this error:-

```<code>fatal: [localhost]: FAILED! => {"cache_control": "no-cache", "cf_ray": "4dd5a65fea0cba46-ATL", "changed": false, "connection": "close", "content": "<html><body><h1>400 Bad request</h1>\nYour browser sent an invalid request.\n</body></html>\n", "content_type": "text/html", "date": "Mon, 27 May 2019 05:39:42 GMT",
</code>```

Please help

答:
I suspect the problem is that your URL contains spaces (), which aren't valid URL characters. If I run your code against a sample web server, I see the following error after the uri module has successfully negotiated an SSL connection:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: http.client.InvalidURL: URL can't contain control characters. '/slm/webservic
  e/v2.0/user?query=(FirstName = "test1")&fetch=true' (found at least ' ')
  fatal: [localhost]: FAILED! => {"changed": false, "content": "", "elapsed": 0, "msg": "Status code was -1 and not [200]: An unknown error occurred: URL can't contain control
  characters. '/slm/webservice/v2.0/user?query=(FirstName = \"test1\")&fetch=true' (found at least ' ')", "redirected": false, "status": -1, "url": "https://localhost:8080/slm/
  webservice/v2.0/user?query=(FirstName = \"test1\")&fetch=true"}

Spaces in a URL should be encoded as + or as %20, so you could write your URL like this:

```<code>https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName+=+"test1")&fetch=true
</code>```

Or like this:

```<code>https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName%20=%20"test1")&fetch=true
</code>```

Or, if the query is valid without spaces, just write:

```<code>https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName="test1")&fetch=true
</code>```

Body:
I am looking to convert the html url into ansible uri module, when i load the url in browser it gives results, but from uri module i am getting errors

My URL:-
https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName = test1)&fetch=true

Ansible uri module:-

      uri:
        url: https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName = "test1")&fetch=true
        user: myusername
        password: mypass
        force_basic_auth: yes
        follow_redirects: all
        return_content: yes
        method: GET
      register: get_data
    - debug: var=get_data

I am getting this error:-

fatal: [localhost]: FAILED! => {"cache_control": "no-cache", "cf_ray": "4dd5a65fea0cba46-ATL", "changed": false, "connection": "close", "content": "
400 Bad request
\nYour browser sent an invalid request.\n\n", "content_type": "text/html", "date": "Mon, 27 May 2019 05:39:42 GMT",

Please help

Body:
I suspect the problem is that your URL contains spaces (), which aren't valid URL characters. If I run your code against a sample web server, I see the following error after the uri module has successfully negotiated an SSL connection:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: http.client.InvalidURL: URL can't contain control characters. '/slm/webservic
  e/v2.0/user?query=(FirstName = "test1")&fetch=true' (found at least ' ')
  fatal: [localhost]: FAILED! => {"changed": false, "content": "", "elapsed": 0, "msg": "Status code was -1 and not [200]: An unknown error occurred: URL can't contain control
  characters. '/slm/webservice/v2.0/user?query=(FirstName = \"test1\")&fetch=true' (found at least ' ')", "redirected": false, "status": -1, "url": "https://localhost:8080/slm/
  webservice/v2.0/user?query=(FirstName = \"test1\")&fetch=true"}

Spaces in a URL should be encoded as + or as %20, so you could write your URL like this:

https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName+=+"test1")&fetch=true

Or like this:

https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName%20=%20"test1")&fetch=true

Or, if the query is valid without spaces, just write:

https://rally1.rallydev.com/slm/webservice/v2.0/user?query=(FirstName="test1")&fetch=true


问:
How to fix an SQL design
I'm doing the study of a medical software. This software asks the patients questions about their symptoms and from them it can determine the possible pathologies. My study involves comparing the symptoms and pathologies found by the software with those from the hospital.

In order to make my work easier, I decided to enter the data in a database made with javadb on netbeans 8.2.

But it seems like that I did something wrong since my statement doesn't work.

I thank you in advance anybody who would take the time to help me.

SQL design:

```<code>Create table Patients(
nip varchar(32) primary key,
sexe varchar(8) not null,
age int not null,
dateArrivee timestamp not null,
constraint ck_sexe check(sexe='Male' or sexe='Female'),
constraint ck_age check (age>=0)
);
</code>```

```<code>Create table Symptoms(
symptomID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
symptom varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
</code>```

```<code>Create table Pathologies(
pathologyID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
pathology varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
</code>```

Values entered:

```<code>Insert into Patients values ('001','Male', 25, '2019-05-27 14:00:00');

Insert into Patients values ('002', 'Female', 30, '2019-05-26 15:00:00');

Insert into Symptoms values (, '001', 'Headache', 'SOFTWARE');

Insert into Pathologies values (,'001', 'Fever', 'SOFTWARE');

Insert into Symptoms values (,'001', 'Stomache', 'HOSTPITAL');

Insert into Pathologies values (, '001', 'Gastro-enteritis', 'HOSPITAL');

Insert into Symptoms values(,'002', 'Headache', 'SOFTWARE');

Insert into Pathologies values (,'002', 'Unknow', 'SOFTWARE');
</code>```

SQL statement:

```<code>Select *
from (Patients inner join
      Symptoms
      on Patients.nip = Symptoms.nip
     ) inner join
     Pathologies
    on Symptoms.nip = Pathologies.nip
 where Symptoms.origin = 'MEDVIR' and
       Pathologies.origin = 'MEDVIR';
</code>```

So sorry I forgot to put the errors I'm getting.

SQL design:

First I have an error concerning the auto_incrementation, even thought this was the good method. It says that the syntax is incorrect near the 'generated'.

Values entered:

Here I have an error concerning the a wrong syntax near the coma (',').

SQL statement:

Lastly I have an error saying that the object 'Patients' is unavaible.

答:
If I am not wrong, you are trying to fetch entries where 'Origin' = 'MEDVIR'
Although, none of your insert statements have Origin as 'MEDVIR'

Please check below,

```<code>Select *
from (Patients inner join
      Symptoms
      on Patients.nip = Symptoms.nip
     ) inner join
     Pathologies
    on Symptoms.nip = Pathologies.nip
 where Symptoms.origin IN ('SOFTWARE', 'HOSPITAL') and
       Pathologies.origin IN ('SOFTWARE', 'HOSPITAL');
</code>```

Also, some of your INSERT statement has an extra comma before the values, which would cause a syntax error.

Title: How to fix an SQL design

Body:
I'm doing the study of a medical software. This software asks the patients questions about their symptoms and from them it can determine the possible pathologies. My study involves comparing the symptoms and pathologies found by the software with those from the hospital.

In order to make my work easier, I decided to enter the data in a database made with javadb on netbeans 8.2.

But it seems like that I did something wrong since my statement doesn't work.

I thank you in advance anybody who would take the time to help me.

SQL design:

Create table Patients(
nip varchar(32) primary key,
sexe varchar(8) not null,
age int not null,
dateArrivee timestamp not null,
constraint ck_sexe check(sexe='Male' or sexe='Female'),
constraint ck_age check (age>=0)
);

Create table Symptoms(
symptomID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
symptom varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);

Create table Pathologies(
pathologyID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
pathology varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);

Values entered:

Insert into Patients values ('001','Male', 25, '2019-05-27 14:00:00');

Insert into Patients values ('002', 'Female', 30, '2019-05-26 15:00:00');

Insert into Symptoms values (, '001', 'Headache', 'SOFTWARE');

Insert into Pathologies values (,'001', 'Fever', 'SOFTWARE');

Insert into Symptoms values (,'001', 'Stomache', 'HOSTPITAL');

Insert into Pathologies values (, '001', 'Gastro-enteritis', 'HOSPITAL');

Insert into Symptoms values(,'002', 'Headache', 'SOFTWARE');

Insert into Pathologies values (,'002', 'Unknow', 'SOFTWARE');

SQL statement:

Select *
from (Patients inner join
      Symptoms
      on Patients.nip = Symptoms.nip
     ) inner join
     Pathologies
    on Symptoms.nip = Pathologies.nip
 where Symptoms.origin = 'MEDVIR' and
       Pathologies.origin = 'MEDVIR';

So sorry I forgot to put the errors I'm getting.

SQL design:

First I have an error concerning the auto_incrementation, even thought this was the good method. It says that the syntax is incorrect near the 'generated'.

Values entered:

Here I have an error concerning the a wrong syntax near the coma (',').

SQL statement:

Lastly I have an error saying that the object 'Patients' is unavaible.

Body:
If I am not wrong, you are trying to fetch entries where 'Origin' = 'MEDVIR'
Although, none of your insert statements have Origin as 'MEDVIR'

Please check below,

Select *
from (Patients inner join
      Symptoms
      on Patients.nip = Symptoms.nip
     ) inner join
     Pathologies
    on Symptoms.nip = Pathologies.nip
 where Symptoms.origin IN ('SOFTWARE', 'HOSPITAL') and
       Pathologies.origin IN ('SOFTWARE', 'HOSPITAL');

Also, some of your INSERT statement has an extra comma before the values, which would cause a syntax error.


问:
Problem with my quicksort, it doesn't sort correctly
OK I am trying to make Prima algorithm so i need my edges array sorted, I tried to use quicksort here but it didn't work as I planned.

```<code>#include <iostream>

using namespace std;

void Sort (int arr[100][4], int m, int l) {
     int i,j,x,v;

    i=m;
    j=l;
    x=(i+j)/2;
    do
    {
        while (((arr[i][3]<arr[x][3]))and(i<=l)) i++;
        while (((arr[j][3]>arr[x][3]))and(j>=m)) j--;
        if (i<=j)
        {
        v=arr[i][1];
        arr[i][1]=arr[j][1];
        arr[j][1]=v;
        v=arr[i][2];
        arr[i][2]=arr[j][2];
        arr[j][2]=v;
        v=arr[i][3];
        arr[i][3]=arr[j][3];
        arr[j][3]=v;
        i++;
        j--;
        }
    }
    while (i<=j);
    if (i<l) Sort(arr,i,l);
    if (m<j) Sort(arr,m,j);
}

int main () {
    int i,x,y,z,n,m;
    int a[100][4];
    fill(&a[0][0],&a[0][0]+400,0);
    cout<<"Enter number of nodes and edges\n";
    cin>>n>>m;
    cout<<"Enter edges and their weights\n";
    for (i=0;i<m;i++) {
        cin>>x>>y>>z;
        a[i][1]=min(x,y);
        a[i][2]=max(x,y);
        a[i][3]=z;
        }
    Sort (a,0,m-1);
    for (i=0;i<m;i++) {
        cout<<i+1<<") "<<a[i][1]<<' '<<a[i][2]<<' '<<a[i][3]<<endl;
    }
    return 0;
}

</code>```

what I put is

5 10

1 2 4

1 3 7

4 1 5

5 1 8

2 3 3

2 4 6

2 5 6

3 4 8

3 5 2

4 5 4

what I get is
1) 3 5 2

2) 2 3 3

3) 1 4 5

4) 1 2 4

5) 4 5 4

6) 2 5 6

7) 2 4 6

8) 1 3 7

9) 1 5 8

10) 3 4 8

I don't understand why 5 is going ahead of 4's. Hope you could help.

答:
You choose the pivot element in the middle of the (sub)array, which is fine, but you leave it in that position when you run the partitioning loop, and rely on it to stay there, which is not ok.  With your approach, the pivot is likely to be swapped to a different position during the ordinary course of partitioning, after which the remainder of the partitioning will be based on the key swapped into the pivot's original position, which is likely to be different.

The usual approach is to start by swapping the pivot element to one end of the array or the other, partition the rest of the array, and then afterward swap the pivot into its correct position, as discovered via the partitioning process.

Body:
OK I am trying to make Prima algorithm so i need my edges array sorted, I tried to use quicksort here but it didn't work as I planned.

#include <iostream>

using namespace std;

void Sort (int arr[100][4], int m, int l) {
     int i,j,x,v;

    i=m;
    j=l;
    x=(i+j)/2;
    do
    {
        while (((arr[i][3]<arr[x][3]))and(i<=l)) i++;
        while (((arr[j][3]>arr[x][3]))and(j>=m)) j--;
        if (i<=j)
        {
        v=arr[i][1];
        arr[i][1]=arr[j][1];
        arr[j][1]=v;
        v=arr[i][2];
        arr[i][2]=arr[j][2];
        arr[j][2]=v;
        v=arr[i][3];
        arr[i][3]=arr[j][3];
        arr[j][3]=v;
        i++;
        j--;
        }
    }
    while (i<=j);
    if (i<l) Sort(arr,i,l);
    if (m<j) Sort(arr,m,j);
}

int main () {
    int i,x,y,z,n,m;
    int a[100][4];
    fill(&a[0][0],&a[0][0]+400,0);
    cout<<"Enter number of nodes and edges\n";
    cin>>n>>m;
    cout<<"Enter edges and their weights\n";
    for (i=0;i<m;i++) {
        cin>>x>>y>>z;
        a[i][1]=min(x,y);
        a[i][2]=max(x,y);
        a[i][3]=z;
        }
    Sort (a,0,m-1);
    for (i=0;i<m;i++) {
        cout<<i+1<<") "<<a[i][1]<<' '<<a[i][2]<<' '<<a[i][3]<<endl;
    }
    return 0;
}

what I put is

5 10

1 2 4

1 3 7

4 1 5

5 1 8

2 3 3

2 4 6

2 5 6

3 4 8

3 5 2

4 5 4

what I get is
1) 3 5 2

2) 2 3 3

3) 1 4 5

4) 1 2 4

5) 4 5 4

6) 2 5 6

7) 2 4 6

8) 1 3 7

9) 1 5 8

10) 3 4 8

I don't understand why 5 is going ahead of 4's. Hope you could help.


问:
How to execute nmap from ping script
I'm learning bash for pentesting, so i started with kinda usefull things for me. I created a script, thath scan whole network by my requirements. But at the end of script i want to do Nmap of this Ips.

And thats the problem, no idea how to execute it.

```<code>time=$(date +"%T")
ip=(192.168.0)
echo -e "Scan started at $time"
for x in $(seq 1 254); do
    ping -c 1 $ip.$x | grep "from" &
done

echo -n "Would you like to do NMAP scan (y/n)? "
read nmap
if [ "$nmap" != "${nmap#[Yy]}" ] ;then
    #here i guess have to be something
else
    #here i guess have to be something
fi
</code>```

If user chose "y" than NMAP should scan IPs, which are pinged as live.

答:
Here is a simple solution on how to use ping and nmap together</p>

```<code>#!/bin/bash
ipfile=$(mktemp)               # create tmpfile for online ip's
trap 'rm -f "$ipfile"' EXIT    # rm tmpfile on exit

BASE="192.168.0"               # define your IP base

for (( i=1; i <= 254; i++ )); do
    ip="$BASE.$i"
    printf "Scanning %s " "$ip"

    # check if ip is online
    if ping -c 1 "$ip" | grep "from" >/dev/null; then
        printf "online\n"

        # write ip's into tmpfile
        printf "%s\n" "$ip" >> "$ipfile"
    else
        printf "offline\n"
    fi
done

echo -n "Would you like to do NMAP scan (y/n)? "
read -r answer
if [ "$answer" = "y" ]; then
    # check all ip's in tmpfile with nmap
    nmap -iL "$ipfile"
fi
</code>```

Title: How to execute nmap from ping script

Body:
I'm learning bash for pentesting, so i started with kinda usefull things for me. I created a script, thath scan whole network by my requirements. But at the end of script i want to do Nmap of this Ips.

And thats the problem, no idea how to execute it.

time=$(date +"%T")
ip=(192.168.0)
echo -e "Scan started at $time"
for x in $(seq 1 254); do
    ping -c 1 $ip.$x | grep "from" &
done

echo -n "Would you like to do NMAP scan (y/n)? "
read nmap
if [ "$nmap" != "${nmap#[Yy]}" ] ;then
    #here i guess have to be something
else
    #here i guess have to be something
fi

If user chose "y" than NMAP should scan IPs, which are pinged as live.

Body:
Here is a simple solution on how to use ping and nmap together

#!/bin/bash
ipfile=$(mktemp)               # create tmpfile for online ip's
trap 'rm -f "$ipfile"' EXIT    # rm tmpfile on exit

BASE="192.168.0"               # define your IP base

for (( i=1; i <= 254; i++ )); do
    ip="$BASE.$i"
    printf "Scanning %s " "$ip"

    # check if ip is online
    if ping -c 1 "$ip" | grep "from" >/dev/null; then
        printf "online\n"

        # write ip's into tmpfile
        printf "%s\n" "$ip" >> "$ipfile"
    else
        printf "offline\n"
    fi
done

echo -n "Would you like to do NMAP scan (y/n)? "
read -r answer
if [ "$answer" = "y" ]; then
    # check all ip's in tmpfile with nmap
    nmap -iL "$ipfile"
fi


问:
how to recive the response of a post method send with guzzle
I am calling an api with guzzle and Sending some data and that api return me  some data that i want to recive them and show them so here is my code :

```<code>$requestapi = $client->post('http:url/api/v1/transaction/Verify', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "tn":"1905463527",
        }'
    ]);
</code>```

now when i dd the $requestapi its now showing me the result that verify api returns and just showing me the 200 response .

答:
GuzzleHttp\Client::post method returns GuzzleHttp\Psr7\Response object.
You can simply use getBody method to access the response body.

```<code>$response = $client->post(...);
$contents = $response->getBody()->getContents();
</code>```

Body:
I am calling an api with guzzle and Sending some data and that api return me  some data that i want to recive them and show them so here is my code :

$requestapi = $client->post('http:url/api/v1/transaction/Verify', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "tn":"1905463527",
        }'
    ]);

now when i dd the $requestapi its now showing me the result that verify api returns and just showing me the 200 response .

Body:
GuzzleHttp\Client::post method returns GuzzleHttp\Psr7\Response object.
You can simply use getBody method to access the response body.

$response = $client->post(...);
$contents = $response->getBody()->getContents();


问:
How to make a perfect cube
In Unity, I create a cube with scale 1,1,1. Position is 0,1,0.
Then I placed it above a plane which is 15,1,5000. Position is 0,0,0.
I checked if the cube is below 1 in Y-axis, this will mean to me that the cube fall on the plane. I can control this cube by going left or right. If I go to left, there's no issue. If I go to right, my position becomes 0.9999998~. This makes my checking of falling become true even though the cube is still on the plane. Somehow, the cube seems not be be a perfect cube. Hope someone can enlighten me on why is this happening. Thanks!</p>

答:
This may not be the answer you want, but - in poor words - computers' arithmetic is finite (search for floating point arithmetic). So, the "perfect cube" that you're looking for does not exist in the finite representation a machine could perform.
Moreover, Unity has its own physics engine that (like all physics engines) approximates the calculus of real world during each operation (translation, rotation, scaling).

The only way in which you can overcome the problem is by doing comparisons not with exact values (0, 1) but with ranges.
To maintain "order" in the coordinate system of your scene you could also - at fixed intervals - "adjust" your values, so, for example, manually setting the coordinate value to 1 if it is between 0.95 and 1.05 (adjust the values with your world's coordinate system, of course).

Related note: in your comment you say "But my point is that why it seems like the cube is not perfect 1x1x1. Somehow it's like 1x1x0.9999998". The fact is that a VR system, like Unity, does not maintain the objects' size in memory, but their vertices' coordinates. You feel like the object's dimensions have changed due to the translation, but this is not true in a strict way: it's just a finite approximation of the vertices' values for their X, Y, Z.

Title: How to make a perfect cube


问:
How to destroy a body based on its position in box2d?
I am new to objective-c. I am currently working on a game using cocos2d and box2d. Let me describe my game in details:

In my game I have a main character standing on top of a building. Below the building there's this the road. Enemies pass by the road at various random speeds entering the screen from right and exiting from the left. I have created the enemies as b2_dynamicBodies and set a random velocity for each of them using SetLinearVelocity(). The main character shoots the enemies. When the projectile hits the enemies, both the projectile and the enemy are destroyed. What I want to do is that the enemies which are not shot and which move out of the screen, I want to destroy these enemies once they move out of the screen by cheking their coordinates. I have tried using world->DestroyBody(body), but it doesnt work. Pls help me with this!

p.s. I am not creating the enemies as individual distinct bodies, but I have a method which creates a body and makes it move and then I have called the method inside init with a time interval.

答:
Assign tag to the sprite.Here i am using 10.check that sprite moves out off the screen by getting their x-position.If it is Less than 0 or greater than 480(for landscape).Then use the following code to destroy that body.

```<code>for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{

    if (b->GetUserData() != NULL) {

        CCSprite *temp1 = (CCSprite*)b->GetUserData();

        if(temp1.tag == 10)
        {
            NSLog(@"Destroying here");
                            world->DestroyBody(b);
            [self removeChild:temp1 cleanup:YES];

        }

    }
</code>```

}

ContentLicense: CC BY-SA 2.5

Body:
Assign tag to the sprite.Here i am using 10.check that sprite moves out off the screen by getting their x-position.If it is Less than 0 or greater than 480(for landscape).Then use the following code to destroy that body.

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{

    if (b->GetUserData() != NULL) {

        CCSprite *temp1 = (CCSprite*)b->GetUserData();

        if(temp1.tag == 10)
        {
            NSLog(@"Destroying here");
                            world->DestroyBody(b);
            [self removeChild:temp1 cleanup:YES];

        }

    }

}


问:
Why does casting the result from a controller in a unit test return null?
I am in the process of equipping my sources with unit tests, but I made a mistake here.
What can I do at this point if the value is really "null"?
Is that even possible?

I have tried to figure out how others solve it but with the following thread I don't quite get along.
C# in my unit test i want to see if it is null or an empty string

--> If I use IsNullOrEmpty() like in the example above, how does that look like in my code snippet?

This is the affected area in my unit test:

```<code>Assert.That(deviceInfo.SerialNumber == null);
</code>```

The following error message appears:

Message: System.ArgumentNullException : Value cannot be null. Parameter name: source

Edit - This is what my environment looks like:

Here is the class with the DeviceDetails object which has all information in the body.

```<code>public virtual IActionResult DevicesIdGet([FromRoute][Required]string id)
{
    var device = _deviceManager.GetDevice(id);

    if (device == null)
        return NotFound();

    var deviceDetails = new DeviceDetails
    {
        IsOnline = device.IsOnline(),
        SerialNumber = null
    };

    return Ok(deviceDetails);
}
</code>```

Unit-Test

```<code> private Device _testDevice;

 [SetUp]
 public void SetUp()
    {
        _testDevice = new Device
        {
            Id = 1,
            DeviceType = 1,
            DisplayName = "TestDevice",
            IpAddress = IPAddress.Parse("127.0.0.1"),
            IpAddressString = "127.0.0.1"
        };
    }

[Test]
public void If_DeviceIsAvailable_Then_DeviceIdIsSelected()
{
    // ARRANGE
    var deviceManagerMock = new Mock<IDeviceManager>();
    deviceManagerMock.Setup(manager => manager.GetDevices(false))
        .Returns(new List<Device>
                 {
                     _testDevice
                 })
        .Verifiable();

    var subject = new DevicesApiController(deviceManagerMock.Object);

    // ACT
    var result = subject.DevicesIdGet("1");

    // ASSERT
    var deviceInfos = result as IEnumerable<DeviceDetails>;
    var deviceInfo = deviceInfos.Single();
    Assert.That(deviceInfo.IsOnline == true);
    Assert.That(deviceInfo.SerialNumber == null);
}
</code>```

答:
On the basis of code posted, it appears deviceInfo can be null. You can you the following:</p>

```<code> if (deviceInfo == null)
      throw new ArgumentNullException(“source”);

 // rest of the code
</code>```

Body:
I am in the process of equipping my sources with unit tests, but I made a mistake here.
What can I do at this point if the value is really "null"?
Is that even possible?

I have tried to figure out how others solve it but with the following thread I don't quite get along.
C# in my unit test i want to see if it is null or an empty string

--> If I use IsNullOrEmpty() like in the example above, how does that look like in my code snippet?

This is the affected area in my unit test:

Assert.That(deviceInfo.SerialNumber == null);

The following error message appears:

Message: System.ArgumentNullException : Value cannot be null. Parameter name: source

Edit - This is what my environment looks like:

Here is the class with the DeviceDetails object which has all information in the body.

public virtual IActionResult DevicesIdGet([FromRoute][Required]string id)
{
    var device = _deviceManager.GetDevice(id);

    if (device == null)
        return NotFound();

    var deviceDetails = new DeviceDetails
    {
        IsOnline = device.IsOnline(),
        SerialNumber = null
    };

    return Ok(deviceDetails);
}

Unit-Test

 private Device _testDevice;

 [SetUp]
 public void SetUp()
    {
        _testDevice = new Device
        {
            Id = 1,
            DeviceType = 1,
            DisplayName = "TestDevice",
            IpAddress = IPAddress.Parse("127.0.0.1"),
            IpAddressString = "127.0.0.1"
        };
    }

[Test]
public void If_DeviceIsAvailable_Then_DeviceIdIsSelected()
{
    // ARRANGE
    var deviceManagerMock = new Mock<IDeviceManager>();
    deviceManagerMock.Setup(manager => manager.GetDevices(false))
        .Returns(new List<Device>
                 {
                     _testDevice
                 })
        .Verifiable();

    var subject = new DevicesApiController(deviceManagerMock.Object);

    // ACT
    var result = subject.DevicesIdGet("1");

    // ASSERT
    var deviceInfos = result as IEnumerable<DeviceDetails>;
    var deviceInfo = deviceInfos.Single();
    Assert.That(deviceInfo.IsOnline == true);
    Assert.That(deviceInfo.SerialNumber == null);
}

Body:
On the basis of code posted, it appears deviceInfo can be null. You can you the following:

 if (deviceInfo == null)
      throw new ArgumentNullException(“source”);

 // rest of the code


问:
How to read variable values in Python cplex api?
I have modeled a MIP problem in Python Cplex API. Is there any way to read variable values - variable-wise?

Currently I am reading variable values into a list and mapping those from the LP file"

```<code>    for i, j in zip(cpx.variables.get_names(), cpx.solution.get_values()):
        cplex_details_inp.append((i, j))
</code>```

By this method, I am able to read all variable values at a time,
but this method is causing memory issue due to the fact that there are 500k variables.

How to read values variable wise?  I don't find any specific document or examples for this.

答:
```<code>for i in cpx.variables.get_names():
           cplex_details_inp.append([i,cpx.solution.get_values(i)])
</code>```

This code could help.

Body:
I have modeled a MIP problem in Python Cplex API. Is there any way to read variable values - variable-wise?

Currently I am reading variable values into a list and mapping those from the LP file"

    for i, j in zip(cpx.variables.get_names(), cpx.solution.get_values()):
        cplex_details_inp.append((i, j))

By this method, I am able to read all variable values at a time,
but this method is causing memory issue due to the fact that there are 500k variables.

How to read values variable wise?  I don't find any specific document or examples for this.

Body:
for i in cpx.variables.get_names():
           cplex_details_inp.append([i,cpx.solution.get_values(i)])

This code could help.


问:
Copy information from one pdf to another pragmatically
I am having a pdf with a certain layout and I want to take the information from there and place it into a new pdf with an updated layout. What I am thinking as the correct course of action is to map the elements of the first pdf, find the elements that I need and then paste them into the new pdf.

I have read the resources from the itextpdf site but I can not properly piece them together.

Any study materials or how-to would be really helpful. Thanks

Edit 1: I have done something like that

```<code> val reader = PdfReader(path)

        val size = reader.numberOfPages

        for (i in 1..size) {
            val content = reader.getPageContent(i)
            println(content?.contentToString())
        }
</code>```

which of course is not working.

答:
I would structure the program as follows:

read all the required elements in your source document.

store the data in some kind of internal storage object

write the stored data into a new document

Your storage object could look like this:

```<code>public class FieldContainer {
    public String field1;
    public String field2;
    // ...
}
</code>```

Body:
I am having a pdf with a certain layout and I want to take the information from there and place it into a new pdf with an updated layout. What I am thinking as the correct course of action is to map the elements of the first pdf, find the elements that I need and then paste them into the new pdf.

I have read the resources from the itextpdf site but I can not properly piece them together.

Any study materials or how-to would be really helpful. Thanks

Edit 1: I have done something like that

 val reader = PdfReader(path)

        val size = reader.numberOfPages

        for (i in 1..size) {
            val content = reader.getPageContent(i)
            println(content?.contentToString())
        }

which of course is not working.

Body:
I would structure the program as follows:

read all the required elements in your source document.

store the data in some kind of internal storage object

write the stored data into a new document

Your storage object could look like this:

public class FieldContainer {
    public String field1;
    public String field2;
    // ...
}


问:
Firestore/Firebase Emulator Not Running
I'm trying to test my functions locally using the guide listed here
https://firebase.google.com/docs/functions/local-emulator

I have installed the latest firebase-tools using

npm install -g firebase-tools

In my package.json I confirmed to be running

```<code>"firebase-admin": "^7.3.0",
"firebase-functions": "^2.3.1",
</code>```

When I try to run my functions using

firebase emulators:start

It gives me the below output. What am I doing wrong?

```<code>Starting emulators: ["functions"]
⚠  Your requested "node" version "8" doesn't match your global version "11"
✔  functions: Emulator started at http://localhost:5001
i  functions: Watching "[FUNCTIONS FOLDER PATH]" for Cloud Functions...
⚠  Default "firebase-admin" instance created!
⚠  Ignoring trigger "[FUNCTION NAME]" because the service "firebaseauth.googleapis.com" is not yet supported.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.

etc.
etc.
etc.
i  functions: HTTP trigger initialized at http://localhost:5001/[APP NAME]/us-central1/[FUNCTION NAME]

[2019-05-15T21:43:52.436Z]  @firebase/database: FIREBASE WARNING:
{"code":"app/invalid-credential","message":"Credential implementation provided to
initializeApp() via the \"credential\" property failed to fetch a valid Google
OAuth2 access token with the following error: \"Error fetching access token: Error
while making request: getaddrinfo ENOTFOUND metadata.google.internal
metadata.google.internal:80. Error code: ENOTFOUND\"."}
</code>```

答:
Could be you don't have firestore configured properly in your firebase.json file. This makes emulator not being started.

What you need is to run firebase init firestore in your project directory. This would create firestore rules and indexes files and update your firebase.json correspondingly.

Title: Firestore/Firebase Emulator Not Running

Body:
I'm trying to test my functions locally using the guide listed here
https://firebase.google.com/docs/functions/local-emulator

I have installed the latest firebase-tools using

npm install -g firebase-tools

In my package.json I confirmed to be running

"firebase-admin": "^7.3.0",
"firebase-functions": "^2.3.1",

When I try to run my functions using

firebase emulators:start

It gives me the below output. What am I doing wrong?

Starting emulators: ["functions"]
⚠  Your requested "node" version "8" doesn't match your global version "11"
✔  functions: Emulator started at http://localhost:5001
i  functions: Watching "[FUNCTIONS FOLDER PATH]" for Cloud Functions...
⚠  Default "firebase-admin" instance created!
⚠  Ignoring trigger "[FUNCTION NAME]" because the service "firebaseauth.googleapis.com" is not yet supported.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.
⚠  Ignoring trigger "[FUNCTION NAME]" because the Cloud Firestore emulator is not running.

etc.
etc.
etc.
i  functions: HTTP trigger initialized at http://localhost:5001/[APP NAME]/us-central1/[FUNCTION NAME]

[2019-05-15T21:43:52.436Z]  @firebase/database: FIREBASE WARNING:
{"code":"app/invalid-credential","message":"Credential implementation provided to
initializeApp() via the \"credential\" property failed to fetch a valid Google
OAuth2 access token with the following error: \"Error fetching access token: Error
while making request: getaddrinfo ENOTFOUND metadata.google.internal
metadata.google.internal:80. Error code: ENOTFOUND\"."}


问:
Two images on my website are different height to others
two of these images are different height

I'm doing a web dev course online and first HTML/CSS section revolves around making a website as you cover each topic. I'm trying to make all these images appear one next to the other and have the same size - for some reason two of the divs still remain larger than the rest, setting height does not work for these two.

Here is what I tried in CSS:

```<code>body{
font-family: 'Barlow', sans-serif;
background:white;
max-width: 1000px;
margin: 0 auto;

.product {
border: 1px solid grey;
width: 200px;
margin: 5px;
padding: 5px;
display: inline-block;
}

img{
max-width: 100%;
height: 200px;
}
</code>```

And example of how all divs from .product class were created:

```<code> <div class="product">
<a href="product-details-lip-balm.html">
    <img src="images/makeup5.jpg" alt="Lip balm">
</a>
<h4><a href="product-details-lip-balm.html">Lip balm</a></h4>
<p> £ 5</p>
<p> Organic lip balm by Make Me Bio</p>
<a href="product-detail.html" class="button">More info</a>
<a href="" class="button">Add To Cart</a>
</code>```

two images have different height

答:
```<code>img{
  max-height:200px;
}
</code>```

will work!

Body:
two of these images are different height

I'm doing a web dev course online and first HTML/CSS section revolves around making a website as you cover each topic. I'm trying to make all these images appear one next to the other and have the same size - for some reason two of the divs still remain larger than the rest, setting height does not work for these two.

Here is what I tried in CSS:

body{
font-family: 'Barlow', sans-serif;
background:white;
max-width: 1000px;
margin: 0 auto;

.product {
border: 1px solid grey;
width: 200px;
margin: 5px;
padding: 5px;
display: inline-block;
}

img{
max-width: 100%;
height: 200px;
}

And example of how all divs from .product class were created:

Lip balm

 £ 5

 Organic lip balm by Make Me Bio

More info
Add To Cart

two images have different height

Body:
img{
  max-height:200px;
}

will work!


问:
I cannot initialize Flask SocketIO with app.from_object parameter
I have an app.py file where I initialize my app. I have another file (run.py) where I run Flask server from. Everything works with a standard flask app. However I am trying to integrate flask-socketio and it keeps failing with different errors depending on how I try to initialize the app.

I have tried the following ways to initialize flask-socketio:

```<code>socketio = SocketIO(app.config.from_object(app_config[env_name]))
socketio = SocketIO(app, **app.config[env_name])
socketio = SocketIO(**app.config[env_name])
</code>```

Here is the relevant code from my app.py file.

```<code>def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])
  async_mode = None

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)
  socketio = SocketIO(app.config.from_object(app_config[env_name]))
  return socketio
</code>```

My run.py file looks like this:

```<code>rom src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  app.run(app, host='0.0.0.0', port=port)
</code>```

You will notice I am importing from a config.py file. That is where my environment variables are being for (dev, test, prod). Each environment is it's own class. For example:

```<code>class Development(object):
    """
    Development environment configuration
    """
    DEBUG = True
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS=False
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
    UPLOADED_FILES_DEST = os.getenv('UPLOADED_FILES_DEST')
</code>```

As you can see, most of those values are set in an environment variable since it is bad practice to put such sensitive information into a repo.

I would like to be able to initialize flask-socketio so I can setup rooms where users can share location based information.

Thanks in advance.

答:
I found the issue. I cannot instantiate SocketIO in my app.py file. I have to export app from my app.py file and instantiate SocketIO in my run.py file. My final code looks like this:

app.py

```<code>def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)

  return app
</code>```

Finally, my run.py file looks like this.

```<code>import os
import logging
from dotenv import load_dotenv, find_dotenv
from flask_socketio import SocketIO, join_room, emit
from src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)
socketio = SocketIO(app)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  socketio.run(app, host='0.0.0.0', port=port)
</code>```

Body:
I have an app.py file where I initialize my app. I have another file (run.py) where I run Flask server from. Everything works with a standard flask app. However I am trying to integrate flask-socketio and it keeps failing with different errors depending on how I try to initialize the app.

I have tried the following ways to initialize flask-socketio:

socketio = SocketIO(app.config.from_object(app_config[env_name]))
socketio = SocketIO(app, **app.config[env_name])
socketio = SocketIO(**app.config[env_name])

Here is the relevant code from my app.py file.

def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])
  async_mode = None

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)
  socketio = SocketIO(app.config.from_object(app_config[env_name]))
  return socketio

My run.py file looks like this:

rom src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  app.run(app, host='0.0.0.0', port=port)

You will notice I am importing from a config.py file. That is where my environment variables are being for (dev, test, prod). Each environment is it's own class. For example:

class Development(object):
    """
    Development environment configuration
    """
    DEBUG = True
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS=False
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
    UPLOADED_FILES_DEST = os.getenv('UPLOADED_FILES_DEST')

As you can see, most of those values are set in an environment variable since it is bad practice to put such sensitive information into a repo.

I would like to be able to initialize flask-socketio so I can setup rooms where users can share location based information.

Thanks in advance.

Body:
I found the issue. I cannot instantiate SocketIO in my app.py file. I have to export app from my app.py file and instantiate SocketIO in my run.py file. My final code looks like this:

app.py

def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)

  return app

Finally, my run.py file looks like this.

import os
import logging
from dotenv import load_dotenv, find_dotenv
from flask_socketio import SocketIO, join_room, emit
from src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)
socketio = SocketIO(app)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  socketio.run(app, host='0.0.0.0', port=port)


问:
Find all duplicate ids and add unique key
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

```<code><input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
</code>```

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

```<code><input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
</code>```

JS

```<code> $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });
</code>```

Any ideas? Thank you all.

答:
```<code>var a = [];
var i =0;
 jQuery('[id]').each(function(){
    if(a.indexOf(this.id) !== -1){ //checks if id exists in array
        i++;
    }
    else{
        i = 1;
        a.push(this.id);
    }
    jQuery(this).attr('id', jQuery(this).attr('id') + i);
 });
</code>```

Explaination : I am storing each new id in array. At each iteration it checks whether the id is repeated, if so then the attribute is incremented to 1.

Body:
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />

JS

 $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });

Any ideas? Thank you all.

Body:
var a = [];
var i =0;
 jQuery('[id]').each(function(){
    if(a.indexOf(this.id) !== -1){ //checks if id exists in array
        i++;
    }
    else{
        i = 1;
        a.push(this.id);
    }
    jQuery(this).attr('id', jQuery(this).attr('id') + i);
 });

Explaination : I am storing each new id in array. At each iteration it checks whether the id is repeated, if so then the attribute is incremented to 1.


问:
What to watch out for when converting a std::string to a char* for C function?
I have read many posts asking the question on how to convert a C++ std::string or const std::string& to a char* to pass it to a C function and it seems there is quite a few caveat's in regards to doing this.  One has to beware about the string being contiguous and a lot of other things.  The point is that I've never really understood all the points one needs to be aware of and why?

I wondered if someone could sum up the caveats and downfalls about doing a conversion from a std::string to a char* that is needed to pass to a C function?

This when the std::string is a const reference and when it's just a non-const reference, and when the C function will alter the char* and when it will not alter it.

答:
Basically, there are three points that are important:

According to the still current standard, std::string isn’t actually guaranteed to use contiguous storage (as far as I know this is due to change). But in fact, all current implementations probably use contiguous storage anyway. For that reason, c_str() (and data()) may actually create a copy of the string internally …

The pointer returned by c_str() (and data()) is valid only as long as no non-const methods on the original string are invoked. This makes its use unsuitable when the C function hangs on to the pointer (as opposed to only using it during the duration of the actual function call).

If there is any chance at all that the string is going to be modified, casting away constness from the c_str() is not a good idea. You must create a buffer with a copy of the string, and pass that into the C function. If you create a buffer, remember to add a null termination.


问:
Strange domain fowarding
My client has a shared hostingprovider, were he can setup multiple domains on 1 hostingaccount. we have the following problem.

example: if you type.. www.domain.com... u go to.. www.domain.com (nothing wrong) however if u type domain.com (without www.) u go to www.domain.com/domain.com

so it fowards (once) you to a map (on the server) which has the same name as the domain.  after the one time foward.. u can click on home and go to www.domain.com and everything is fine.

so it seems that this one time fowarding happens only if u type it in the url bar without www.

the hostingprovider is claiming its a coding problem, its not PHP, because it happens even if the php-file is totally empty of any code, they say it might be a htaccess problem, although i have never had this problem before on any other hostingcompany, but this company doesnt give any support on this problem so i need to find the solution myself

current htacces code is

```<code>RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^cms/.*$ - [L]
RewriteRule ^test/.*$ - [L]
RewriteRule ^plesk-stat/.*$ - [L]
RewriteRule \.(gif|jpg|png|css|flv|js|swf|php|ico|webm|mp4)$ - [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+\.php)$ index.php?url=$1 [QSA,L]
RewriteCond %{REQUEST_URI} !(\.)
RewriteCond %{REQUEST_URI} !(\.)
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} .*
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</code>```

besides this code, it also contains mod_deflate.c  and mod_expires.c code, but this didnt seem relative to the problem

i cannot find where or how this htaccess file is creating this problem, and i was hoping you guys could help me

答:
Try to use this</p>

```<code>RewriteCond %{HTTP_HOST} !^www
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R=301,QSA,L]
</code>```

Title: Strange domain fowarding

Body:
My client has a shared hostingprovider, were he can setup multiple domains on 1 hostingaccount. we have the following problem.

example: if you type.. www.domain.com... u go to.. www.domain.com (nothing wrong) however if u type domain.com (without www.) u go to www.domain.com/domain.com

so it fowards (once) you to a map (on the server) which has the same name as the domain.  after the one time foward.. u can click on home and go to www.domain.com and everything is fine.

so it seems that this one time fowarding happens only if u type it in the url bar without www.

the hostingprovider is claiming its a coding problem, its not PHP, because it happens even if the php-file is totally empty of any code, they say it might be a htaccess problem, although i have never had this problem before on any other hostingcompany, but this company doesnt give any support on this problem so i need to find the solution myself

current htacces code is

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^cms/.*$ - [L]
RewriteRule ^test/.*$ - [L]
RewriteRule ^plesk-stat/.*$ - [L]
RewriteRule \.(gif|jpg|png|css|flv|js|swf|php|ico|webm|mp4)$ - [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+\.php)$ index.php?url=$1 [QSA,L]
RewriteCond %{REQUEST_URI} !(\.)
RewriteCond %{REQUEST_URI} !(\.)
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} .*
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

besides this code, it also contains mod_deflate.c  and mod_expires.c code, but this didnt seem relative to the problem

i cannot find where or how this htaccess file is creating this problem, and i was hoping you guys could help me

Body:
Try to use this

RewriteCond %{HTTP_HOST} !^www
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R=301,QSA,L]


问:
I am getting error when creating stored procedure with while loop in mysql
i have created one stored procedure for sum of perticular condition but getting syntax error.

create table script :

```<code>CREATE TABLE count_smaller_coverage (count_records INT(11) ,block_id INT(11))
</code>```

insert data :

```<code>INSERT INTO count_smaller_coverage
SELECT '114000','1' UNION
SELECT '112000','2' UNION
SELECT '98765','3' UNION
SELECT '78965','4' UNION
SELECT '4125','5' UNION
SELECT '123654','6' UNION
SELECT '78999','7' UNION
SELECT '89888','8' UNION
SELECT '99654','9' UNION
SELECT '75365','10' UNION
SELECT '25638','11' UNION
SELECT '85236','12' UNION
SELECT '65478','13' UNION
SELECT '65478','14' UNION
SELECT '85236','15'
</code>```

Stored Procedure :

```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS test_mysql_while_loop$$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE strat INT;
DECLARE END INT;
DECLARE SumofCount BIGINT;
DECLARE block_id VARCHAR(2000);
SET strat=(SELECT MIN(block_id) FROM count_smaller_coverage);
SET END =(SELECT MAX(block_id) FROM count_smaller_coverage);
CREATE TABLE blocks_parts (block_id VARCHAR(2000), Counts BIGINT);

test: WHILE strat<=END DO

BEGIN

IF SumofCount > 800000 THEN
SET SumofCount=0;
SET block_id = NULL;
END IF;

SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

IF SumofCount BETWEEN 800000 AND 1000000 THEN
INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
END IF;

IF SumofCount BETWEEN 800000 AND 100000 THEN
    LEAVE test;
END IF;

SET strat=strat+1;

END test;
END$$
DELIMITER ;
</code>```

Error :

Query: CREATE PROCEDURE test_mysql_while_loop() BEGIN DECLARE strat INT; DECLARE end INT; DECLARE SumofCount BIGINT; DECLARE block_id V...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test;
END' at line 33

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.060 sec

答:
```<code>DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `Test`$$

CREATE DEFINER=`root`@`%` PROCEDURE `Test`()

BEGIN

SET @SumofCount=0;
SET @block_id='';
SET @Start=(SELECT MIN(block_id) FROM count_smaller_coverage);
SET @End =(SELECT MAX(block_id) FROM count_smaller_coverage);
SET @v1=5;

myloop: WHILE @Start<=@End DO
IF @SumofCount > 800000 THEN
SET @SumofCount=0;
END IF;
SET @SumofCount=(IFNULL(@SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=@Start));
SET @block_id = (SELECT CONCAT(@block_id ,CAST(block_id AS CHAR),',') AS id FROM count_smaller_coverage WHERE block_id=@Start);

IF @SumofCount BETWEEN 800000 AND 1000000 THEN
SET @block_id = CONCAT(LEFT(@block_id, CHAR_LENGTH(@block_id) -1), '');
INSERT INTO blocks_parts(block_id,Counts) VALUES (@block_id,@SumofCount);
SET @block_id='';
END IF;
IF @Start = @End THEN
SET @block_id = CONCAT(LEFT(@block_id, CHAR_LENGTH(@block_id) -1), '');
INSERT INTO blocks_parts(block_id,Counts) VALUES (@block_id,@SumofCount);
END IF;

SET @Start=@Start+1;

END WHILE myloop;

    END$$

DELIMITER ;
</code>```

Body:
i have created one stored procedure for sum of perticular condition but getting syntax error.

create table script :

CREATE TABLE count_smaller_coverage (count_records INT(11) ,block_id INT(11))

insert data :

INSERT INTO count_smaller_coverage
SELECT '114000','1' UNION
SELECT '112000','2' UNION
SELECT '98765','3' UNION
SELECT '78965','4' UNION
SELECT '4125','5' UNION
SELECT '123654','6' UNION
SELECT '78999','7' UNION
SELECT '89888','8' UNION
SELECT '99654','9' UNION
SELECT '75365','10' UNION
SELECT '25638','11' UNION
SELECT '85236','12' UNION
SELECT '65478','13' UNION
SELECT '65478','14' UNION
SELECT '85236','15'

Stored Procedure :

DELIMITER $$
DROP PROCEDURE IF EXISTS test_mysql_while_loop$$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE strat INT;
DECLARE END INT;
DECLARE SumofCount BIGINT;
DECLARE block_id VARCHAR(2000);
SET strat=(SELECT MIN(block_id) FROM count_smaller_coverage);
SET END =(SELECT MAX(block_id) FROM count_smaller_coverage);
CREATE TABLE blocks_parts (block_id VARCHAR(2000), Counts BIGINT);

test: WHILE strat<=END DO

BEGIN

IF SumofCount > 800000 THEN
SET SumofCount=0;
SET block_id = NULL;
END IF;

SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

IF SumofCount BETWEEN 800000 AND 1000000 THEN
INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
END IF;

IF SumofCount BETWEEN 800000 AND 100000 THEN
    LEAVE test;
END IF;

SET strat=strat+1;

END test;
END$$
DELIMITER ;

Error :

Query: CREATE PROCEDURE test_mysql_while_loop() BEGIN DECLARE strat INT; DECLARE end INT; DECLARE SumofCount BIGINT; DECLARE block_id V...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test;
END' at line 33

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.060 sec


问:
How to check if element exists in an Object?
How to use *ngIf to check if an element exists in an Object?

.ts file

```<code>this.data = ["cat", "dog"];

</code>```

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

答:
You can use ngFor first to iterate every element in a loop and then use ngIf to check if value exist or not.

for example:

```<code><div *ngFor="let element of data">
    <div *ngIf="element.cat">
     </div>
</div>
</code>```

Another method is make seperate function for this but I think this is easy way to do.I hope it will help you.:)

Body:
How to use *ngIf to check if an element exists in an Object?

.ts file

this.data = ["cat", "dog"];

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

Body:
You can use ngFor first to iterate every element in a loop and then use ngIf to check if value exist or not.

for example:

<div *ngFor="let element of data">
    <div *ngIf="element.cat">
     </div>
</div>

Another method is make seperate function for this but I think this is easy way to do.I hope it will help you.:)


问:
How to change className?
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

```<code>    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [
            <div
              id="firstDiv"
              key={1}
              className={"first"}
              onClick={this.changeClass}
            />
          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return <div>{this.state.myDiv.map(div => div)}</div>;
      }
    }

    export default App;
</code>```

答:
Don't put your jsx in state. only add className and state and onChangeClass use this.stateState to update className.</p>

```<code>import React, { Component } from "react";
import "./styles/style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      className:"first"
    };
  }

  changeClass = () => {
     this.setState({ classNmae: "two" });
  };

  render() {
    return <div>
       <div
          id="firstDiv"
          className={this.state.className}
          onClick={this.changeClass}
       />
    </div>;
  }
}

export default App;
</code>```

Title: How to change className?

Body:
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [

          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return
{this.state.myDiv.map(div => div)}
;
      }
    }

    export default App;

Body:
Don't put your jsx in state. only add className and state and onChangeClass use this.stateState to update className.

import React, { Component } from "react";
import "./styles/style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      className:"first"
    };
  }

  changeClass = () => {
     this.setState({ classNmae: "two" });
  };

  render() {
    return <div>
       <div
          id="firstDiv"
          className={this.state.className}
          onClick={this.changeClass}
       />
    </div>;
  }
}

export default App;


问:
How can I rename a field during serialization with Json4s?
How to easily rename field-names in json4s? From their documentation, i've tried the following snippet but it doesn't seem to rename the serial field to id.

```<code>case class Person(serial: Int, firstName: String)

val rename = FieldSerializer[Person](renameTo("serial", "id"))

implicit val format = DefaultFormats + rename

write(Person(1, "Guest")) //returns {"serial":1,"firstName":"Guest"}
</code>```

With Jackson library, it's pretty easy by declaring an annotation. But i'm looking for a pure scala library/solution. Is there a better library or way for object-to-json serialization in scala with easy field-renaming?

答:
Your code snippet has wrongly named implicit. It should be:</p>

```<code>implicit val formats: Formats = DefaultFormats + rename
</code>```

Body:
How to easily rename field-names in json4s? From their documentation, i've tried the following snippet but it doesn't seem to rename the serial field to id.

case class Person(serial: Int, firstName: String)

val rename = FieldSerializer[Person](renameTo("serial", "id"))

implicit val format = DefaultFormats + rename

write(Person(1, "Guest")) //returns {"serial":1,"firstName":"Guest"}

With Jackson library, it's pretty easy by declaring an annotation. But i'm looking for a pure scala library/solution. Is there a better library or way for object-to-json serialization in scala with easy field-renaming?

Body:
Your code snippet has wrongly named implicit. It should be:

implicit val formats: Formats = DefaultFormats + rename


问:
Ajax doesn't update attribute in database
Ajax does not update the viewed attribute after a lesson has been fully watched.

application.js:

```<code>$('#video').onended(function() {
  $.ajax({
    url: '/courses/:id/lessons/:id/viewed',
    type: 'patch'
 });
});
</code>```

lessons controller;

```<code>def viewed
  @lesson = Lesson.find(params[:id])
  @lesson.update_attribute(:viewed, true)
end
</code>```

lessons/show.html.erb:

```<code><h2><%= @lesson.name %></h2>
<div id="video">
<video controls="true" width="auto" height="auto">
  <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
</video>
</div>
</code>```

config/routes.rb:

```<code>patch 'courses/:id/lessons/:id/viewed' => 'lessons#viewed'
</code>```

add_view_to_lessons migration:

```<code>def change
  add_column :lessons, :viewed, :boolean
end
</code>```

答:
I would do something like this:

routes.rb

```<code>resources :lessons do
  member do
    patch :viewed
  end
end
</code>```

use rails helpers, it will help you have consistency on the order of the segments, the variables, named_routes, etc

show.html

```<code><h2><%= @lesson.name %></h2>
<div id="video" data-viewed-url="<%= viewed_lesson_path(@lesson) %>">
  <video controls="true" width="auto" height="auto">
    <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
  </video>
</div>
</code>```

I'm passing the URL as a data attribute of the #video element so I don't have to mess with URLs with javascript, let rails handle these things, it's really good at it

js

```<code>$('#video').onended(function() {
  $.ajax({
    url: this.dataset.viewedUrl,
    type: 'patch'
 });
});
</code>```

get the URL from the element's data attribute

Body:
Ajax does not update the viewed attribute after a lesson has been fully watched.

application.js:

$('#video').onended(function() {
  $.ajax({
    url: '/courses/:id/lessons/:id/viewed',
    type: 'patch'
 });
});

lessons controller;

def viewed
  @lesson = Lesson.find(params[:id])
  @lesson.update_attribute(:viewed, true)
end

lessons/show.html.erb:

<%= @lesson.name %>

<video controls="true" width="auto" height="auto">
  <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
</video>

config/routes.rb:

patch 'courses/:id/lessons/:id/viewed' => 'lessons#viewed'

add_view_to_lessons migration:

def change
  add_column :lessons, :viewed, :boolean
end

Body:
I would do something like this:

routes.rb

resources :lessons do
  member do
    patch :viewed
  end
end

use rails helpers, it will help you have consistency on the order of the segments, the variables, named_routes, etc

show.html

<h2><%= @lesson.name %></h2>
<div id="video" data-viewed-url="<%= viewed_lesson_path(@lesson) %>">
  <video controls="true" width="auto" height="auto">
    <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
  </video>
</div>

I'm passing the URL as a data attribute of the #video element so I don't have to mess with URLs with javascript, let rails handle these things, it's really good at it

js

$('#video').onended(function() {
  $.ajax({
    url: this.dataset.viewedUrl,
    type: 'patch'
 });
});

get the URL from the element's data attribute


答:
First, let's fix the route:

```<code>path "/lessons/:id/viewed" => "lessons#viewed", as: :lesson_viewed
</code>```

We don't need course's id if it is a named route unless we're actually doing something useful with that information.

I would recommend you to add a data attribute in your erb to specify the route to call

```<code><h2><%= @lesson.name %></h2>

<div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>">

  <video controls="true" width="auto" height="auto">
    <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
  </video>
</div>
</code>```

Notice the change in <div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>"> line.

Now Ajax can simply call that route:

```<code>$('#video').onended(function() {
  $.ajax({
    url: $('#video').data("lesson-viewed-url"),
    type: 'patch' // Can move the HTTP verb to data attribute as well, leaving this upto the implementor for now
 });
});
</code>```

Title: Ajax doesn't update attribute in database

Body:
First, let's fix the route:

path "/lessons/:id/viewed" => "lessons#viewed", as: :lesson_viewed

We don't need course's id if it is a named route unless we're actually doing something useful with that information.

I would recommend you to add a data attribute in your erb to specify the route to call

<h2><%= @lesson.name %></h2>

<div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>">

  <video controls="true" width="auto" height="auto">
    <source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
  </video>
</div>

Notice the change in <div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>"> line.

Now Ajax can simply call that route:

$('#video').onended(function() {
  $.ajax({
    url: $('#video').data("lesson-viewed-url"),
    type: 'patch' // Can move the HTTP verb to data attribute as well, leaving this upto the implementor for now
 });
});


问:
sed: How to join the lines of a record with an empty line delimiting records
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

```<code>KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'
</code>```

I need to combine the lines like this:

```<code>KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

I'm a novice with sed but pieced together this ugly line.

```<code>sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'
</code>```

yea - there is a better way...

答:
You don't need to use sed for this. Just use paste:

▶ paste - - - - < input
KDFW    N 32°53.83'     W 097°02.26'
TOC     N 32°48.49'     W 097°01.39'
DART    N 32°17.15'     W 096°48.66'
```

<p>Note that as mentioned in the BSD manual for paste:</p>

<blockquote>
  <p>If <code>-</code> is specified for one or more of the input files, the standard input is used; standard input is read one line at a time, circularly, for each instance of <code>-</code>.</p>
</blockquote>

<p>Note also that this output is by default tab-separated, and you could have, say, space-separated output too, which seems to be what your sed is doing:</p>

<pre class="lang-none prettyprint-override"><code>▶ paste -d' ' - - - - < input
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

Body:
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

I need to combine the lines like this:

KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

I'm a novice with sed but pieced together this ugly line.

sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'

yea - there is a better way...

Body:
You don't need to use sed for this. Just use paste:

▶ paste - - - - < input
KDFW    N 32°53.83'     W 097°02.26'
TOC     N 32°48.49'     W 097°01.39'
DART    N 32°17.15'     W 096°48.66'

Note that as mentioned in the BSD manual for paste:

If - is specified for one or more of the input files, the standard input is used; standard input is read one line at a time, circularly, for each instance of -.

Note also that this output is by default tab-separated, and you could have, say, space-separated output too, which seems to be what your sed is doing:

▶ paste -d' ' - - - - < input
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'