问:
checking,if a string of an array of strings is available in a string
all string functions(preg_match,strpos...) in php I know allow me to find a string in a string. My intention is to find a string of an array of strings in a string like this:

```<code>         $pattern = array("jpg", "bmp");
         $subject = $bild->dateiname;
</code>```

Any ideas,how to implemnet my intention using php-function(s)?

答:
Find the string in an array</p>

```<code>```
<?php

  $pattern = array("jpg", "bmp");

  $yourString ="bmp dd ddd ddd";
  $string = (explode(" ",$yourString));

    echo findeStirng($pattern,$string);

    function findeStirng($pattern,$string){
         foreach ($string as $val){
             foreach ($pattern as $valpat){
             $find="";
             if ($val==$valpat){
                 $find ="finde string";
                 return $find;
                 break;
             }
             }
             }
         }
?>

```
</code>```

Body:
all string functions(preg_match,strpos...) in php I know allow me to find a string in a string. My intention is to find a string of an array of strings in a string like this:

         $pattern = array("jpg", "bmp");
         $subject = $bild->dateiname;

Any ideas,how to implemnet my intention using php-function(s)?

Body:
Find the string in an array

<pre>
<?php

  $pattern = array("jpg", "bmp");

  $yourString ="bmp dd ddd ddd";
  $string = (explode(" ",$yourString));

    echo findeStirng($pattern,$string);

    function findeStirng($pattern,$string){
         foreach ($string as $val){
             foreach ($pattern as $valpat){
             $find="";
             if ($val==$valpat){
                 $find ="finde string";
                 return $find;
                 break;
             }
             }
             }
         }
?>

</pre>


来源: stackexchange

问:
How to extract values from list to add to another list in python
I have the following code:

```<code>items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])
</code>```

response['Contents'] has a schema like this:

```<code>{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}
</code>```

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

答:
Just append them as a list/tuple to your original list:

```<code>items = []
for i in response['Contents']:  # assuming response['Contents'] is a list
    items.append([
        's3://' + response['Name'] + '/' + i['Key'],
        i['Key'].rsplit('/', 1)[-1],
        i['Size']
    ])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])

response['Contents'] has a schema like this:

{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

Body:
Just append them as a list/tuple to your original list:

items = []
for i in response['Contents']:  # assuming response['Contents'] is a list
    items.append([
        's3://' + response['Name'] + '/' + i['Key'],
        i['Key'].rsplit('/', 1)[-1],
        i['Size']
    ])


问:
Unable to source .profile in shell script
To start off, I am a complete noob to Debian, Python, and shell scripts, so please speak to me like I am a toddler.

I have a python script I am running through a virtualenv, and I want to execute it via a shell script. Here is what I'm typing in to the terminal to do so:

source .profile
workon cv
cd Desktop/Camera
python main.py

I tried turning this into a shell script, but I receive the error -- source: not found

I've found no answer to my problem, at least not in any terms I can understand. Any advice would be appreciated. Furthermore, before you answer, I also have no idea why it is I need to execute source .profile, I'm simply following a beginner guide for the project which can be found here: https://www.hackster.io/hackerhouse/smart-security-camera-90d7bd

Thanks in advance, and sorry if this is a dumb question.

答:
Best practice for Shell would be shebang at the begging like @Veda suggested.

Execute the shell script using bash like bash shell.sh as the link suggests using relative locations rather than absolute ones


问:
How do I make my layout fill the screen when I rotate it?
I have one problem with my code and I could use some help. I made an app that tracks the statistics of a football game.The app works fine the problem is when I rotate my phone screen which is when 2 problems appear:
The layout doesn´t match the screen width, making the text and buttons overlap one another and when I turn the phone around, for some reason, the scores reset. I have a reset button but I don´t know why it activates when I rotate the screen. Would appreciate some help. Thanks for reading!
Here´s the code in XML and Java:

```<code>public class MainActivity extends AppCompatActivity {
int golosA = 0;
int faltasA = 0;
int forasDeJogoA = 0;
int cartoesAmarelosA = 0;
int expulsoesA = 0;
int golosB = 0;
int faltasB = 0;
int forasDeJogoB = 0;
int cartoesAmarelosB = 0;
int expulsoesB = 0;
int cantosA = 0 ;
int cantosB = 0 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void resetScore(View v) {
    golosA=0;
    faltasA=0;
    expulsoesA=0;
    cartoesAmarelosA = 0;
    forasDeJogoA = 0 ;
    golosB=0;
    faltasB=0;
    expulsoesB=0;
    cartoesAmarelosB = 0;
    forasDeJogoB = 0 ;
    cantosA = 0 ;
    cantosB = 0 ;

    displayFaltasEquipaA(0);
    displayGolosButtonA(0);
    displayExpulsoes(0);
    displayCartoesA(0);
    displayForasJogoA(0);
    displayCartoesB(0);
    displayExpulsoesB(0);
    displayForasJogoB(0);
    displayGolosButtonB(0);
    displayFaltasEquipaB(0);
    displayCantosA(0);
    displayCantosB(0);
}

public void displayGolosButtonA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamA(View view) {
    golosA = golosA + 1;
    displayGolosButtonA(golosA);
}

public void displayFaltasEquipaA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamA(View view) {
    faltasA = faltasA + 1;
    displayFaltasEquipaA(faltasA);
}
public void displayCantosA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamA);
    scoreView.setText(String.valueOf(score));
}

public void cantosA(View view) {
  cantosA  = cantosA + 1;
    displayCantosA(cantosA);
}
public void displayCantosB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamB);
    scoreView.setText(String.valueOf(score));
}

public void cantosB(View view) {
    cantosB  = cantosB + 1;
    displayCantosB(cantosB);
}

public void displayForasJogoA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void forasEquipaA(View view) {
    forasDeJogoA = forasDeJogoA + 1;
    displayForasJogoA(forasDeJogoA + 1);
}

public void displayCartoesA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_a);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamA(View view) {
    cartoesAmarelosA = cartoesAmarelosA + 1;
    displayCartoesA(cartoesAmarelosA);
}

public void displayExpulsoes(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_a);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesTeamA(View view) {
    expulsoesA = expulsoesA + 1;
    displayExpulsoes(expulsoesA);
}

public void displayGolosButtonB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamB(View view) {
    golosB = golosB + 1;
    displayGolosButtonB(golosB);
}

public void displayFaltasEquipaB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamB(View view) {
    faltasB = faltasB + 1;
    displayFaltasEquipaB(faltasB);
}

public void displayForasJogoB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void forasJogoB(View view) {
    forasDeJogoB = forasDeJogoB + 1;
    displayForasJogoB(forasDeJogoB + 1);
}

public void displayCartoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_b);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamB(View view) {
    cartoesAmarelosB = cartoesAmarelosB + 1;
    displayCartoesB(cartoesAmarelosB);
}

