问:
How do I create ENTITY references in the DOCTYPE using perl/LibXML
I'm trying to create the following DTD containing entity declarations:

```<code><!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd"
[ <!ENTITY icon.url "https://example.com/icon.png">
<!ENTITY base.url "https://example.com/content/" > ]>
</code>```

I can successfully create the DOCTYPE without the entity references:

```<code>#!/usr/bin/perl -w
use strict;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0','UTF-8');
my $dtd = $doc->createInternalSubset( "LinkSet", "-//NLM//DTD LinkOut 1.0//EN", "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd" );

my $ls = $doc->createElement( "LinkSet" );
$doc->setDocumentElement($ls);

print $doc->toString;
exit;
</code>```

Results in:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd">
<LinkSet/>
</code>```

The XML::LibXML documentation shows how to add an entity reference to a document, but not how to declare an entity in the DOCTYPE.

A similar (but PHP-based) question points to creating the ENTITY references as a string and parsing that.
Is this the best approach in Perl too?

答:
The documentation for XML::LibXML::Document
says this

[The Document Class] inherits all functions from XML::LibXML::Node as specified in the DOM
  specification. This enables access to the nodes besides the root element
  on document level - a "DTD" for example. The support for these nodes is
  limited at the moment.

It also makes it clear later on that the source of these limitations is libxml2 itself, not the Perl module. This makes sense, as the DTD has a completely different syntax from XML (or even an XML Processing Instruction) even though it may look superficially similar.

The only way appears to be to parse a basic document with the required DTD and work with that

Like so

use strict;
use warnings 'all';

use XML::LibXML;

my $doc = XML::LibXML->load_xml(string => <<__END_XML__);
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd"
[
  <!ENTITY icon.url "https://example.com/icon.png">
  <!ENTITY base.url "https://example.com/content/">
]>

<LinkSet/>
__END_XML__

print $doc;
```

<h3>output</h3>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd" [
<!ENTITY icon.url "https://example.com/icon.png">
<!ENTITY base.url "https://example.com/content/">
]>
<LinkSet/>
</code>```

Body:
I'm trying to create the following DTD containing entity declarations:

<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd"
[ <!ENTITY icon.url "https://example.com/icon.png">
<!ENTITY base.url "https://example.com/content/" > ]>

I can successfully create the DOCTYPE without the entity references:

#!/usr/bin/perl -w
use strict;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0','UTF-8');
my $dtd = $doc->createInternalSubset( "LinkSet", "-//NLM//DTD LinkOut 1.0//EN", "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd" );

my $ls = $doc->createElement( "LinkSet" );
$doc->setDocumentElement($ls);

print $doc->toString;
exit;

Results in:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd">
<LinkSet/>

The XML::LibXML documentation shows how to add an entity reference to a document, but not how to declare an entity in the DOCTYPE.

A similar (but PHP-based) question points to creating the ENTITY references as a string and parsing that.
Is this the best approach in Perl too?

Body:
The documentation for XML::LibXML::Document
says this

[The Document Class] inherits all functions from XML::LibXML::Node as specified in the DOM
  specification. This enables access to the nodes besides the root element
  on document level - a "DTD" for example. The support for these nodes is
  limited at the moment.

It also makes it clear later on that the source of these limitations is libxml2 itself, not the Perl module. This makes sense, as the DTD has a completely different syntax from XML (or even an XML Processing Instruction) even though it may look superficially similar.

The only way appears to be to parse a basic document with the required DTD and work with that

Like so

use strict;
use warnings 'all';

use XML::LibXML;

my $doc = XML::LibXML->load_xml(string => <<__END_XML__);
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd"
[
  <!ENTITY icon.url "https://example.com/icon.png">
  <!ENTITY base.url "https://example.com/content/">
]>

<LinkSet/>
__END_XML__

print $doc;

output

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE LinkSet PUBLIC "-//NLM//DTD LinkOut 1.0//EN" "https://www.ncbi.nlm.nih.gov/projects/linkout/doc/LinkOut.dtd" [
<!ENTITY icon.url "https://example.com/icon.png">
<!ENTITY base.url "https://example.com/content/">
]>
<LinkSet/>


来源: stackexchange

问:
error creating bean with name employeeController. injection of autowired dependencies failed. could not autowire fields
Error From Console

```<code> SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed;
  nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ram.service.EmployeeService com.ram.controller.EmployeeController.employeeService;
  nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed;
  nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ram.dao.EmployeeDao com.ram.service.EmployeeServiceImpl.employeeDao;
  nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed;
</code>```

EmployeeController.java

```<code>@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Qualifier(value="employeeService")
    public void setEmployeeService(EmployeeService employeeService){
        this.employeeService = employeeService;
    }

    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public String listEmployee(Model model) {
        model.addAttribute("employee", new Employee());
        model.addAttribute("listEmployee", employeeService.listEmployee());
        return "employee";
    }
</code>```

答:
This line is most imporatant from the log. Unfortunately, the log is incomplete, so it's unclear which property of EmployeeDao is missing:

```<code>nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed;
</code>```

What fields are you mapping into EmployeeDao? Because one of those cannot be found, perhaps not marked with @Component?

ContentLicense: CC BY-SA 3.0

Body:
Error From Console

 SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed;
  nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ram.service.EmployeeService com.ram.controller.EmployeeController.employeeService;
  nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed;
  nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ram.dao.EmployeeDao com.ram.service.EmployeeServiceImpl.employeeDao;
  nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed;

EmployeeController.java

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Qualifier(value="employeeService")
    public void setEmployeeService(EmployeeService employeeService){
        this.employeeService = employeeService;
    }

    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public String listEmployee(Model model) {
        model.addAttribute("employee", new Employee());
        model.addAttribute("listEmployee", employeeService.listEmployee());
        return "employee";
    }

Body:
This line is most imporatant from the log. Unfortunately, the log is incomplete, so it's unclear which property of EmployeeDao is missing:

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed;

What fields are you mapping into EmployeeDao? Because one of those cannot be found, perhaps not marked with @Component?


问:
How to Override Node Bootstrap styles in Rails 5.1?
When using the "new" Rails 5.1 Paradigm of Yarn & Webpack: If I include bootstrap using Yarn (NOT using a gem) as follows:

```<code>yarn add jquery
yarn add bootstrap
</code>```

Then with application.js of:

```<code>*= require bootstrap/dist/css/bootstrap
</code>```

Everything seems to be working great... Except overriding a bootstrap style.

What is the proper way now to override a style that is provided by bootstrap (e.g. a body style that comes from /bootstrap/less/scaffolding.less)

Anything put in a .css file in /app/assets/stylesheets such as before_bootstrap.css:

```<code>body {
  background-color: #333;
}
</code>```

gets overridden by the style in scaffolding.less, regardless of whether you require that css file before or after the application.css line:

```<code>  *= require_tree .
  *= require_self
  *= require before_bootstrap
  *= require bootstrap/dist/css/bootstrap
  *= require after_bootstrap
</code>```

The old way, I suppose, would have been to use a bootstrap_and_overrides.css file and @import ??? but I don't see how that works with the node/webpack paradigm.

答:
Ok, I have this working, here's what I did:

Added my sass files (variables, the bootswatch file, and some globals) to the /app/javascripts root folder

Created an packs/app pack folder as my projects base pack

in that pack folder:

Created index.js where my import statements are

Created styles.scss where sass import statements are

My styles.scss starts with:

```<code>@import "../../variables.scss";

$icon-font-path: "~bootstrap-sass/assets/fonts/bootstrap/";
@import "~bootstrap-sass/assets/stylesheets/_bootstrap.scss";

@import "../../bootswatch.scss";
@import "../../utils.scss";
</code>```

which is working great, loads base bootstrap, followed by the bootswatch, and variables stick.

As the project progresses i'll make new pack folders if necessary for specific functionality, though this is a pretty pure "rails" app, so we'll see as it grows.

Body:
When using the "new" Rails 5.1 Paradigm of Yarn & Webpack: If I include bootstrap using Yarn (NOT using a gem) as follows:

yarn add jquery
yarn add bootstrap

Then with application.js of:

*= require bootstrap/dist/css/bootstrap

Everything seems to be working great... Except overriding a bootstrap style.

What is the proper way now to override a style that is provided by bootstrap (e.g. a body style that comes from /bootstrap/less/scaffolding.less)

Anything put in a .css file in /app/assets/stylesheets such as before_bootstrap.css:

body {
  background-color: #333;
}

gets overridden by the style in scaffolding.less, regardless of whether you require that css file before or after the application.css line:

  *= require_tree .
  *= require_self
  *= require before_bootstrap
  *= require bootstrap/dist/css/bootstrap
  *= require after_bootstrap

The old way, I suppose, would have been to use a bootstrap_and_overrides.css file and @import ??? but I don't see how that works with the node/webpack paradigm.

Body:
Ok, I have this working, here's what I did:

Added my sass files (variables, the bootswatch file, and some globals) to the /app/javascripts root folder

Created an packs/app pack folder as my projects base pack

in that pack folder:

Created index.js where my import statements are

Created styles.scss where sass import statements are

My styles.scss starts with:

@import "../../variables.scss";

$icon-font-path: "~bootstrap-sass/assets/fonts/bootstrap/";
@import "~bootstrap-sass/assets/stylesheets/_bootstrap.scss";

@import "../../bootswatch.scss";
@import "../../utils.scss";

which is working great, loads base bootstrap, followed by the bootswatch, and variables stick.

As the project progresses i'll make new pack folders if necessary for specific functionality, though this is a pretty pure "rails" app, so we'll see as it grows.


问:
Rspec: execute code in let and return value
I have a following code for assigning value to variable before execute test:

```<code> let!(:cash_payment){
    cash_payment = PaymentMethod.find_by_id(1)
    create(:payment_method, :cash) unless cash_payment
    return cash_payment
  }
