问:
How to increment and get the next IPv6 network address from the current network address
Using standard python packages, how can I get the next few IPv6 network address if we give any IPv6 network address as input. Basically I want to iterate over the network address which was given and on each iteration it should increment and get the next network

For example, if my start network address 4001:1::/32, then on each iteration I would like to get the next network address as 4001:2::/32, 4001:3::/32, 4001:4::/32  and so on.

```<code>>>> inet = iterate_on('4001:1::/32')
>>> next(inet)
4001:2::/32
>>> next(inet)
4001:3::/32
</code>```

Note: Here is my previous question for fetching IPv4 networks.

答:
The library ipcalc has routines to make math on ip addresses fairly easy.  But if it would be preferable to not install ipcalc, a class that inherits from ipaddress.IPv6Network can be constructed.

Code

```<code>import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        return self.__class__((new_base_addr, self.prefixlen))

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)
</code>```

Test Code:

```<code>import itertools as it
network = BetterIPv6Network(u'4001:1::/32')
network_addrs = (network + i * network.size() for i in it.count())
print(next(network_addrs))
print(next(network_addrs))
print(next(network_addrs))
</code>```

Results:

```<code>4001:1::/32
4001:2::/32
4001:3::/32
</code>```

Python 3.4:

Python 3.4 did not accept tuples to init ipaddress.IPv6Network. This code will work around that.

```<code>import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        new_base_addr_str = str(self.__class__(new_base_addr)).split('/')[0]
        return self.__class__(
            new_base_addr_str + '/' + str(self).split('/')[1])

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)
</code>```

Body:
Using standard python packages, how can I get the next few IPv6 network address if we give any IPv6 network address as input. Basically I want to iterate over the network address which was given and on each iteration it should increment and get the next network

For example, if my start network address 4001:1::/32, then on each iteration I would like to get the next network address as 4001:2::/32, 4001:3::/32, 4001:4::/32  and so on.

>>> inet = iterate_on('4001:1::/32')
>>> next(inet)
4001:2::/32
>>> next(inet)
4001:3::/32

Note: Here is my previous question for fetching IPv4 networks.

Body:
The library ipcalc has routines to make math on ip addresses fairly easy.  But if it would be preferable to not install ipcalc, a class that inherits from ipaddress.IPv6Network can be constructed.

Code

import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        return self.__class__((new_base_addr, self.prefixlen))

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)

Test Code:

import itertools as it
network = BetterIPv6Network(u'4001:1::/32')
network_addrs = (network + i * network.size() for i in it.count())
print(next(network_addrs))
print(next(network_addrs))
print(next(network_addrs))

Results:

4001:1::/32
4001:2::/32
4001:3::/32

Python 3.4:

Python 3.4 did not accept tuples to init ipaddress.IPv6Network. This code will work around that.

import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        new_base_addr_str = str(self.__class__(new_base_addr)).split('/')[0]
        return self.__class__(
            new_base_addr_str + '/' + str(self).split('/')[1])

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)


来源: stackexchange

问:
Add a div to create padding
I have a span.  Inside it I have two divs.  One used as padding and a second with content.  If the content is multi-line it wraps around my padding div, which I want to prevent.

This jsfiddle shows what I currently have. https://jsfiddle.net/ju637z98/

```<code><span>
  <span style="width: 20px; display: inline-block;">

  </span>
  <span style="display: inline; " >
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </span>
</span>
</code>```

If I change the content div to

```<code>display: inline-block
</code>```

the two divs end up being stacked on top of each other.

I'm trying to avoid styling the content div because the the padding div won't always be present so I'd like to avoid having two different styles to achieve what I need.

Any help would be appreciated.

Edit: updated the snipped above and the jsfiddle to use spans instead of divs.

答:
I would erase that first DIV and use margin-left: 20px; (or whatever value) on the content DIV (and make that an inline-block)

    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.

```

ContentLicense: CC BY-SA 3.0

Title: Add a div to create padding

Body:
I have a span.  Inside it I have two divs.  One used as padding and a second with content.  If the content is multi-line it wraps around my padding div, which I want to prevent.

This jsfiddle shows what I currently have. https://jsfiddle.net/ju637z98/

    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.

If I change the content div to

display: inline-block

the two divs end up being stacked on top of each other.

I'm trying to avoid styling the content div because the the padding div won't always be present so I'd like to avoid having two different styles to achieve what I need.

Any help would be appreciated.

Edit: updated the snipped above and the jsfiddle to use spans instead of divs.

Body:
I would erase that first DIV and use margin-left: 20px; (or whatever value) on the content DIV (and make that an inline-block)

<span>
  <div style="display: inline-block; margin-left: 20px;" >
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </div>
</span>


问:
RequireJs Google maps google is not define
I have a simple nodejs project that should load asynchronously the google maps api javascript, i followed this answer https://stackoverflow.com/a/15796543
and my app.js is like this:

```<code>var express = require("express"),
    app = express(),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override");
    https = require("https");
    requirejs = require('requirejs');