public void displayExpulsoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_b);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesB(View v) {
    expulsoesB = expulsoesB + 1;
    displayExpulsoesB(expulsoesB);
}
</code>```

}

答:
I am not 100% positive but my gut tells me You need to add an onOrientationChanged listener and have it set text to same values again when in horizontal/landscape mode.

It has to do with the activity lifecycle and when the orientation changes it temporarily stops/pauses (not sure which) the activity if you don’t save those values or set the values then they are set to the default value which looks like 0 in your code.

Body:
I have one problem with my code and I could use some help. I made an app that tracks the statistics of a football game.The app works fine the problem is when I rotate my phone screen which is when 2 problems appear:
The layout doesn´t match the screen width, making the text and buttons overlap one another and when I turn the phone around, for some reason, the scores reset. I have a reset button but I don´t know why it activates when I rotate the screen. Would appreciate some help. Thanks for reading!
Here´s the code in XML and Java:

public class MainActivity extends AppCompatActivity {
int golosA = 0;
int faltasA = 0;
int forasDeJogoA = 0;
int cartoesAmarelosA = 0;
int expulsoesA = 0;
int golosB = 0;
int faltasB = 0;
int forasDeJogoB = 0;
int cartoesAmarelosB = 0;
int expulsoesB = 0;
int cantosA = 0 ;
int cantosB = 0 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void resetScore(View v) {
    golosA=0;
    faltasA=0;
    expulsoesA=0;
    cartoesAmarelosA = 0;
    forasDeJogoA = 0 ;
    golosB=0;
    faltasB=0;
    expulsoesB=0;
    cartoesAmarelosB = 0;
    forasDeJogoB = 0 ;
    cantosA = 0 ;
    cantosB = 0 ;

    displayFaltasEquipaA(0);
    displayGolosButtonA(0);
    displayExpulsoes(0);
    displayCartoesA(0);
    displayForasJogoA(0);
    displayCartoesB(0);
    displayExpulsoesB(0);
    displayForasJogoB(0);
    displayGolosButtonB(0);
    displayFaltasEquipaB(0);
    displayCantosA(0);
    displayCantosB(0);
}

public void displayGolosButtonA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamA(View view) {
    golosA = golosA + 1;
    displayGolosButtonA(golosA);
}

public void displayFaltasEquipaA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamA(View view) {
    faltasA = faltasA + 1;
    displayFaltasEquipaA(faltasA);
}
public void displayCantosA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamA);
    scoreView.setText(String.valueOf(score));
}

public void cantosA(View view) {
  cantosA  = cantosA + 1;
    displayCantosA(cantosA);
}
public void displayCantosB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.cantos_teamB);
    scoreView.setText(String.valueOf(score));
}

public void cantosB(View view) {
    cantosB  = cantosB + 1;
    displayCantosB(cantosB);
}

public void displayForasJogoA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_a);
    scoreView.setText(String.valueOf(score));
}

public void forasEquipaA(View view) {
    forasDeJogoA = forasDeJogoA + 1;
    displayForasJogoA(forasDeJogoA + 1);
}

public void displayCartoesA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_a);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamA(View view) {
    cartoesAmarelosA = cartoesAmarelosA + 1;
    displayCartoesA(cartoesAmarelosA);
}

public void displayExpulsoes(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_a);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesTeamA(View view) {
    expulsoesA = expulsoesA + 1;
    displayExpulsoes(expulsoesA);
}

public void displayGolosButtonB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.golos_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void golosTeamB(View view) {
    golosB = golosB + 1;
    displayGolosButtonB(golosB);
}

public void displayFaltasEquipaB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.faltas_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void faltasTeamB(View view) {
    faltasB = faltasB + 1;
    displayFaltasEquipaB(faltasB);
}

public void displayForasJogoB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.foras_equipa_b);
    scoreView.setText(String.valueOf(score));
}

public void forasJogoB(View view) {
    forasDeJogoB = forasDeJogoB + 1;
    displayForasJogoB(forasDeJogoB + 1);
}

public void displayCartoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.c_amarelos_b);
    scoreView.setText(String.valueOf(score));
}

public void amarelosTeamB(View view) {
    cartoesAmarelosB = cartoesAmarelosB + 1;
    displayCartoesB(cartoesAmarelosB);
}

public void displayExpulsoesB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.expulsoes_b);
    scoreView.setText(String.valueOf(score));
}

public void expulsoesB(View v) {
    expulsoesB = expulsoesB + 1;
    displayExpulsoesB(expulsoesB);
}

}


问:
How Can I Make WordPress's <?php the_title_attribute(); ?> Render %20 for Spaces?
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

```<code><a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

```<code>a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet</a>
</code>```

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

答:
My suggestion would be to use the echo param of the_title_attribute() and urlencode() the spaces:

```<code><a href="http://twitter.com/share?text=<?php echo urlencode(the_title_attribute('', '', 0)); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

<a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Body:
My suggestion would be to use the echo param of the_title_attribute() and urlencode() the spaces:

<a href="http://twitter.com/share?text=<?php echo urlencode(the_title_attribute('', '', 0)); ?>&amp;via=ianhines&amp;url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>


问:
Clicking an image gives an incremented value in knockoutJS
The following are the html and JS code

HTML body.

```<code>    <h2 data-bind="text: currentCat().name" id="cat-name"></h2>
    <div data-bind="text: currentCat().clickCount" id="cat-count"></div>
    <img src="" data-bind="click: incrementCount(), attr: {src: currentCat().imgSrc}" id="cat-img" alt="cute cat">
    <h4>NickNames</h4>
    <ul data-bind="foreach: currentCat().nickNames">
        <li data-bind="text: name"></li>
    </ul>
</div>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>
</code>```

JS code

```<code> var ViewModel = function() {
    this.currentCat = ko.observable( new Cat() );
    console.log(this.currentCat().clickCount())
    this.incrementCount = function(){

this.currentCat().clickCount(this.currentCat().clickCount() + 1);
    };
}

var Cat = function() {
    this.clickCount = ko.observable(0);
    this.name = ko.observable('Tabby');
    this.imgSrc = ko.observable('tabby.jpg');
    this.imgAttribution = ko.observable('XXXX');

    this.nickNames = ko.observableArray(
        [
            {name: 'Tabtab'},
            {name: 'T-bone'},
            {name: 'Mr. T'},
            {name: 'Tabitha Tab Tabby'}
        ]
    );
}
ko.applyBindings(new ViewModel())
</code>```

However, on rendering the HTML page, the click count is 1 instead of the expected value 0. Did I miss something ?

答:
The click binding expects a function reference, not an expression to run. The expression you've provided is run right away, when the binding is initialized. You need to change your binding to provide the function itself:

```<code>data-bind="click: incrementCount"
</code>```

Body:
The following are the html and JS code

HTML body.

NickNames

JS code

 var ViewModel = function() {
    this.currentCat = ko.observable( new Cat() );
    console.log(this.currentCat().clickCount())
    this.incrementCount = function(){

this.currentCat().clickCount(this.currentCat().clickCount() + 1);
    };
}

var Cat = function() {
    this.clickCount = ko.observable(0);
    this.name = ko.observable('Tabby');
    this.imgSrc = ko.observable('tabby.jpg');
    this.imgAttribution = ko.observable('XXXX');

    this.nickNames = ko.observableArray(
        [
            {name: 'Tabtab'},
            {name: 'T-bone'},
            {name: 'Mr. T'},
            {name: 'Tabitha Tab Tabby'}
        ]
    );
}
ko.applyBindings(new ViewModel())

However, on rendering the HTML page, the click count is 1 instead of the expected value 0. Did I miss something ?

Body:
The click binding expects a function reference, not an expression to run. The expression you've provided is run right away, when the binding is initialized. You need to change your binding to provide the function itself:

data-bind="click: incrementCount"


问:
Using wordpress in a subdirectory error
I have a non-wordpress site where i installed wordpress in a subdirectory

www.example.com/wordpress/

I have created an htaccess file in the wordpress folder (whre i have all its content)

```<code>    # BEGIN WordPress
   <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]
    </IfModule>
    # END WordPress
</code>```

And made this change in the index.php (inside wordpress folder)

```<code><?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . './wordpress/wp-blog-header.php' );
</code>```

The admin works ok but when try to visit the site it gives me an error 500.
what am i missing?

Aclaration: I want to use wordpress in this url www.example.com/wordpress/
since i have other content in the root.

答:
Error 500 is Internal Server Error
Internal server error in WordPress is often caused by plugin and/or theme functions. Other possible causes of internal server error in WordPress that we know of are:

Corrupted .htaccess file

PHP memory limit

Possible Solutions:

Checking for Corroupt .htacess

Increasing your PHP limit

Deactivating all Plug-ins

Re-Uploading the Core files

Checking file Permissions

Enable WP-Debug Mode

Title: Using wordpress in a subdirectory error

Body:
I have a non-wordpress site where i installed wordpress in a subdirectory

www.example.com/wordpress/

I have created an htaccess file in the wordpress folder (whre i have all its content)

    # BEGIN WordPress
   <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]
    </IfModule>
    # END WordPress

And made this change in the index.php (inside wordpress folder)

<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . './wordpress/wp-blog-header.php' );

The admin works ok but when try to visit the site it gives me an error 500.
what am i missing?

Aclaration: I want to use wordpress in this url www.example.com/wordpress/
since i have other content in the root.


问:
Sending image to Bot not working with Windows 10 Skype

I am trying to send an image to my Bot.  This works in most versions of Skype, but for some reason it fails in the Windows 10 version of the Skype app.

The Bot is implemented and has been working for a while.  It can be found by going to https://www.chtter.net and adding the Skype Bot.

When an image is sent to the Bot, the image is then downloaded to AWS S3, and then forwarded to the intended recipient of the image.

The problem is that when this is done using the "Classic" desktop version of Skype it works fine.  If you send the image using the Android version of Skype, it works fine.  But using the Windows 10 app, the Bot seems to throw an "Internal Server Error", and the file that is uploaded to S3 is not viewable.  This doesn't seem to be an issue with the Bot code, since it works in many cases.  It seems to be a difference between the Windows 10 app (or how it handles the Bot interface, or something) and other versions of Skype.

Has anyone else seen this, and is there some solution?

答: There are some known issues with the Skype Image Service right now (2017-12). Also, Skype does not maintain feature parity across their client app portfolio & unfortunately the Skype client differences can't be addressed from the bot-code side of things.</p>


问:
Given an array of scores, return true if each score is equal or lesser than the one before. The array will be length 2 or more
What is the problem to my code? I have tried to do this peoblem, but I don't find a good solution. Please help me, if you can!?</p>

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int[] scores = new int[n];
    int c = 0;

    for(int i = 0; i < scores.length; i++){
        scores[i] = scan.nextInt();
    }

    for(int j = scores.length-1; j >= 0; j--){
        boolean b = scores[j] <= scores[j-1] ? true : false;
        if(b == false){
            c++;
        }
    }
    if(c > 0){
        System.out.print(false);
    }
</code>```