</code>```

The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment. So after that, in my test, reference to cash_payment will be nil. Please tell me how.

答:
The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment.

Not true.

So after that, in my test, reference to cash_payment will be nil

This only happens when you don't have any payment methods in the database (PaymentMethod.find_by_id(1) returns nil).

If that happens, you want to create a payment method from a factory girl, but you fail to assign it to anything. This value is ignored.

```<code>create(:payment_method, :cash) unless cash_payment
</code>```

Should be more like

```<code>cash_payment ||= create(:payment_method, :cash)
</code>```

Then it'd work. Alternatively, use what @gabrielhilal suggests. That one is good too.

Body:
I have a following code for assigning value to variable before execute test:

 let!(:cash_payment){
    cash_payment = PaymentMethod.find_by_id(1)
    create(:payment_method, :cash) unless cash_payment
    return cash_payment
  }

The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment. So after that, in my test, reference to cash_payment will be nil. Please tell me how.

Body:
The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment.

Not true.

So after that, in my test, reference to cash_payment will be nil

This only happens when you don't have any payment methods in the database (PaymentMethod.find_by_id(1) returns nil).

If that happens, you want to create a payment method from a factory girl, but you fail to assign it to anything. This value is ignored.

create(:payment_method, :cash) unless cash_payment

Should be more like

cash_payment ||= create(:payment_method, :cash)

Then it'd work. Alternatively, use what @gabrielhilal suggests. That one is good too.


问:
Get *File from an image hosted at AWS with Golang
I can succeffully list all files(jpg photos) inside a S3 Bucket and make an []s3.Objects with it. Now I want to get a pointer to file from one of those photos, but I still cannot download them.

```<code>package main

import (
    "fmt"
    "log"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "os"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/s3"
    //"github.com/aws/aws-sdk-go/service/s3/s3manager"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
)

func main() {
    acess := "***********"
    secret := "******"
    log.Println(acess + secret)
    creds := credentials.NewStaticCredentials(acess, secret, "")
    _, err := creds.Get()

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    sess := s3.New(session.New(), &aws.Config{
        Credentials: creds,
        Region: aws.String("sa-east-1"),
        //LogLevel:    aws.LogLevel(aws.LogDebug),
    })

    params := &s3.ListObjectsInput{
        Bucket: aws.String("cescocats"),
    }
    //

    resp, err := sess.ListObjects(params)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    var allPhotos []s3.Object

    //log.Println(resp.String())
    for _, key := range resp.Contents {
        allPhotos = append(allPhotos, *key)
    }

    log.Println(allPhotos)
    // Set up a new s3manager client

    manager := s3manager.NewDownloader(session.New(), func(d *s3manager.Downloader) {
        d.PartSize = 1 * 1024 * 1024 // 64MB per part
    })
    log.Println(manager)
    buff := new([]byte)

    hehe := s3.GetObjectInput{Key:allPhotos[0].Key}
    manager.Download(aws.WriteAtBuffer{}, hehe)

}
</code>```

How do download a file from S3 using github.com/aws/aws-sdk-go ? Is there any other way? Do I really need to download the file to get its content?

答:
Try something like this:

```<code>log.Printf("Fetching s3://%v/%v", bucket, key)

buff := &aws.WriteAtBuffer{}
s3dl := s3manager.NewDownloader(sess)
_, err := s3dl.Download(buff, &s3.GetObjectInput{
    Bucket: aws.String(bucket),
    Key:    aws.String(key),
})

if err != nil {
    log.Printf("Could not download from S3: %v", err)
}
</code>```

Then you can get the contents as buff.Bytes()

Body:
I can succeffully list all files(jpg photos) inside a S3 Bucket and make an []s3.Objects with it. Now I want to get a pointer to file from one of those photos, but I still cannot download them.

package main

import (
    "fmt"
    "log"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "os"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/s3"
    //"github.com/aws/aws-sdk-go/service/s3/s3manager"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
)

func main() {
    acess := "***********"
    secret := "******"
    log.Println(acess + secret)
    creds := credentials.NewStaticCredentials(acess, secret, "")
    _, err := creds.Get()

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    sess := s3.New(session.New(), &aws.Config{
        Credentials: creds,
        Region: aws.String("sa-east-1"),
        //LogLevel:    aws.LogLevel(aws.LogDebug),
    })

    params := &s3.ListObjectsInput{
        Bucket: aws.String("cescocats"),
    }
    //

    resp, err := sess.ListObjects(params)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    var allPhotos []s3.Object

    //log.Println(resp.String())
    for _, key := range resp.Contents {
        allPhotos = append(allPhotos, *key)
    }

    log.Println(allPhotos)
    // Set up a new s3manager client

    manager := s3manager.NewDownloader(session.New(), func(d *s3manager.Downloader) {
        d.PartSize = 1 * 1024 * 1024 // 64MB per part
    })
    log.Println(manager)
    buff := new([]byte)

    hehe := s3.GetObjectInput{Key:allPhotos[0].Key}
    manager.Download(aws.WriteAtBuffer{}, hehe)

}

How do download a file from S3 using github.com/aws/aws-sdk-go ? Is there any other way? Do I really need to download the file to get its content?

Body:
Try something like this:

log.Printf("Fetching s3://%v/%v", bucket, key)

buff := &aws.WriteAtBuffer{}
s3dl := s3manager.NewDownloader(sess)
_, err := s3dl.Download(buff, &s3.GetObjectInput{
    Bucket: aws.String(bucket),
    Key:    aws.String(key),
})

if err != nil {
    log.Printf("Could not download from S3: %v", err)
}

Then you can get the contents as buff.Bytes()


问:
fly-out menu from collapsable sidebar menu
Im trying to create a flyout sub menu from a collapsible sidebar menu but the flyout menu wont display completely because the width of the sidebar is too small. How can i have the flyout without changing the sidebar width?

```<code><div class="sidebar_menu">
  <i class="fa fa-times">x</i>
  <a id="logo_image" href="index.html"></a>
  <ul class="navigation_selection">
    <li class="nav_item"><a class="current"href="index.html">Home</a></li>
    <li class="nav_item" id="work"><a href="#">Work</a>
      <ul id="sub_menu">
        <li class="nav_item drop_item"><a href="#">Residential</a></li>
        <li class="nav_item drop_item"><a href="#">Commercial</a></li>
        <li class="nav_item drop_item"><a href="#">Historical</a></li>
      </ul>
    </li>
    <li class="nav_item"><a href="#">About</a></li>
    <li class="nav_item"><a href="#">Contact</a></li>
  </ul>
</div>
</code>```

```<code>    *{
  padding: 0;
  margin: 0;
  text-decoration: none;
  list-style: none;
}

body{
  background: #f5f5f5;
  background-size: cover;
}

.toggle_menu{
  position: fixed;
  padding: 15px 15px 15px 15px;
  margin: 20px;
  color: #f5f5f5;
  background-color: #05CC56;
  cursor: pointer;
  z-index: 10000000;
  font-size: 100%;
  opacity: 0;
  text-align: center;
  box-shadow: 1px 0px 5px #000;
}

.sidebar_menu{
  color: #f5f5f5;
  position: fixed;
  width: 250px;
  margin-left: 0;
  height: 100vh;
  overflow: hidden;
  background-color: rgba(17, 45, 17, 0.8);
  transition: all 0.3s ease-in-out;
  padding: 5px;
  border-right: solid 3px #05CC56;
  z-index: 100000;
  box-shadow: 1px 0px 5px #000;}

.fa-times{
  right: 10px;
  top: 10px;
  opacity: 0.5;
  cursor: pointer;
  position: absolute;
  color: #fff;
  transition: all 0.3s ease-in-out;
}

.fa-times:hover{
  opacity: 1;
}

.opacity_one:hover{
  opacity: 1;
}

#logo_image{
  float: left;
  background: url(../img/DDCLogo.png) no-repeat center;
  background-size:  200px auto;
  height: 100px;
  width: 250px;
  z-index: 10000;
  margin-bottom: 30px;
}

.navigation_selection{
  margin: 0 0;
  display: block;
  width: 200px;
  margin-left: 25px;
}

.sidebar_menu > ul > li > ul{
  margin: 0;
  padding: 0;
  width: 0;
  height: 0;
  z-index: 1000000000;
  position: relative;
  left: -200px;

}

.sidebar_menu ul > li:hover > ul{
  width:200px;
  display:block;
  position:relative;
  top:0;
  border: 0;
  left:200px;
  z-index: 1000000000;
}

.sidebar_menu ul > li:hover > ul > li > a{
  background:#e8e8e8;
}

.nav_item{
  font-weight: 200;
  font-family: 'Open Sans';
  color: #f5f5f5;
  padding: 12px 0;
  box-sizing: border-box;
  font-size: 14px;
  color: #d8d8d8;
  border-bottom: solid 1px #f5f5f5;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  width: 100%;
}

.nav_item > a{
  display: block;
  color: #f5f5f5;
  transition: all 0.4s ease-in-out;
  width: 100%;
}

.nav_item > .current{
  color: #05CC56;
}

.nav_item:hover > a{
  color: #05CC56;
  margin-left: 10px;
  transition: all 0.4s ease-in-out;
}

.hide_menu{
  margin-left: -270px;
}

.opacity_one{
  opacity: 0.5;
  transition: all 0.3s ease-in-out;
}

.slide > img{
  width: 100vw;
  height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  object-fit: cover;
  z-index: 1;
}

