问:
bash vs csh vs others - which is better for application maintenance?

Possible Duplicate:

  What Linux shell should I use?

I am starting to get proficient in a Linux environment and i'm trying to pick a weapon of choice in terms of command shell scripting (as i'm still a big n00b at this) that will help me (and others) manage, test and administer a set of server side applications running on a *NIX environment.

My question is: What is(are) the preferred command shell(s)  out there when the following criteria are considered:

How easy is it to learn/understand for a junior dev who has never had an exposure to shell scripting?

Is there a big pool of developers out there that know this shell script?

Is it safe and easy to use - will script errors be silent or give intelligent error output, will it let the uninitiated shoot them selves in the foot?

How portable is it? - Can i expect the same script to run in OpenSolaris as well as Redhat, FreeBSD? (granted command syntax and options for specific OS will change accordingly)

How standard is it? Is it expected to be included on most distro's of *NIX or does it have to be installed additionally?

I understand that there are camps out there who hold strong feelings for/against specific command shells, i am just looking for an informed opinion.

答:
These days, just about any non-embedded (or large embedded) operating system has a POSIX:2001 a.k.a. Single Unix v3 compatibility layer. This is native on unix platforms (Linux, Mac OS X, Solaris, *BSD, etc.) and installable on other platforms such as Windows and Android. POSIX specifies a shell language, usually known as POSIX sh. This language is derived from the Bourne shell.

Most unix systems have one of two implementations of POSIX sh: ksh or bash, which have additional useful features compared to POSIX. However some less mainstream systems (especially embedded ones) may have only POSIX-mandated features.

Given your objectives, I see three choices:

Restrict yourself to POSIX sh. Pro: you don't have to worry about differing variants, since there's a standard and compliant implementations are readily available. Con: you don't benefit from bash and ksh's extensions.

Use the intersection of ksh and bash. This is attractive in appearance, but it does mean you have to use two reference documents instead of just one — and even the features that bash and ksh have in common don't always use the same syntax. Figuring out which one you want to use on a given system is also a pain.

Choose one of ksh or bash. Both bash and ksh are available on all unix-like platforms and on Windows. Both have an open source implementation (the only one for bash, ATT ksh93 for ksh) that can be installed on most platforms. I'd go for bash over ksh for two reasons. First, it's the default on Linux, so you'll find more people who're used to it. Second, there are systems that come with an older, less-featured implementation of ksh; even if you can install ksh93, it's another thing you have to think about when deploying.

Forget about csh for scripting, and forget about zsh if you want common default availability.

See also What are the fundamental differences between the mainstream *NIX shells?, particularly the “for scripting” part of my answer.

Note that shell programming involves other utilities beyond the shell. POSIX specifies those other utilities. “Bash plus other POSIX utilities” is a reasonable choice, distinct from “POSIX utilities (including sh)”.


来源: stackexchange

问:
Why does JavaScript: new Date(year, month, 0).getDate() return the number of days in the month?
I know that this little javascript code,var whatever = new Date(year, month, 0).getDate(), returns the number of days in a particular month of a particular year. But what I don’t seem to understand is the logic behind it.

What exactly is that zero doing there after we mention the year and the month? Please Explain.

答:
When you give a parameter out of range, the next larger time increment is adjusted to make the time valid. So:

```<code>> new Date(2016,2,1)
2016-03-01T08:00:00.000Z
</code>```

So if we specify (2016,2,1), we get 3/1. So if we specify (2016,2,0), we'll get a day before that, adjusting the month as necessary to get something valid, that is, the last day of the previous month.

```<code>> new Date(2016,2,0)
2016-02-29T08:00:00.000Z
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When you give a parameter out of range, the next larger time increment is adjusted to make the time valid. So:

> new Date(2016,2,1)
2016-03-01T08:00:00.000Z

So if we specify (2016,2,1), we get 3/1. So if we specify (2016,2,0), we'll get a day before that, adjusting the month as necessary to get something valid, that is, the last day of the previous month.

> new Date(2016,2,0)
2016-02-29T08:00:00.000Z

ContentLicense: CC BY-SA 3.0


问:
Output "linux shell" vs "php system()" - sorting
Let's execute command:

```<code># zcat -f /var/log/remotelog*|grep -e "10\.0\.1\.15"|grep -e "7,35)"|sort -k 1M -k 2r|tail -n 250 3>&1
</code>```

Got output like this:

```<code>Apr  3 11:38:49 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:38:35 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:20 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:06:16 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:15 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:05:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  2 17:54:02 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  2 17:53:31 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  1 02:02:27 10.0.1.15 GPOND[927]: Success upgrade ONU(7,35)
Apr  1 02:02:23 10.0.1.15 GPOND[927]: Success Download-OS ONU(7,35)
Mar 31 15:03:51 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Mar 31 15:03:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
</code>```

Very nice...

But then i do it this way:

```<code><?php
$e = "zcat -f /var/log/remotelog*|grep -e \"10\.0\.1\.15\"|grep -e \"7,35)\"|sort -k 1M -k 2r|tail -n 250 3>&1";
system($e, $ret);
echo $ret ;
?>
</code>```

And i got this output:

```<code>Mar 31 15:03:51 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Mar 31 15:03:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:38:49 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:38:35 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:20 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:06:16 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:15 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:05:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  2 17:54:02 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  2 17:53:31 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  1 02:02:27 10.0.1.15 GPOND[927]: Success upgrade ONU(7,35)
Apr  1 02:02:23 10.0.1.15 GPOND[927]: Success Download-OS ONU(7,35)
</code>```

Why? I don't understand...

答:
If I understand correctly, the second one (through PHP) is the "correct" output.

As the list is first sorted by month name and the month name is dependent on the locale settings, I suspect that the locale settings (LC_* environment variables) are different in command line and in PHP, which affects the output of the sort.

Body:
Let's execute command:

# zcat -f /var/log/remotelog*|grep -e "10\.0\.1\.15"|grep -e "7,35)"|sort -k 1M -k 2r|tail -n 250 3>&1

Got output like this:

Apr  3 11:38:49 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:38:35 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:20 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:06:16 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:15 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:05:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  2 17:54:02 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  2 17:53:31 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  1 02:02:27 10.0.1.15 GPOND[927]: Success upgrade ONU(7,35)
Apr  1 02:02:23 10.0.1.15 GPOND[927]: Success Download-OS ONU(7,35)
Mar 31 15:03:51 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Mar 31 15:03:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)

Very nice...

But then i do it this way:

<?php
$e = "zcat -f /var/log/remotelog*|grep -e \"10\.0\.1\.15\"|grep -e \"7,35)\"|sort -k 1M -k 2r|tail -n 250 3>&1";
system($e, $ret);
echo $ret ;
?>

And i got this output:

Mar 31 15:03:51 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Mar 31 15:03:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:38:49 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:38:35 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:20 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:06:16 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  3 11:06:15 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  3 11:05:41 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  2 17:54:02 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link on(operational)
Apr  2 17:53:31 10.0.1.15 GPOND[927]: ONU(7,35) eth port 1 link off(operational)
Apr  1 02:02:27 10.0.1.15 GPOND[927]: Success upgrade ONU(7,35)
Apr  1 02:02:23 10.0.1.15 GPOND[927]: Success Download-OS ONU(7,35)

Why? I don't understand...


问:
Concatenate StringVector with Rcpp
I can not figure out how to concatenate 2 strings with Rcpp; and the documentation did not help me while I suspect there is an obvious answer.

http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/

http://gallery.rcpp.org/articles/strings_with_rcpp/

```<code>StringVector concatenate(StringVector a, StringVector b)
{
 StringVector c;
 c= ??;
 return c;
}
</code>```

I would expect this output :

```<code>a=c("a","b"); b=c("c","d");
concatenate(a,b)
[1] "ac" "bd"
</code>```

答:
I'm leaving this answer up, but note the warning provided by @nrussell regarding the use of push_back()!

I'm still getting to grips with Rcpp myself, so I've gone for a string builder in a loop

```<code>library(Rcpp)