答:
I really didn't understand your code, but this for loop would do what you need:

```<code>for(int i=0; i<scores.length-2; i++) {
    if(scores[i] > scores[i+1]) {
        return false;
    }
}
return true;
</code>```

Basically what we need to do here is to run on all of the elements in the array except the last element (which is in the place scores.length-1) because we will check the last element when we compare the second last element to it.
Once we have found 2 neighboring elements that doesn't satisfy the if condition there is no need to check further, we can return false right away.

If we have scanned ALL the elements and we didn't find any violation we can return true.

Body:
What is the problem to my code? I have tried to do this peoblem, but I don't find a good solution. Please help me, if you can!?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int[] scores = new int[n];
    int c = 0;

    for(int i = 0; i < scores.length; i++){
        scores[i] = scan.nextInt();
    }

    for(int j = scores.length-1; j >= 0; j--){
        boolean b = scores[j] <= scores[j-1] ? true : false;
        if(b == false){
            c++;
        }
    }
    if(c > 0){
        System.out.print(false);
    }

Body:
I really didn't understand your code, but this for loop would do what you need:

for(int i=0; i<scores.length-2; i++) {
    if(scores[i] > scores[i+1]) {
        return false;
    }
}
return true;

Basically what we need to do here is to run on all of the elements in the array except the last element (which is in the place scores.length-1) because we will check the last element when we compare the second last element to it.
Once we have found 2 neighboring elements that doesn't satisfy the if condition there is no need to check further, we can return false right away.

If we have scanned ALL the elements and we didn't find any violation we can return true.


问:
how do I resize a div based on the size of another div inside?
I have a vertical nav "slider" that now needs to be dynamically resized based in the number of links available to the user.  I've searched all over, but all the solutions I've found haven't quite worked.  It may simply be the way I have my css working. Any time I try to change the height attribute, the whole thing goes haywire.  I'm trying to do this entirely in css.  I know it seems like it should be simple, I just can't figure it out myself.

It's basically:

```<code><div class="slideMenu">
    <ul class="nav">menu items...</ul>
</div>
</code>```

Here's the css:

```<code>.slideMenu {
  background: #449bb5;
  width: 140px;
  height: 100%;
  padding-right: 40px;
  position: absolute;
  z-index: 3;
  -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  left: -180px;
  color: #FFFFFF;
  opacity: 100;
  transition: .4s ease-in-out;
}

.slideMenu:not(:hover) {
    transition-delay: .4s;
}

.slideMenu:hover {
  transform: translate3d(160px, 0, 0);
}

.slideMenu .nav {
  position: absolute;
  top: 30%;
  height: auto;
  -webkit-transform: translateY(50%);
  -ms-transform: translateY(50%);
  transform: translateY(-50%);
  font-weight: 400;
}
</code>```

JSFiddle here

答:
You don't need to specify a height.  Doing so in this instance with 100% says that the height is 100% of it's parent container... The body.  Not what you want.  Leave it out.  You have other issues here that you can improve, which I marked in the comments of the code below.

body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, "sans-serif" !important;
  font-size: 12px;
}

.slideMenu {
  background: #449bb5;
  width: 140px;
  /* height: 100%; remove this */
  padding-right: 40px;
  position: absolute;
  z-index: 3;
  -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  left: -180px;
  top: 0;
  color: #FFFFFF;
  opacity: 100;
  transition: .4s ease-in-out;
}

.slideMenu:not(:hover) {
    transition-delay: .4s;
}

.slideMenu:hover/*, .slideMenu:focus*/ {
  transform: translate3d(160px, 0, 0);
}

.slideMenu .nav {
  /*position: absolute; changed to relative */
  position: relative;
  top: 30%;
  /* height: auto; remove. unnecessary */
  /*
  -webkit-transform: translateY(50%);
  -ms-transform: translateY(50%);
  transform: translateY(-50%);
  remove this. it's trying to center your menu */
  font-weight: 400;
}

.slideMenu .nav li {
  padding-bottom: 10px;
  padding-top: 10px;
  list-style-type: none;
}

.slideMenu .nav li a {
  display: block;
  text-decoration: none;
  color: white;
  cursor: pointer;
}

.slideMenu .nav li a:hover {
  color: #aaa;
}