.cycle-slideshow{
  width: 100%;
  height: 100vh;
  display: block;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.sidebar_menu > h2{
  font-family: 'Open Sans';
  font-weight: 400;
  margin-left: 25px;
  color: #fff;
  position:
}

.box{
  font-family: 'Open Sans';
  color: #f5f5f5;
  position: absolute;
  bottom: 20px;
  right: 0;
  background-color: #4e5054;
  height: 20%;
  width: 35%;
  z-index: 9999;
  opacity: 0.75;
  overflow: scroll;
  padding: 5px 5px 5px 40px;
  box-shadow: 1px 0px 5px #000;
}

.box > h3{
  font-weight: lighter;
  padding: 0 0 10px 0
}

.foot{
  position: absolute;
  bottom: 0;
  margin-left: 25px;
  margin-bottom: 20px;
  font-size: 10px;
  font-family: 'Open Sans';
  color: #05CC56;
  text-decoration: none;
  font-weight: 200;
}

.foot > a{
  color: #05CC56;
}

.logo{
  position: absolute;
  bottom: 15px;
  left: 15px;
  width: 45%;
  z-index: 10000000;
  opacity: 0;
  transition: all 0.3s ease-in-out;
}

.logo_show{
  opacity: 0.8;
  transition: all 0.3s ease-in-out;
}

@media only screen and (max-width: 500px) {
    body {
        display: none;
    }
}
</code>```

https://jsfiddle.net/9jc9tsqm/

Ignore all the unused styles.

答: Yes, remove overflow:hidden from .sidebar_menu, but you should also delete the height:0 of the #sub_menu and make it's position absolute. Give nav_item a position of relative. That way you can add a background color and what not to the #sub_menu or other stylings if you want.</p>

Body:
Im trying to create a flyout sub menu from a collapsible sidebar menu but the flyout menu wont display completely because the width of the sidebar is too small. How can i have the flyout without changing the sidebar width?

  x

Home

Work

Residential

Commercial

Historical

About

Contact

    *{
  padding: 0;
  margin: 0;
  text-decoration: none;
  list-style: none;
}

body{
  background: #f5f5f5;
  background-size: cover;
}

.toggle_menu{
  position: fixed;
  padding: 15px 15px 15px 15px;
  margin: 20px;
  color: #f5f5f5;
  background-color: #05CC56;
  cursor: pointer;
  z-index: 10000000;
  font-size: 100%;
  opacity: 0;
  text-align: center;
  box-shadow: 1px 0px 5px #000;
}

.sidebar_menu{
  color: #f5f5f5;
  position: fixed;
  width: 250px;
  margin-left: 0;
  height: 100vh;
  overflow: hidden;
  background-color: rgba(17, 45, 17, 0.8);
  transition: all 0.3s ease-in-out;
  padding: 5px;
  border-right: solid 3px #05CC56;
  z-index: 100000;
  box-shadow: 1px 0px 5px #000;}

.fa-times{
  right: 10px;
  top: 10px;
  opacity: 0.5;
  cursor: pointer;
  position: absolute;
  color: #fff;
  transition: all 0.3s ease-in-out;
}

.fa-times:hover{
  opacity: 1;
}

.opacity_one:hover{
  opacity: 1;
}

#logo_image{
  float: left;
  background: url(../img/DDCLogo.png) no-repeat center;
  background-size:  200px auto;
  height: 100px;
  width: 250px;
  z-index: 10000;
  margin-bottom: 30px;
}

.navigation_selection{
  margin: 0 0;
  display: block;
  width: 200px;
  margin-left: 25px;
}

.sidebar_menu > ul > li > ul{
  margin: 0;
  padding: 0;
  width: 0;
  height: 0;
  z-index: 1000000000;
  position: relative;
  left: -200px;

}

.sidebar_menu ul > li:hover > ul{
  width:200px;
  display:block;
  position:relative;
  top:0;
  border: 0;
  left:200px;
  z-index: 1000000000;
}

.sidebar_menu ul > li:hover > ul > li > a{
  background:#e8e8e8;
}

.nav_item{
  font-weight: 200;
  font-family: 'Open Sans';
  color: #f5f5f5;
  padding: 12px 0;
  box-sizing: border-box;
  font-size: 14px;
  color: #d8d8d8;
  border-bottom: solid 1px #f5f5f5;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  width: 100%;
}

.nav_item > a{
  display: block;
  color: #f5f5f5;
  transition: all 0.4s ease-in-out;
  width: 100%;
}

.nav_item > .current{
  color: #05CC56;
}

.nav_item:hover > a{
  color: #05CC56;
  margin-left: 10px;
  transition: all 0.4s ease-in-out;
}

.hide_menu{
  margin-left: -270px;
}

.opacity_one{
  opacity: 0.5;
  transition: all 0.3s ease-in-out;
}

.slide > img{
  width: 100vw;
  height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  object-fit: cover;
  z-index: 1;
}

.cycle-slideshow{
  width: 100%;
  height: 100vh;
  display: block;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.sidebar_menu > h2{
  font-family: 'Open Sans';
  font-weight: 400;
  margin-left: 25px;
  color: #fff;
  position:
}

.box{
  font-family: 'Open Sans';
  color: #f5f5f5;
  position: absolute;
  bottom: 20px;
  right: 0;
  background-color: #4e5054;
  height: 20%;
  width: 35%;
  z-index: 9999;
  opacity: 0.75;
  overflow: scroll;
  padding: 5px 5px 5px 40px;
  box-shadow: 1px 0px 5px #000;
}

.box > h3{
  font-weight: lighter;
  padding: 0 0 10px 0
}

.foot{
  position: absolute;
  bottom: 0;
  margin-left: 25px;
  margin-bottom: 20px;
  font-size: 10px;
  font-family: 'Open Sans';
  color: #05CC56;
  text-decoration: none;
  font-weight: 200;
}

.foot > a{
  color: #05CC56;
}

.logo{
  position: absolute;
  bottom: 15px;
  left: 15px;
  width: 45%;
  z-index: 10000000;
  opacity: 0;
  transition: all 0.3s ease-in-out;
}

.logo_show{
  opacity: 0.8;
  transition: all 0.3s ease-in-out;
}

@media only screen and (max-width: 500px) {
    body {
        display: none;
    }
}

https://jsfiddle.net/9jc9tsqm/

Ignore all the unused styles.


问:
How to replace occurrences with javascript inside delimiters?
How to replace all occurrences that are within two characters.
Example:

```<code>I love :octocat: beach and you do :joy: not like it
</code>```

Replace with a url that will be generated based on what's inside the delimiters

```<code>I love [img of octocat] beach and you do [img of joy] not like it
</code>```

Javascript needs to capture what's inside : and replace

I've tried several things without success. can anybody help me?

答:
Lucky for you String.prototype.replace accepts a RegExp and a function. So, in your example you can write a regex to find strings between 2 characters and replace them.

The RegEx for your example using colons would simply be /:(.*?):/g, and you could do whatever you want in your function, e.g. replace the string with the string + additional characters. e.g.

```<code>var str = "I love :octocat: beach and you do :joy: not like it"
str = str.replace(/:(.*?):/ig, function (str){
  return str + 'BLAHBLAHBLAH'
})
</code>```

The value of str is now "I love :octocat:BLAHBLAHBLAH beach and you do :joy:BLAHBLAHBLAH not like it", fun stuff eh?

Body:
How to replace all occurrences that are within two characters.
Example:

I love :octocat: beach and you do :joy: not like it

Replace with a url that will be generated based on what's inside the delimiters

I love [img of octocat] beach and you do [img of joy] not like it

Javascript needs to capture what's inside : and replace

I've tried several things without success. can anybody help me?

Body:
Lucky for you String.prototype.replace accepts a RegExp and a function. So, in your example you can write a regex to find strings between 2 characters and replace them.

The RegEx for your example using colons would simply be /:(.*?):/g, and you could do whatever you want in your function, e.g. replace the string with the string + additional characters. e.g.

var str = "I love :octocat: beach and you do :joy: not like it"
str = str.replace(/:(.*?):/ig, function (str){
  return str + 'BLAHBLAHBLAH'
})

The value of str is now "I love :octocat:BLAHBLAHBLAH beach and you do :joy:BLAHBLAHBLAH not like it", fun stuff eh?


问:
Can e-mail (SMTP) be sent directly over RS-232
I'm in somewhat of an odd situation here. I'm looking to send SMTP e-mails from a remote embedded system which is directly connected to an iridium modem into a local server. The current system sends files in chunks of data and I don't know exactly how this would work with e-mail. I was thinking of using mutt to send attachments (.wav or .jpeg files), but again I don't know if this works without direct internet access. If anyone has any idea if this is possible, please let me know.

Edit: I'm using RUDICS communication, not a SBD modem

Thanks

答: It's possible but somewhat complex. You would need to setup a PPP connection with the modem and then email would be able to flow across the serial line to the other server.</p>


问:
Can't merge two lists into a dictionary
I can't merge two lists into a dictionary.I tried the following :

Map two lists into a dictionary in Python

I tried all solutions and I still get an empty dictionary

```<code>from sklearn.feature_extraction import DictVectorizer
from itertools import izip
import itertools

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

diction = dict(itertools.izip(words,lines))
new_dict = {k: v for k, v in zip(words, lines)}
print new_dict
</code>```

I get the following :

{'word': ''}
['word=']

The two lists are not empty.

I'm using python2.7

EDIT :

Output from the two lists (I'm only showing a few because it's a vector with 11k features)

```<code>//lines
['change', 'I/O', 'fcnet2', 'ifconfig',....
//words
['word', 'word', 'word', .....
</code>```

EDIT :

Now at least I have some output @DamianLattenero

```<code>{'word\n': 'XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'}
['word\n=XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n']
</code>```

答:
I tryed this and worked for me, I created two files, added numbers 1 to 4, letters a to d, and the code creates the dictionary ok, I didn't need to import itertools, actually there is an extra line not needed:

```<code>lines = [1,2,3,4]
words = ["a","b","c","d"]

diction = dict(zip(words,lines))
# new_dict = {k: v for k, v in zip(words, lines)}
print(diction)
</code>```

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

If that worked, and not the other, you must have a problem in loading the list, try loading like this:

```<code>def create_list_from_file(file):
  with open(file, "r") as ins:
    my_list = []
    for line in ins:
      my_list.append(line)
    return my_list

lines = create_list_from_file("/home/vesko_/evnt_classification/bag_of_words")
words = create_list_from_file("/home/vesko_/evnt_classification/sdas")

diction = dict(zip(words,lines))
# new_dict = {k: v for k, v in zip(words, lines)}
print(diction)
</code>```

Observation:
  If you files.txt looks like this:

```<code>1
2
3
4
</code>```

and

```<code>a
b
c
d
</code>```

the result will have for keys in the dictionary, one per line:

```<code>{'a\n': '1\n', 'b\n': '2\n', 'c\n': '3\n', 'd': '4'}
</code>```

But if you file looks like:

```<code>1 2 3 4
</code>```

and

```<code>a b c d
</code>```

the result will be {'a b c d': '1 2 3 4'}, only one value

Title: Can't merge two lists into a dictionary

Body:
I can't merge two lists into a dictionary.I tried the following :

Map two lists into a dictionary in Python

I tried all solutions and I still get an empty dictionary

from sklearn.feature_extraction import DictVectorizer
from itertools import izip
import itertools

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r")
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r")
lines = text_file.read().split('\n')
words = text_fiel2.read().split('\n')

diction = dict(itertools.izip(words,lines))
new_dict = {k: v for k, v in zip(words, lines)}
print new_dict

I get the following :

{'word': ''}
['word=']

The two lists are not empty.

I'm using python2.7

EDIT :

Output from the two lists (I'm only showing a few because it's a vector with 11k features)

//lines
['change', 'I/O', 'fcnet2', 'ifconfig',....
//words
['word', 'word', 'word', .....

EDIT :

Now at least I have some output @DamianLattenero

{'word\n': 'XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'}
['word\n=XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n']

Body:
I tryed this and worked for me, I created two files, added numbers 1 to 4, letters a to d, and the code creates the dictionary ok, I didn't need to import itertools, actually there is an extra line not needed:

lines = [1,2,3,4]
words = ["a","b","c","d"]

diction = dict(zip(words,lines))
# new_dict = {k: v for k, v in zip(words, lines)}
print(diction)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

If that worked, and not the other, you must have a problem in loading the list, try loading like this:

def create_list_from_file(file):
  with open(file, "r") as ins:
    my_list = []
    for line in ins:
      my_list.append(line)
    return my_list

lines = create_list_from_file("/home/vesko_/evnt_classification/bag_of_words")
words = create_list_from_file("/home/vesko_/evnt_classification/sdas")

diction = dict(zip(words,lines))
# new_dict = {k: v for k, v in zip(words, lines)}
print(diction)

Observation:
  If you files.txt looks like this:

1
2
3
4

and

a
b
c
d

the result will have for keys in the dictionary, one per line:

{'a\n': '1\n', 'b\n': '2\n', 'c\n': '3\n', 'd': '4'}

But if you file looks like:

1 2 3 4

and

a b c d

the result will be {'a b c d': '1 2 3 4'}, only one value


问:
Authenticating ldap user with multiple suffix value/domain
I am trying to authenticate and then query AD tree using Spring Ldap Security and Spring Ldap.

Following is my configuration file -

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:ldap="http://www.springframework.org/schema/ldap"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <http use-expressions="true">
        <form-login login-page="/myApp/ldap" default-target-url="/myApp/ldap/config"
            authentication-failure-url="/myApp/ldap?error=true" />
        <logout />
    </http>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <beans:bean id="adAuthenticationProvider" scope="prototype"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
        <!-- the domain name (may be null or empty). If no domain name is configured, it is assumed that the username will always contain the domain name. -->
        <beans:constructor-arg index="0" value="${sample.ldap.domain}" />
        <!-- an LDAP url (or multiple URLs) -->
        <beans:constructor-arg index="1" value="${sample.ldap.url}" />
        <!-- Determines whether the supplied password will be used as the credentials in the successful authentication token. -->
        <beans:property name="useAuthenticationRequestCredentials"
            value="true" />
        <!-- by setting this property to true, when the authentication fails the error codes will also be used to control the exception raised. -->
        <beans:property name="convertSubErrorCodesToExceptions"
            value="true" />
    </beans:bean>

    <authentication-manager erase-credentials="false">
        <authentication-provider ref="adAuthenticationProvider" />
    </authentication-manager>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value> <!-- OVERRIDE is 2 -->
        </beans:property>
    </beans:bean>

    <ldap:context-source id="contextSource"
                         url="${sample.ldap.url}"
                         base="${sample.ldap.base}"
                         referral="follow"
                         authentication-source-ref="authenticationSource"
                         base-env-props-ref="baseEnvironmentProperties"/>

    <util:map id="baseEnvironmentProperties">
        <beans:entry key="com.sun.jndi.ldap.connect.timeout" value="60000" />
        <beans:entry key="java.naming.ldap.attributes.binary" value="objectGUID objectSid"/>
    </util:map>

    <beans:bean id="authenticationSource"
        class="org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource" />

    <ldap:ldap-template id="ldapTemplate"
        context-source-ref="contextSource" />

</beans:beans>
</code>```

And property file is -

```<code>sample.ldap.url=ldap://xxx.xxx.xxx.xxx:3268
sample.ldap.base=dc=example,dc=com
sample.ldap.clean=true
sample.ldap.directory.type=AD
sample.ldap.domain=example.com
</code>```

These setting works fine for following login -

username - example@example.com or example
Password - blah

but fails when i try -
username - example2@example.net or example
Password - blah2

These both are valid logins, and have been validated by login using AD Explorer.

Seems like i need to update my configuration to support UPN suffix/domains as default works fine and other do not.

Is there a way i can append to this config file to support this logic, supporting authenticating/querying multiple domains?

答:
Reason it's not allowing me to login with configured UPN suffix is because ActiveDirectoryLdapAuthenticationProvider seems to be making assumption that UPN suffix is always same as Domain Name.

Please refer this post - https://github.com/spring-projects/spring-security/issues/3204

I think there should be a better way to handle this though, or maybe better library for authentication.

Body:
I am trying to authenticate and then query AD tree using Spring Ldap Security and Spring Ldap.

Following is my configuration file -

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:ldap="http://www.springframework.org/schema/ldap"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <http use-expressions="true">
        <form-login login-page="/myApp/ldap" default-target-url="/myApp/ldap/config"
            authentication-failure-url="/myApp/ldap?error=true" />
        <logout />
    </http>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <beans:bean id="adAuthenticationProvider" scope="prototype"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">

        <beans:constructor-arg index="0" value="${sample.ldap.domain}" />

        <beans:constructor-arg index="1" value="${sample.ldap.url}" />

        <beans:property name="useAuthenticationRequestCredentials"
            value="true" />

        <beans:property name="convertSubErrorCodesToExceptions"
            value="true" />
    </beans:bean>

    <authentication-manager erase-credentials="false">
        <authentication-provider ref="adAuthenticationProvider" />
    </authentication-manager>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <ldap:context-source id="contextSource"
                         url="${sample.ldap.url}"
                         base="${sample.ldap.base}"
                         referral="follow"
                         authentication-source-ref="authenticationSource"
                         base-env-props-ref="baseEnvironmentProperties"/>

    <util:map id="baseEnvironmentProperties">
        <beans:entry key="com.sun.jndi.ldap.connect.timeout" value="60000" />
        <beans:entry key="java.naming.ldap.attributes.binary" value="objectGUID objectSid"/>
    </util:map>

    <beans:bean id="authenticationSource"
        class="org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource" />

    <ldap:ldap-template id="ldapTemplate"
        context-source-ref="contextSource" />

</beans:beans>

And property file is -

sample.ldap.url=ldap://xxx.xxx.xxx.xxx:3268
sample.ldap.base=dc=example,dc=com
sample.ldap.clean=true
sample.ldap.directory.type=AD
sample.ldap.domain=example.com

These setting works fine for following login -

username - example@example.com or example
Password - blah

but fails when i try -
username - example2@example.net or example
Password - blah2

These both are valid logins, and have been validated by login using AD Explorer.

Seems like i need to update my configuration to support UPN suffix/domains as default works fine and other do not.

Is there a way i can append to this config file to support this logic, supporting authenticating/querying multiple domains?


问:
Invalid route in a Laravel search form
Hi i'm following a tutorial bout how to set a search form but I'm getting a route error (NotFoundHttpException).

form

```<code>   {!! Form::open(['method'=>'GET' ,'url' => 'search', 'class'=>'form-group main-form', 'id'=>'search-form', 'role'=>'form']) !!}
      {{ csrf_field() }}
      <div style="display:none"><input name="utf8" type="hidden" value="✓"></div>
      <input class="form-group main-form" id="q_objname_en_cont" name="searchKey"  placeholder='Search by Job title' required="required" style="height:40px;width:60%" type="search">
      <input class="btn btn-warning" type="submit" value="Search">
   {!! Form::close() !!}
</code>```

Route

```<code>//Search route(get)
Route::get('search/{searchkey}', 'EmploiController@search')->where('searchkey', '[A-Za-z]+')->name('search');
</code>```

url (browser)

```<code>http://localhost:8000/search?_token=LJpgN3AwCFoDElOkFsSOX8BBLU1IFOzMvUYiokQj&utf8=%E2%9C%93&searchKey=quia
</code>```

答:
I think everything is wrong with the tutorial you're following, there are not security concerns, and certainly, that is not the proper way to implement a search in Laravel, you are exposing your csrf_token to the world in every request to that route.

My advice for you is to read better resources and take a deep dive into the docs.

https://laracasts.com/discuss/channels/laravel/search-option-in-laravel-5?page=1

Title: Invalid route in a Laravel search form

Body:
Hi i'm following a tutorial bout how to set a search form but I'm getting a route error (NotFoundHttpException).

form

   {!! Form::open(['method'=>'GET' ,'url' => 'search', 'class'=>'form-group main-form', 'id'=>'search-form', 'role'=>'form']) !!}
      {{ csrf_field() }}

<input name="utf8" type="hidden" value="✓">

      <input class="form-group main-form" id="q_objname_en_cont" name="searchKey"  placeholder='Search by Job title' required="required" style="height:40px;width:60%" type="search">
      <input class="btn btn-warning" type="submit" value="Search">
   {!! Form::close() !!}

Route

//Search route(get)
Route::get('search/{searchkey}', 'EmploiController@search')->where('searchkey', '[A-Za-z]+')->name('search');

url (browser)

http://localhost:8000/search?_token=LJpgN3AwCFoDElOkFsSOX8BBLU1IFOzMvUYiokQj&utf8=%E2%9C%93&searchKey=quia


问:
Access Array inside an object (json)
I have this json file and I want to access the array that is inside this object:

```<code>best-sellers": [
    {
      "title": "Chuteira Nike HyperVenomX Proximo II Society",
      "price": 499.90,
      "installments": {
        "number": 10,
        "value": 49.90
      },
      "high-top": true,
      "category": "society",
      "image": ""
    },
    {
      "title": "Chuteira Nike HyperVenom Phantom III Cano Alto Campo",
      "price": 899.90,
      "installments": {
        "number": 10,
        "value": 89.90
      },
      "high-top": true,
      "category": "campo",
      "image": ""
    }
}
]
</code>```

This is the code on my component:

```<code>   ngOnInit(): void {
      this.service
      .lista()
      .subscribe(chuteiras =>{
        this.chuteiras = chuteiras;
      })
  }
</code>```

and my template looks like this:

```<code><div *ngFor="let chuteira of chuteiras.best-sellers">
</code>```

But angular is not reconigzing it the `best-sellers", here's the error that I'm getting:

Cannot read property 'best' of undefined

答:
Just use bracket notation,</p>

```<code><div *ngFor="let chuteira of chuteiras["best-sellers"]">
</code>```

Title: Access Array inside an object (json)

Body:
I have this json file and I want to access the array that is inside this object:

best-sellers": [
    {
      "title": "Chuteira Nike HyperVenomX Proximo II Society",
      "price": 499.90,
      "installments": {
        "number": 10,
        "value": 49.90
      },
      "high-top": true,
      "category": "society",
      "image": ""
    },
    {
      "title": "Chuteira Nike HyperVenom Phantom III Cano Alto Campo",
      "price": 899.90,
      "installments": {
        "number": 10,
        "value": 89.90
      },
      "high-top": true,
      "category": "campo",
      "image": ""
    }
}
]

This is the code on my component:

   ngOnInit(): void {
      this.service
      .lista()
      .subscribe(chuteiras =>{
        this.chuteiras = chuteiras;
      })
  }

and my template looks like this:

But angular is not reconigzing it the `best-sellers", here's the error that I'm getting:

Cannot read property 'best' of undefined

Body:
Just use bracket notation,

<div *ngFor="let chuteira of chuteiras["best-sellers"]">


问:
Filtered Out Values Using "NOT EXISTS" when doing a JOIN with a different table
Let's say I am joining two tables on a column called "Searched" in both tables. However, I want the output to be limited to where that join from my Catalog table is not equal to any value in another third table called Part1 (well actually I am interested in comparing it to about 5 other tables) but at least to get it to work for one for a start. Currently, the query I am running (in MS Access) is outputting nothing, why is that? I was expecting to see a JOIN with 2 columns reduced by the values that are equal between the "Searched" in Cat2 and Part4.</p>

```<code>SELECT DISTINCT Searches.Search, Cat2.Category
FROM Searches LEFT JOIN Cat2
ON Cat2.Searched = Searches.Search
WHERE NOT EXISTS (SELECT Part4.Searched FROM Part4 INNER JOIN Cat2 ON Cat2.Searched = Part4.Searched);
</code>```

答:
It is not outputting anything because the NOT EXISTS subquery is always returning at least one row.

The reason is because you are doing a JOIN, instead of using a correlation clause.  So, try this:

```<code>SELECT DISTINCT Searches.Search, Cat2.Category
FROM Searches LEFT JOIN
     Cat2
     ON Cat2.Searched = Searches.Search
WHERE NOT EXISTS (SELECT 1
                  FROM Part4
                  WHERE Cat2.Searched = Part4.Searched
                 );
</code>```

The reference Cat2.Searched in the subquery now refers to the Cat2 in the outer query.  That is the logic you are looking for.

For performance, you want indexes on Part4(Searched) and Cat2(Searched, Category).

Body:
Let's say I am joining two tables on a column called "Searched" in both tables. However, I want the output to be limited to where that join from my Catalog table is not equal to any value in another third table called Part1 (well actually I am interested in comparing it to about 5 other tables) but at least to get it to work for one for a start. Currently, the query I am running (in MS Access) is outputting nothing, why is that? I was expecting to see a JOIN with 2 columns reduced by the values that are equal between the "Searched" in Cat2 and Part4.

SELECT DISTINCT Searches.Search, Cat2.Category
FROM Searches LEFT JOIN Cat2
ON Cat2.Searched = Searches.Search
WHERE NOT EXISTS (SELECT Part4.Searched FROM Part4 INNER JOIN Cat2 ON Cat2.Searched = Part4.Searched);

Body:
It is not outputting anything because the NOT EXISTS subquery is always returning at least one row.

The reason is because you are doing a JOIN, instead of using a correlation clause.  So, try this:

SELECT DISTINCT Searches.Search, Cat2.Category
FROM Searches LEFT JOIN
     Cat2
     ON Cat2.Searched = Searches.Search
WHERE NOT EXISTS (SELECT 1
                  FROM Part4
                  WHERE Cat2.Searched = Part4.Searched
                 );

The reference Cat2.Searched in the subquery now refers to the Cat2 in the outer query.  That is the logic you are looking for.

For performance, you want indexes on Part4(Searched) and Cat2(Searched, Category).


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
Depending on the size of the database depends on how inefficient it becomes, the simnplest way to describe would be like so:

when you specifically do:

```<code>SELECT column1,column2,column3 FROM table1
</code>```

Mysql knows exactly exactly what columns it looking for, but when you do

```<code>SELECT * FROM table1
</code>```

Mysql does not know the columns you want, it knows you want all of them but not the names, so it has to perform extra tasks that analyse the table to discover the columns, thus resulting in using resources.

Body:
Depending on the size of the database depends on how inefficient it becomes, the simnplest way to describe would be like so:

when you specifically do:

SELECT column1,column2,column3 FROM table1

Mysql knows exactly exactly what columns it looking for, but when you do

SELECT * FROM table1

Mysql does not know the columns you want, it knows you want all of them but not the names, so it has to perform extra tasks that analyse the table to discover the columns, thus resulting in using resources.

ContentLicense: CC BY-SA 2.5


问:
How can I solve syntax error for the following code in Python 2.7?
I have used the following code for optimizing a problem via pyomo, coopr.

However the compiler gives an error, as follows:

invalid syntax

I tried to use correct syntax but I can not find the error:

```<code>model = AbstractModel()
model.x = Var(initialize = 1.5)
model.y = Var(initialize = 1.5)
import pyomo
from coopr.pyomo import *
def rosenbrock(model):
    return (1.0-model.x)**2 \
           + 100.0*(model.y - model.x**2)**2
model.obj=Objective(rule=rosenbrock, sense=minimize)
SyntaxError: invalid syntax
</code>```

答:
That code appears to be syntactically valid.  Indeed I have just successfully compiled it in Python 3.6

Two possibilities occur to me:

There is a problem with your line continuation.  Note that the backslash
must be followed only by exactly the new line character. If you have additional white space then this will cause an error.  For that reason, Python programmers are recommended to avoid line continuation.

The environment in which this code is running is a specialised embedded Python with some special constraints of which I am not aware.

Hope one of these helps ...

OwnerDisplayName: iman

Body:
I have used the following code for optimizing a problem via pyomo, coopr.

However the compiler gives an error, as follows:

invalid syntax

I tried to use correct syntax but I can not find the error:

model = AbstractModel()
model.x = Var(initialize = 1.5)
model.y = Var(initialize = 1.5)
import pyomo
from coopr.pyomo import *
def rosenbrock(model):
    return (1.0-model.x)**2 \
           + 100.0*(model.y - model.x**2)**2
model.obj=Objective(rule=rosenbrock, sense=minimize)
SyntaxError: invalid syntax


问:
Trying to get a picture and text side by side inside a div
I've been searching around for this and found a lot of similar cases but for whatever reason, the solution doesn't work in my scenario.

The text and picture are being stacked on top of each other. I'm having trouble keeping it inside the headerBlock div but side by side.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  vertical-align: middle;
  text-align: justify;
}

div.headerImg img {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg"><img src="/somepicturehere">
    </div>
  </div>

  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>

  <div id="rightBlock"></div>

  <div id="footerBlock"></div>

</div></code>```

答:
If you make .headerText and .headerImg display: inline-block;, then that should do the trick.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  display: inline-block;
}
div.headerImg {
  display: inline-block;
}
div.headerImg img {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg">
      <img src="/somepicturehere">
    </div>
  </div>
  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>
  <div id="rightBlock"></div>
  <div id="footerBlock"></div>
</div></code>```

And if you want to vertically align them, use display: flex; and align-items: center; on the container:

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
  display: flex;
  align-items: center;
}

div.headerText {
  display: inline-block;
}
div.headerImg {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg">
      <img src="/somepicturehere">
    </div>
  </div>
  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>
  <div id="rightBlock"></div>
  <div id="footerBlock"></div>
</div></code>```

Body:
I've been searching around for this and found a lot of similar cases but for whatever reason, the solution doesn't work in my scenario.

The text and picture are being stacked on top of each other. I'm having trouble keeping it inside the headerBlock div but side by side.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  vertical-align: middle;
  text-align: justify;
}

div.headerImg img {
  vertical-align: middle;
}

Some text here

Body:
If you make .headerText and .headerImg display: inline-block;, then that should do the trick.

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
}

div.headerText {
  display: inline-block;
}
div.headerImg {
  display: inline-block;
}
div.headerImg img {
  vertical-align: middle;
}

<div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg">
      <img src="/somepicturehere">
    </div>
  </div>
  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>
  <div id="rightBlock"></div>
  <div id="footerBlock"></div>
</div>

And if you want to vertically align them, use display: flex; and align-items: center; on the container:

#wrap {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

#headerBlock {
  height: 200px;
  background:  #776b68;
  display: flex;
  align-items: center;
}

div.headerText {
  display: inline-block;
}
div.headerImg {
  display: inline-block;
}

<div id="wrap">
  <div id="headerBlock">
    <div class="headerText">Some text here</div>
    <div class="headerImg">
      <img src="/somepicturehere">
    </div>
  </div>
  <!--Ignore these, it's for future use-->
  <div id="leftBlock"></div>
  <div id="rightBlock"></div>
  <div id="footerBlock"></div>
</div>


问:
Ajax not posting data to controller
I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.

here is my ajax call,

```<code> $.ajax({
            type: 'POST',
            url:' @Url.Action("PostAmount", "Deal")',
            data: { country: 2, amount: 4.02 },
            datatype:JSON,

            success: function (data) {
                alert("hiiii"+data);
            }
        });
</code>```

and my action,

```<code> [HttpPost]
        public JsonResult PostAmount(int country,double amount)
        {
            AllocationViewModel mod = new AllocationViewModel();
            return Json(mod);
        }
</code>```

答:
You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request.
Also use a string for the datatype parameter (https://api.jquery.com/jquery.post/), as suggested in the answers above.

```<code>var dataToPost = { country: 2, amount: 4.02 };

$.ajax({
    type: 'POST',
    url:' @Url.Action("PostAmount", "Deal")',
    data: JSON.stringify(dataToPost),
    datatype: 'json',
    success: function (data) {
        alert("hiiii"+data);
    }
});
</code>```

The other way around is JSON.parse(yourJsonObject). This way you can parse a JSON string into a Javascript object.

Title: Ajax not posting data to controller

Body:
I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.

here is my ajax call,

 $.ajax({
            type: 'POST',
            url:' @Url.Action("PostAmount", "Deal")',
            data: { country: 2, amount: 4.02 },
            datatype:JSON,

            success: function (data) {
                alert("hiiii"+data);
            }
        });

and my action,

 [HttpPost]
        public JsonResult PostAmount(int country,double amount)
        {
            AllocationViewModel mod = new AllocationViewModel();
            return Json(mod);
        }

Body:
You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request.
Also use a string for the datatype parameter (https://api.jquery.com/jquery.post/), as suggested in the answers above.

var dataToPost = { country: 2, amount: 4.02 };

$.ajax({
    type: 'POST',
    url:' @Url.Action("PostAmount", "Deal")',
    data: JSON.stringify(dataToPost),
    datatype: 'json',
    success: function (data) {
        alert("hiiii"+data);
    }
});

The other way around is JSON.parse(yourJsonObject). This way you can parse a JSON string into a Javascript object.


问:
In Power Builder trying to replace a escape character with ~ sign
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

```<code>Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")
</code>```

Any help here please.

答:
From the PowerBuilder help:

Replace PowerScript function

Replaces a portion of one string with another.

Syntax:  Replace ( string1, start, n, string2 )

You need to designate how many characters you wish to replace.  If you want to insert string2 into string1 you use 0.

So with your example you should try something like:

```<code>IF POS(Signature, "'") > 0 THEN
  Signature = Replace (Signature, POS(Signature, "'"), 1, "~'")
END IF
</code>```

Body:
I am new to the power builder I am trying to use replace function. I needed to replace a aposthope(') in string with ~' but it is giving me an error "Bad argument list for function: replace" .

Signature = "Gagandeep S'ingh"

Signature = Replace (Signature , "'", "~'")

Any help here please.

Body:
From the PowerBuilder help:

Replace PowerScript function

Replaces a portion of one string with another.

Syntax:  Replace ( string1, start, n, string2 )

You need to designate how many characters you wish to replace.  If you want to insert string2 into string1 you use 0.

So with your example you should try something like:

IF POS(Signature, "'") > 0 THEN
  Signature = Replace (Signature, POS(Signature, "'"), 1, "~'")
END IF


问:
Finding three most similar matches to a given short binary sequence in a long one
I´m new in C programming and have a problem I cant solve.

From a file with a lot of information, structured like

"id" \t 2048 times '0' or '1'
e.g.:

```<code>81283 \t   0101011010.....0110
</code>```

I've to find, from a new sequence introduced by the user, the 3 most similar elements with the same size of the sequence introduced by the user.

E.g. sequence introduced by user, 010101, the program has to show like

n1= 010101

n2= 010100

n3= 010010

Those are the 3 most similar sequences from all the 2048 '0' '1' in each line.

I hope that the problem was well explain.
I have this code below, but it does not solve the problem.

Can anyone help me?

Thanks.

```<code>int procura(int *v, int *c, int tam){
int i,j,t;
FILE *fp;
fp=fopen("fich.txt","r");
v=(int*)malloc(sizeof(int));
c=(int*)malloc(sizeof(int));
while(!feof(fp)){
    fscanf(fp,"%d",&v);
}
t = sizeof(v)/sizeof(*v);
for(i=0;i<tam;i++){
    for(j=0;j<t;j++){
        if(c[i]==v[j])
            return 1;
        else
            return 0;
    }
}
</code>```

}

```<code>int main(){
int *v, *c;
int i,tam,a;
printf("array size\n");
scanf("%d",&tam);
c=(int*)malloc(tam*sizeof(int));
printf("Seq\n");
for(i=0;i<tam;i++){
    scanf("%d",&c[i]);
}
printf("%d",procura(v,c, tam));

return 0;
</code>```

}

答:
A few things:

```<code>v=(int*)malloc(sizeof(int));
c=(int*)malloc(sizeof(int));
</code>```

These overwrites the pointers, so you lose the original v and c.

sizeof(v)/sizeof is a syntax error

Getting the size of a pointer with sizeof returns the size of the pointer, not what it points to

Your reassignment of v and c above makes those variables points to memory for only a single int, and then you loop over tam elements meaning you go out of bounds of the memory

With fscanf(fp,"%d",&v) you pass a pointer to the pointer

Read Why is “while ( !feof (file) )” always wrong?

No error checking, what happens if you can't open a file?

Your function will return immediately after the first c[i]==v[j] check, and it will return unconditionally

And probably much more.

Body:
I´m new in C programming and have a problem I cant solve.

From a file with a lot of information, structured like

"id" \t 2048 times '0' or '1'
e.g.:

81283 \t   0101011010.....0110

I've to find, from a new sequence introduced by the user, the 3 most similar elements with the same size of the sequence introduced by the user.

E.g. sequence introduced by user, 010101, the program has to show like

n1= 010101

n2= 010100

n3= 010010

Those are the 3 most similar sequences from all the 2048 '0' '1' in each line.

I hope that the problem was well explain.
I have this code below, but it does not solve the problem.

Can anyone help me?

Thanks.

int procura(int *v, int *c, int tam){
int i,j,t;
FILE *fp;
fp=fopen("fich.txt","r");
v=(int*)malloc(sizeof(int));
c=(int*)malloc(sizeof(int));
while(!feof(fp)){
    fscanf(fp,"%d",&v);
}
t = sizeof(v)/sizeof(*v);
for(i=0;i<tam;i++){
    for(j=0;j<t;j++){
        if(c[i]==v[j])
            return 1;
        else
            return 0;
    }
}

}

int main(){
int *v, *c;
int i,tam,a;
printf("array size\n");
scanf("%d",&tam);
c=(int*)malloc(tam*sizeof(int));
printf("Seq\n");
for(i=0;i<tam;i++){
    scanf("%d",&c[i]);
}
printf("%d",procura(v,c, tam));

return 0;

}

Body:
A few things:

v=(int*)malloc(sizeof(int));
c=(int*)malloc(sizeof(int));

These overwrites the pointers, so you lose the original v and c.

sizeof(v)/sizeof is a syntax error

Getting the size of a pointer with sizeof returns the size of the pointer, not what it points to

Your reassignment of v and c above makes those variables points to memory for only a single int, and then you loop over tam elements meaning you go out of bounds of the memory

With fscanf(fp,"%d",&v) you pass a pointer to the pointer

Read Why is “while ( !feof (file) )” always wrong?

No error checking, what happens if you can't open a file?

Your function will return immediately after the first c[i]==v[j] check, and it will return unconditionally

And probably much more.


问:
Using iPython with remote docker container in a local project directory
I am completely new to Docker and I followed the instructions found on this page https://cmusatyalab.github.io/openface/setup/:

```<code>docker pull bamos/openface
docker run -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash
cd /root/openface
./demos/compare.py images/examples/{lennon*,clapton*}
</code>```

And I was able to run an example of openface following the example. However, normally I develop in iPython and would like to do so. However, I cannot import openface from iPython, since presumably it is not installed locally. Similarly, I do not know how to cd into my project directory, which is in /Users/name/documents/my-project.

What is the idiomatic way to proceed?

答:
My recommended approach is using docker volumes. As you already have the project outside the container, you can start the container with a volume to map your project directory to a directory inside the container. That's idiomatic.

For instance:

```<code>docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash
</code>```

Body:
I am completely new to Docker and I followed the instructions found on this page https://cmusatyalab.github.io/openface/setup/:

docker pull bamos/openface
docker run -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash
cd /root/openface
./demos/compare.py images/examples/{lennon*,clapton*}

And I was able to run an example of openface following the example. However, normally I develop in iPython and would like to do so. However, I cannot import openface from iPython, since presumably it is not installed locally. Similarly, I do not know how to cd into my project directory, which is in /Users/name/documents/my-project.

What is the idiomatic way to proceed?

Body:
My recommended approach is using docker volumes. As you already have the project outside the container, you can start the container with a volume to map your project directory to a directory inside the container. That's idiomatic.

For instance:

docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash


问:
Prevent original template being applied in inherited control
I am having an issue in an application where I would like to derive my own custom control from a control included in a commercial library (scichart).

I am overriding OnApplyTemplate, as in the below code, but am running into an issue where when calling GetAndAssertTemplateChild (A function in the library that is pretty much the same as GetTemplateChild but throws and error if the result is equal to null) the part cannot be found in the template.

While investigating this issue I found that OnApplyTemplate is being called multiple times, it is first called with the template of the control being inherited from, and is then recalled with the template of the new control. Is there any way to avoid this and to never apply the base classes template.

```<code>public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}
</code>```

答:
Is there any way to avoid this and to never apply the base classes template

If you only want to call the derived class' OnApplyTemplate() method, you should avoid calling the base class' method in the overridden method:

```<code>public override void OnApplyTemplate()
{
    //DON't CALL THIS ONE: base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}
</code>```

And if you want to provide your own default custom ControlTemplate from scratch, you should define a static constructor in your control class:

```<code>static YourControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(YourControl),
        new FrameworkPropertyMetadata(typeof(YourControl)));
}
</code>```

...and define the default template in a ResourceDictionary called "generic.xaml" located in a folder called "Themes" at the root folder of the project in which the control class is defined.

Body:
I am having an issue in an application where I would like to derive my own custom control from a control included in a commercial library (scichart).

I am overriding OnApplyTemplate, as in the below code, but am running into an issue where when calling GetAndAssertTemplateChild (A function in the library that is pretty much the same as GetTemplateChild but throws and error if the result is equal to null) the part cannot be found in the template.

While investigating this issue I found that OnApplyTemplate is being called multiple times, it is first called with the template of the control being inherited from, and is then recalled with the template of the new control. Is there any way to avoid this and to never apply the base classes template.

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

Body:
Is there any way to avoid this and to never apply the base classes template

If you only want to call the derived class' OnApplyTemplate() method, you should avoid calling the base class' method in the overridden method:

public override void OnApplyTemplate()
{
    //DON't CALL THIS ONE: base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

And if you want to provide your own default custom ControlTemplate from scratch, you should define a static constructor in your control class:

static YourControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(YourControl),
        new FrameworkPropertyMetadata(typeof(YourControl)));
}

...and define the default template in a ResourceDictionary called "generic.xaml" located in a folder called "Themes" at the root folder of the project in which the control class is defined.


问:
Can i use JQuery/Javascript with Ionic instead of Typescript
I'm developing mobile applications using Visual Studio 2017 and Apache Cordova.
I've always coded using JQuery and Javascript however i have never written a code using Typescript.

When searching the web almost everyone is using Typescript with Ionic. (thinking of starting to benefit and use the Ionic Framework)
Is it the same if i use JQuery or Javascript instead of Typescript with Ionic?

Or its recommended that i learn Typescript and start using it with Ionic?

Thank you for the clarification.

This is how i usually write the code for Cordova using JQuery:

```<code>function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
return array;
}

function beginGame() {

$('#info').hide();

var level = 0;

$('#game_title h2').html('Level 1');
$('#game_question h3').html('What is the most common language?');

$('#game_body').html('');
var gameBody = document.getElementById('game_body');
var columnAnswer, buttonAnswer;

var answers = [['Arabic', ''], ['Spanish', ''], ['English', 'right_answer'], ['Chinese', '']];
var arr = shuffleArray(answers);
console.log(arr);

for (var i = 0; i < arr.length; i++) {
    columnAnswer = document.createElement('div');
    columnAnswer.className = 'col-xs-12';

    buttonAnswer = document.createElement('button');
    buttonAnswer.id = 'answer_button_'+i;
    buttonAnswer.className = 'btn btn-primary btn-sx answer_button ' + arr[i][1];
    buttonAnswer.type = 'button';
    buttonAnswer.innerHTML = arr[i][0];
    //buttonAnswer.setAttribute('onclick', 'onQuoteClick(' + quotes[i].id + ')');
    console.log(buttonAnswer);
    columnAnswer.appendChild(buttonAnswer);

    gameBody.appendChild(columnAnswer);
}

$('.answer_button').click(function () {
    var button_id = $(this).attr('id');
    if ($('#' + button_id).hasClass('right_answer')) {
        //alert('Right Answer');
        $('#info').show();
        fillInformation();
    } else {
        alert('Wrong Answer');
    }
});

}
function fillInformation() {
$('#game_title h2').html('English');
$('#info_image img').attr("src", './images/level_1.png');
$('#info_text h5').html('English Language');
}
</code>```

答:
Yes, it's totally worth working with Typescript and doing it the standard way.

The main difference with what you are used to is not Typescript vs Javascript, it's vanilla Js vs Angular.

Angular is the framework upon which Ionic rests and which it is extending. The Angular framework is by default in Typescript.

But that shouldn't be a problem for you, since Typescript is backwards compatible with Javascript. Any vanilla Js code in a .ts file compiles and runs just fine (although you are losing on the benefits of Typescript if you are not following best practices).

You can also definitely use jquery, just like you are used to.

Body:
I'm developing mobile applications using Visual Studio 2017 and Apache Cordova.
I've always coded using JQuery and Javascript however i have never written a code using Typescript.

When searching the web almost everyone is using Typescript with Ionic. (thinking of starting to benefit and use the Ionic Framework)
Is it the same if i use JQuery or Javascript instead of Typescript with Ionic?

Or its recommended that i learn Typescript and start using it with Ionic?

Thank you for the clarification.

This is how i usually write the code for Cordova using JQuery:

function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
return array;
}

function beginGame() {

$('#info').hide();

var level = 0;

$('#game_title h2').html('Level 1');
$('#game_question h3').html('What is the most common language?');

$('#game_body').html('');
var gameBody = document.getElementById('game_body');
var columnAnswer, buttonAnswer;

var answers = [['Arabic', ''], ['Spanish', ''], ['English', 'right_answer'], ['Chinese', '']];
var arr = shuffleArray(answers);
console.log(arr);

for (var i = 0; i < arr.length; i++) {
    columnAnswer = document.createElement('div');
    columnAnswer.className = 'col-xs-12';

    buttonAnswer = document.createElement('button');
    buttonAnswer.id = 'answer_button_'+i;
    buttonAnswer.className = 'btn btn-primary btn-sx answer_button ' + arr[i][1];
    buttonAnswer.type = 'button';
    buttonAnswer.innerHTML = arr[i][0];
    //buttonAnswer.setAttribute('onclick', 'onQuoteClick(' + quotes[i].id + ')');
    console.log(buttonAnswer);
    columnAnswer.appendChild(buttonAnswer);

    gameBody.appendChild(columnAnswer);
}

$('.answer_button').click(function () {
    var button_id = $(this).attr('id');
    if ($('#' + button_id).hasClass('right_answer')) {
        //alert('Right Answer');
        $('#info').show();
        fillInformation();
    } else {
        alert('Wrong Answer');
    }
});

}
function fillInformation() {
$('#game_title h2').html('English');
$('#info_image img').attr("src", './images/level_1.png');
$('#info_text h5').html('English Language');
}


问:
Assigning elements to a list using for loop?
I have to figure out which is larger, the first or last element in a given list, and set all the other elements to be that value.

I wrote a code using a for loop, but I get an error that the list index is out of range.  What is my mistake?

The code is below:

```<code>def max_end3(nums):
    for i in nums:
        if (nums[0] > nums[len(nums)-1]):
            nums[i] = nums[0]
        else:
            nums[i] = nums[len(nums)-1]
        return (nums)
</code>```

答:
To replace each element in the given list I would pre-compute the wanted value, and then assign it to each element, thus:

```<code>def max_end3(nums):
    larger = max((nums[0], nums[-1]))
    for i in range(len(nums)):
        nums[i] = larger
</code>```

You could alternatively leave the original list unchanged, and generate a new list of the wanted values. If the new list is assigned to the same name as the old one, it will have a similar effect, eg.

```<code>nums = [max((nums[0], nums[-1]))] * len(nums)
</code>```

Body:
I have to figure out which is larger, the first or last element in a given list, and set all the other elements to be that value.

I wrote a code using a for loop, but I get an error that the list index is out of range.  What is my mistake?

The code is below:

def max_end3(nums):
    for i in nums:
        if (nums[0] > nums[len(nums)-1]):
            nums[i] = nums[0]
        else:
            nums[i] = nums[len(nums)-1]
        return (nums)

Body:
To replace each element in the given list I would pre-compute the wanted value, and then assign it to each element, thus:

def max_end3(nums):
    larger = max((nums[0], nums[-1]))
    for i in range(len(nums)):
        nums[i] = larger

You could alternatively leave the original list unchanged, and generate a new list of the wanted values. If the new list is assigned to the same name as the old one, it will have a similar effect, eg.

nums = [max((nums[0], nums[-1]))] * len(nums)


问:
Divide a rectangle into 2 triangles along diagonal using css
I want to make a div into 2 triangles (as shown in below, no problem if 1 is background of parent) upper one with one color and lower one with another. I dont mind how it is implemented but i want to do it in css (not javascript). I tried with css rotation, (code below), but its not responsive. In smaller or wider screen it is distorted . Any way to implement this in css?

body {
  background: #eee;
}

.darker {
  position: fixed;
  top: -94%;
  left: -10%;
  width: 150%;
  height: 150%;
  background: #dd4f39;
  -webkit-transform: rotate(30deg);
          transform: rotate(30deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="darker"> </div></code>```

答:
This is one way of doing it. But this use case is strictly with respect to vw. Just make sure to give the same value to these elements

div and it's pseudo element should have same width and border-left respectively.
div and it's pseudo element should have same height and border-top respectively.

html, body {
  margin: 0;
}

.box {
  width: 100vw;
  height: 100vh;
  background-color: white;
}

.box::after {
  content: ' ';
  border-top: 100vh solid #dd4f39;
  border-left: 100vw solid transparent;
  width: 0;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

JS fiddle
https://jsfiddle.net/kqsrmrss/2/

Body:
This is one way of doing it. But this use case is strictly with respect to vw. Just make sure to give the same value to these elements

div and it's pseudo element should have same width and border-left respectively.
div and it's pseudo element should have same height and border-top respectively.

html, body {
  margin: 0;
}

.box {
  width: 100vw;
  height: 100vh;
  background-color: white;
}

.box::after {
  content: ' ';
  border-top: 100vh solid #dd4f39;
  border-left: 100vw solid transparent;
  width: 0;
  position: absolute;
}

<div class="box"></div>

JS fiddle
https://jsfiddle.net/kqsrmrss/2/

ContentLicense: CC BY-SA 4.0


问:
Using tensorflow on Android NDK side directly (Not using JAVA api)
I am trying to run a neural network on Android in C++. The examples (https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/android) show how to use tensorflow using JAVA apis which call C++ using JNI functions. Has anyone tried to use tensorflow directly in C++ on Android? How can the tensorflow library be built and linked for using C++ apis on Android. Can you please guide me on that? I want to use C++ apis on Android in the similar way as done in iOS examples.</p>

答:
Here is how I solved this problem. Although there is not much documentation of using c++ apis on android and compiling and linking tensorflow to NDK, the makefile have important comments as well as there are associated scripts. Compilation steps are very similar to that of ios.

Install following dependencies a)autoconf b) automake c)automake. Then run tensorflow/contrib/makefile/download_dependencies.sh; I ran on May 10, 2017 repository for the first time, when it worked perfectly. In the later version around June 1, due to some changes in tensorflow/workspace.bzl, that I do not understand in download_dependencies.sh fails to recognise the tar files download_dependencies is trying to download. I just replaced workspace.bzl from May 10 repo commit.