requirejs.config({
    waitSeconds : 500,
    isBuild: true,
    paths : {
        'async': 'node_modules/requirejs-plugins/src/async',
    }
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var router = express.Router();
router.get('/', function(req, res) {
    res.send("Hello World!");
});

requirejs(["async!http://maps.google.com/maps/api/js?key=mykey&sensor=false"], function() {
    console.log(google);
});

app.listen(3000, function() {
    console.log("asd");
});
</code>```

package.json:

```<code>{
 "name": "rest-google-maps-api",
 "version": "2.0.0",
 "dependencies": {
     "express": "^4.7.1",
     "method-override": "^2.1.2",
     "body-parser": "^1.5.1",
     "requirejs": "2.3.3",
     "requirejs-plugins": "1.0.2"
 }
}
</code>```

i've got always the same error:

ReferenceError: google is not defined

答:
The main issue here is that you are trying to run in Node code that is really meant to be used in a browser.

The async plugin

This plugin needs to be able to add script elements to document and needs window. I see you set isBuild: true in your RequireJS configuration. It does silence the error that async immediately raises if you do not use this flag, but this is not a solution because:

isBuild is really meant to be set internally by RequireJS's optimizer (or any optimizer that is compatible with RequireJS), not manually like you are doing.

isBuild means to indicate to plugins that they are running as part of an optimization run. However, your code is using the plugin at run time rather than as part of an optimization. So setting isBuild: true is a lie and will result in undesirable behavior. The async plugin is written in such a way that it effectively does nothing if isBuild is true. Other plugins may crash.

Google's Map API

It also expects a browser environment. The very first line I see when I download its code is this:

```<code>window.google = window.google || {};
</code>```

Later in the code there are references to window.document and window.postMessage.

I don't know if it is possible to run the code you've been trying to load from Google in Node. I suspect you'd most likely need something like jsdom to provide a browser-like environment to the API.

Body:
I have a simple nodejs project that should load asynchronously the google maps api javascript, i followed this answer https://stackoverflow.com/a/15796543
and my app.js is like this:

var express = require("express"),
    app = express(),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override");
    https = require("https");
    requirejs = require('requirejs');

requirejs.config({
    waitSeconds : 500,
    isBuild: true,
    paths : {
        'async': 'node_modules/requirejs-plugins/src/async',
    }
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var router = express.Router();
router.get('/', function(req, res) {
    res.send("Hello World!");
});

requirejs(["async!http://maps.google.com/maps/api/js?key=mykey&sensor=false"], function() {
    console.log(google);
});

app.listen(3000, function() {
    console.log("asd");
});

package.json:

{
 "name": "rest-google-maps-api",
 "version": "2.0.0",
 "dependencies": {
     "express": "^4.7.1",
     "method-override": "^2.1.2",
     "body-parser": "^1.5.1",
     "requirejs": "2.3.3",
     "requirejs-plugins": "1.0.2"
 }
}

i've got always the same error:

ReferenceError: google is not defined

Body:
The main issue here is that you are trying to run in Node code that is really meant to be used in a browser.

The async plugin

This plugin needs to be able to add script elements to document and needs window. I see you set isBuild: true in your RequireJS configuration. It does silence the error that async immediately raises if you do not use this flag, but this is not a solution because:

isBuild is really meant to be set internally by RequireJS's optimizer (or any optimizer that is compatible with RequireJS), not manually like you are doing.

isBuild means to indicate to plugins that they are running as part of an optimization run. However, your code is using the plugin at run time rather than as part of an optimization. So setting isBuild: true is a lie and will result in undesirable behavior. The async plugin is written in such a way that it effectively does nothing if isBuild is true. Other plugins may crash.

Google's Map API

It also expects a browser environment. The very first line I see when I download its code is this:

window.google = window.google || {};

Later in the code there are references to window.document and window.postMessage.

I don't know if it is possible to run the code you've been trying to load from Google in Node. I suspect you'd most likely need something like jsdom to provide a browser-like environment to the API.


问:
npgsql - stop using 'template1' database
I want to use elephantsql database with entity framework (whichever version). I found tutorial on the internet about npgsql which can help me connect those 2 piece of technology.

I made an object which will represent object from DB :

```<code>[Table("typychorob", Schema = "public")]
public class TypChoroby
{
    public TypChoroby()
    {
    }

    [Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.Identity), Required]
    public int ID { get; set; }

    [Column("nazwa"), MaxLength(50)]
    public string Nazwa { get; set; }
}
</code>```

I created class which will represent dBContext. Uzytkownik is nearly the same as TypChoroby.

```<code>public class PrzychodniaContext : DbContext
{
    public DbSet<Uzytkownik> Uzytkownicy { get; set; }
    public DbSet<TypChoroby> TypyChorob { get; set; }

    public PrzychodniaContext() : base()
    {
    }
}
</code>```

I try to use those things in the following style :

```<code>using (var context = new PrzychodniaContext())
        {
            context.Database.Log = post;
            var chorobska = context.TypyChorob.ToList();
        }
</code>```

This always creates error like this :

```<code>{"28000: no pg_hba.conf entry for host \"178.37.126.100\", user \"jnwnqqog\", database \"template1\", SSL off"}
</code>```

It's elephantSql simplest plan so i cannot edit pg_hba.conf which is a file where i can give myself some privileges.

My ConnectionString :

```<code><add name="PrzychodniaContext" connectionString="Server=YouDontWantToKnowButYouKnow;Database=jnwnqqog;User Id=jnwnqqog;Password=YouDontWantToKnow;MAXPOOLSIZE=5;" providerName="Npgsql" />
</code>```

What i tried?

1) First i know what's going on. In documentation of npgsql in create database command i found :

```<code>template
The name of the template from which to create the new database, or DEFAULT to use the default template (template1).
</code>```

Honetsly i do not know how to change that. I though that it would be good to change that to 'jnwnqqog', because it's my DB at elephantSQL. But i do not know.

2) I'd used
    Database.SetInitializer(null);
I assumed that it will stop trying to create new database. It did not stopped this behaviour.

3) I tried to enable/disable SSL.

4) I changed entity framework from 5.0 to 6.0 along with npgsql.

For all curious :
-why elephantsql and postgresql with visual studio? - university project. Honestly i would like to use mssql but i cannot. Only progresql.

Edit : I tried to read many questions/tutorials/bug tracker stories/etc. Did not find my answer.
Edit2 : Sorry i forgot. ElephantSQL is an postgresql database hosted in cloud.

答:
Updating npgsql dll and adding EntityAdminDatabase=[DATABASE_NAME] in connection string Works for me.

Thank's

Body:
I want to use elephantsql database with entity framework (whichever version). I found tutorial on the internet about npgsql which can help me connect those 2 piece of technology.

I made an object which will represent object from DB :

[Table("typychorob", Schema = "public")]
public class TypChoroby
{
    public TypChoroby()
    {
    }

    [Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.Identity), Required]
    public int ID { get; set; }

    [Column("nazwa"), MaxLength(50)]
    public string Nazwa { get; set; }
}

I created class which will represent dBContext. Uzytkownik is nearly the same as TypChoroby.

public class PrzychodniaContext : DbContext
{
    public DbSet<Uzytkownik> Uzytkownicy { get; set; }
    public DbSet<TypChoroby> TypyChorob { get; set; }

    public PrzychodniaContext() : base()
    {
    }
}

I try to use those things in the following style :

using (var context = new PrzychodniaContext())
        {
            context.Database.Log = post;
            var chorobska = context.TypyChorob.ToList();
        }

This always creates error like this :

{"28000: no pg_hba.conf entry for host \"178.37.126.100\", user \"jnwnqqog\", database \"template1\", SSL off"}

It's elephantSql simplest plan so i cannot edit pg_hba.conf which is a file where i can give myself some privileges.

My ConnectionString :

<add name="PrzychodniaContext" connectionString="Server=YouDontWantToKnowButYouKnow;Database=jnwnqqog;User Id=jnwnqqog;Password=YouDontWantToKnow;MAXPOOLSIZE=5;" providerName="Npgsql" />

What i tried?

1) First i know what's going on. In documentation of npgsql in create database command i found :

template
The name of the template from which to create the new database, or DEFAULT to use the default template (template1).

Honetsly i do not know how to change that. I though that it would be good to change that to 'jnwnqqog', because it's my DB at elephantSQL. But i do not know.

2) I'd used
    Database.SetInitializer(null);
I assumed that it will stop trying to create new database. It did not stopped this behaviour.

3) I tried to enable/disable SSL.

4) I changed entity framework from 5.0 to 6.0 along with npgsql.

For all curious :
-why elephantsql and postgresql with visual studio? - university project. Honestly i would like to use mssql but i cannot. Only progresql.

Edit : I tried to read many questions/tutorials/bug tracker stories/etc. Did not find my answer.
Edit2 : Sorry i forgot. ElephantSQL is an postgresql database hosted in cloud.


问:
Nginx error while deploying RoR to AWS Beanstalk
I am trying to deploy a Ruby on Rails API to AWS Elastic Beanstalk without any luck. I could once deploy succesfully and I'd only got errors because production environment doesn't db:seed. But suddenly every time i wanted to deploy I would have the following errors on logs

```<code>-------------------------------------
/var/app/support/logs/passenger.log
-------------------------------------
[ 2016-12-16 13:22:39.2849 5408/7f442ea10780 agents/Watchdog/Main.cpp:728 ]: All Phusion Passenger agents started!
2016/12/16 13:22:40 [error] 5427#0: *3 "/var/app/current/public/index.html" is not found (2: No such file or directory), client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"
2016/12/16 13:22:40 [error] 5427#0: *3 testing "/var/app/current/public" existence failed (2: No such file or directory) while logging request, client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"

-------------------------------------
/var/log/eb-activity.log
-------------------------------------
  + service passenger restart
   --> Downloading a Phusion Passenger agent binary for your platform
  ---------------------------------------
  No precompiled Nginx engine could be downloaded. Compiling it from source instead.
  --------------------------------------------

  Your system does not have a lot of virtual memory

  Installing...
  Downloading Nginx 1.8.1 source code...
  Extracting tarball...
  Compiling support libraries (step 1 of 2)...
  Compiling Nginx engine (step 2 of 2)...

  ./configure: error: invalid option "--with-http_v2_module"
  *** ERROR: command failed: cd /tmp/passenger-install.158a2iu/nginx-1.8.1 && env PASSENGER_INCLUDEDIR=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.1.0/src PASSENGER_LIBS=/tmp/passenger-install.158a2iu/common/libpassenger_common/Logging.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Exceptions.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/SystemTime.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/StrIntUtils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/StrIntUtilsNoStrictAliasing.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/IOUtils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/WatchdogLauncher.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/AppTypes.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/CachedFileStat.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/UnionStationFilterSupport.o\ /tmp/passenger-install.158a2iu/common/libboost_oxt.a /bin/bash ./configure --prefix=/tmp --with-cc-opt=-Wno-error --without-http_fastcgi_module --without-http_scgi_module --without-http_uwsgi_module --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-http_addition_module --add-module=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.1.0/src/nginx_module
</code>```

I even git revert commits in order to go back to the version that deployed succesfully but got the same errors!

PD:
Another thing I had to do (before it worked the first time) was set the Root volume size of the EC2 instance to 16 GiB because i would get the error that nokogiri gem couldn't be installed by budler, and it actually fixed that

答:
The error you are seeing is almost probably because you have Passenger Gem listed in the Gemfile. Removing it or putting it into the development section if needed should solve the issue.
Passenger is pre-installed on the AWS ElasticBeanstalk Ruby Stack.

Body:
I am trying to deploy a Ruby on Rails API to AWS Elastic Beanstalk without any luck. I could once deploy succesfully and I'd only got errors because production environment doesn't db:seed. But suddenly every time i wanted to deploy I would have the following errors on logs

-------------------------------------
/var/app/support/logs/passenger.log
-------------------------------------
[ 2016-12-16 13:22:39.2849 5408/7f442ea10780 agents/Watchdog/Main.cpp:728 ]: All Phusion Passenger agents started!
2016/12/16 13:22:40 [error] 5427#0: *3 "/var/app/current/public/index.html" is not found (2: No such file or directory), client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"
2016/12/16 13:22:40 [error] 5427#0: *3 testing "/var/app/current/public" existence failed (2: No such file or directory) while logging request, client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"

-------------------------------------
/var/log/eb-activity.log
-------------------------------------
  + service passenger restart
   --> Downloading a Phusion Passenger agent binary for your platform
  ---------------------------------------
  No precompiled Nginx engine could be downloaded. Compiling it from source instead.
  --------------------------------------------

  Your system does not have a lot of virtual memory

  Installing...
  Downloading Nginx 1.8.1 source code...
  Extracting tarball...
  Compiling support libraries (step 1 of 2)...
  Compiling Nginx engine (step 2 of 2)...

  ./configure: error: invalid option "--with-http_v2_module"
  *** ERROR: command failed: cd /tmp/passenger-install.158a2iu/nginx-1.8.1 && env PASSENGER_INCLUDEDIR=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.1.0/src PASSENGER_LIBS=/tmp/passenger-install.158a2iu/common/libpassenger_common/Logging.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Exceptions.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/SystemTime.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/StrIntUtils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/StrIntUtilsNoStrictAliasing.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/IOUtils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/WatchdogLauncher.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/AppTypes.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/Utils/CachedFileStat.o\ /tmp/passenger-install.158a2iu/common/libpassenger_common/UnionStationFilterSupport.o\ /tmp/passenger-install.158a2iu/common/libboost_oxt.a /bin/bash ./configure --prefix=/tmp --with-cc-opt=-Wno-error --without-http_fastcgi_module --without-http_scgi_module --without-http_uwsgi_module --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-http_addition_module --add-module=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.1.0/src/nginx_module

I even git revert commits in order to go back to the version that deployed succesfully but got the same errors!

PD:
Another thing I had to do (before it worked the first time) was set the Root volume size of the EC2 instance to 16 GiB because i would get the error that nokogiri gem couldn't be installed by budler, and it actually fixed that


问:
pandas / numpy np.where(df['x'].str.contains('y')) vs np.where('y' in df['x'])
As a newb to python and pandas, I tried:

```<code>df_rows = np.where('y' in df['x'])[0]
for i in df_rows:
    print df_rows.iloc[i]
</code>```

returned no rows, but

```<code>df_rows = np.where(df['x'].str.contains('y'))[0]
for i in df_rows:
    print df_rows.iloc[i]
</code>```

did work and returned rows containing 'y' in df['x'].

What am I missing? Why did the first form fail? (Python 2.7)

答:
These are different operations:

The in check searches if any element is equal to 'y'. (note: For Series of strings that may not even work correctly).

The .str.contains method searches the string-representation of each element if it contains 'y'.

The first one can only return True or False (that's because Pythons data model says so and enforces it). The second one is a normal method and returns a Series containing True or False (because normal methods can do what they like).

```<code>>>> import pandas as pd
>>> s = pd.Series(['abc', 'def', 'ghi'])
>>> s.str.contains('a')
0     True
1    False
2    False
dtype: bool
>>> s.eq('a')  # looking for an identical match
0    False
1    False
2    False
dtype: bool
</code>```

Body:
As a newb to python and pandas, I tried:

df_rows = np.where('y' in df['x'])[0]
for i in df_rows:
    print df_rows.iloc[i]

returned no rows, but

df_rows = np.where(df['x'].str.contains('y'))[0]
for i in df_rows:
    print df_rows.iloc[i]

did work and returned rows containing 'y' in df['x'].

What am I missing? Why did the first form fail? (Python 2.7)

Body:
These are different operations:

The in check searches if any element is equal to 'y'. (note: For Series of strings that may not even work correctly).

The .str.contains method searches the string-representation of each element if it contains 'y'.

The first one can only return True or False (that's because Pythons data model says so and enforces it). The second one is a normal method and returns a Series containing True or False (because normal methods can do what they like).

>>> import pandas as pd
>>> s = pd.Series(['abc', 'def', 'ghi'])
>>> s.str.contains('a')
0     True
1    False
2    False
dtype: bool
>>> s.eq('a')  # looking for an identical match
0    False
1    False
2    False
dtype: bool


问:
Uploaded images to Firebase are all black. How to get rid of it?
The user selects the image from the camera or gallery, so now the image is in an Imageview to show the user the picture. Now the user uploads it to the server, but every picture I upload is black. Why is this happening?
This is the code:

```<code>mUpload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lalala-14247.appspot.com");

        mImageview.setDrawingCacheEnabled(true);
        mImageview.buildDrawingCache();
        Bitmap bitmap = mImageview .getDrawingCache();

        ByteArrayOutputStream baas = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);

        byte[] data = baas.toByteArray();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        UploadTask uploadTask = storageRef.child("Photo").child(timeStamp).putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();

            }
        });

    }

});
</code>```

My dependencies:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
testCompile 'junit:junit:4.12'
</code>```