.slideMenuTab {
 background: #449bb5;
 position: relative;
 width: 40px;
 z-index: 3;
 -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
 box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
 left: 165px;
 color: #FFFFFF;
 text-align: right;
 padding-right: 8px;
 padding-top: 6px;
 padding-bottom: 3px;
 border-radius: 8px;
 cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideMenu">
   <div class="slideMenuTab"><img src="images/hamburger.png"/></div>
    <ul class="nav">
      <li>Create Pick</li>
      <hr>
      <li>Create Return</li>
      <hr>
      <li>Create Adjustment</li>
      <hr>
      <li>Create MTR</li>
      <hr>
      <li>Receive MTR</li>
      <hr>
      <li>Order Signage       </li>
      <li>Create Pick</li>
      <hr>
      <li>Create Return</li>
      <hr>
      <li>Create Adjustment</li>
      <hr>
      <li>Create MTR</li>
      <hr>
      <li>Receive MTR</li>
      <hr>
      <li>Order Signage       </li>
      <li>Create Pick</li>
      <hr>
      <li>Create Return</li>
      <hr>
      <li>Create Adjustment</li>
      <hr>
      <li>Create MTR</li>
      <hr>
      <li>Receive MTR</li>
      <hr>
      <li>Order Signage</li>

    </ul>
</div></code>```

Body:
I have a vertical nav "slider" that now needs to be dynamically resized based in the number of links available to the user.  I've searched all over, but all the solutions I've found haven't quite worked.  It may simply be the way I have my css working. Any time I try to change the height attribute, the whole thing goes haywire.  I'm trying to do this entirely in css.  I know it seems like it should be simple, I just can't figure it out myself.

It's basically:

menu items...

Here's the css:

.slideMenu {
  background: #449bb5;
  width: 140px;
  height: 100%;
  padding-right: 40px;
  position: absolute;
  z-index: 3;
  -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  left: -180px;
  color: #FFFFFF;
  opacity: 100;
  transition: .4s ease-in-out;
}

.slideMenu:not(:hover) {
    transition-delay: .4s;
}

.slideMenu:hover {
  transform: translate3d(160px, 0, 0);
}

.slideMenu .nav {
  position: absolute;
  top: 30%;
  height: auto;
  -webkit-transform: translateY(50%);
  -ms-transform: translateY(50%);
  transform: translateY(-50%);
  font-weight: 400;
}

JSFiddle here

Body:
You don't need to specify a height.  Doing so in this instance with 100% says that the height is 100% of it's parent container... The body.  Not what you want.  Leave it out.  You have other issues here that you can improve, which I marked in the comments of the code below.

body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, "sans-serif" !important;
  font-size: 12px;
}

.slideMenu {
  background: #449bb5;
  width: 140px;
  /* height: 100%; remove this */
  padding-right: 40px;
  position: absolute;
  z-index: 3;
  -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
  left: -180px;
  top: 0;
  color: #FFFFFF;
  opacity: 100;
  transition: .4s ease-in-out;
}

.slideMenu:not(:hover) {
    transition-delay: .4s;
}

.slideMenu:hover/*, .slideMenu:focus*/ {
  transform: translate3d(160px, 0, 0);
}

.slideMenu .nav {
  /*position: absolute; changed to relative */
  position: relative;
  top: 30%;
  /* height: auto; remove. unnecessary */
  /*
  -webkit-transform: translateY(50%);
  -ms-transform: translateY(50%);
  transform: translateY(-50%);
  remove this. it's trying to center your menu */
  font-weight: 400;
}

.slideMenu .nav li {
  padding-bottom: 10px;
  padding-top: 10px;
  list-style-type: none;
}

.slideMenu .nav li a {
  display: block;
  text-decoration: none;
  color: white;
  cursor: pointer;
}

.slideMenu .nav li a:hover {
  color: #aaa;
}

.slideMenuTab {
 background: #449bb5;
 position: relative;
 width: 40px;
 z-index: 3;
 -webkit-box-shadow: -3px 0px 5px 0px rgba(0, 0, 0, 0.2);
 box-shadow: 3px 0px 5px 0px rgba(0, 0, 0, 0.2);
 left: 165px;
 color: #FFFFFF;
 text-align: right;
 padding-right: 8px;
 padding-top: 6px;
 padding-bottom: 3px;
 border-radius: 8px;
 cursor: pointer;
}

<div class="slideMenu">
   <div class="slideMenuTab"><img src="images/hamburger.png"/></div>
    <ul class="nav">
      <li><a data-type="ticketdialogbutton" data-class="PickTicket">Create Pick</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReturnTicket">Create Return</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="AdjustmentTicket">Create Adjustment</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="CreateMTRTicket">Create MTR</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReceiveMTRTicket">Receive MTR</a></li>
      <hr>
      <li><a href="https://ecom.schwarz.com" target="_blank" data-type="ticketdialogbutton">Order Signage</a>       </li>
      <li><a data-type="ticketdialogbutton" data-class="PickTicket">Create Pick</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReturnTicket">Create Return</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="AdjustmentTicket">Create Adjustment</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="CreateMTRTicket">Create MTR</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReceiveMTRTicket">Receive MTR</a></li>
      <hr>
      <li><a href="https://ecom.schwarz.com" target="_blank" data-type="ticketdialogbutton">Order Signage</a>       </li>
      <li><a data-type="ticketdialogbutton" data-class="PickTicket">Create Pick</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReturnTicket">Create Return</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="AdjustmentTicket">Create Adjustment</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="CreateMTRTicket">Create MTR</a></li>
      <hr>
      <li><a data-type="ticketdialogbutton" data-class="ReceiveMTRTicket">Receive MTR</a></li>
      <hr>
      <li><a href="https://ecom.schwarz.com" target="_blank" data-type="ticketdialogbutton">Order Signage</a></li>

    </ul>
</div>


问:
using a generic method when using interface
Im stuck on a generics issue.
I have a method that returns DbSet from a DbContext object based on the object type.

Now I want to write I method where I pass in a object that implements a interface called IBaseData (that all entities implements). I want to use the existing method to return the correct DbSet based on the type of the IBaseData object, but I can't get it to work.

I've tried various versions of , typeof and gettype.

Existing method:

```<code>public GenericRepository<T> GetRepo<T>() where T : class
{
    return new GenericRepository<T>(_context);
}
</code>```

New method (this is just what Im trying to do):

```<code>public async Task SetDateLastInvoked<T>(IBaseData data, int id)
{
    var tmp = GetRepo<typeof(data)>().Where(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}
</code>```

答:
Ended up with this, based on previous answer:

```<code>public async Task SetLastInvoked<T>(int id) where T : class, IBaseData
{
    var tmp = await GetRepo<T>().Single(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}
</code>```

I also created another method based on the same pattern:

```<code>public async Task DeleteItem<T>(int id, bool removeRow) where T : class, IBaseData
{
    if (removeRow)
    {
        GetRepo<T>().Delete(await GetRepo<T>().Single(obj => obj.Id.Equals(id)));
    }
    else
    {
        var tmp = await GetRepo<T>().Single(obj => obj.Id.Equals(id));
        tmp.Active = false;
    }

    await SaveChangesAsync();
}
</code>```

Body:
Im stuck on a generics issue.
I have a method that returns DbSet from a DbContext object based on the object type.

Now I want to write I method where I pass in a object that implements a interface called IBaseData (that all entities implements). I want to use the existing method to return the correct DbSet based on the type of the IBaseData object, but I can't get it to work.

I've tried various versions of , typeof and gettype.

Existing method:

public GenericRepository<T> GetRepo<T>() where T : class
{
    return new GenericRepository<T>(_context);
}

New method (this is just what Im trying to do):

public async Task SetDateLastInvoked<T>(IBaseData data, int id)
{
    var tmp = GetRepo<typeof(data)>().Where(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}

Body:
Ended up with this, based on previous answer:

public async Task SetLastInvoked<T>(int id) where T : class, IBaseData
{
    var tmp = await GetRepo<T>().Single(obj => obj.Id.Equals(id));
    tmp.DateLastInvoked = DateTime.Now;

    await SaveChangesAsync();
}

I also created another method based on the same pattern:

public async Task DeleteItem<T>(int id, bool removeRow) where T : class, IBaseData
{
    if (removeRow)
    {
        GetRepo<T>().Delete(await GetRepo<T>().Single(obj => obj.Id.Equals(id)));
    }
    else
    {
        var tmp = await GetRepo<T>().Single(obj => obj.Id.Equals(id));
        tmp.Active = false;
    }

    await SaveChangesAsync();
}


问:
Start error with Microsoft Bot Framework, Visual Studio 2015 and 2017

Downloaded bot emulator and vs template code as described in https://learn.microsoft.com/en-us/bot-framework/resources-tools-downloads.

Created a new bot application after launching VS 2015 [Version: 14 Update 3] with admin privileges (and also with VS 2017 [Version: 15.2] with same end result) on my Windows 10 machine (Version: 1703; OS Build: 16199.1000).

Updated all nuget packages.

Pressed F5 to run the application. I get following error:

Server Error in '/' Application.

Specified argument was out of the range of valid values.
Parameter name: site

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: site

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +280

[HttpException (0x80004005): Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10041024
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

The Application event log has following information:

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 5/24/2017 11:36:28 PM
Event time (UTC): 5/25/2017 6:36:28 AM
Event ID: 9914b02cd15f4282b9043b1f70097b3e
Event sequence: 1
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/2/ROOT-1-131401677887853236
    Trust level:

    Application Virtual Path: /
    Application Path: c:\users\User A\documents\visual studio 2017\Projects\MyFirstBotApp\MyFirstBotApp\
    Machine name: DESKTOP-BQ93HFB

Process information:
    Process ID: 14320
    Process name: iisexpress.exe
    Account name: DESKTOP-BQ93HFB\User A

Exception information:
    Exception type: ArgumentOutOfRangeException
    Exception message: Specified argument was out of the range of valid values.
Parameter name: site
   at System.Web.Configuration.WebConfigurationHost.InitForConfiguration(String& locationSubPath, String& configPath, String& locationConfigPath, IInternalConfigRoot configRoot, Object[] hostInitConfigurationParams)
   at System.Configuration.Configuration..ctor(String locationSubPath, Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInternalConfigConfigurationFactory.Create(Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site, String locationSubPath, String server, String userName, String password, IntPtr tokenHandle)
   at System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel webLevel, ConfigurationFileMap fileMap, String path, String site, String locationSubPath, String server, String userName, String password, IntPtr userToken)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)   at System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException)

Request information:
    Request URL: http://localhost:3979/
    Request path: /
    User host address: ::1
    User:

    Is authenticated: False
    Authentication Type:

    Thread account name: DESKTOP-BQ93HFB\User A

Thread information:
    Thread ID: 5
    Thread account name: DESKTOP-BQ93HFB\User A
    Is impersonating: False
    Stack trace:    at System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException)

I checked the Project Properties under Web tab. The deployment server is set as IIS Express. I also verified that I have IIS Express with version 10.0.14358.1000 installed. (Note: I can run and create Web Api applications without any problems.)

Not sure what else to check here to resolve the problem. Any help is appreciated.

答:
Had pretty much the same problem.

After installing Windows 10 1709 update, staring VS 2015 took a while. After it started, loaded my project and hit F5 resulting in the following exception:

```<code>Exception information:
    Exception type: ArgumentOutOfRangeException
    Exception message: Specified argument was out of the range of valid values.
Parameter name: site
   at System.Web.Configuration.WebConfigurationHost.InitForConfiguration(String& locationSubPath, String& configPath, String& locationConfigPath, IInternalConfigRoot configRoot, Object[] hostInitConfigurationParams)
   at System.Configuration.Configuration..ctor(String locationSubPath, Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInternalConfigConfigurationFactory.Create(Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site, String locationSubPath, String server, String userName, String password, IntPtr tokenHandle)
   at System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel webLevel, ConfigurationFileMap fileMap, String path, String site, String locationSubPath, String server, String userName, String password, IntPtr userToken)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)   at System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException)
</code>```

First, I closed my VS and deleted the Content of .vs folder. Loaded my solution again, VS seemed to recreate the config properly but still did not work.

Second, downloaded IIS 10 Express installation, uninstalled the existing one, installed the new one ..seems to work.

But now my SQL server seems not to work, but that is another story.

Body:
Had pretty much the same problem.

After installing Windows 10 1709 update, staring VS 2015 took a while. After it started, loaded my project and hit F5 resulting in the following exception:

Exception information:
    Exception type: ArgumentOutOfRangeException
    Exception message: Specified argument was out of the range of valid values.
Parameter name: site
   at System.Web.Configuration.WebConfigurationHost.InitForConfiguration(String& locationSubPath, String& configPath, String& locationConfigPath, IInternalConfigRoot configRoot, Object[] hostInitConfigurationParams)
   at System.Configuration.Configuration..ctor(String locationSubPath, Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInternalConfigConfigurationFactory.Create(Type typeConfigHost, Object[] hostInitConfigurationParams)
   at System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site, String locationSubPath, String server, String userName, String password, IntPtr tokenHandle)
   at System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel webLevel, ConfigurationFileMap fileMap, String path, String site, String locationSubPath, String server, String userName, String password, IntPtr userToken)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)   at System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException)

First, I closed my VS and deleted the Content of .vs folder. Loaded my solution again, VS seemed to recreate the config properly but still did not work.

Second, downloaded IIS 10 Express installation, uninstalled the existing one, installed the new one ..seems to work.

But now my SQL server seems not to work, but that is another story.

ContentLicense: CC BY-SA 4.0


问:
What is '.' in SQL Server query
I just started working on one existing project and see the query which looks something like this -

```<code>select 100. * somecolumn1 / NULLIF(somecolumn2, 0.) AS ColumnValue,
from dbo.SomeTable
</code>```

I am not sure what is '.' operator in select statement. Could anyone please help me understand?

Also this is just a portion of massive SQL Server query. And if I comment this particular select statement the query runs in about 7 seconds otherwise it takes about 5 minutes to execute the query. Can this statement be optimized?

答:
SQL Server does integer division.  So, 1/2 = 0, not 0.5.

To avoid integer division, you want to use values with decimal places.  The simplest way to accomplish that is to use numeric literals.  I would always include a 0 after (and before) the decimal place, so the value is easier to see:

```<code>select 100.0 * somecolumn1 / NULLIF(somecolumn2, 0.0) AS ColumnValue,
from dbo.SomeTable
</code>```

I often accomplish this by multiplying by 1.0.  Alternative, you can use cast() or convert() on an integer column.

Title: What is '.' in SQL Server query

Body:
I just started working on one existing project and see the query which looks something like this -

select 100. * somecolumn1 / NULLIF(somecolumn2, 0.) AS ColumnValue,
from dbo.SomeTable

I am not sure what is '.' operator in select statement. Could anyone please help me understand?

Also this is just a portion of massive SQL Server query. And if I comment this particular select statement the query runs in about 7 seconds otherwise it takes about 5 minutes to execute the query. Can this statement be optimized?

Body:
SQL Server does integer division.  So, 1/2 = 0, not 0.5.

To avoid integer division, you want to use values with decimal places.  The simplest way to accomplish that is to use numeric literals.  I would always include a 0 after (and before) the decimal place, so the value is easier to see:

select 100.0 * somecolumn1 / NULLIF(somecolumn2, 0.0) AS ColumnValue,
from dbo.SomeTable

I often accomplish this by multiplying by 1.0.  Alternative, you can use cast() or convert() on an integer column.


答:
IIUC, and if your dataframes aren't too big, you can use a cartesian join and filters, then drop duplicates to get the first value matches like this:

```<code>df_is_case = df[df['is_case'] == True]
df_joined = df_is_case.assign(key=1)\
                         .merge(df.assign(key=1),
                                on='key',
                                suffixes=('','_y'))\
                         .query('index < index_y and value_a <= value_b_y')

df_out = pd.concat([df_joined, df_is_case])\
           .drop_duplicates(subset='index')[['index', 'is_case', 'value_a', 'value_b', 'index_y']]\
           .rename(columns={'index_y':'output'})

print(df_out)
</code>```

Output:

```<code>         index  is_case   value_a   value_b      output
3   03/01/2005     True  0.598082  0.189099  06/01/2005
23  07/01/2005     True  0.513017  0.397304  08/01/2005
50  08/01/2005     True  0.691884  0.922642  17/01/2005
68  16/01/2005     True  0.363920  0.355211  17/01/2005
17  20/01/2005     True  0.210786  0.839850         NaN
</code>```

Title: Returning a pandas DataFrame with the indexes of first next cases of >= value

Body:
Initial DataFrame

index        is_case        value_a         value_b
03/01/2005      True    0.598081665     0.189099313
04/01/2005     False    0.480809369     0.142255603
05/01/2005     False    0.963128886     0.422756089
06/01/2005     False    0.687675456     0.739599384
07/01/2005      True    0.513017431     0.397303797
08/01/2005      True    0.691884131     0.922642361
09/01/2005     False    0.659555415     0.222993436
10/01/2005     False    0.920539474     0.553573214
11/01/2005     False    0.360990121     0.535021421
12/01/2005     False    0.512528553     0.343931584
13/01/2005     False    0.083391071     0.277004714
14/01/2005     False    0.382696661     0.204780359
15/01/2005     False    0.838666246     0.337101306
16/01/2005      True    0.363920089     0.355211134
17/01/2005     False    0.354853214     0.691884131
18/01/2005     False    0.089324832     0.910276245
19/01/2005     False    0.611991454     0.513667459
20/01/2005      True    0.210785609     0.839849547

Desired Output:

The important thing about the output is to contain the column output and the index. Other columns may or may not be in the output.

index        is_case        value_a         value_b          output
03/01/2005      True    0.598081665     0.189099313      06/01/2005
07/01/2005      True    0.513017431     0.397303797      08/01/2005
08/01/2005      True    0.691884131     0.922642361      17/01/2005
16/01/2005      True    0.363920089     0.355211134      17/01/2005
20/01/2005      True    0.210785609     0.839849547             NaN

Transformation Logic

Get the value_a of all rows where is_case is True and search from the next row onwards for a value_b which is greater or equal than value_a, it returns the first index that meets this criteria in column output.

Body:
IIUC, and if your dataframes aren't too big, you can use a cartesian join and filters, then drop duplicates to get the first value matches like this:

df_is_case = df[df['is_case'] == True]
df_joined = df_is_case.assign(key=1)\
                         .merge(df.assign(key=1),
                                on='key',
                                suffixes=('','_y'))\
                         .query('index < index_y and value_a <= value_b_y')

df_out = pd.concat([df_joined, df_is_case])\
           .drop_duplicates(subset='index')[['index', 'is_case', 'value_a', 'value_b', 'index_y']]\
           .rename(columns={'index_y':'output'})

print(df_out)

Output:

         index  is_case   value_a   value_b      output
3   03/01/2005     True  0.598082  0.189099  06/01/2005
23  07/01/2005     True  0.513017  0.397304  08/01/2005
50  08/01/2005     True  0.691884  0.922642  17/01/2005
68  16/01/2005     True  0.363920  0.355211  17/01/2005
17  20/01/2005     True  0.210786  0.839850         NaN


问:
Is a DOM Text Node guaranteed to not be interpreted as HTML?
Does anyone know whether a DOM Node of type Text is guaranteed not be interpreted as HTML by the browser?

More details follow.

Background

I'm building a simple web comment system for a friend, and I've been thinking about XSS attacks.  I don't think filtering or escaping HTML tags is a very elegant solution--it's too easy to come up with a convolution that will slip past the filter.  The fundamental issue is that I want to guarantee that, for certain pieces of content (i.e. the content that random unauthenticated web users POST), the browser never tries to interpret or run the content.

A plain(text) start

The first thought that came to mind is just to use Content-Type: text/plain, but this has to apply to a whole page.  You can put a plaintext IFRAME in the middle of a page, but it's ugly, and it creates focus problems if the user clicks into the frame.

innerText/textContent/JQuery

It turns out that there are some browser-specific (innerText in IE, textContent in FF, Safari, etc.) attributes that, when set, are required to create a single Text node.

JQuery tries to avoid the difference in browser-specific attributes, by implementing a single function text(val) that skips the browser-specific attributes and goes directly to document.createTextNode(text), which, as you can guess, creates a Text node.

W3 DOM Text Nodes

So I think this is close to what I want, it looks good--Text nodes can't have children, and it appears like they can't be interpreted as HTML.  But I am not 100% sure from the official docs.

Interface Node: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1950641247

Interface Text: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772

textContent: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent

The part from textContent is particularly encouraging, because it says "on setting, no parsing is performed either, the input string is taken as pure textual content."  But is this fundamental to all Text nodes, or only nodes on which you set textContent?  This probably seems like a dumb quibble, but it might be important because IE doesn't support textContent (see above).

Back around to the initial question

Can anyone confirm/reject that this will work?  That is, that a w3 DOM compliant browser will never interpret a Text node as HTML, no matter what the content?  I'd be extremely grateful to have this tormenting little uncertainty resolved.

Thank you for your time!

答:
I don't think filtering or escaping HTML tags is a very elegant solution--it's too easy to come up with a convolution that will slip past the filter

That is absolutely untrue, filtering > to > and < to < will completely stop any HTML injection.

Body:
I don't think filtering or escaping HTML tags is a very elegant solution--it's too easy to come up with a convolution that will slip past the filter

That is absolutely untrue, filtering > to &gt; and < to &lt; will completely stop any HTML injection.


问:
Fluent Validations. Error: Validation type names in unobtrusive client validation rules must be unique
I got the erorr:

Validation type names in unobtrusive
  client validation rules must be
  unique. The following validation type
  was seen more than once: required. The
  following validation type was seen
  more than once: required

I used server validation. And all worked fine.
But now I`m stating to use client-side validation and I got this problem.

This is my validation class code:

```<code>public class TestViewDataValidation : BaseTestCreateViewDataValidation<BaseTestCreateViewData>
    {

public TestViewDataValidation ()
        {
            this.RuleFor(x => x.Login).NotNull();
            this.RuleFor(x => x.Login).NotEmpty();
            this.RuleFor(x => x.Login).EmailAddress();
        }
}
</code>```

But if I leave one validator - all works fine.
What should I do to have more that one validation for field.

答:
FluentValidation.NET is called Fluent because it provides a fluent interface for chaining methods:

```<code>public TestViewDataValidation()
{
    RuleFor(x => x.Login)
        .NotNull()
        .NotEmpty()
        .EmailAddress();
}
</code>```

Remark: the usage of NotNull and NotEmpty rules seem reduntant to me in this case. NotEmpty should be enough.

Body:
I got the erorr:

Validation type names in unobtrusive
  client validation rules must be
  unique. The following validation type
  was seen more than once: required. The
  following validation type was seen
  more than once: required

I used server validation. And all worked fine.
But now I`m stating to use client-side validation and I got this problem.

This is my validation class code:

public class TestViewDataValidation : BaseTestCreateViewDataValidation<BaseTestCreateViewData>
    {

public TestViewDataValidation ()
        {
            this.RuleFor(x => x.Login).NotNull();
            this.RuleFor(x => x.Login).NotEmpty();
            this.RuleFor(x => x.Login).EmailAddress();
        }
}

But if I leave one validator - all works fine.
What should I do to have more that one validation for field.

Body:
FluentValidation.NET is called Fluent because it provides a fluent interface for chaining methods:

public TestViewDataValidation()
{
    RuleFor(x => x.Login)
        .NotNull()
        .NotEmpty()
        .EmailAddress();
}

Remark: the usage of NotNull and NotEmpty rules seem reduntant to me in this case. NotEmpty should be enough.


问:
How to make Javers compare by field values rather than ID/object reference
I have an object like:

```<code>class Person {
    Phone phone;
}

class Phone {
    String number;
    String prefix;
    Phone(String n, String p) {
        number = n;
        prefix = p;
    }
}

Now consider this code:

Person p = new Person();
p.phone = new Phone("444444", "01");
javers.commit(p);
p.phone = new Phone("555555", "01");
javers.commit(p);
</code>```

In this case sees that the reference of Phone has changed. While that's good info, I don't really care about that. I just want to know when the value of the number field has changed, that's really what I am tracking.

How would I achieve that? I tried defining the Phone class as a ValueObject, but it doesn't seem to do the job, I still get it as reference change rather than value change in the resulting Commit snapshot. Should I register it as a Value instead?

答: Map Phone as ValueObject or let JaVers to apply default mapping, which is also ValueObject object. ValueObject are always compared property by property and never by reference. What do you mean by it doesn't seem to do the job?</p>

Body:
I have an object like:

class Person {
    Phone phone;
}

class Phone {
    String number;
    String prefix;
    Phone(String n, String p) {
        number = n;
        prefix = p;
    }
}

Now consider this code:

Person p = new Person();
p.phone = new Phone("444444", "01");
javers.commit(p);
p.phone = new Phone("555555", "01");
javers.commit(p);

In this case sees that the reference of Phone has changed. While that's good info, I don't really care about that. I just want to know when the value of the number field has changed, that's really what I am tracking.

How would I achieve that? I tried defining the Phone class as a ValueObject, but it doesn't seem to do the job, I still get it as reference change rather than value change in the resulting Commit snapshot. Should I register it as a Value instead?


问:
Signal handle in macOS, revealing the sender process
Is there an option to get the sender process as input to signal handler callback.

Here's the signature of the method that apply callbacks to signal reception.

```<code>void    (*signal(int, void (*)(int)))(int);
</code>```

If I want to assign callback to certain signal

```<code>signal(signum, cbk_function);
</code>```

However, the cbs_function prototype allows it to get the signal index only, I wonder if I can get the pid of the process that sent this signal to current process.

I need it in order to detect shutdown event in user-space process.

答:
If you use sigaction instead of signal,
you can specify a signal handler that takes a siginfo_t * parameter. Siginfo_t is a structure, which contains a si_pid element. The standard documents this as:

pid_t     si_pid;    // Sending process ID.

I wrote the following program to show how to implement this.

```<code>#include <signal.h>

/* Can't call standard string functions from signal hander. Write our own. */

int ltoa(unsigned long i, char *buf)
{
    char mybuf[20] = "0";
    char *mbp = mybuf;
    char *bp = buf;

    if (i == 0)
        *mbp++ = '0';
    else while (i > 0) {
        *mbp++ = '0' + (i % 10);
        i /= 10;
    }
    while (--mbp >= mybuf)
        *bp++ = *mbp;
    *bp = '\0';
    return bp - buf;
}

void handler(int sig, siginfo_t *si, void *uc)
{
    unsigned long pid = si->si_pid;
    char buf[20];
    int buflen;

    write(1, "Received signal ", 16);
    buflen = ltoa(sig, buf);
    write(1, buf, buflen);
    write(1, " from ", 6);
    buflen = ltoa(pid, buf);
    write(1, buf, buflen);
    write(1, "\n", 1);
}

int main()
{
    struct sigaction sa = { .sa_sigaction=handler, .sa_flags=SA_SIGINFO };
    struct sigaction oldsa;

    sigaction(SIGINT, &sa, &oldsa);

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

I don't have a Mac, so I ran this on Linux, but it should work on most POSIX-conforming systems, including Mac OS X:

```<code>$ cc sig.c
$ ./a.out
^CReceived signal 2 from 0
$ ./a.out&
[1] 3454
$ kill -2 3454
$ Received signal 2 from 2740
</code>```

Body:
Is there an option to get the sender process as input to signal handler callback.

Here's the signature of the method that apply callbacks to signal reception.

void    (*signal(int, void (*)(int)))(int);

If I want to assign callback to certain signal

signal(signum, cbk_function);

However, the cbs_function prototype allows it to get the signal index only, I wonder if I can get the pid of the process that sent this signal to current process.

I need it in order to detect shutdown event in user-space process.

Body:
If you use sigaction instead of signal,
you can specify a signal handler that takes a siginfo_t * parameter. Siginfo_t is a structure, which contains a si_pid element. The standard documents this as:

pid_t     si_pid;    // Sending process ID.

I wrote the following program to show how to implement this.

#include <signal.h>

/* Can't call standard string functions from signal hander. Write our own. */

int ltoa(unsigned long i, char *buf)
{
    char mybuf[20] = "0";
    char *mbp = mybuf;
    char *bp = buf;

    if (i == 0)
        *mbp++ = '0';
    else while (i > 0) {
        *mbp++ = '0' + (i % 10);
        i /= 10;
    }
    while (--mbp >= mybuf)
        *bp++ = *mbp;
    *bp = '\0';
    return bp - buf;
}

void handler(int sig, siginfo_t *si, void *uc)
{
    unsigned long pid = si->si_pid;
    char buf[20];
    int buflen;

    write(1, "Received signal ", 16);
    buflen = ltoa(sig, buf);
    write(1, buf, buflen);
    write(1, " from ", 6);
    buflen = ltoa(pid, buf);
    write(1, buf, buflen);
    write(1, "\n", 1);
}

int main()
{
    struct sigaction sa = { .sa_sigaction=handler, .sa_flags=SA_SIGINFO };
    struct sigaction oldsa;

    sigaction(SIGINT, &sa, &oldsa);

    pause();
}

I don't have a Mac, so I ran this on Linux, but it should work on most POSIX-conforming systems, including Mac OS X:

$ cc sig.c
$ ./a.out
^CReceived signal 2 from 0
$ ./a.out&
[1] 3454
$ kill -2 3454
$ Received signal 2 from 2740


问:
Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

```<code>  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;
</code>```

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

答:
If you want to apply Spring dependency injection in tests, you have 2 basic options:

If you want to have the beans declared in XML, declare both MessagingProperties and MessagingPropertiesRefactor in XML file and annotate the test class the following way:

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration("your.xml")
</code>```

The beans should be successfully autowired.

To have the beans declared in JavaConfig, do the following

2.1. Annotate you test class like this:

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration
</code>```

2.2. Inside the test class, define context configuration class that declates the beans that you need:

```<code>@Configuration
static class Config {

    @Bean
    public MessagingProperties messagingProperties() {
        // Assuming MessagingProperties has default ctor.
        return new MessagingProperties();
    }

    // Same for MessagingPropertiesRefactor
}
</code>```

Enjoy the autowired beans :)

*The config class does not have to be nested into the test class.

For more info regarding the topic, please consult Spring documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-javaconfig, Chapter 3.5.4. Context management.

Body:
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

Body:
If you want to apply Spring dependency injection in tests, you have 2 basic options:

If you want to have the beans declared in XML, declare both MessagingProperties and MessagingPropertiesRefactor in XML file and annotate the test class the following way:

@RunWith(SpringRunner.class)
@ContextConfiguration("your.xml")

The beans should be successfully autowired.

To have the beans declared in JavaConfig, do the following

2.1. Annotate you test class like this:

@RunWith(SpringRunner.class)
@ContextConfiguration

2.2. Inside the test class, define context configuration class that declates the beans that you need:

@Configuration
static class Config {

    @Bean
    public MessagingProperties messagingProperties() {
        // Assuming MessagingProperties has default ctor.
        return new MessagingProperties();
    }

    // Same for MessagingPropertiesRefactor
}

Enjoy the autowired beans :)