cppFunction('StringVector concatenate(StringVector a, StringVector b)
{
  StringVector c;
  std::ostringstream x;
  std::ostringstream y;

 // concatenate inputs
  for (int i = 0; i < a.size(); i++)
    x << a[i];

  for (int i = 0; i < b.size(); i++)
    y << b[i];

  c.push_back(x.str());
  c.push_back(y.str());

  return c;

}')

a=c("a","b"); b=c("c","d");
concatenate(a,b)
# [1] "ab" "cd"
</code>```

Comparing the performance of (i) repeated calls to push_back against (ii) a preallocate-and-fill strategy, we can see that the latter is preferable:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector pbpaste(CharacterVector lhs, CharacterVector rhs)
{
    R_xlen_t i = 0, sz = lhs.size();
    CharacterVector res;

    for (std::ostringstream oss; i < sz; i++, oss.str("")) {
        oss << lhs[i] << rhs[i];
        res.push_back(oss.str());
    }

    return res;
}

// [[Rcpp::export]]
CharacterVector sspaste(CharacterVector lhs, CharacterVector rhs)
{
    R_xlen_t i = 0, sz = lhs.size();
    CharacterVector res(sz);

    for (std::ostringstream oss; i < sz; i++, oss.str("")) {
        oss << lhs[i] << rhs[i];
        res[i] = oss.str();
    }

    return res;
}

/*** R

lhs <- as.character(1:5000); rhs <- as.character(5001:10000)

all.equal(pbpaste(lhs, rhs), sspaste(lhs, rhs))
# [1] TRUE

microbenchmark::microbenchmark(
    "push_back" = pbpaste(lhs, rhs),
    "preallocate" = sspaste(lhs, rhs),
    times = 200L
)
# Unit: milliseconds
#         expr        min         lq       mean     median         uq        max neval cld
#    push_back 101.521579 105.334649 115.156544 107.275678 110.957420 256.722239   200   b
#  preallocate   1.364213   1.585818   1.789564   1.778153   1.934758   2.955352   200   a

*/
```

Title: Concatenate StringVector with Rcpp

Body:
I can not figure out how to concatenate 2 strings with Rcpp; and the documentation did not help me while I suspect there is an obvious answer.

http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/

http://gallery.rcpp.org/articles/strings_with_rcpp/

StringVector concatenate(StringVector a, StringVector b)
{
 StringVector c;
 c= ??;
 return c;
}

I would expect this output :

a=c("a","b"); b=c("c","d");
concatenate(a,b)
[1] "ac" "bd"

Body:
I'm leaving this answer up, but note the warning provided by @nrussell regarding the use of push_back()!

I'm still getting to grips with Rcpp myself, so I've gone for a string builder in a loop

library(Rcpp)

cppFunction('StringVector concatenate(StringVector a, StringVector b)
{
  StringVector c;
  std::ostringstream x;
  std::ostringstream y;

 // concatenate inputs
  for (int i = 0; i < a.size(); i++)
    x << a[i];

  for (int i = 0; i < b.size(); i++)
    y << b[i];

  c.push_back(x.str());
  c.push_back(y.str());

  return c;

}')

a=c("a","b"); b=c("c","d");
concatenate(a,b)
# [1] "ab" "cd"

Comparing the performance of (i) repeated calls to push_back against (ii) a preallocate-and-fill strategy, we can see that the latter is preferable:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector pbpaste(CharacterVector lhs, CharacterVector rhs)
{
    R_xlen_t i = 0, sz = lhs.size();
    CharacterVector res;

    for (std::ostringstream oss; i < sz; i++, oss.str("")) {
        oss << lhs[i] << rhs[i];
        res.push_back(oss.str());
    }

    return res;
}

// [[Rcpp::export]]
CharacterVector sspaste(CharacterVector lhs, CharacterVector rhs)
{
    R_xlen_t i = 0, sz = lhs.size();
    CharacterVector res(sz);

    for (std::ostringstream oss; i < sz; i++, oss.str("")) {
        oss << lhs[i] << rhs[i];
        res[i] = oss.str();
    }

    return res;
}

/*** R

lhs <- as.character(1:5000); rhs <- as.character(5001:10000)

all.equal(pbpaste(lhs, rhs), sspaste(lhs, rhs))
# [1] TRUE

microbenchmark::microbenchmark(
    "push_back" = pbpaste(lhs, rhs),
    "preallocate" = sspaste(lhs, rhs),
    times = 200L
)
# Unit: milliseconds
#         expr        min         lq       mean     median         uq        max neval cld
#    push_back 101.521579 105.334649 115.156544 107.275678 110.957420 256.722239   200   b
#  preallocate   1.364213   1.585818   1.789564   1.778153   1.934758   2.955352   200   a

*/


问:
How can I log values of effects given that we don't subsribe to them anywhere?

What I understand yes we dont need to subscribe to effects like observables as we are not consuming the results,
for example like:

const subscribe = source.subscribe(val => console.log(val))
```

<p>But is it possible to log without subscribing ?
Here is my code, say I want to log, addUserStats$ effect.</p>

<p>user-profile-effects.ts:</p>

<pre class="lang-ts prettyprint-override"><code>@Injectable()
export class UserProfileEffects {

  constructor(
    private actions$: Actions,
    private userProfileActions: UserProfileActions,
    private userProfile: UserProfile,
    private auth: Authorization
  ) { }

  @Effect()
  updateToken$ = this.actions$
    .ofType(UserProfileActions.UPDATE_TOKEN)
    .map(action => action.payload)
    .map((token: string) => this.auth.accessToken = token)
    .switchMap(token => this.userProfile.getStats(true))
    .map(response => this.userProfileActions.updateData(response));

  @Effect()
  addUserStats$ = this.actions$
    .ofType(UserProfileActions.UPDATE)
    .map(action => action.payload)
    .map((data: any) => this.userProfileActions.addStats(data.items));
}
</code>```

effects.ts:

export default [
  NowStatEffects,
  UserProfileEffects
];
```

<p>core.module.ts:</p>

<pre class="lang-ts prettyprint-override"><code>import effects from './effects';
@NgModule({
  imports: [
    CoreStoreModule,
    ...effects.map(effect => EffectsModule.run(effect)),
  ],
  declarations: [
  ],
  exports: [
    CoreStoreModule,
  ],
  providers: [
    ...APP_SERVICES
  ]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }
}
</code>```

答:
You can tap into observable stream by chaining do() operator. It will:

Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source.

  @Effect()
  addUserStats$ = this.actions$
    .ofType(UserProfileActions.UPDATE)
    .map(action => action.payload)
    .do((data: any) => console.log(data.items))
    .map(payload => { /* do something else */ )
```

<p>or shorter version:</p>

```    .do(console.log)
```

Body:
What I understand yes we dont need to subscribe to effects like observables as we are not consuming the results,
for example like:

const subscribe = source.subscribe(val => console.log(val))

But is it possible to log without subscribing ?
Here is my code, say I want to log, addUserStats$ effect.

user-profile-effects.ts:

@Injectable()
export class UserProfileEffects {

  constructor(
    private actions$: Actions,
    private userProfileActions: UserProfileActions,
    private userProfile: UserProfile,
    private auth: Authorization
  ) { }

  @Effect()
  updateToken$ = this.actions$
    .ofType(UserProfileActions.UPDATE_TOKEN)
    .map(action => action.payload)
    .map((token: string) => this.auth.accessToken = token)
    .switchMap(token => this.userProfile.getStats(true))
    .map(response => this.userProfileActions.updateData(response));

  @Effect()
  addUserStats$ = this.actions$
    .ofType(UserProfileActions.UPDATE)
    .map(action => action.payload)
    .map((data: any) => this.userProfileActions.addStats(data.items));
}

effects.ts:

export default [
  NowStatEffects,
  UserProfileEffects
];

core.module.ts:

import effects from './effects';
@NgModule({
  imports: [
    CoreStoreModule,
    ...effects.map(effect => EffectsModule.run(effect)),
  ],
  declarations: [
  ],
  exports: [
    CoreStoreModule,
  ],
  providers: [
    ...APP_SERVICES
  ]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }
}

Body:
You can tap into observable stream by chaining do() operator. It will:

Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source.

  @Effect()
  addUserStats$ = this.actions$
    .ofType(UserProfileActions.UPDATE)
    .map(action => action.payload)
    .do((data: any) => console.log(data.items))
    .map(payload => { /* do something else */ )

or shorter version:

    .do(console.log)


问:
Toggle nav not opening
The website is http://109.74.0.128/~app/assistanstv/assistanstv/www.assistans.tv/tv.html

HTML:

```<code><nav class="menu">
    <ul class="active">
        <li class="current-item"><a href="#">Home</a></li>
        <li><a href="#">Barnasisstans</a></li>
        <li><a href="#">Intervjuer</a></li>
        <li><a href="#">Juridik</a></li>
        <li><a href="#">LSS2020</a></li>
        <li><a href="#">Resor</a></li>
        <li><a href="#">Utbildning</a></li>
    </ul>

    <a class="toggle-nav" href="#">☰</a>
    </nav>
</code>```

jquery

```<code>jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
        jQuery(this).toggleClass('active');
        jQuery('.menu ul').toggleClass('active');

        e.preventDefault();
    });
});
</code>```

the css code is too long, i cant get it work anyway. This drive me soon crazy. Whats wrong?!

Edit: Problem solved. The problem was

it was a / in the end. I solved it by deleted the last /

答:
I think you want this:

```<code>$(document).ready(function() {
    $('.toggle-nav').click(function(e) {
            $('.toggle-nav').removeClass('active')
        $(this).toggleClass('active');
        $('.menu ul').toggleClass('active');
        e.preventDefault();
    });
});
</code>```

CSS

```<code>.active {
  background:tomato;
}
</code>```

this class just a sample for showing toggling of class

updatelink of your code

Title: Toggle nav not opening

Body:
The website is http://109.74.0.128/~app/assistanstv/assistanstv/www.assistans.tv/tv.html

HTML:

Home

Barnasisstans

Intervjuer

Juridik

LSS2020

Resor

Utbildning

    ☰

jquery

jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
        jQuery(this).toggleClass('active');
        jQuery('.menu ul').toggleClass('active');

        e.preventDefault();
    });
});

the css code is too long, i cant get it work anyway. This drive me soon crazy. Whats wrong?!

Edit: Problem solved. The problem was

it was a / in the end. I solved it by deleted the last /

Body:
I think you want this:

$(document).ready(function() {
    $('.toggle-nav').click(function(e) {
            $('.toggle-nav').removeClass('active')
        $(this).toggleClass('active');
        $('.menu ul').toggleClass('active');
        e.preventDefault();
    });
});

CSS

.active {
  background:tomato;
}

this class just a sample for showing toggling of class

updatelink of your code


问:
java.lang.IllegalArgumentException in java spring using constructor injection
Hello i am using constructor injection in my spring demo app when i run this program i got :

java.lang.IllegalArgumentException exception

Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .

Here is my EmployeeBean.java

```<code>package cris;