答:
Try this,

```<code>Uri file = Uri.fromFile(new File("your_image_path"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});
</code>```

For more info please check https://firebase.google.com/docs/storage/android/upload-files

Body:
The user selects the image from the camera or gallery, so now the image is in an Imageview to show the user the picture. Now the user uploads it to the server, but every picture I upload is black. Why is this happening?
This is the code:

mUpload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lalala-14247.appspot.com");

        mImageview.setDrawingCacheEnabled(true);
        mImageview.buildDrawingCache();
        Bitmap bitmap = mImageview .getDrawingCache();

        ByteArrayOutputStream baas = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);

        byte[] data = baas.toByteArray();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        UploadTask uploadTask = storageRef.child("Photo").child(timeStamp).putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();

            }
        });

    }

});

My dependencies:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
testCompile 'junit:junit:4.12'

Body:
Try this,

Uri file = Uri.fromFile(new File("your_image_path"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

For more info please check https://firebase.google.com/docs/storage/android/upload-files


问:
PHP Undefined index data when I try to POST from Ajax
I am trying to update a mysql database using an Ajax POST request to a php file, but I receive the following error:

```<code>Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}
</code>```

Here is my Ajax code:

```<code>$('#addbut').click(function()
    {
        console.log($("#firstteam").val());
        console.log($("#score1").val());
        console.log($("#score2").val());
        console.log($("#secondteam").val());

        var data = {
        firstteam:$("#firstteam").val(),
        secondteam:$("#secondteam").val(),
        score1:$("#score1").val(),
        score2:$("#score2").val()}

        $("#firstteam").val('');
        $("#secondteam").val('');
        $("#score1").val('');
        $("#score2").val('');

        $.ajax({
            type: "POST",
            url: "php/post.php",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType:'json',

            //if received a response from the server
            success: function(response)
            {
                 var res = response.d;
                 if (res == true)
                 {
                     $("#error").html("<div><b>Success!</b></div>"+response);
                     updateTable();
                 }
                 //display error message
                 else {
                     $("#error").html("<div><b>Information is Invalid!</b></div>"+response);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown)
            {
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            }
        });

    });
</code>```

Here us my PHP code:

```<code><?php
    $data = $_POST['data'] or $_REQUEST['data'];
    $js = json_decode($data,true);
    $t1 = $js['firstteam'];
    $t2 = $js['secondteam'];
    $s1 = $js['score1'];
    $s2 = $js['score2'];

    updateFunction($t1,$s1,$s2);
    updateFunction($t2,$s2,$s1);

    function updateFunction($name, $s1, $s2)
    {
        $conn = new mysqli("localhost:3306","root","","leagues");
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        if ($s1 > $s2)
            $sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
        else
            if ($s1 == $s2)
                $sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
            else
                if ($s1 < $s2)
                    $sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";

        if ($conn->query($sql) === TRUE)
        {
            $response = json_encode(array('d' => true));
            echo $response;
        }
        $conn->close();
    }
?>
</code>```

I tried some suggestions, but I don't know why my PHP code doesn't parse the data correctly. The Console.log from my Ajax function prints exactly what I want.

Here is what my debugger shows:

答:
It doesn't work, because by putting

```<code>$.ajax({
    ...
    data: '{"key":"value"}',
    ...});
</code>```

you just put that string ({"key":"value"}) in raw form into request body.
Therefore there is no form parameter named data.

To retrieve this raw data from body use:

```<code>$data = file_get_contents('php://input');

OR

$data = stream_get_contents(STDIN);
</code>```

instead of

```<code>$data = $_POST['data'] or $_REQUEST['data'];
</code>```

Body:
I am trying to update a mysql database using an Ajax POST request to a php file, but I receive the following error:

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}

Here is my Ajax code:

$('#addbut').click(function()
    {
        console.log($("#firstteam").val());
        console.log($("#score1").val());
        console.log($("#score2").val());
        console.log($("#secondteam").val());

        var data = {
        firstteam:$("#firstteam").val(),
        secondteam:$("#secondteam").val(),
        score1:$("#score1").val(),
        score2:$("#score2").val()}

        $("#firstteam").val('');
        $("#secondteam").val('');
        $("#score1").val('');
        $("#score2").val('');

        $.ajax({
            type: "POST",
            url: "php/post.php",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType:'json',

            //if received a response from the server
            success: function(response)
            {
                 var res = response.d;
                 if (res == true)
                 {
                     $("#error").html("
Success!
"+response);
                     updateTable();
                 }
                 //display error message
                 else {
                     $("#error").html("
Information is Invalid!
"+response);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown)
            {
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            }
        });

    });

Here us my PHP code:

<?php
    $data = $_POST['data'] or $_REQUEST['data'];
    $js = json_decode($data,true);
    $t1 = $js['firstteam'];
    $t2 = $js['secondteam'];
    $s1 = $js['score1'];
    $s2 = $js['score2'];

    updateFunction($t1,$s1,$s2);
    updateFunction($t2,$s2,$s1);

    function updateFunction($name, $s1, $s2)
    {
        $conn = new mysqli("localhost:3306","root","","leagues");
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        if ($s1 > $s2)
            $sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
        else
            if ($s1 == $s2)
                $sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
            else
                if ($s1 < $s2)
                    $sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";

        if ($conn->query($sql) === TRUE)
        {
            $response = json_encode(array('d' => true));
            echo $response;
        }
        $conn->close();
    }
?>

I tried some suggestions, but I don't know why my PHP code doesn't parse the data correctly. The Console.log from my Ajax function prints exactly what I want.

Here is what my debugger shows:

Body:
It doesn't work, because by putting

$.ajax({
    ...
    data: '{"key":"value"}',
    ...});

you just put that string ({"key":"value"}) in raw form into request body.
Therefore there is no form parameter named data.

To retrieve this raw data from body use:

$data = file_get_contents('php://input');

OR

$data = stream_get_contents(STDIN);

instead of

$data = $_POST['data'] or $_REQUEST['data'];


问:
Unable to get the proper result for the inorder traversal in binary tree, Java Datastructure
I have wrote the code for the preorder and inorder traversal in binary tree data structure, but the outcome of the preorder traversal is correct but i am getting some error in inorder traversal, can anyone show me the fault in my code.
Thanks in advance.</p>

```<code>public class treepractice {
static Node root = null;

static class Node{
    int data;
    Node left, right;
    Node(int d){
        data = d;
        left=right = null;
    }
}

public static void main(String[] agrs){
    treepractice tree = new treepractice();
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
//  root.right.left = new Node(6);

    tree.printInorder(root);
    System.out.println();
    tree.printPreorder(root);
    System.out.println();

}

private static void printPreorder(Node root) {
    if(root == null)
        return;
        System.out.print(root.data + " ");
        printPreorder(root.left);
        printPreorder(root.right);
}

private static void printInorder(Node root) {
    if(root == null)
        return;
        printPreorder(root.left);
        System.out.print(root.data + " ");
        printPreorder(root.right);
}
}
</code>```

答:
You are calling printPreorder method from printInorder, You have to call printInorder

```<code>private static void printInorder(Node root) {
    if (root == null)
        return;
    printInorder(root.left);
    System.out.print(root.data + " ");
    printInorder(root.right);
}
</code>```

Body:
I have wrote the code for the preorder and inorder traversal in binary tree data structure, but the outcome of the preorder traversal is correct but i am getting some error in inorder traversal, can anyone show me the fault in my code.
Thanks in advance.

public class treepractice {
static Node root = null;

static class Node{
    int data;
    Node left, right;
    Node(int d){
        data = d;
        left=right = null;
    }
}

public static void main(String[] agrs){
    treepractice tree = new treepractice();
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
//  root.right.left = new Node(6);

    tree.printInorder(root);
    System.out.println();
    tree.printPreorder(root);
    System.out.println();

}

private static void printPreorder(Node root) {
    if(root == null)
        return;
        System.out.print(root.data + " ");
        printPreorder(root.left);
        printPreorder(root.right);
}

private static void printInorder(Node root) {
    if(root == null)
        return;
        printPreorder(root.left);
        System.out.print(root.data + " ");
        printPreorder(root.right);
}
}

Body:
You are calling printPreorder method from printInorder, You have to call printInorder

private static void printInorder(Node root) {
    if (root == null)
        return;
    printInorder(root.left);
    System.out.print(root.data + " ");
    printInorder(root.right);
}


问:
Pass data from Rails views to VueJS components in webpacker
I'm trying to fiddle with Rails 5.1's new webpacker gem, along with VueJS, but can't get my erb views to pass data to VueJS components...

Let's say I have a user show view

# view/users/show.html.erb
<%= javascript_pack_tag "user-card" %>
<%= content_tag :div,
  id: "user-card",
  data: {
    username: @user.name
  } do %>
<% end %>
```

<p>And my javascript:</p>

<pre class="lang-javascript prettyprint-override"><code>// app/javascript/packs/user-card.js
require("user-card")

// app/javascript/user-card/index.js
import Vue from 'vue/dist/vue.esm'
import UserCard from './components/UserCard'

document.addEventListener('DOMContentLoaded', () => {
  let element = document.getElementById("user-card")
  let username = element.dataset.username
  console.log(username); // => "pecpec"

  const app = new Vue({
    el: element,
    template: '<UserCard/>',
    components: { UserCard },
    data () {
      return { username }
    }
  })

// app/javascript/user-card/components/UserCard.vue
<template>
  <div>
    <h3>Hello {{ username }}</h3>
  </div>
</template>

<script>
export default {
  props: ['username'],
  data () {
    return {
      username: ""
    }
  }
}
</script>
</code>```

I've been spending a few hours over this, by now, but none of my attempts have proven successful. I've tried passing the data to the component as a prop:
props: ['username'], mounting the component with

Vue.component(UserCard, {
  props: ['username']
  // or
  data () {
    return { username: username }
  }
})
```

... but that didn't work either

Update:
I was missing props: ['username'] in the component and updated the code above accordingly, though that doesn't seem to have made a different. Still no luck!

答:
It works! Here's my solution... Not sure if it's the canonical way to do it, but it works nonetheless. It seems so painfully obvious now... Hope this will help others. Here's the whole updated code:

# view/users/show.html.erb
<%= javascript_pack_tag "user-card" %>
<%= content_tag :div,
  nil,
  id: "user-card",
  data: { username: @user.name }
 %>
```

<pre class="lang-javascript prettyprint-override"><code>// app/javascript/packs/user-card.js
require("user-card")

// app/javascript/user-card/index.js
import Vue from 'vue/dist/vue.esm'
import UserCard from './components/UserCard'

document.addEventListener('DOMContentLoaded', () => {
  let element = document.getElementById("user-card")
  let username = element.dataset.username

  const app = new Vue({
    el: element,
    data: { username: username },
    template: '<UserCard :username="username"/>',
    components: { UserCard }
  })
})

// app/javascript/user-card/components/UserCard.vue
<template>
  <div>
    <h3>Hello {{ username }}</h3>
  </div>
</template>

<script>
export default {
  props: ['username']
}
</script>
</code>```

Body:
I'm trying to fiddle with Rails 5.1's new webpacker gem, along with VueJS, but can't get my erb views to pass data to VueJS components...

Let's say I have a user show view

# view/users/show.html.erb
<%= javascript_pack_tag "user-card" %>
<%= content_tag :div,
  id: "user-card",
  data: {
    username: @user.name
  } do %>
<% end %>

And my javascript:

// app/javascript/packs/user-card.js
require("user-card")

// app/javascript/user-card/index.js
import Vue from 'vue/dist/vue.esm'
import UserCard from './components/UserCard'

document.addEventListener('DOMContentLoaded', () => {
  let element = document.getElementById("user-card")
  let username = element.dataset.username
  console.log(username); // => "pecpec"

  const app = new Vue({
    el: element,
    template: '<UserCard/>',
    components: { UserCard },
    data () {
      return { username }
    }
  })

// app/javascript/user-card/components/UserCard.vue
<template>

Hello {{ username }}

</template>

I've been spending a few hours over this, by now, but none of my attempts have proven successful. I've tried passing the data to the component as a prop:
props: ['username'], mounting the component with

Vue.component(UserCard, {
  props: ['username']
  // or
  data () {
    return { username: username }
  }
})

... but that didn't work either

Update:
I was missing props: ['username'] in the component and updated the code above accordingly, though that doesn't seem to have made a different. Still no luck!

Body:
It works! Here's my solution... Not sure if it's the canonical way to do it, but it works nonetheless. It seems so painfully obvious now... Hope this will help others. Here's the whole updated code:

# view/users/show.html.erb
<%= javascript_pack_tag "user-card" %>
<%= content_tag :div,
  nil,
  id: "user-card",
  data: { username: @user.name }
 %>

// app/javascript/packs/user-card.js
require("user-card")

// app/javascript/user-card/index.js
import Vue from 'vue/dist/vue.esm'
import UserCard from './components/UserCard'

document.addEventListener('DOMContentLoaded', () => {
  let element = document.getElementById("user-card")
  let username = element.dataset.username

  const app = new Vue({
    el: element,
    data: { username: username },
    template: '<UserCard :username="username"/>',
    components: { UserCard }
  })
})

// app/javascript/user-card/components/UserCard.vue
<template>
  <div>
    <h3>Hello {{ username }}</h3>
  </div>
</template>

<script>
export default {
  props: ['username']
}
</script>


问:
How do I copy a list and then replace the characters?
I am looking to copy a list that I have in python and then replace the characters.

For example:

If the code asks you to input a word: (and you type) 'hello'

'hello' will get added to a list.

what I want to do is copy that list and then replace 'hello' with '*****'
and i want the '*' to be the same index as the 'hello' index.

Thanks!

ps. I think my actual code is irrelevant, I just need a basic understanding.

edit:

```<code>import getpass

hangman_pics = ['''
    +---+
        |
        |
        |
       ===''','''
    +---+
    O   |
        |
        |
       ===''','''
    +---+
    O   |
    |   |
        |
       ===''','''
    +---+
    O   |
   /|   |
        |
       ===''','''
    +---+
    O   |
   /|\  |
        |
       ===''','''
    +---+
    O   |
   /|\  |
   /    |
       ===''','''
    +---+
    O   |
   /|\  |
   / \  |
       ===''']

let_list = []
alreadyGuessed = []
correctGuessed = []
falseGuessed = []
lettersLeft = []

def player_input():
    word_input = getpass.getpass("Choose the word: ")
    for letter in word_input:
        let_list.append(letter)

def player_guess():
    while let_list:
        print ("Please enter your guess: ")
        guess = input()
        if guess in let_list:
            if guess in alreadyGuessed:
                print ('Oops, you already guessed ' + guess)
            else:
                alreadyGuessed.append(guess)
                correctGuessed.append(guess)
                print (guess + ' is correct!')
        elif guess in alreadyGuessed:
            print ('Oops, you already guessed ' + guess)
        else:
            alreadyGuessed.append(guess)
            falseGuessed.append(guess)
            print (guess + ' is wrong, sorry')
        while set(let_list) == set(correctGuessed):
            print ('Congratulations! You win!')
            return False
            break
        while len(falseGuessed) == len(hangman_pics):
            print ('Oh no, you killed him! You lose :(')
            return False
            break

player_input()
player_guess()
</code>```

答:
```<code>list2 = []
for word in list1:
    if word == "hello":
        list2.append("*****")
    else:
        list2.append(word)
</code>```

Body:
I am looking to copy a list that I have in python and then replace the characters.

For example:

If the code asks you to input a word: (and you type) 'hello'

'hello' will get added to a list.

what I want to do is copy that list and then replace 'hello' with '*****'
and i want the '*' to be the same index as the 'hello' index.

Thanks!

ps. I think my actual code is irrelevant, I just need a basic understanding.

edit:

import getpass

hangman_pics = ['''
    +---+
        |
        |
        |
       ===''','''
    +---+
    O   |
        |
        |
       ===''','''
    +---+
    O   |
    |   |
        |
       ===''','''
    +---+
    O   |
   /|   |
        |
       ===''','''
    +---+
    O   |
   /|\  |
        |
       ===''','''
    +---+
    O   |
   /|\  |
   /    |
       ===''','''
    +---+
    O   |
   /|\  |
   / \  |
       ===''']

let_list = []
alreadyGuessed = []
correctGuessed = []
falseGuessed = []
lettersLeft = []

def player_input():
    word_input = getpass.getpass("Choose the word: ")
    for letter in word_input:
        let_list.append(letter)

def player_guess():
    while let_list:
        print ("Please enter your guess: ")
        guess = input()
        if guess in let_list:
            if guess in alreadyGuessed:
                print ('Oops, you already guessed ' + guess)
            else:
                alreadyGuessed.append(guess)
                correctGuessed.append(guess)
                print (guess + ' is correct!')
        elif guess in alreadyGuessed:
            print ('Oops, you already guessed ' + guess)
        else:
            alreadyGuessed.append(guess)
            falseGuessed.append(guess)
            print (guess + ' is wrong, sorry')
        while set(let_list) == set(correctGuessed):
            print ('Congratulations! You win!')
            return False
            break
        while len(falseGuessed) == len(hangman_pics):
            print ('Oh no, you killed him! You lose :(')
            return False
            break

player_input()
player_guess()


问:
Getting list of running containers from a cluster
I am running docker containers on an AWS via ECS. I have setup a cluster with some basic configuration.

Now I am looking forward to get no. of all running containers on this cluster (spread across 2-3 EC2 instances)? Does AWS / Docker provide any API for this?

I know on a container instance, doing docker ps -a will return me list of all running / stopped containers, while docker ps will return running containers on one system. But I want an API (which can be called from outside) or command (which I can run on any of the instance part of the cluster) and it shows me total number of running containers across cluster?

答:
I am not sure of getting the containers information in AWS environment. But Docker has a very good support for API in the single server or in running the cluster, especially cluster with Docker Swarm.

For using docker API you need to configure the docker daemon port on the manager node in the cluster(if the cluster is running in docker swarm) or configure all the nodes individually and can access the APIs.

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

```<code>DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"
</code>```

2) Configuring at /etc/docker/daemon.json:

```<code>{
"hosts": ["tcp://127.0.0.1:6000", "unix:///var/run/docker.sock"]
}
</code>```

Restart the docker service once the port is configured.

If the docker default socket(unix:///var/run/docker.sock) is not configured, Docker may not have configured properly and will wait for infinite period.

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

```<code>Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)
</code>```

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

```<code>#docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once you have enabled the Docker daemon port you can access the services running the cluster with Docker API:

curl -X GET http://127.0.0.1:6000/services?id=all

Or API for individual servers with:

curl -X GET http://127.0.0.1:6000/containers/json?all

For more docker APIs refer here

NOTE: Tested for Docker Version 17.04 and Docker Swarm.

To check the information through CLI in the cluster:

Cluster information:

```<code>#docker node ls
ID                           HOSTNAME                STATUS  AVAILABILITY  MANAGER STATUS
7pl9bab4g2yjwctjxq2aax3ud    radisysuser-VirtualBox  Ready   Active
o45wire6qhu8i5eujl6iyon2p *  labadmin-VirtualBox     Ready   Active        Leader
odwdr5uey085hpb8tnwtj11e0    radisysuser-VirtualBox  Ready   Active
</code>```

Services/containers info:

```<code># docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE
sccuf1jgkphn        redis               replicated          3/3                 redis:latest
</code>```

Individual services info:

```<code># docker service ps redis
ID                  NAME                IMAGE               NODE                     DESIRED STATE       CURRENT STATE                     ERROR               PORTS
jgix9p141pxt        redis.1             redis:latest        radisysuser-VirtualBox   Running             Running less than a second ago
1i4yc8f9cqm5        redis.2             redis:latest        radisysuser-VirtualBox   Running             Running less than a second ago
dk1tubki2dg8         \_ redis.2         redis:latest        radisysuser-VirtualBox   Shutdown            Shutdown less than a second ago
stpl55l6wwci        redis.3             redis:latest        labadmin-VirtualBox      Running             Running 4 hours ago
</code>```

Hope this will helpful.

Body:
I am not sure of getting the containers information in AWS environment. But Docker has a very good support for API in the single server or in running the cluster, especially cluster with Docker Swarm.

For using docker API you need to configure the docker daemon port on the manager node in the cluster(if the cluster is running in docker swarm) or configure all the nodes individually and can access the APIs.

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"

2) Configuring at /etc/docker/daemon.json:

{
"hosts": ["tcp://127.0.0.1:6000", "unix:///var/run/docker.sock"]
}

Restart the docker service once the port is configured.

If the docker default socket(unix:///var/run/docker.sock) is not configured, Docker may not have configured properly and will wait for infinite period.

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

#docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once you have enabled the Docker daemon port you can access the services running the cluster with Docker API:

curl -X GET http://127.0.0.1:6000/services?id=all

Or API for individual servers with:

curl -X GET http://127.0.0.1:6000/containers/json?all

For more docker APIs refer here

NOTE: Tested for Docker Version 17.04 and Docker Swarm.

To check the information through CLI in the cluster:

Cluster information:

#docker node ls
ID                           HOSTNAME                STATUS  AVAILABILITY  MANAGER STATUS
7pl9bab4g2yjwctjxq2aax3ud    radisysuser-VirtualBox  Ready   Active
o45wire6qhu8i5eujl6iyon2p *  labadmin-VirtualBox     Ready   Active        Leader
odwdr5uey085hpb8tnwtj11e0    radisysuser-VirtualBox  Ready   Active

Services/containers info:

# docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE
sccuf1jgkphn        redis               replicated          3/3                 redis:latest

Individual services info:

# docker service ps redis
ID                  NAME                IMAGE               NODE                     DESIRED STATE       CURRENT STATE                     ERROR               PORTS
jgix9p141pxt        redis.1             redis:latest        radisysuser-VirtualBox   Running             Running less than a second ago
1i4yc8f9cqm5        redis.2             redis:latest        radisysuser-VirtualBox   Running             Running less than a second ago
dk1tubki2dg8         \_ redis.2         redis:latest        radisysuser-VirtualBox   Shutdown            Shutdown less than a second ago
stpl55l6wwci        redis.3             redis:latest        labadmin-VirtualBox      Running             Running 4 hours ago

Hope this will helpful.


答:
Use map function in python; for example,

```<code>test = ['h', 'l', 'l', 'o']
def your_logic(element):
    if condition:
        return "*"
    return element

# every element in the list will be converted using your condition
result_list = map(your_logic, test)
</code>```

Title: How do I copy a list and then replace the characters?

Body:
Use map function in python; for example,

test = ['h', 'l', 'l', 'o']
def your_logic(element):
    if condition:
        return "*"
    return element

# every element in the list will be converted using your condition
result_list = map(your_logic, test)


问:
Node.js app can't access any env variables when pm2 is started from a script but can when launched from ssh
I am trying to launch a node.js app on a production EC2 server with pm2 process manager.

When I ssh into the instance and run pm2 start app.js, PM2 starts just fine and has access to all environment variables. Everything good.

However, I want to run pm2 start app.js from a Codedeploy hook script called applicationstart.sh, the app fails with an errored status becasue it is missing all environment variables.

Here is where the script is added so it is launched with each deployment and calls pm2 start: appspec.yml

```<code>version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/teller-install
hooks:
  AfterInstall:
    - location: scripts/afterinstall.sh
      timeout: 1000
      runas: root
  ApplicationStart:
    - location: scripts/applicationstart.sh
      timeout: 300
      runas: ubuntu
</code>```

Here is the applicationstart script:

```<code>#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
pm2 start app.js
exit 0
</code>```

I am logged in as ubuntu when I run the script from ssh and I set the script in the appconfig.yml to run as ubuntu as well.

Why would there be any difference between starting pm2 from terminal and starting it from a launch hook script?

Here is running directly from ssh:

I can provide any information necessary in dire need of solution. Thanks!

答:
I had to add source /etc/profile before I call pm2 start app.js to load in environment variables.

The script now looks like

```<code>#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
source /etc/profile
pm2 start app.js
exit 0
</code>```

Body:
I am trying to launch a node.js app on a production EC2 server with pm2 process manager.

When I ssh into the instance and run pm2 start app.js, PM2 starts just fine and has access to all environment variables. Everything good.

However, I want to run pm2 start app.js from a Codedeploy hook script called applicationstart.sh, the app fails with an errored status becasue it is missing all environment variables.

Here is where the script is added so it is launched with each deployment and calls pm2 start: appspec.yml

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/teller-install
hooks:
  AfterInstall:
    - location: scripts/afterinstall.sh
      timeout: 1000
      runas: root
  ApplicationStart:
    - location: scripts/applicationstart.sh
      timeout: 300
      runas: ubuntu

Here is the applicationstart script:

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
pm2 start app.js
exit 0

I am logged in as ubuntu when I run the script from ssh and I set the script in the appconfig.yml to run as ubuntu as well.

Why would there be any difference between starting pm2 from terminal and starting it from a launch hook script?

Here is running directly from ssh:

I can provide any information necessary in dire need of solution. Thanks!

Body:
I had to add source /etc/profile before I call pm2 start app.js to load in environment variables.

The script now looks like

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
source /etc/profile
pm2 start app.js
exit 0


问:
Multiple columns processing and dynamically naming new columns
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

```<code>aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)
</code>```

This is what I want:

```<code>aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)
</code>```

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

答:
This is a base solution, i.e. no packages.

First define get_only which when given a list converts it to a data.frame and applies get_only to each row.  When given a vector it returns the single non-NA in it or NA if there is not only one.

Define root to be the column names without the suffixes.

Convert the data frame to a list of columns, group them by root and apply get_only to each such group.

Finally, convert the resulting list to a data frame.

```<code>get_only <- function(x) UseMethod("get_only")
get_only.list <- function(x) apply(data.frame(x), 1, get_only)
get_only.default <- function(x) if (sum(!is.na(x)) == 1) na.omit(x) else NA

root <- sub("_.*", "", names(dataf1))
as.data.frame(lapply(split(as.list(dataf1), root), FUN = get_only))
</code>```

giving:

```<code>  age country hight
1  43     fra   183
2  23     ija    NA
3  NA     spa   198
4  NA    <NA>    NA
5  NA    <NA>   182
</code>```

Body:
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)

This is what I want:

aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

Body:
This is a base solution, i.e. no packages.

First define get_only which when given a list converts it to a data.frame and applies get_only to each row.  When given a vector it returns the single non-NA in it or NA if there is not only one.

Define root to be the column names without the suffixes.

Convert the data frame to a list of columns, group them by root and apply get_only to each such group.

Finally, convert the resulting list to a data frame.

get_only <- function(x) UseMethod("get_only")
get_only.list <- function(x) apply(data.frame(x), 1, get_only)
get_only.default <- function(x) if (sum(!is.na(x)) == 1) na.omit(x) else NA

root <- sub("_.*", "", names(dataf1))
as.data.frame(lapply(split(as.list(dataf1), root), FUN = get_only))

giving:

  age country hight
1  43     fra   183
2  23     ija    NA
3  NA     spa   198
4  NA    <NA>    NA
5  NA    <NA>   182


问:
Shopping Cart Dictionary and Session Variable - Moving from Code-Behind to Class
I am building a shopping cart using ASP.NET (C#). I have the cart working in the code behind, but I have to implement it across several product pages, so I would like to move it to a class for maintainability, but I'm having trouble.

I am using a Dictionary to store the product ID and quantity desired, then I store that Dictionary into a Session variable to store the cart between postbacks and navigating the site. The Dictionary is a global variable in multiple pages' code-behind.

```<code>public partial class products : System.Web.UI.Page
{
    Dictionary<int, int> CartList;
</code>```

On Page_Load, I am checking if the Session variable has a value:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CartList"] == null)
    {
        CartList = new Dictionary<int, int>();
        Session["CartList"] = CartList;
    }
}
</code>```

When an Add to Cart button is clicked I have the following event handler. The button passes the product ID to the event handler in an attribute that was assigned to it when it was dynamically created. Then we loop through the dictionary to see if that product is already in the cart, and if so, we update the quantity by 1, then store the updated dictonary into the session variable:

```<code>protected void btnAddProduct_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int pId = Convert.ToInt32(btn.Attributes["data-id"]);

    CartList = (Dictionary<int, int>)Session["CartList"];

    int count = 1;

    if (pId  > 0)
    {
        if (CartList.Count > 0)
        {
            foreach (KeyValuePair<int, int> item in CartList)
            {
                if (item.Key == pId)
                {
                    count = item.Value + 1;
                }
            }
        }

        if (count > 1)
        {
            CartList[pId] = count;
        }
        else
        {
            CartList.Add(pId, count);
        }
    }

    Session["CartList"] = CartList;
}
</code>```

On the Cart Display page, I have a global CartList Dictonary again:

```<code>public partial class cart : System.Web.UI.Page
{

   Dictionary<int, int> CartList;
</code>```

On Page_PreInit, I am checking if my session variable has a value, and if so, we display the cart:

```<code>protected void Page_PreInit(object sender, EventArgs e)
{

    if (Session["CartList"] != null)
    {
        CartList = (Dictionary<int, int>)Session["CartList"];
        DisplayCartList();

    }
    else
    {
        lbl = new Label();
        lbl.Text = "<h1>There are no items in your cart.</h1>";
        Master.FindControl("ContentPlaceHolder1").Controls.Add(lbl);
    }
 }
</code>```

I've read that a session variable might not be the best approach for this, so any ideas in that regard are appreciated. I understand that using Cache may be better, but I'm not very familiar with it yet. Either way, I would like to have the Dictionary and Session or Cache variable inside a class that is accessible across the website.

I have read about using a Session Wrapper class such as this example: How to access session variables from any class in ASP.NET? to hold the session, but I can't seem to get my head wrapped around that idea.

答:
I kinda figured it out. Not exactly what I was looking for, but I was able to move the Add to Cart function to a class by passing the Dictionary to a static class. </p>

```<code> public static class Cart
 {
    public static string AddCartItem(this Dictionary<int, string[]> CartList, int pId)
    {
        products p = new products();

        ProductOptions po = new ProductOptions();

        if (pId > 0)
        {
            p.GetDataById(pId);
            po.GetDataByProductId(pId);
        }

        CartList = (Dictionary<int, string[]>)HttpContext.Current.Session["CartList"];

        int count = 1;

        if (p.ID > 0)
        {
            if (CartList.Count > 0)
            {
                foreach (KeyValuePair<int, string[]> item in CartList)
                {
                    if (item.Key == p.ID)
                    {
                        count = Convert.ToInt32(item.Value[0]) + 1;
                    }
                }
            }

            if (count > 1)
            {
                CartList[p.ID][0] = count.ToString();
            }
            else
            {
                string[] value = new string[] { count.ToString(), po.Options };
                CartList.Add(p.ID, value);
            }
        }

        HttpContext.Current.Session["CartList"] = CartList;

        return p.Name;
    }

}
</code>```

<p>Note: I also changed the Dictionary from 'int, int' to 'int, string[]' so that I could send product options such as size, color, flavor, etc. to the shopping cart along with the quantity ordered - all paired with the product Id. </p>

Body:
I am building a shopping cart using ASP.NET (C#). I have the cart working in the code behind, but I have to implement it across several product pages, so I would like to move it to a class for maintainability, but I'm having trouble.

I am using a Dictionary to store the product ID and quantity desired, then I store that Dictionary into a Session variable to store the cart between postbacks and navigating the site. The Dictionary is a global variable in multiple pages' code-behind.

public partial class products : System.Web.UI.Page
{
    Dictionary<int, int> CartList;

On Page_Load, I am checking if the Session variable has a value:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CartList"] == null)
    {
        CartList = new Dictionary<int, int>();
        Session["CartList"] = CartList;
    }
}

When an Add to Cart button is clicked I have the following event handler. The button passes the product ID to the event handler in an attribute that was assigned to it when it was dynamically created. Then we loop through the dictionary to see if that product is already in the cart, and if so, we update the quantity by 1, then store the updated dictonary into the session variable:

protected void btnAddProduct_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int pId = Convert.ToInt32(btn.Attributes["data-id"]);

    CartList = (Dictionary<int, int>)Session["CartList"];

    int count = 1;

    if (pId  > 0)
    {
        if (CartList.Count > 0)
        {
            foreach (KeyValuePair<int, int> item in CartList)
            {
                if (item.Key == pId)
                {
                    count = item.Value + 1;
                }
            }
        }

        if (count > 1)
        {
            CartList[pId] = count;
        }
        else
        {
            CartList.Add(pId, count);
        }
    }

    Session["CartList"] = CartList;
}

On the Cart Display page, I have a global CartList Dictonary again:

public partial class cart : System.Web.UI.Page
{

   Dictionary<int, int> CartList;

On Page_PreInit, I am checking if my session variable has a value, and if so, we display the cart:

protected void Page_PreInit(object sender, EventArgs e)
{

    if (Session["CartList"] != null)
    {
        CartList = (Dictionary<int, int>)Session["CartList"];
        DisplayCartList();

    }
    else
    {
        lbl = new Label();
        lbl.Text = "
There are no items in your cart.
";
        Master.FindControl("ContentPlaceHolder1").Controls.Add(lbl);
    }
 }

I've read that a session variable might not be the best approach for this, so any ideas in that regard are appreciated. I understand that using Cache may be better, but I'm not very familiar with it yet. Either way, I would like to have the Dictionary and Session or Cache variable inside a class that is accessible across the website.

I have read about using a Session Wrapper class such as this example: How to access session variables from any class in ASP.NET? to hold the session, but I can't seem to get my head wrapped around that idea.

Body:
I kinda figured it out. Not exactly what I was looking for, but I was able to move the Add to Cart function to a class by passing the Dictionary to a static class.

 public static class Cart
 {
    public static string AddCartItem(this Dictionary<int, string[]> CartList, int pId)
    {
        products p = new products();

        ProductOptions po = new ProductOptions();

        if (pId > 0)
        {
            p.GetDataById(pId);
            po.GetDataByProductId(pId);
        }

        CartList = (Dictionary<int, string[]>)HttpContext.Current.Session["CartList"];

        int count = 1;

        if (p.ID > 0)
        {
            if (CartList.Count > 0)
            {
                foreach (KeyValuePair<int, string[]> item in CartList)
                {
                    if (item.Key == p.ID)
                    {
                        count = Convert.ToInt32(item.Value[0]) + 1;
                    }
                }
            }

            if (count > 1)
            {
                CartList[p.ID][0] = count.ToString();
            }
            else
            {
                string[] value = new string[] { count.ToString(), po.Options };
                CartList.Add(p.ID, value);
            }
        }

        HttpContext.Current.Session["CartList"] = CartList;

        return p.Name;
    }

}

Note: I also changed the Dictionary from 'int, int' to 'int, string[]' so that I could send product options such as size, color, flavor, etc. to the shopping cart along with the quantity ordered - all paired with the product Id.


答:
.wrapper{
  padding-left:20px;
  border:thin black solid;
  text-align:justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
 This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
</div></code>```

Is this the same that you want?
Hope this helps.

Title: Add a div to create padding

Body:
I have a span.  Inside it I have two divs.  One used as padding and a second with content.  If the content is multi-line it wraps around my padding div, which I want to prevent.

This jsfiddle shows what I currently have. https://jsfiddle.net/ju637z98/

    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.

If I change the content div to

display: inline-block

the two divs end up being stacked on top of each other.

I'm trying to avoid styling the content div because the the padding div won't always be present so I'd like to avoid having two different styles to achieve what I need.

Any help would be appreciated.

Edit: updated the snipped above and the jsfiddle to use spans instead of divs.

Body:
.wrapper{
  padding-left:20px;
  border:thin black solid;
  text-align:justify;
}

<div class="wrapper">
 This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
</div>

Is this the same that you want?
Hope this helps.


问:
SharedPreferences Logout not working
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}
</code>```

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

答:
Try this, hope it helps</p>

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.commit(); // to apply the changes
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

Title: SharedPreferences Logout not working

Body:
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Body:
Try this, hope it helps

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.commit(); // to apply the changes
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}


问:
Not able to open the large File Size PDF in IE 11
I am not able to open the large size PDF file(more than 1 gb) in IE 11. I am getting this error to open the PDF file "File does not begin with -%pdf- in internet explorer 11".

I am having Adobe Reader XI and Windows 7 in my system.
Can anybody help me out to fix this issue?

答:
The first line of a PDF file is a header identifying the version of the PDF specification to which the file conforms. For a file conforming to PDF 1.7, the header should be
%PDF−1. 7

It appears your document is missing this header. Confirm you have a valid PDF before attempting to open it. This error is not related to file size.


问:
Decode base64 encoded JSON to POJO with jackson and spring-boot
I have a request coming like this

```<code>{
    "varA"  : "A",
    "varB" : "TCFNhbiBKb3NlMRgwFgYDVQQK"
}
</code>```

where key varB is a base64 encoded JSON string. something like this:

```<code>{
    "nestedVarB1": "some value here",
    "nestedVarB2" : "some other value here"
}
</code>```

I want to convert it into some POJOs like this:

```<code>@Data
public class MyRequest {
    private String varA;
    private B varB;
}

@Data
public class B {
    private String nestedVarB1;
    private String nestedVarB2;
}
</code>```

I went through several solutions on stack overflow like this and this, but I want to convert the JSON directly into an object of type MyRequest maybe by writing some sort of Jackson deserializer.

How can I convert the JSON directly into MyRequest using Jackson and Spring Boot?

Note:

POJOs MyRequest and B are very big and B could be further nested, so doing it manually would be a big task.

I don't have any control over the request coming, it is coming from a third party source. So, can't change the format of the request.

答:
I've done some experiments and here is a simple Jackson Deserializer which should work for you.

Deserializer implements the ContextualDeserializer interface to get access to actual bean property (for example varB). It's necessary for detecting correct result type, because deserializer itself can be attached to a field of any type.

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import java.io.IOException;
import java.util.Base64;

public class Base64Deserializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    private Class<?> resultClass;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
        this.resultClass = property.getType().getRawClass();
        return this;
    }

    @Override
    public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String value = parser.getValueAsString();
        Base64.Decoder decoder = Base64.getDecoder();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] decodedValue = decoder.decode(value);

            return objectMapper.readValue(decodedValue, this.resultClass);
        } catch (IllegalArgumentException | JsonParseException e) {
            String fieldName = parser.getParsingContext().getCurrentName();
            Class<?> wrapperClass = parser.getParsingContext().getCurrentValue().getClass();

            throw new InvalidFormatException(
                parser,
                String.format("Value for '%s' is not a base64 encoded JSON", fieldName),
                value,
                wrapperClass
            );
        }
    }
}
```

<p>Here is an example of mapped class.
</p>

```public class MyRequest {

    private String varA;

    @JsonDeserialize(using = Base64Deserializer.class)
    private B varB;

    public String getVarA() {
        return varA;
    }

    public void setVarA(String varA) {
        this.varA = varA;
    }

    public B getVarB() {
        return varB;
    }

    public void setVarB(B varB) {
        this.varB = varB;
    }
}
```

Body:
I have a request coming like this

{
    "varA"  : "A",
    "varB" : "TCFNhbiBKb3NlMRgwFgYDVQQK"
}

where key varB is a base64 encoded JSON string. something like this:

{
    "nestedVarB1": "some value here",
    "nestedVarB2" : "some other value here"
}

I want to convert it into some POJOs like this:

@Data
public class MyRequest {
    private String varA;
    private B varB;
}

@Data
public class B {
    private String nestedVarB1;
    private String nestedVarB2;
}

I went through several solutions on stack overflow like this and this, but I want to convert the JSON directly into an object of type MyRequest maybe by writing some sort of Jackson deserializer.

How can I convert the JSON directly into MyRequest using Jackson and Spring Boot?

Note:

POJOs MyRequest and B are very big and B could be further nested, so doing it manually would be a big task.

I don't have any control over the request coming, it is coming from a third party source. So, can't change the format of the request.

Body:
I've done some experiments and here is a simple Jackson Deserializer which should work for you.

Deserializer implements the ContextualDeserializer interface to get access to actual bean property (for example varB). It's necessary for detecting correct result type, because deserializer itself can be attached to a field of any type.

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import java.io.IOException;
import java.util.Base64;

public class Base64Deserializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    private Class<?> resultClass;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
        this.resultClass = property.getType().getRawClass();
        return this;
    }

    @Override
    public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String value = parser.getValueAsString();
        Base64.Decoder decoder = Base64.getDecoder();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] decodedValue = decoder.decode(value);

            return objectMapper.readValue(decodedValue, this.resultClass);
        } catch (IllegalArgumentException | JsonParseException e) {
            String fieldName = parser.getParsingContext().getCurrentName();
            Class<?> wrapperClass = parser.getParsingContext().getCurrentValue().getClass();

            throw new InvalidFormatException(
                parser,
                String.format("Value for '%s' is not a base64 encoded JSON", fieldName),
                value,
                wrapperClass
            );
        }
    }
}