*The config class does not have to be nested into the test class.

For more info regarding the topic, please consult Spring documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-javaconfig, Chapter 3.5.4. Context management.


问:
How to extract values from list to add to another list in python
I have the following code:

```<code>items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])
</code>```

response['Contents'] has a schema like this:

```<code>{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}
</code>```

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

答:
First off, you can't do items[i].append() because i is a dict and items is a list (among other reasons). Perhaps you should consider making a new list inside your for loop, appending each item, and then converting it into a tuple to append to items:

```<code>items = list()
for contents in response['Contents']:
    i = list()
    i.append('s3://' + response['Name'] + '/' + contents['Key'])
    i.append(contents['Key'].rsplit('/', 1)[-1])
    i.append(contents['Size'])
    items.append(tuple(i))
</code>```

Body:
I have the following code:

items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])

response['Contents'] has a schema like this:

{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

Body:
First off, you can't do items[i].append() because i is a dict and items is a list (among other reasons). Perhaps you should consider making a new list inside your for loop, appending each item, and then converting it into a tuple to append to items:

items = list()
for contents in response['Contents']:
    i = list()
    i.append('s3://' + response['Name'] + '/' + contents['Key'])
    i.append(contents['Key'].rsplit('/', 1)[-1])
    i.append(contents['Size'])
    items.append(tuple(i))


问:
Firebase addListener in onclick method
Is it possible to attach a firebase database listener in a button's onClick method?

I put datareference.addValueEventListener in the onClick method, but it crashes when I click on the button and try to update a value in firebase.

Do I create a whole new object and use setvalue to substitute the old value? In my case, I want to update the points of a user, and here is my onClick method

```<code>public void itemClick(View view) {
    int position;
    position = (Integer) view.getTag();
    if (taskList.get(position).getWorker()!=null && taskList.get(position).getWorker().compareTo(userEmail)==0) {
        if (taskList.get(position).getStates().compareTo("COMPLETE")==0)
            Toast.makeText(getContext(), getString(R.string.already_complete), Toast.LENGTH_LONG).show();
            taskList.get(position).setStates("COMPLETE");
            db.updateStates(taskList.get(position).getStates(), taskList.get(position).getName());
            Double awardpoint = taskList.get(position).getPoints();
            update(awardpoint);
            search();
            Toast.makeText(getContext(), getString(R.string.successful_complete), Toast.LENGTH_LONG).show();
        }else
            Toast.makeText(getContext(), getString(R.string.fail_complete), Toast.LENGTH_LONG).show();
}
</code>```

Here is my update method, I didnt put anything here, but it still crashes

```<code> private void update ( Double point){
    databaseReference.child("points").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
</code>```

}
Here is my onCreate method