public class Employee {
    private int id;
    private String name;
    public Employee() { }
    public Employee(int id,String name) {
        this.id=id;
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    void show() {
        System.out.println(id+" "+name);

    }
}
</code>```

Here is my Address Bean using setter injection

```<code>package cris;

public class Address {
private String city,state,country;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String toString()
{
    return city+" "+state+" "+country;
}
}
</code>```

Here is my spring.xml ie spring config file

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
</code>```

And here is my Application Main Method

```<code>package cris;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
public static void main(String[] args) {
    ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
    Employee emp = (Employee)context.getBean("e");
    emp.show();
}
}
</code>```

kindly provide me suggestion where i am wrong so i will catch the exception thanks

The Exception:

```<code>Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)
</code>```

答:
When filling POJO's, (for what I know) Spring calls the no-arg constructor by default. If you decide to write a cTor with parameters yourself, you will not get a default cTor generated and you'll have to add a no-arg cTor for spring yourself.</p>

```<code>public Employee() { }
</code>```

Body:
Hello i am using constructor injection in my spring demo app when i run this program i got :

java.lang.IllegalArgumentException exception

Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .

Here is my EmployeeBean.java

package cris;

public class Employee {
    private int id;
    private String name;
    public Employee() { }
    public Employee(int id,String name) {
        this.id=id;
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    void show() {
        System.out.println(id+" "+name);

    }
}

Here is my Address Bean using setter injection

package cris;

public class Address {
private String city,state,country;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String toString()
{
    return city+" "+state+" "+country;
}
}

Here is my spring.xml ie spring config file

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>

And here is my Application Main Method

package cris;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
public static void main(String[] args) {
    ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
    Employee emp = (Employee)context.getBean("e");
    emp.show();
}
}

kindly provide me suggestion where i am wrong so i will catch the exception thanks

The Exception:

Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)

Body:
When filling POJO's, (for what I know) Spring calls the no-arg constructor by default. If you decide to write a cTor with parameters yourself, you will not get a default cTor generated and you'll have to add a no-arg cTor for spring yourself.

public Employee() { }


问:
Python: Why it always asks to install pyparsing whenever I want install something?
I'm not sure why pip always throw the exception that 'can not find pyparsing'.
even When I try to download pyparsing i get:

```<code>pip install pyparsing
Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 72, in <module>
    import packaging.requirements
  File "/usr/local/lib/python2.7/dist-packages/packaging/requirements.py", line 9, in <module>
    from pyparsing import stringStart, stringEnd, originalTextFor, ParseException
ImportError: No module named pyparsing
</code>```

It doesn't make sense?!

答:
Even after I did what Shahin and Paul said, I still get the same error. So I removed pip and reinstall it:</p>

```<code>sudo apt-get purge python-pip
curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
python get-pip.py
</code>```

Body:
I'm not sure why pip always throw the exception that 'can not find pyparsing'.
even When I try to download pyparsing i get:

pip install pyparsing
Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 72, in <module>
    import packaging.requirements
  File "/usr/local/lib/python2.7/dist-packages/packaging/requirements.py", line 9, in <module>
    from pyparsing import stringStart, stringEnd, originalTextFor, ParseException
ImportError: No module named pyparsing

It doesn't make sense?!

Body:
Even after I did what Shahin and Paul said, I still get the same error. So I removed pip and reinstall it:

sudo apt-get purge python-pip
curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
python get-pip.py


问:
What would be a simple regular expression for password check during signup?
What I want to do is just check when the user is signing up that whether the password entered is at least 6 characters and has no space in it. Thats pretty much it. What would be a regex that I could use in Java Pattern Matcher classes for this purpose?

Thanks for your help guys.

答:
Why do you want to use a regex? </p>

```<code>public boolean isPasswordValid( String password )
{
    return ((password.length() >= 6) && (!password.contains(" "));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Why do you want to use a regex?

public boolean isPasswordValid( String password )
{
    return ((password.length() >= 6) && (!password.contains(" "));
}


问:
Dynamics 365-Assigning Resource to a task
I am trying to allocate a resource to a task in Dynamics 365 programmatically. The code is:

```<code>private static void AssignResourceToTask(XrmServiceContext xrm)
{
    Guid TaskId = new Guid("e0bdf7c7-6a14-e711-8114-e0071b6ac161");
    Guid ResourceId = new Guid("cd01ae07-b9cd-e611-80e7-c4346bac0910");
    Guid ProjectId = new Guid("7982feea-a0f2-e611-8130-e0071b6a92f1");

    var AssignResource = new msdyn_resourceassignment
    {
        msdyn_resourceassignmentId = Guid.NewGuid(),
        msdyn_bookableresourceid = new Microsoft.Xrm.Client.CrmEntityReference("bookableresource", ResourceId),
        msdyn_taskid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_projecttask", TaskId),
        msdyn_projectid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_project", ProjectId),
    };

    AssignResource.msdyn_bookableresourceid.Name = "Amy Alberts";
    xrm.AddObject(AssignResource);
    xrm.SaveChanges();
}
</code>```

But I am unable to assign a resource to a task using the above code.

答:
Have you tried Microsoft.Crm.Sdk.AssignRequest? Your code would look like:

```<code>_serviceProxy.EnableProxyTypes();
_service = (IOrganizationService)_serviceProxy;

var assignRequest = new AssignRequest
{
    Assignee = new EntityReference("contact", ResourceId),
    Target = new EntityReference("task", TaskId)
};

_service.Execute(assignRequest);
</code>```

Microsoft have an example here.

Body:
I am trying to allocate a resource to a task in Dynamics 365 programmatically. The code is:

private static void AssignResourceToTask(XrmServiceContext xrm)
{
    Guid TaskId = new Guid("e0bdf7c7-6a14-e711-8114-e0071b6ac161");
    Guid ResourceId = new Guid("cd01ae07-b9cd-e611-80e7-c4346bac0910");
    Guid ProjectId = new Guid("7982feea-a0f2-e611-8130-e0071b6a92f1");

    var AssignResource = new msdyn_resourceassignment
    {
        msdyn_resourceassignmentId = Guid.NewGuid(),
        msdyn_bookableresourceid = new Microsoft.Xrm.Client.CrmEntityReference("bookableresource", ResourceId),
        msdyn_taskid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_projecttask", TaskId),
        msdyn_projectid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_project", ProjectId),
    };

    AssignResource.msdyn_bookableresourceid.Name = "Amy Alberts";
    xrm.AddObject(AssignResource);
    xrm.SaveChanges();
}

But I am unable to assign a resource to a task using the above code.

Body:
Have you tried Microsoft.Crm.Sdk.AssignRequest? Your code would look like:

_serviceProxy.EnableProxyTypes();
_service = (IOrganizationService)_serviceProxy;

var assignRequest = new AssignRequest
{
    Assignee = new EntityReference("contact", ResourceId),
    Target = new EntityReference("task", TaskId)
};

_service.Execute(assignRequest);

Microsoft have an example here.


问:
Autoplay html video on hover?
I've searched across the internet and found some good examples but for some reason when I try to implement them with my code it's not working. I can't figure out what I seem to be doing wrong..

(I'm sorry for the dutch class names, hope it isn't too confusing). Sorry If I'm being really dumb about this.

HTML:

```<code><div class="drievijfde-wrapper portfolio-wrapper">
    <div class="single-item singlevidjs drievijfde-padding" style="background-image:url(img/work-placeholder.png); background-position: center center; background-size: cover;">
        <video loop preload="auto" id="portfolio-vid">
            <source src="video/test reel_1.mp4" type="video/mp4">
        </video>
        <a href="#">
            <div class="metadata">
                Interior Lamps
            </div>
        </a>
    </div>