Here is an example of mapped class.

public class MyRequest {

    private String varA;

    @JsonDeserialize(using = Base64Deserializer.class)
    private B varB;

    public String getVarA() {
        return varA;
    }

    public void setVarA(String varA) {
        this.varA = varA;
    }

    public B getVarB() {
        return varB;
    }

    public void setVarB(B varB) {
        this.varB = varB;
    }
}


问:
JMS vs Hibernate Session
My project connects to a database using hibernate, getting connections from a connection pool on JBoss. I want to replace some of the reads/writes to tables with publish/consume from queues. I built a working example that uses OracleAQ, however, I am connecting to the DB using:

AQjmsFactory.getQueueConnectionFactory followed by createQueueConnection,
then using createQueueSession to get a (JMS) QueueSession on which I can call createProducer and createConsumer.

So I know how to do what I want using a jms.QueueSession. But using hibernate, I get a hibernate.session, which doesn't have those methods.

I don't want to open a new connection every time I perform an action on a queue - which is what I am doing now in my working example. Is there a way to perform queue operations from a hibernate.session? Only with SQL queries?

答:
I think you're confusing a JMS (message queue) session with a Hibernate (database) session. The Hibernate framework doesn't have any overlap with JMS, so it can't be used to do both things.

You'll need 2 different sessions for this to work:

A Hibernate Session (org.hibernate.Session) for DB work

A JMS Session (javax.jms.Session) to to JMS/queue work

Depending on your use case, you may also want an XA transaction manager to do a proper two-phase commit across both sessions and maintain transactional integrity.

Title: JMS vs Hibernate Session