```<code> public void onCreate(){

    currentUser = FirebaseAuth.getInstance().getCurrentUser();
    String curren_uid = currentUser.getUid();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(curren_uid);
}
</code>```

Here is the exception, and it seems that there's a null pointer exception.
I looked a simliar question on stackOverflow, and it says i should "only listenning the bussniness i interest in ".. but my reference is already pointed to the user with specific uid.

```<code>12-06 20:17:47.401 4399-4399/ca.uottawa.leyaoli.seg2105_final_project E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ca.uottawa.leyaoli.seg2105_final_project, PID: 4399
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.update(Tab2.java:161)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.itemClick(Tab2.java:153)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.TaskListAdapter.onClick(TaskListAdapter.java:93)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24701)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
Yes you can add addValueEventListener inside onClick method

But to perform update on the firebase database you need to do it outside the addValueEventListener

Title: Firebase addListener in onclick method

Body:
Is it possible to attach a firebase database listener in a button's onClick method?

I put datareference.addValueEventListener in the onClick method, but it crashes when I click on the button and try to update a value in firebase.

Do I create a whole new object and use setvalue to substitute the old value? In my case, I want to update the points of a user, and here is my onClick method

public void itemClick(View view) {
    int position;
    position = (Integer) view.getTag();
    if (taskList.get(position).getWorker()!=null && taskList.get(position).getWorker().compareTo(userEmail)==0) {
        if (taskList.get(position).getStates().compareTo("COMPLETE")==0)
            Toast.makeText(getContext(), getString(R.string.already_complete), Toast.LENGTH_LONG).show();
            taskList.get(position).setStates("COMPLETE");
            db.updateStates(taskList.get(position).getStates(), taskList.get(position).getName());
            Double awardpoint = taskList.get(position).getPoints();
            update(awardpoint);
            search();
            Toast.makeText(getContext(), getString(R.string.successful_complete), Toast.LENGTH_LONG).show();
        }else
            Toast.makeText(getContext(), getString(R.string.fail_complete), Toast.LENGTH_LONG).show();
}

Here is my update method, I didnt put anything here, but it still crashes

 private void update ( Double point){
    databaseReference.child("points").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

}
Here is my onCreate method

 public void onCreate(){

    currentUser = FirebaseAuth.getInstance().getCurrentUser();
    String curren_uid = currentUser.getUid();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(curren_uid);
}

Here is the exception, and it seems that there's a null pointer exception.
I looked a simliar question on stackOverflow, and it says i should "only listenning the bussniness i interest in ".. but my reference is already pointed to the user with specific uid.

12-06 20:17:47.401 4399-4399/ca.uottawa.leyaoli.seg2105_final_project E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ca.uottawa.leyaoli.seg2105_final_project, PID: 4399
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.update(Tab2.java:161)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.itemClick(Tab2.java:153)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.TaskListAdapter.onClick(TaskListAdapter.java:93)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24701)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)


问:
Displaying stats and calculating the average from certain user inputs
I have this application that I needed to create for my class project and I am down to my last part (minus the int validation for the scanner).

This app needs to be able to accept any amount of user input from the scanner, but the user can only enter numbers that are between 0-100 (for example, 10 100's, 20 0's, etc). To stop it, the user will type in "999" and when they type in "999", that is when the application will stop asking for numbers.

At that point, I have to display certain stats for the valid numbers (aka the numbers that are between 0-100). The stats that I need to show is this: The total numbers that was entered, the highest number, the lowest number, and the average of all of those numbers.

Can't figure out how I would do that.

Here is the code:
https://gist.github.com/tcipack/8f1ed6bd0d7d79b158ee191d228b0a24

答:
OK so here's one of the possibilities:

```<code>package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main (String[]args) {

        Scanner in = new Scanner(System.in);
        List<Integer> listOfNumbers = new ArrayList<>();

        int number;

        System.out.print("Enter your number: ");

        while ((number = in.nextInt()) != 999){

            while (number < 0 || number > 100){
                System.out.print("Invalid input. Try again: ");
                number = in.nextInt();
            }
            System.out.print("Enter your number: ");
            listOfNumbers.add(number);
        }

        int maxNumber = listOfNumbers.stream().mapToInt(x -> x).max().getAsInt();
        int minNumber = listOfNumbers.stream().mapToInt(x -> x).min().getAsInt();
        double average = listOfNumbers.stream().mapToInt(x -> x).average().getAsDouble();
        int totalEntered = listOfNumbers.size();

        System.out.printf("Out of %d numbers entered, max is %d, min is %d and average is %.2f", totalEntered,
                                                                      maxNumber,minNumber,average);

    }
}
</code>```

Sample test:

Enter your number: 5

Enter your number: 10

Enter your number: -12

Invalid input. Try again: 9

Enter your number: 999

Out of 3 numbers entered, max is 10, min is 5 and average is 8.00

I used Stream methods to quickly get min, max and average, then we just print it out.

Body:
OK so here's one of the possibilities:

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main (String[]args) {

        Scanner in = new Scanner(System.in);
        List<Integer> listOfNumbers = new ArrayList<>();

        int number;

        System.out.print("Enter your number: ");

        while ((number = in.nextInt()) != 999){

            while (number < 0 || number > 100){
                System.out.print("Invalid input. Try again: ");
                number = in.nextInt();
            }
            System.out.print("Enter your number: ");
            listOfNumbers.add(number);
        }

        int maxNumber = listOfNumbers.stream().mapToInt(x -> x).max().getAsInt();
        int minNumber = listOfNumbers.stream().mapToInt(x -> x).min().getAsInt();
        double average = listOfNumbers.stream().mapToInt(x -> x).average().getAsDouble();
        int totalEntered = listOfNumbers.size();

        System.out.printf("Out of %d numbers entered, max is %d, min is %d and average is %.2f", totalEntered,
                                                                      maxNumber,minNumber,average);

    }
}

Sample test:

Enter your number: 5

Enter your number: 10

Enter your number: -12

Invalid input. Try again: 9

Enter your number: 999

Out of 3 numbers entered, max is 10, min is 5 and average is 8.00

I used Stream methods to quickly get min, max and average, then we just print it out.


问:
How to prevent F5 key from saving data from userform in access
I have a bound form in MS Access and I use a submit button to insert the data from form to table. I have around 10 fields in form and even if I fill only 1 field and press the F5 button, it saves the data with just one field. How to stop F5 key from doing this.

Edit -  also when I close the form with partially filled data or if it gets closed accidently or when if i open design mode from there, it collects that partially filled data and then creates an entry, how to stop userform making entries via other means and make it only create record on button click.

答:
In my opinion, you should not stop the F5 button from doing this, you should stop anything else than your submit button from saving data.

This can be achieved with some VBA code:

The save button is named cmdSave in this example

```<code>Private saveButtonPressed As Boolean