</div>
</code>```

JS:

```<code>var figure = $(".singlevidjs").hover( hoverVideo, hideVideo );

function hoverVideo(e) {
    $('video', this).get(0).play();
}

function hideVideo(e) {
    $('video', this).get(0).pause();
}
</code>```

答:
You can use following jQuery code for this

```<code>$('#portfolio-vid').mouseover(function(){
    $(this).get(0).play();
}).mouseout(function(){
    $(this).get(0).pause();
})
</code>```

Title: Autoplay html video on hover?

Body:
I've searched across the internet and found some good examples but for some reason when I try to implement them with my code it's not working. I can't figure out what I seem to be doing wrong..

(I'm sorry for the dutch class names, hope it isn't too confusing). Sorry If I'm being really dumb about this.

HTML:

        <video loop preload="auto" id="portfolio-vid">
            <source src="video/test reel_1.mp4" type="video/mp4">
        </video>

                Interior Lamps

JS:

var figure = $(".singlevidjs").hover( hoverVideo, hideVideo );

function hoverVideo(e) {
    $('video', this).get(0).play();
}

function hideVideo(e) {
    $('video', this).get(0).pause();
}

Body:
You can use following jQuery code for this

$('#portfolio-vid').mouseover(function(){
    $(this).get(0).play();
}).mouseout(function(){
    $(this).get(0).pause();
})


问:
Using regex to find sentence between tags in string?
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

```<code>var result = elements.match(/<p>(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});
</code>```

答:
Use DOM instead of regex. You can use jquery to parsing string and get text of target element. Use jQuery.parseHTML() to parse string into DOM or use only jQuery().

var html = '
Hello world!
';
console.log($(html).text());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I need to get the sentence between tags like
Hello world!
 using regex .

Attribute of tags may differ like
Hello world!

I have code like this

var result = elements.match(/
(.*?)<\/p>/g).map(function(val1){
    return val1.replace(/<\/?p>/g,'');
});

Body:
Use DOM instead of regex. You can use jquery to parsing string and get text of target element. Use jQuery.parseHTML() to parse string into DOM or use only jQuery().

var html = '<p class="test" style="color:red">Hello world!</p>';
console.log($(html).text());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
New line in Zebra ZPL

How do I put new line characters for my "Text"? Say for example:

Hello World
```
<p>will become</p>
<pre class="lang-none prettyprint-override"><code>Hello
World
</code>```

Is there anyway that I can put a new line character for my code like this?

```<code>^FT78,76^A0N,28,28^FH\^FDHello\nWorld^FS
</code>```

If the "text" in my label is too long, how would I put another line to it?

答:
Doesn't answer the original question but for anyone using ZPL for unicode this may be of help.

I am using ^TB for Arabic text and found \& didn't work to create a new line.

What did work was to convert new line to hex (_0A) and use that.

For example:

```<code>^XA
^LL0406
^CI28
^CWZ,E:TT0003M_.FNT
^PA0,1,1,0

^FO609,50,2
^AZN,40,35
^TBN,559,300
^FH
^FD
_D8_B4_D8_B4_D8_B4_0A <-- new line
_D8_B4_D8_B4_D8_B4_0A <-- new line
_D8_B4_D8_B4_D8_B4
^FS

^PQ1
^XZ
</code>```

... would output a ticket like this:

```<code>ششش
ششش
ششش
</code>```

Title: New line in Zebra ZPL

Body:
How do I put new line characters for my "Text"? Say for example:

Hello World

will become

Hello
World

Is there anyway that I can put a new line character for my code like this?

^FT78,76^A0N,28,28^FH\^FDHello\nWorld^FS

If the "text" in my label is too long, how would I put another line to it?

Body:
Doesn't answer the original question but for anyone using ZPL for unicode this may be of help.

I am using ^TB for Arabic text and found \& didn't work to create a new line.

What did work was to convert new line to hex (_0A) and use that.

For example:

^XA
^LL0406
^CI28
^CWZ,E:TT0003M_.FNT
^PA0,1,1,0

^FO609,50,2
^AZN,40,35
^TBN,559,300
^FH
^FD
_D8_B4_D8_B4_D8_B4_0A <-- new line
_D8_B4_D8_B4_D8_B4_0A <-- new line
_D8_B4_D8_B4_D8_B4
^FS

^PQ1
^XZ

... would output a ticket like this:

ششش
ششش
ششش


问:
Text alignment without using table in html and css
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

```<code><div>
    <table>
        <thead>
            <tr><th><span>Login Page</span></th></tr>
        </thead>
        <tbody>
            <tr>
            <th><label>Username:</label></th>
            <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <th><label>Password:</label></th>
                <td><input type="text" value="" /></td>
            </tr>
            <tr>
                <td><input type="button" value="Submit" /></td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

```<code><div class="box">
    <span>Login Page</span>
    <br />
    <span>
        <label>Username:</label>
        <input type="text" value="" />
        <br />
        <label>Password:</label>
        <input type="text" value="" />
        <br />
        <input type="button" value="Submit" />
    </span>
</div>
</code>```

style.css

```<code>.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}
</code>```

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?

答:
@iSahilSharma Please find following code without using table. I hope you were expecting the same. A part from it just a suggestion that start using Bootstrap framework instead of using custom coding.