Step 2 is to run tensorflow/contrib/makefile/compile_android_protobuf.sh like this

NDK_ROOT=absolute/path/to/ndk/folder ./tensorflow/contrib/makefile/compile_android_protobuf.sh

Run make. But first you may need to make some changes in Makefile. Replace -fPIE flags with -fPIC flags. Also add -fPIC flag to HOST_CXXFLAGS. Then run make like this:

make -f tensorflow/contrib/makefile/Makefile TARGET=ANDROID NDK_ROOT=absolute/path/to/ndk/folder

Alternatively one can also run build_all_android.sh which runs all 3 steps in one go, but you may need to do Makefile changes for flags.

This generated tensorflow/contrib/makefile/gen/protobuf/lib/libprotobuf.a and tensorflow/contrib/makefile/gen/lib/libtensorflow-core.a; This can be linked to Android NDK project in Android.mk file under LOCAL_LDLIBS. One should use these Linked flags -Wl,--build-id -Wl,--allow-multiple-definition -Wl,--whole-archive Also -std=c++11 in LOCAL_CFLAGS in Android.mk file and APP_STL := gnustl_shared in Application.mk file.

This should be sufficient to build a shared library of your NDK project.


问:
Column names as variables
I want to pass column name as a parameter. Here I have written a query to select the column 'user_id' from table users, but it returns user_id as text.