Private Sub cmdSave_Click()
    saveButtonPressed = True
    DoCmd.RunCommand acCmdSaveRecord
End Sub

Private Sub Form_BeforeInsert(Cancel As Integer)
    If Not saveButtonPressed Then
        'Update through other means
        Cancel = True
    End If
    saveButtonPressed = False
End Sub

Private Sub Form_BeforeUpdate(Cancel As Integer)
    If Not saveButtonPressed Then
        'Update through other means
        Cancel = True
    End If
    saveButtonPressed = False
End Sub
</code>```

Body:
In my opinion, you should not stop the F5 button from doing this, you should stop anything else than your submit button from saving data.

This can be achieved with some VBA code:

The save button is named cmdSave in this example

Private saveButtonPressed As Boolean

Private Sub cmdSave_Click()
    saveButtonPressed = True
    DoCmd.RunCommand acCmdSaveRecord
End Sub

Private Sub Form_BeforeInsert(Cancel As Integer)
    If Not saveButtonPressed Then
        'Update through other means
        Cancel = True
    End If
    saveButtonPressed = False
End Sub

Private Sub Form_BeforeUpdate(Cancel As Integer)
    If Not saveButtonPressed Then
        'Update through other means
        Cancel = True
    End If
    saveButtonPressed = False
End Sub


问:
Write data to GCP BigTable from external Hosting with .NET application
We have a .NET application hosted in Rackspace. We'd like to write analytics data (simple logs) to BigTable, or any other product on the Google Cloud Platform from an external hosting.

Is it possible?

Is there any .NET library available for connecting and writing data to GCP BigTable?

Thanks!

答:
I'm the Cloud Bigtable client tech lead.  We are actively working on a C# client.  Here's the repository with all C# Google Cloud libraries, including our C# client that is in development.  Here's the nugget.  We don't have any public docs yet, but we do have test code that could be used as examples.

We can work with you on priorities.  Please feel free to have a more in depth conversation on our public discussion forum.  Once we have a general sense of your use case, we can potentially have more private discussions about how to fit your priorities into our ongoing development efforts.

FWIW, this is my github profile with more contact info.

Warning: The Cloud Bigtable C# client is currently pre-alpha.


问:
Strange results from OpenReadAsync() when reading data from Azure Blob storage
I'm having a go at modifying an existing C# (dot net core) app that reads a type of binary file to use Azure Blob Storage.

I'm using Windows.Azure.Storage (8.6.0).

The issue is that this app reads the binary data from files from a Stream in very small blocks (e.g. 5000-6000 bytes). This reflects how the data is structured.

Example pseudo code:

```<code>var blocks = new List<byte[]>();
var numberOfBytesToRead = 6240;
var numberOfBlocksToRead = 1700;