.main_container{
   width:100%;
  }
  .inner_box {
  margin: 40px auto;
  width: 30%;
  }

  .inner_box span{
  clear: both;
  display: block;
  }
  .inner_box span:first-child{
   margin-bottom:10px;
  }
  .inner_box span:nth-child(n+2){
   margin-bottom:20px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main_container">
 <div class="inner_box">
            <span>Login Page</span>
            <span>
                <label>Username:</label>
                <input type="text" value="" />
            </span>
            <span>
                <label>Password:</label>
                <input type="text" value="" />
            </span>
            <span>

                <input type="button" value="Submit" />
            </span>
    </div>
</div></code>```

Body:
I'm trying to learn HTML and CSS and using the old-school approach by creating a login page with three input controls (two text and one button). However, I'm using

 for the alignment issues of textboxes. But I've read somewhere that using tables is not considered a good approach. This is what I'm doing:

Home.html

Login Page

            Username:
            <input type="text" value="" />

                Password:
                <input type="text" value="" />

                <input type="button" value="Submit" />

However, I'm using some beginner stuff of CSS to align input controls without using tables and this is what I'm trying:

Home.html

    Login Page

        Username:
        <input type="text" value="" />

        Password:
        <input type="text" value="" />

        <input type="button" value="Submit" />

style.css

.box {
   margin: 10px 10px 10px 10px;
   border: dotted 2px #fff;
   width: 500px;
}

.box span:first-child {
    border: dotted 1px;
    margin-left: 30%;
    font-family: Arial, sans-serif;
    width: 50%;
}

.box span label:nth-of-type(odd)
{
    color:blue;
    font-family: Arial, sans-serif;
}

.box span label:nth-of-type(even)
{
    color: red;
    font-family: Arial, sans-serif;
    display: inline-block;
}

My concern is using css, I'm able to align the input controls but I have to use multiple break tags (
) and also extra code for alignment which is easier by simply using the
 tag. Can someone suggest me the standard approach and either I'm on the right path or not?

Body:
@iSahilSharma Please find following code without using table. I hope you were expecting the same. A part from it just a suggestion that start using Bootstrap framework instead of using custom coding.

.main_container{
   width:100%;
  }
  .inner_box {
  margin: 40px auto;
  width: 30%;
  }

  .inner_box span{
  clear: both;
  display: block;
  }
  .inner_box span:first-child{
   margin-bottom:10px;
  }
  .inner_box span:nth-child(n+2){
   margin-bottom:20px;
  }

<div class="main_container">
 <div class="inner_box">
            <span>Login Page</span>
            <span>
                <label>Username:</label>
                <input type="text" value="" />
            </span>
            <span>
                <label>Password:</label>
                <input type="text" value="" />
            </span>
            <span>

                <input type="button" value="Submit" />
            </span>
    </div>
</div>


问:
How to get all keys from Ordered Dictionary?
```<code>def izracunaj_dohvatljiva_stanja(funkcije_prijelaza):
    dohvatljiva = []
    dohvatljiva.extend(pocetno_stanje)
    pomocna = collections.OrderedDict
    for i in xrange(len(dohvatljiva)):
        for temp in pomocna.keys(): <-----------------------------------this line
            if temp.split(',')[0] == dohvatljiva[i]:
                if funkcije_prijelaza.get(temp) not in dohvatljiva:
                    dohvatljiva.extend(funkcije_prijelaza.get(temp))
</code>```

I am trying to get all keys from ordered dict so i can iterate over it but after running error occurs:
click for pic

答:
It's quite an old thread to add new answer. But when I faced a similar problem and searched for it's solution, I came to answer this.

Here is an easy way, we can sort a dictionary in Python 3(Prior to Python 3.6).

```<code>import collections

d={
    "Apple": 5,
    "Banana": 95,
    "Orange": 2,
    "Mango": 7
}

# sorted the dictionary by value using OrderedDict
od = collections.OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print(od)
sorted_fruit_list = list(od.keys())
print(sorted_fruit_list)
</code>```

Output:

```<code>OrderedDict([('Orange', 2), ('Apple', 5), ('Mango', 7), ('Banana', 95)])
['Orange', 'Apple', 'Mango', 'Banana']
</code>```

Update:

From Python 3.6 and later releases, we can sort dictionary by it's values.

```<code>d={
    "Apple": 5,
    "Banana": 95,
    "Orange": 2,
    "Mango": 7
}

sorted_data = {item[0]:item[1] for item in sorted(d.items(), key=lambda x: x[1])}
print(sorted_data)
sorted_fruit_list = list(sorted_data.keys())
print(sorted_fruit_list)
</code>```

Output:

```<code>{'Orange': 2, 'Apple': 5, 'Mango': 7, 'Banana': 95}
['Orange', 'Apple', 'Mango', 'Banana']
</code>```

Body:
def izracunaj_dohvatljiva_stanja(funkcije_prijelaza):
    dohvatljiva = []
    dohvatljiva.extend(pocetno_stanje)
    pomocna = collections.OrderedDict
    for i in xrange(len(dohvatljiva)):
        for temp in pomocna.keys(): <-----------------------------------this line
            if temp.split(',')[0] == dohvatljiva[i]:
                if funkcije_prijelaza.get(temp) not in dohvatljiva:
                    dohvatljiva.extend(funkcije_prijelaza.get(temp))

I am trying to get all keys from ordered dict so i can iterate over it but after running error occurs:
click for pic

Body:
It's quite an old thread to add new answer. But when I faced a similar problem and searched for it's solution, I came to answer this.

Here is an easy way, we can sort a dictionary in Python 3(Prior to Python 3.6).

import collections

d={
    "Apple": 5,
    "Banana": 95,
    "Orange": 2,
    "Mango": 7
}

# sorted the dictionary by value using OrderedDict
od = collections.OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print(od)
sorted_fruit_list = list(od.keys())
print(sorted_fruit_list)

Output:

OrderedDict([('Orange', 2), ('Apple', 5), ('Mango', 7), ('Banana', 95)])
['Orange', 'Apple', 'Mango', 'Banana']

Update:

From Python 3.6 and later releases, we can sort dictionary by it's values.

d={
    "Apple": 5,
    "Banana": 95,
    "Orange": 2,
    "Mango": 7
}

sorted_data = {item[0]:item[1] for item in sorted(d.items(), key=lambda x: x[1])}
print(sorted_data)
sorted_fruit_list = list(sorted_data.keys())
print(sorted_fruit_list)

Output:

{'Orange': 2, 'Apple': 5, 'Mango': 7, 'Banana': 95}
['Orange', 'Apple', 'Mango', 'Banana']


问:
subtracting variables within two different netcdf files
I have two netcdf files: downwelling radiation named rsds.nc and confined radiation named rsns.nc. rsds.nc contains a variable named rsds and rsns.nc contains a variable named rsns. Now I would like to have the upwelling radiation rsus.nc by subtracting the variables within rsds.nc and rsns.nc, respectively.

I tried the following methods:

```<code>ncdiff rsds.nc rsns.nc rsus.nc
ncbo op_typ=diff rsds.nc rsns.nc rsus.nc
</code>```

All of them produced a rsus.nc but the variable rsus, within this file is missing. Any idea of why this is so?

答:
Two alternative CDO solutions.

The sledgehammer approach

The cdo sub command can do this on one line:

```<code>cdo sub rsds.nc rsns.nc rsus.nc
</code>```

You will get the warning

cdo sub (Warning): Input streams have different parameters!

But you can ignore that.  Note that you may want to change the variable name to something more appropriate, so you can do this on one line as:

```<code>cdo setname,rsus -sub rsds.nc rsns.nc rsus.nc
</code>```

The expr approach

This just mimics the accepted answer but in cdo equivalent commands

```<code>cdo cat rsds.nc rsns.nc tmp.nc
cdo expr,"rsus=rsds-rsns" temp.nc rsus.nc
</code>```

By the way, with all solutions on Thurs page you might want to use cdo chgattr or the nco equivalent to ensure the meta data is correct for your new field, especially if you intend to keep the files long term or pass them to other people.

Body:
I have two netcdf files: downwelling radiation named rsds.nc and confined radiation named rsns.nc. rsds.nc contains a variable named rsds and rsns.nc contains a variable named rsns. Now I would like to have the upwelling radiation rsus.nc by subtracting the variables within rsds.nc and rsns.nc, respectively.

I tried the following methods:

ncdiff rsds.nc rsns.nc rsus.nc
ncbo op_typ=diff rsds.nc rsns.nc rsus.nc

All of them produced a rsus.nc but the variable rsus, within this file is missing. Any idea of why this is so?

Body:
Two alternative CDO solutions.

The sledgehammer approach

The cdo sub command can do this on one line:

cdo sub rsds.nc rsns.nc rsus.nc

You will get the warning

cdo sub (Warning): Input streams have different parameters!

But you can ignore that.  Note that you may want to change the variable name to something more appropriate, so you can do this on one line as:

cdo setname,rsus -sub rsds.nc rsns.nc rsus.nc

The expr approach

This just mimics the accepted answer but in cdo equivalent commands

cdo cat rsds.nc rsns.nc tmp.nc
cdo expr,"rsus=rsds-rsns" temp.nc rsus.nc

By the way, with all solutions on Thurs page you might want to use cdo chgattr or the nco equivalent to ensure the meta data is correct for your new field, especially if you intend to keep the files long term or pass them to other people.


问:
Process multiple files in Python with one code
I'm having some trouble with my code. I want to do the following: I have about 30 csv files which I need to process and I want the result in one single csv file. So far I have the following code (sample):

```<code>import pandas as pd
import csv as csv

df = pd.read_csv ("file.csv",
                  delimiter=",",skiprows=1)

datamean10=df[61:240].mean()
datamean15=df[241:420].mean()

list10=[]
list15=[]

list10.append(datamean10.clip(0))
list15.append(datamean15.clip(0))

csvfile = "C:/Users/bla/bla/list10.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list10)

csvfile = "C:/Users/bla/bla/list15.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list15)
</code>```

So this code does what I want for a single file. I wrote another script to go through all the files:

```<code>import sys, os
for root, dir, files in os.walk('C:/Users/bla/bla/bla'):
    for file in files:
        if file.endswith('.csv'):
            os.system ('averagelist.py {}'.format(root + '\\' + file))
</code>```

Needless to say this script deletes the lists again and starts off with a blank list while I want to append the results to the same list. So that the resulting files have a row of average values for each file that is processed. Can somebody tell me how to do this? Thank you very much in advance.

答:
This should be a working combination.</p>

```<code>import pandas as pd
import csv as csv

df = pd.read_csv ("file.csv",
                  delimiter=",",skiprows=1)

datamean10=df[61:240].mean()
datamean15=df[241:420].mean()

list10=[]
list15=[]

list10.append(datamean10.clip(0))
list15.append(datamean15.clip(0))

csvfile = "C:/Users/bla/bla/list10.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list10)

import sys, os
for root, dir, files in os.walk('C:/Users/bla/bla/bla'):
    for file in files:
        if file.endswith('.csv'):
            #csvfile = "C:/Users/bla/bla/list15.csv"
            with open(file, 'w') as output:
                writer = csv.writer(output, lineterminator='\n')
                writer.writerows(list15)
</code>```

Body:
I'm having some trouble with my code. I want to do the following: I have about 30 csv files which I need to process and I want the result in one single csv file. So far I have the following code (sample):

import pandas as pd
import csv as csv

df = pd.read_csv ("file.csv",
                  delimiter=",",skiprows=1)

datamean10=df[61:240].mean()
datamean15=df[241:420].mean()

list10=[]
list15=[]

list10.append(datamean10.clip(0))
list15.append(datamean15.clip(0))

csvfile = "C:/Users/bla/bla/list10.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list10)

csvfile = "C:/Users/bla/bla/list15.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list15)

So this code does what I want for a single file. I wrote another script to go through all the files:

import sys, os
for root, dir, files in os.walk('C:/Users/bla/bla/bla'):
    for file in files:
        if file.endswith('.csv'):
            os.system ('averagelist.py {}'.format(root + '\\' + file))

Needless to say this script deletes the lists again and starts off with a blank list while I want to append the results to the same list. So that the resulting files have a row of average values for each file that is processed. Can somebody tell me how to do this? Thank you very much in advance.

Body:
This should be a working combination.

import pandas as pd
import csv as csv

df = pd.read_csv ("file.csv",
                  delimiter=",",skiprows=1)

datamean10=df[61:240].mean()
datamean15=df[241:420].mean()

list10=[]
list15=[]

list10.append(datamean10.clip(0))
list15.append(datamean15.clip(0))

csvfile = "C:/Users/bla/bla/list10.csv"
with open(csvfile, 'w') as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(list10)

import sys, os
for root, dir, files in os.walk('C:/Users/bla/bla/bla'):
    for file in files:
        if file.endswith('.csv'):
            #csvfile = "C:/Users/bla/bla/list15.csv"
            with open(file, 'w') as output:
                writer = csv.writer(output, lineterminator='\n')
                writer.writerows(list15)


问:
Ruby - Extract value of a particular key from array of hashes
I have an array of hashes - @profiles which has data as:

```<code>[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]
</code>```

I want to get full_name of say user_id = 7? I'm doing the following: but it's throwing an error that expression @profiles.find{|h| h[':user_id'] == current_user.id} is nil.

```<code>name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']
</code>```

if I use select instead of find then error is - no implicit conversion of String into Integer.

How do I search through the array of hashes?

UPDATE:

After @Eric's answer, I restructured my job model & view actions:

```<code>  def full_names
    profile_arr||= []
    profile_arr = self.applications.pluck(:user_id)
    @profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
    @full_names = @profiles.each_with_object({}) do |profile, names|
      names[profile[:user_id]] = profile[:full_name]
    end
  end
</code>```

In the view....,

```<code>p @current_job.full_names[current_user.id]
</code>```

答:
@profiles is an array of hashes, with symbols as keys, whereas what you use is String objects.

So ':user_id' is a string, and you want symbol: :user_id:

```<code>@profiles.find{ |h| h[:user_id] == current_user.id }
</code>```

I want to get full_name of say user_id == 7

```<code>@profiles.find { |hash| hash[:user_id] == 7 }.fetch(:full_name, nil)
</code>```

Note, I used Hash#fetch for case, when there is no hash with value 7 at key :user_id.

Body:
I have an array of hashes - @profiles which has data as:

[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]

I want to get full_name of say user_id = 7? I'm doing the following: but it's throwing an error that expression @profiles.find{|h| h[':user_id'] == current_user.id} is nil.

name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']

if I use select instead of find then error is - no implicit conversion of String into Integer.

How do I search through the array of hashes?

UPDATE:

After @Eric's answer, I restructured my job model & view actions:

  def full_names
    profile_arr||= []
    profile_arr = self.applications.pluck(:user_id)
    @profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
    @full_names = @profiles.each_with_object({}) do |profile, names|
      names[profile[:user_id]] = profile[:full_name]
    end
  end

In the view....,

p @current_job.full_names[current_user.id]

Body:
@profiles is an array of hashes, with symbols as keys, whereas what you use is String objects.

So ':user_id' is a string, and you want symbol: :user_id:

@profiles.find{ |h| h[:user_id] == current_user.id }

I want to get full_name of say user_id == 7

@profiles.find { |hash| hash[:user_id] == 7 }.fetch(:full_name, nil)

Note, I used Hash#fetch for case, when there is no hash with value 7 at key :user_id.


问:
Check if a stdClass object has "entries" in PHP
I have a model that checks for entries en a database. Like this:

```<code>public function getByID($id)
{
    if(false == is_numeric($id))
        return false;

    $images = array();

    $query = $this->db->where("id_album", $id)->order_by("order", "ASC")->get("images");

    foreach($query->result() as $row)
        $images[] = $row;

    return (object) $images;
}
</code>```

In my view I want to know if I have a rows or not, to show the images or not. I do this:

```<code><?php if(false != isset($content->images)): ?>
    ```<?php print_r($content->images); ?>```
<?php endif; ?>
</code>```

But every time I try to skip when I've no results (i get a stdClass() empty) I fail. I tried isset, $content->images != NULL, !$content->images... I don't know how to do it to skip the "Severity: Notice Message: Undefined variable".

Thank you in advance.

UPDATE:

$content has more sets than images, like $content->_data or $content->title.

When I've NO images on database and i've no return from MySQL, doing this:

```<code><?php echo count($content->images); ?>
```<?php print_r($content->images); ?>```
</code>```

The output is:

```<code>1
stdClass ( )
</code>```

答:
I wanted to check if some object has all of the given properties. So I did this:

```<code>function hasAllProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc && property_exists($object, $property);
        },
        true
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAllProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
</code>```

Then in addition you may also want to check if just one or more of the properties exists:

```<code>function hasAnyProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc || property_exists($object, $property);
        },
        false
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAnyProperties($someObject, ['moo']) ? 'TRUE' : 'FALSE') . "\n";
</code>```

Body:
I have a model that checks for entries en a database. Like this:

public function getByID($id)
{
    if(false == is_numeric($id))
        return false;

    $images = array();

    $query = $this->db->where("id_album", $id)->order_by("order", "ASC")->get("images");

    foreach($query->result() as $row)
        $images[] = $row;

    return (object) $images;
}

In my view I want to know if I have a rows or not, to show the images or not. I do this:

<?php if(false != isset($content->images)): ?>

<?php print_r($content->images); ?>

<?php endif; ?>

But every time I try to skip when I've no results (i get a stdClass() empty) I fail. I tried isset, $content->images != NULL, !$content->images... I don't know how to do it to skip the "Severity: Notice Message: Undefined variable".

Thank you in advance.

UPDATE:

$content has more sets than images, like $content->_data or $content->title.

When I've NO images on database and i've no return from MySQL, doing this:

<?php echo count($content->images); ?>

<?php print_r($content->images); ?>

The output is:

1
stdClass ( )

Body:
I wanted to check if some object has all of the given properties. So I did this:

function hasAllProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc && property_exists($object, $property);
        },
        true
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAllProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";

Then in addition you may also want to check if just one or more of the properties exists:

function hasAnyProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc || property_exists($object, $property);
        },
        false
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAnyProperties($someObject, ['moo']) ? 'TRUE' : 'FALSE') . "\n";


问:
Unable to allocate new pages in table space "XXX" IBM DB2 SQL Replication
Product: IBM DB2

OS: Windows 2008 R2

I am trying to perform SQL replication on my database, I have created the capture tables, while I am trying to register the tables I got the following error message

[IBM][CLI Driver][DB2/NT64] SQL0289N  Unable to allocate new  pages in table space "xxxxxxx".  SQLSTATE=57011"

Thanks In advance.

答:
I suggest you to check the extent size of your tablespace. Run the following command SELECT TBSPACE, OWNER, EXTENTSIZE FROM SYSCAT.TABLESPACES This will give details of EXTENTSIZE of TABLESPACE. You may need to change the extent size depending on your requirements.

An extent is a block of storage within a table space container. It represents the number of pages of data that will be written to a container before writing to the next container. When you create a table space, you can choose the extent size based on your requirements for performance and storage management. See more details here


问:
Locating data volumes in Docker Desktop (Windows)
I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.

I'm using Docker Desktop for Windows. (Windows 10)

In the docs they say that running docker inspect on the object will give you the source:https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume

```<code>$ docker inspect web