```<code>EXECUTE format('SELECT $1 FROM users
WHERE name=''name''')
USING 'user_id';
</code>```

How can I do this?

答:
Can you not use Dynamic SQL to get this result? something like:</p>

```<code>EXECUTE 'SELECT '|| get_columns()|| ' FROM table_name'
</code>```

Title: Column names as variables

Body:
I want to pass column name as a parameter. Here I have written a query to select the column 'user_id' from table users, but it returns user_id as text.

EXECUTE format('SELECT $1 FROM users
WHERE name=''name''')
USING 'user_id';

How can I do this?

Body:
Can you not use Dynamic SQL to get this result? something like:

EXECUTE 'SELECT '|| get_columns()|| ' FROM table_name'


问:
What's difference between get two children in two times and get all children in one time?
Suppose that I have a data store like this.

but I want only username and profileImage. What method should I use for this case?

The first one is query data in two times. Something like this...

```<code>usersRef.child(uid).child("username").addValueListener...
String username = dataSnapshot.getValue(String.class);
usersRef.child(uid).child("profileImage").addValueListener...
String profileImage = dataSnapshot.getValue(String.class);
</code>```

or

The second one is get all children only one time and get only data that I want. Something like this...

```<code> - userRef.addValueListener...
 User user = new User();
datasnapshot.getValue(user.class)
String username = user.username;
String profileImage = user.profileImage;
</code>```

答:
The overhead on separate calls (in this scenario) is fairly small. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786.

The overhead for retrieving extra data, depends on the size of that extra data. In this scenario seems rather large, especially since you have nested collections in there. This is one of the many reasons Firebase recommends flattening our data, moving all your nested collections to their own top-level nodes (userFollowers, userFollowings, userNoficationTokens).

For optimal performance you should have a list that contains the data as you want to display in the app. So if you have a screen that shows a list of user names + images, you should have a list with just that data in the database. You'll find that you're duplicating data in that case, but you gain almost unlimited scalability because of it.

Body:
Suppose that I have a data store like this.

but I want only username and profileImage. What method should I use for this case?

The first one is query data in two times. Something like this...

usersRef.child(uid).child("username").addValueListener...
String username = dataSnapshot.getValue(String.class);
usersRef.child(uid).child("profileImage").addValueListener...
String profileImage = dataSnapshot.getValue(String.class);

or

The second one is get all children only one time and get only data that I want. Something like this...

 - userRef.addValueListener...
 User user = new User();
datasnapshot.getValue(user.class)
String username = user.username;
String profileImage = user.profileImage;


问:
How can I use the display() function in Microsoft Azure Notebook
I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.

When I reproduce the problem on my local computer it works fine.

This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.

Following is the code used to create the file:

```<code>from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')
</code>```

答:
There are two ways given the code you have to show the image.

1) You can call %matplotlib inline at the top of the notebook. This will inline graphics and you will see the image by calling fig

2) You can from IPython.display import Image and Image('xx.png') and the image should be displayed.

Body:
I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.

When I reproduce the problem on my local computer it works fine.

This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.

Following is the code used to create the file:

from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')


问:
HTML button to execute a php script that exe shell script
this is my first time asking question here so please be kind with me...

I have tried and researched many solutions but not work correctly. I am fairly inexperience with javascript, ajax or php so the way I'm approaching this might not be ideal. I need an html button that upon clicking, will call a script.php that have a exec command. What I have so far is after clicking, the webpage go to and display /script.php but doesn't seem to actually run the exec() block.

HTML:

```<code><form method="post" action="script.php">
    <button name="button">Update Inventory</button>
</form>
</code>```

script.php:

```<code><?php
exec("cd /home/jenkins/Desktop/automationutils/Python/Inventory/ && ./init.py");
?>
</code>```

I can run php script.php and it works on the cmd. So I don't think the script is wrong... it's just my button is having a problem. Any help is appreciated.

Thanks

答:
You can include the script to the file that will exec it and put the call in a function and add a listener to run it.
Here is an example to get you started</p>

Body:
this is my first time asking question here so please be kind with me...

I have tried and researched many solutions but not work correctly. I am fairly inexperience with javascript, ajax or php so the way I'm approaching this might not be ideal. I need an html button that upon clicking, will call a script.php that have a exec command. What I have so far is after clicking, the webpage go to and display /script.php but doesn't seem to actually run the exec() block.

HTML:

<form method="post" action="script.php">
    <button name="button">Update Inventory</button>
</form>

script.php:

<?php
exec("cd /home/jenkins/Desktop/automationutils/Python/Inventory/ && ./init.py");
?>

I can run php script.php and it works on the cmd. So I don't think the script is wrong... it's just my button is having a problem. Any help is appreciated.

Thanks


问:
Retrofit: multiple query parameters in @GET
I have problem with multiple parameters in @GET. If I have two, everything is working fine, but if I have three (i need three) it skipping onResponse method and onFailure is executed. Does anyone know why?

This is interface

```<code>@GET("CalendarJson")
Call<List<Raspored>> getKalendar(
        @Query("department") String department,
        @Query("semester") String semester,
        @Query("year") int year);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(basicUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

KalendarService kalendarService = retrofit.create(KalendarService.class);
</code>```

And this is where I call it

```<code>KalendarService.kalendarService.getKalendar(department,semester,year).enqueue(new Callback<List<Raspored>>() {
        @Override
        public void onResponse(Call<List<Raspored>> call, Response<List<Raspored>> response) {
            if(response.isSuccessful()){
                raspored = response.body();
                //TODO
            }
        }

        @Override
        public void onFailure(Call<List<Raspored>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

答: I think it has to do with the datatype of your third parameter</p>

Body:
I have problem with multiple parameters in @GET. If I have two, everything is working fine, but if I have three (i need three) it skipping onResponse method and onFailure is executed. Does anyone know why?

This is interface

@GET("CalendarJson")
Call<List<Raspored>> getKalendar(
        @Query("department") String department,
        @Query("semester") String semester,
        @Query("year") int year);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(basicUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

KalendarService kalendarService = retrofit.create(KalendarService.class);

And this is where I call it

KalendarService.kalendarService.getKalendar(department,semester,year).enqueue(new Callback<List<Raspored>>() {
        @Override
        public void onResponse(Call<List<Raspored>> call, Response<List<Raspored>> response) {
            if(response.isSuccessful()){
                raspored = response.body();
                //TODO
            }
        }

        @Override
        public void onFailure(Call<List<Raspored>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
        }
    });


问:
Difference Between HTML <audio>, <bgsound> and <embed> audio tags
What is the difference between <audio>, <bgsound> and <embed> tags ?

I am trying to add background sound on my website. tried <embed> but it doesn't works on mobile . similarly <bgsound> had some limitations. <audio> tag works for me.

can anybody explain how each differ from one another?

答:
<audio> is the standard, HTML 5, method to include sound. Use this.

<bgsound> is a non-standard, Internet Explorer only, method to include sound that predates HTML 5.

<embed> is a means to include content that has no native support and is expected to be handled by a plugin.