using (var stream = await blob.OpenReadAsync())
{
  stream.Seek(3000, SeekOrigin.Begin); // start reading at a particular position
  for (int i = 1; i <= numberOfBlocksToRead; i++)
  {
    byte[] traceValues = new byte[numberOfBytesToRead];
    stream.Read(traceValues, 0, numberOfBytesToRead);
    blocks.Add(traceValues);
  }
}`
</code>```

If I try to read a 10mb file using OpenReadAsync(), I get invalid/junk values in the byte arrays after around 4,190,000 bytes.

If I set StreamMinimumReadSize to 100Mb it works.

If I read more data per block (e.g. 1mb) it works.

Some of the files can be more than 100Mb, so setting the StreamMinimumReadSize may not be the best solution.

What is going on here, and how can I fix this?

答: Are the invalid/junk values zeros? If so (and maybe even if not) check the return value from stream.Read. That method is not guaranteed to actually read the number of bytes that you ask it to. It can read less. In which case you are supposed to call it again in a loop, until it has read the total amount that you want. A quick web search should show you lots of examples of the necessary looping.</p>

Body:
I'm having a go at modifying an existing C# (dot net core) app that reads a type of binary file to use Azure Blob Storage.

I'm using Windows.Azure.Storage (8.6.0).

The issue is that this app reads the binary data from files from a Stream in very small blocks (e.g. 5000-6000 bytes). This reflects how the data is structured.

Example pseudo code:

var blocks = new List<byte[]>();
var numberOfBytesToRead = 6240;
var numberOfBlocksToRead = 1700;

using (var stream = await blob.OpenReadAsync())
{
  stream.Seek(3000, SeekOrigin.Begin); // start reading at a particular position
  for (int i = 1; i <= numberOfBlocksToRead; i++)
  {
    byte[] traceValues = new byte[numberOfBytesToRead];
    stream.Read(traceValues, 0, numberOfBytesToRead);
    blocks.Add(traceValues);
  }
}`

If I try to read a 10mb file using OpenReadAsync(), I get invalid/junk values in the byte arrays after around 4,190,000 bytes.

If I set StreamMinimumReadSize to 100Mb it works.

If I read more data per block (e.g. 1mb) it works.

Some of the files can be more than 100Mb, so setting the StreamMinimumReadSize may not be the best solution.

What is going on here, and how can I fix this?