"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]
</code>```

however I don't see this, I get the following:

```<code>$ docker inspect blog_postgres-data
[
    {
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/blog_postgres-data/_data",
        "Name": "blog_postgres-data",
        "Options": {},
        "Scope": "local"
    }
]
</code>```

Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?

答:
Your volume directory is /var/lib/docker/volumes/blog_postgres-data/_data, and /var/lib/docker usually mounted in C:\Users\Public\Documents\Hyper-V\Virtual hard disks. Anyway you can check it out by looking in Docker settings.

You can refer to these docs for info on how to share drives with Docker on Windows.

BTW, Source is the location on the host and Destination is the location inside the container in the following output:

```<code>"Mounts": [
{
    "Name": "fac362...80535",
    "Source": "/var/lib/docker/volumes/fac362...80535/_data",
    "Destination": "/webapp",
    "Driver": "local",
    "Mode": "",
    "RW": true,
    "Propagation": ""
}
]
</code>```

Updated to answer questions in the comment:

My main curiosity here is that sharing images etc is great but how do I share my data?

Actually volume is designed for this purpose (manage data in Docker container). The data in a volume is persisted on the host FS and isolated from the life-cycle of a Docker container/image. You can share your data in a volume by:

Mount Docker volume to host and reuse it

docker run -v /path/on/host:/path/inside/container image

Then all your data will persist in /path/on/host; you could back it up, copy it to another machine, and re-run your container with the same volume.

Create and mount a data container.

Create a data container: docker create -v /dbdata --name dbstore training/postgres /bin/true

Run other containers based on this container using --volumes-from: docker run -d --volumes-from dbstore --name db1 training/postgres, then all data generated by db1 will persist in the volume of container dbstore.

For more information you could refer to the official Docker volumes docs.

Simply speaking, volumes is just a directory on your host with all your container data, so you could use any method you used before to backup/share your data.

can I push a volume to docker-hub like I do with images?

No. A Docker image is something you can push to a Docker hub (a.k.a. 'registry'); but data is not. You could backup/persist/share your data with any method you like, but pushing data to a Docker registry to share it does not make any sense.

can I make backups etc?

Yes, as posted above :-)

Body:
I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.

I'm using Docker Desktop for Windows. (Windows 10)

In the docs they say that running docker inspect on the object will give you the source:https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume

$ docker inspect web

"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]

however I don't see this, I get the following:

$ docker inspect blog_postgres-data
[
    {
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/blog_postgres-data/_data",
        "Name": "blog_postgres-data",
        "Options": {},
        "Scope": "local"
    }
]

Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?

Body:
Your volume directory is /var/lib/docker/volumes/blog_postgres-data/_data, and /var/lib/docker usually mounted in C:\Users\Public\Documents\Hyper-V\Virtual hard disks. Anyway you can check it out by looking in Docker settings.

You can refer to these docs for info on how to share drives with Docker on Windows.

BTW, Source is the location on the host and Destination is the location inside the container in the following output:

"Mounts": [
{
    "Name": "fac362...80535",
    "Source": "/var/lib/docker/volumes/fac362...80535/_data",
    "Destination": "/webapp",
    "Driver": "local",
    "Mode": "",
    "RW": true,
    "Propagation": ""
}
]

Updated to answer questions in the comment:

My main curiosity here is that sharing images etc is great but how do I share my data?

Actually volume is designed for this purpose (manage data in Docker container). The data in a volume is persisted on the host FS and isolated from the life-cycle of a Docker container/image. You can share your data in a volume by:

Mount Docker volume to host and reuse it

docker run -v /path/on/host:/path/inside/container image

Then all your data will persist in /path/on/host; you could back it up, copy it to another machine, and re-run your container with the same volume.

Create and mount a data container.

Create a data container: docker create -v /dbdata --name dbstore training/postgres /bin/true

Run other containers based on this container using --volumes-from: docker run -d --volumes-from dbstore --name db1 training/postgres, then all data generated by db1 will persist in the volume of container dbstore.

For more information you could refer to the official Docker volumes docs.

Simply speaking, volumes is just a directory on your host with all your container data, so you could use any method you used before to backup/share your data.

can I push a volume to docker-hub like I do with images?

No. A Docker image is something you can push to a Docker hub (a.k.a. 'registry'); but data is not. You could backup/persist/share your data with any method you like, but pushing data to a Docker registry to share it does not make any sense.

can I make backups etc?

Yes, as posted above :-)


问:
What's the simplest way of returning the larger of two numbers?
Let's say I have an entity that looks like this:

```<code>public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}
</code>```

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}
</code>```

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}
</code>```

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

```<code>public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}
</code>```

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

答:
```<code>public DateTime LastActivity
{
    get { return Pictures.Select(x => x.LastUpdated).Concat(new DateTime[] { this.LastUpdated }).Max();
}
</code>```

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.


问:
REgULAR expression validation in angular
can i validate the string in angular?

please see the image below:

答:
Yes.

ngPattern is the easiest way of doing this.

You can pass either a regex literal or a regex string to ngPattern and it will validate the input using that regex.


问:
Why does greater than behave like this in Javascript?
I'm looking at Comparison operators in Javascript and came across these examples:

```<code>console.log(1 < 2 < 3);
</code>```

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

```<code>console.log(3 > 2 > 1);
</code>```

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?

答:
Because of the precedence of the operation from left to right, and the fach that
true is equivalent to (1)</p>

```<code>console.log(3 > 2 > 1);
3 > 2 => true;
console.log(true > 1 );
1 > 1 => false;
true > 1 => false;
</code>```

Body:
I'm looking at Comparison operators in Javascript and came across these examples:

console.log(1 < 2 < 3);

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

console.log(3 > 2 > 1);

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?

Body:
Because of the precedence of the operation from left to right, and the fach that
true is equivalent to (1)

console.log(3 > 2 > 1);
3 > 2 => true;
console.log(true > 1 );
1 > 1 => false;
true > 1 => false;


问:
passing loop of components to html in react
```<code>formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}
</code>```

This is my loop for multiple tr components which I am trying to display on the page as follows

```<code><TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />
</code>```

My transaction Row component:

```<code>import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (
      <tr key={key}>
            <td height="70"><span className="txt-spcng">19 Jan 17<br /><small className="grey-txt">19 Jan 17</small></span></td>
            <td>{transactionRowData.paymentId}</td>
            <td>KTU7-ZAUOSPZ</td>
            <td><span className="txt-limit">firstname.lastnasdsd</span></td>
            <td className="amnt-dbt">₹ {transactionRowData.amount}</td>
            <td><span className="txt-limit">Payment Successdd sdsd d</span></td>
            <td align="center"><div className="tl-tip"><a href="javscript:void(0)" className="icon-dotted"></a></div></td>
        </tr>
    )
}

export default TransactionTableRow
</code>```

But i get an error Each child in an array or iterator should have a unique "key" prop.

答:
There is not need for you to assing key to the table row in the TransactionTableRow component since you are already assigning to it inside the map. Also since key is a reserved attribute it is not passed down as a prop. Change you code to the following

```<code>formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}
</code>```

TransactionRow component

```<code>const TransactionTableRow = ({transactionRowData}) => {
    return (
      <tr>
            <td height="70"><span className="txt-spcng">19 Jan 17<br /><small className="grey-txt">19 Jan 17</small></span></td>
            <td>{transactionRowData.paymentId}</td>
            <td>KTU7-ZAUOSPZ</td>
            <td><span className="txt-limit">firstname.lastnasdsd</span></td>
            <td className="amnt-dbt">₹ {transactionRowData.amount}</td>
            <td><span className="txt-limit">Payment Successdd sdsd d</span></td>
            <td align="center"><div className="tl-tip"><a href="javscript:void(0)" className="icon-dotted"></a></div></td>
        </tr>
    )
}

export default TransactionTableRow
</code>```

Body:
formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}

This is my loop for multiple tr components which I am trying to display on the page as follows

<TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />

My transaction Row component:

import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (

            19 Jan 17
19 Jan 17
            {transactionRowData.paymentId}
            KTU7-ZAUOSPZ
            firstname.lastnasdsd
            ₹ {transactionRowData.amount}
            Payment Successdd sdsd d

    )
}

export default TransactionTableRow

But i get an error Each child in an array or iterator should have a unique "key" prop.

Body:
There is not need for you to assing key to the table row in the TransactionTableRow component since you are already assigning to it inside the map. Also since key is a reserved attribute it is not passed down as a prop. Change you code to the following

formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}

TransactionRow component

const TransactionTableRow = ({transactionRowData}) => {
    return (
      <tr>
            <td height="70"><span className="txt-spcng">19 Jan 17<br /><small className="grey-txt">19 Jan 17</small></span></td>
            <td>{transactionRowData.paymentId}</td>
            <td>KTU7-ZAUOSPZ</td>
            <td><span className="txt-limit">firstname.lastnasdsd</span></td>
            <td className="amnt-dbt">&#8377; {transactionRowData.amount}</td>
            <td><span className="txt-limit">Payment Successdd sdsd d</span></td>
            <td align="center"><div className="tl-tip"><a href="javscript:void(0)" className="icon-dotted"></a></div></td>
        </tr>
    )
}

export default TransactionTableRow


问:
Restarting a Python Interpreter Quietly
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.

I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.

I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).

So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?

Thanks,

Dan

答:
I'd suggest tackling the root cause problem.

"The application takes a long time to
  start up and I have no ability to
  restart the interpreter without
  restarting the whole application"

I doubt this is actually 100% true.  If the overall application is the result of an act of Congress, okay, it can't be changed.  But if the overall application was written by real people, then finding and moving the code to restart the Python interpreter should be possible.  It's cheaper, simpler and more reliable than anything else you might do to hack around the problem.

OwnerDisplayName: Dan

Title: Restarting a Python Interpreter Quietly

LastEditorDisplayName: Benoit


问:
Twitter Bootstrap Tab Selection Not Changing Content
Although there are plenty of Twitter Bootstrap questions open that regard similar issues to that which I'm having, I haven't been able to find any solutions to my particular issue.  I'm using the twitter bootstraps "tab" feature in order to display content, and while the script succeeds in changing the changing the active tab, the content remains the same.

Here's the code:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Hello, Tabs!</title>

        <link rel="stylesheet" href="public/css/bootstrap.min.css">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
        <script type="text/javascript" src="public/js/bootstrap.min.js"></script>
    </head>
    <body>

     <h3>Version Information:</h3>
     <div class="tabbable tabs-left">
         <ul class="nav nav-tabs" data-tabs="tabs">
             <li class="active">
                 <a href="#project/src/Graph/Graph.pm__0" data-toggle="tab">9424</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__1" data-toggle="tab">9058</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__2" data-toggle="tab">8928</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__3" data-toggle="tab">8926</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__4" data-toggle="tab">8924</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__5" data-toggle="tab">8890</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__6" data-toggle="tab">8889</a>
             </li>
             <li>
                 <a href="#project/src/Graph/Graph.pm__7" data-toggle="tab">8887</a>
             </li>
         </ul>
         <div class="tab-content">
             <div class="tab-pane active" id="project/src/Graph/Graph.pm__0">
                 <p>
                 Author: joe<br>
                 Version: v9424 (1:31 pm February 28, 2013)<br>
                 Action: Modified<br>
                 Message: Finalized a bit of the code... should be better now.<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__1">
                 <p>
                 Author: joe<br>
                 Version: v9058 (9:13 pm February 26, 2013)<br>
                 Action: Modified<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__2">
                 <p>
                 Author: joe<br>
                 Version: v8928 (2:08 am February 25, 2013)<br>
                 Action: Modified<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__3">
                 <p>
                 Author: joe<br>
                 Version: v8926 (1:14 am February 25, 2013)<br>
                 Action: Modified<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__4">
                 <p>
                 Author: joe<br>
                 Version: v8924 (10:26 pm February 24, 2013)<br>
                 Action: Modified<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__5">
                 <p>
                 Author: joe<br>
                 Version: v8890 (9:59 pm February 23, 2013)<br>
                 Action: Modified<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__6">
                 <p>
                 Author: joe<br>
                 Version: v8889 (9:53 pm February 23, 2013)<br>
                 Action: Added<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
             <div class="tab-pane" id="project/src/Graph/Graph.pm__7">
                 <p>
                 Author: joe<br>
                 Version: v8887 (9:40 pm February 23, 2013)<br>
                 Action: Added<br>
                 Message: Hello, world!<br>
                 </p>
             </div>
         </div>
     </div>

    <script type="text/javascript">
    jQuery(document).ready(function ($) {
        $('.nav-tabs').tab();
    });
    </script>
    </body>
</html>
</code>```

All the dependence files are loaded just fine when I run this (for reference, the version of bootstrap being used is 2.3.1).  I've been head-desking about this problem for quite some time now, so any help would be greatly appreciated.

EDIT: Here's a jsfiddle link containing the error code.

答: Just check the bootstrap version... it should be v2.3.1 +</p>

Body:
Although there are plenty of Twitter Bootstrap questions open that regard similar issues to that which I'm having, I haven't been able to find any solutions to my particular issue.  I'm using the twitter bootstraps "tab" feature in order to display content, and while the script succeeds in changing the changing the active tab, the content remains the same.

Here's the code:

<!DOCTYPE html>

        <title>Hello, Tabs!</title>

        <link rel="stylesheet" href="public/css/bootstrap.min.css">

Version Information:

                 9424

                 9058

                 8928

                 8926

                 8924

                 8890

                 8889

                 8887

                 Author: joe

                 Version: v9424 (1:31 pm February 28, 2013)

                 Action: Modified

                 Message: Finalized a bit of the code... should be better now.

                 Author: joe

                 Version: v9058 (9:13 pm February 26, 2013)

                 Action: Modified

                 Message: Hello, world!

                 Author: joe

                 Version: v8928 (2:08 am February 25, 2013)

                 Action: Modified

                 Message: Hello, world!

                 Author: joe

                 Version: v8926 (1:14 am February 25, 2013)

                 Action: Modified

                 Message: Hello, world!

                 Author: joe

                 Version: v8924 (10:26 pm February 24, 2013)

                 Action: Modified

                 Message: Hello, world!

                 Author: joe

                 Version: v8890 (9:59 pm February 23, 2013)

                 Action: Modified

                 Message: Hello, world!

                 Author: joe

                 Version: v8889 (9:53 pm February 23, 2013)

                 Action: Added

                 Message: Hello, world!

                 Author: joe

                 Version: v8887 (9:40 pm February 23, 2013)

                 Action: Added

                 Message: Hello, world!

All the dependence files are loaded just fine when I run this (for reference, the version of bootstrap being used is 2.3.1).  I've been head-desking about this problem for quite some time now, so any help would be greatly appreciated.

EDIT: Here's a jsfiddle link containing the error code.


问:
Insert an object to excel by using python
I want to add some object to my excel sheet,
I'm using openpyxl,
In excel you do it by:
Insert->Object

Is there a way to do it thru openpyxl or any other excel tool that working with python?

答:
```<code>import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]

picture = openpyxl.drawing.Image('/path/to/picture')
picture.anchor(ws.cell('cell to put the image'))
ws.add_image(picture)

wb.save('whatever you want to save the workbook as')
</code>```

This code of course refers to creating a new workbook and adding the image into it. To add the image to your preexisting workbook you would obviously just load that workbook using load_workbook.

Body:
import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]

picture = openpyxl.drawing.Image('/path/to/picture')
picture.anchor(ws.cell('cell to put the image'))
ws.add_image(picture)

wb.save('whatever you want to save the workbook as')

This code of course refers to creating a new workbook and adding the image into it. To add the image to your preexisting workbook you would obviously just load that workbook using load_workbook.


问:
webpack2 tree-shaking with knockout templates
I am using webpack to bundle my typescript project and I am using knockout as my templating engine.

Now, when I build my project for production it stops working - a knockout template is complaining that a property is not defined.

I have the suspicion that the tree-shaking algorithm of webpack2 is removing that property because it isn't used in any typescript code, but only in a knockout data-bind string.

Is there a way to tell webpack to always include a certain property even when it thinks it isn't used?

答:
I'm not that familiar with webpack, but I've ran in to the same problem with google closure compiler. It would remove properties only used in data-binds and obfuscate others...

The solution direction that worked for me was one that knockout itself also uses in its source: ko.exportProperty

It's used like so:

```<code>var VM = function() {
  this.somePropOnlyUsedInView = "Hello world";

  ko.exportProperty(this, "somePropOnlyUsedInView", this.somePropOnlyUsedInView);
}
</code>```

The method does two things:

It uses the obj["string"] notation to force the property name

It actually references the property, making the minifier think it is used and cannot be removed.

Let me know if this utility also works for your webpack based build process, I'm curious to know.

Body:
I'm not that familiar with webpack, but I've ran in to the same problem with google closure compiler. It would remove properties only used in data-binds and obfuscate others...

The solution direction that worked for me was one that knockout itself also uses in its source: ko.exportProperty

It's used like so:

var VM = function() {
  this.somePropOnlyUsedInView = "Hello world";

  ko.exportProperty(this, "somePropOnlyUsedInView", this.somePropOnlyUsedInView);
}

The method does two things:

It uses the obj["string"] notation to force the property name

It actually references the property, making the minifier think it is used and cannot be removed.

Let me know if this utility also works for your webpack based build process, I'm curious to know.