问:
Does Chrome have built-in speech recognition for "x-webkit-speech" input elements?
I'm wondering how

```<code><input type="text" x-webkit-speech speech />
</code>```

Is there a speech recognition enging built into Chrome or is it accessing an underlying speech recognition facility in the operating system?

答: I just confirmed this on my Chrome Cr-48, it works.</p>

Body:
I'm wondering how

<input type="text" x-webkit-speech speech />

Is there a speech recognition enging built into Chrome or is it accessing an underlying speech recognition facility in the operating system?


来源: stackexchange

问:
AutoMapping stored procedure results
I'm wondering if there is any way to map a stored procedure result into into a class.

This is what I have:

```<code>// DbContext Class:
public DbSet<StoredProcedureModelResult> SPMR { get; set; }

// Service Class:
var result = ctx.Set<StoredProcedureModelResult>().FromSql("getXXXX p1 = {0},1).ToList();
</code>```

This works well, however, I'm using database migrations and every time I add one this thing creates StoredProcedureModelResult as a table...

I tried to ignore it onModelCreating:

```<code>modelBuilder.Ignore<SPModels.test>();
</code>```

but this throws an exception:

Cannot create a DbSet for 'StoredProcedureModelResult ' because this type is not included in the model for the context

I just want use the benefit of mapping, and not to get a table creation, this is a simple model (non-entityType)

BTW

.NET Core 1.1

Web API

EF Core (code-first)

Thank you

答:
You don't need to make the type an Entity type (by registering a DbSet in your DbContext).  Just have a method that returns IEnumerable<StoredProcResults> (can be in your DbContext), and in it run

```<code>dbContext.Database.SqlQuery<StoredProcResults>(...)
</code>```

See Database.SqlQuery<T>(...)

ContentLicense: CC BY-SA 4.0

Title: AutoMapping stored procedure results

Body:
I'm wondering if there is any way to map a stored procedure result into into a class.

This is what I have:

// DbContext Class:
public DbSet<StoredProcedureModelResult> SPMR { get; set; }

// Service Class:
var result = ctx.Set<StoredProcedureModelResult>().FromSql("getXXXX p1 = {0},1).ToList();

This works well, however, I'm using database migrations and every time I add one this thing creates StoredProcedureModelResult as a table...

I tried to ignore it onModelCreating:

modelBuilder.Ignore<SPModels.test>();

but this throws an exception:

Cannot create a DbSet for 'StoredProcedureModelResult ' because this type is not included in the model for the context

I just want use the benefit of mapping, and not to get a table creation, this is a simple model (non-entityType)

BTW

.NET Core 1.1

Web API

EF Core (code-first)

Thank you

Body:
You don't need to make the type an Entity type (by registering a DbSet in your DbContext).  Just have a method that returns IEnumerable<StoredProcResults> (can be in your DbContext), and in it run

dbContext.Database.SqlQuery<StoredProcResults>(...)

See Database.SqlQuery<T>(...)

ContentLicense: CC BY-SA 3.0


问:
Why do some of my Textures cause this error?
I've been making a game using the rokonandroid game engine, but I randomly get an error that causes the layout to just stay as it is, and never update.

The following error occurs:

12-13 15:05:17.876: ERROR/Rokon(2798):   addToActive(229433297)
12-13 15:05:17.876: WARN/System.err(2798): java.lang.Exception:   addToActive(229433297)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.Debug.error(Debug.java:71)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.TextureManager.addToActive(TextureManager.java:54)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.Texture.onLoadTexture(Texture.java:228)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.GLHelper.checkTextureValid(GLHelper.java:201)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.GLHelper.bindTexture(GLHelper.java:189)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.GLHelper.drawNormal(GLHelper.java:366)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.DrawableObject.onDrawNormal(DrawableObject.java:382)
12-13 15:05:17.876: WARN/System.err(2798):     at com.stickycoding.rokon.DrawableObject.onDraw(DrawableObject.java:360)
12-13 15:05:17.884: WARN/System.err(2798):     at com.stickycoding.rokon.Layer.onDraw(Layer.java:138)
12-13 15:05:17.884: WARN/System.err(2798):     at com.stickycoding.rokon.Scene.onDraw(Scene.java:934)
12-13 15:05:17.884: WARN/System.err(2798):     at com.stickycoding.rokon.RokonRenderer.onDrawFrame(RokonRenderer.java:40)
12-13 15:05:17.884: WARN/System.err(2798):     at com.stickycoding.rokon.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1112)
12-13 15:05:17.884: WARN/System.err(2798):     at com.stickycoding.rokon.GLSurfaceView$GLThread.run(GLSurfaceView.java:946)

What causes this error?  Anybody know of how to fix this error?  And is it possible that my textures are causing this problem?

答: Do your textures need to have the size with the power of 2, like 64px x 64px, 128x128, 256... etc?</p>

ContentLicense: CC BY-SA 2.5


问:
Not Found Page React Router V4
I want to have a not found component on my routes

```<code>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import PropTypes from 'prop-types';
import Home from './components/home';
import MyWork from './components/work/myWork';
import WorkShow from './components/work/workShow';
import NavigationBar from './components/shared/navbar';
import Footer from './components/shared/footer';
import CategoryShow from './components/category/categoryShow';
import PostIndex from './components/post/postIndex';
import PostShow from './components/post/postShow';
import PostSearch from './components/post/postSearch';
import TagShow from './components/tag/tagShow';
import NotFound from './components/shared/notFound';

const DefaultLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

DefaultLayout.propTypes = ({
  component: PropTypes.shape.isRequired,
});

const BlogLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar path="blog" />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

BlogLayout.propTypes = ({
  component: PropTypes.shape.isRequired,
});

const Work = () => (
  <Switch>
    <Route exact path="/my-work" component={MyWork} />
    <Route path="/my-work/:workName" component={WorkShow} />
  </Switch>
);

const Blog = () => (
  <Switch>
    <Route exact path="/blog" component={PostIndex} />
    <Route path="/blog/search" component={PostSearch} />
    <Route exact path="/blog/:postName" component={PostShow} />
    <Route path="/blog/category/:categoryName" component={CategoryShow} />
    <Route path="/blog/tag/:tagName" component={TagShow} />
  </Switch>
);

const routes = (
  <div>
    <DefaultLayout exact path="/" component={Home} />
    <DefaultLayout path="/my-work" component={Work} />
    <BlogLayout path="/blog" component={Blog} />
  </div>
);

export default routes;
</code>```

I tried:

```<code>const routes = (
      <div>
        <DefaultLayout exact path="/" component={Home} />
        <DefaultLayout path="/my-work" component={Work} />
        <BlogLayout path="/blog" component={Blog} />
        <BlogLayout path="*" component={NotFound} />
      </div>
    );
</code>```

But the NotFound component always renders, I only want this to render when the user enters an incorrect URL. How would I do this in react router v4?

答:
You just need to use Switch and Route without path property.    </p>

```<code>const routes = (
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/my-work" component={Work} />
        <Route path="/blog" component={Blog} />
        <Route component={NotFound} />
    <Switch>
);
</code>```

Title: Not Found Page React Router V4

Body:
I want to have a not found component on my routes

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import PropTypes from 'prop-types';
import Home from './components/home';
import MyWork from './components/work/myWork';
import WorkShow from './components/work/workShow';
import NavigationBar from './components/shared/navbar';
import Footer from './components/shared/footer';
import CategoryShow from './components/category/categoryShow';
import PostIndex from './components/post/postIndex';
import PostShow from './components/post/postShow';
import PostSearch from './components/post/postSearch';
import TagShow from './components/tag/tagShow';
import NotFound from './components/shared/notFound';

const DefaultLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (

        <NavigationBar />

          <Component {...matchProps} />

    )}
  />
);

DefaultLayout.propTypes = ({
  component: PropTypes.shape.isRequired,
});

const BlogLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (

        <NavigationBar path="blog" />

          <Component {...matchProps} />

    )}
  />
);

BlogLayout.propTypes = ({
  component: PropTypes.shape.isRequired,
});

const Work = () => (
  <Switch>
    <Route exact path="/my-work" component={MyWork} />
    <Route path="/my-work/:workName" component={WorkShow} />
  </Switch>
);

const Blog = () => (
  <Switch>
    <Route exact path="/blog" component={PostIndex} />
    <Route path="/blog/search" component={PostSearch} />
    <Route exact path="/blog/:postName" component={PostShow} />
    <Route path="/blog/category/:categoryName" component={CategoryShow} />
    <Route path="/blog/tag/:tagName" component={TagShow} />
  </Switch>
);

const routes = (

    <DefaultLayout exact path="/" component={Home} />
    <DefaultLayout path="/my-work" component={Work} />
    <BlogLayout path="/blog" component={Blog} />

);

export default routes;

I tried:

const routes = (

        <DefaultLayout exact path="/" component={Home} />
        <DefaultLayout path="/my-work" component={Work} />
        <BlogLayout path="/blog" component={Blog} />
        <BlogLayout path="*" component={NotFound} />

    );

But the NotFound component always renders, I only want this to render when the user enters an incorrect URL. How would I do this in react router v4?

Body:
You just need to use Switch and Route without path property.

const routes = (
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/my-work" component={Work} />
        <Route path="/blog" component={Blog} />
        <Route component={NotFound} />
    <Switch>
);


问:
Build error on deploy only: cannot use appengine.AccessToken
A simple Go GAE (Flexible) app I'm writing fails to deploy as soon as I bring in cloud.google.com packages to use Google services. Snippet from deploy log:

```<code>...
golang.org/x/oauth2/google
# golang.org/x/oauth2/google
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:12: cannot use appengine.AccessToken (type func(appengine.Context, ...string) (string, time.Time, error)) as type func("golang.org/x/net/context".Context, ...string) (string, time.Time, error) in assignment
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:13: cannot use appengine.AppID (type func(appengine.Context) string) as type func("golang.org/x/net/context".Context) string in assignment
...
</code>```

This can be reproduced locally via go install -v -tags appenginevm within the app to deploy. The app builds and runs fine without the appenginevm tag.

I've just followed the helloworld example and modified it, and can't find anyone else with this problem (a few Google searches yielded nothing useful).

Anyone know how to fix this / what I'm missing?

Thanks in advance. The full program is below.

```<code>package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "cloud.google.com/go/storage"
)

var (
    client *storage.Client
)

func main() {
    ctx := context.Background()

    var err error
    client, err = storage.NewClient(ctx)
    if err != nil {
        log.Fatal(err)
        return
    }
    defer client.Close()

    http.HandleFunc("/_ah/health", healthCheckHandler)
    http.HandleFunc("/", indexHandler)
    log.Print("Listening on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func httpError(w http.ResponseWriter, err error) {
    log.Println(err)
    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()

    finish := time.Since(start)
    fmt.Fprintf(w, "Done %v %v", finish)
}
</code>```

Here is the app.yaml

```<code>env: flex
runtime: go
</code>```

答:
You probably should use </p>

```<code>import "golang.org/x/net/context"
</code>```

<p>instead of </p>

```<code>import "context"
</code>```

Body:
A simple Go GAE (Flexible) app I'm writing fails to deploy as soon as I bring in cloud.google.com packages to use Google services. Snippet from deploy log:

...
golang.org/x/oauth2/google
# golang.org/x/oauth2/google
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:12: cannot use appengine.AccessToken (type func(appengine.Context, ...string) (string, time.Time, error)) as type func("golang.org/x/net/context".Context, ...string) (string, time.Time, error) in assignment
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:13: cannot use appengine.AppID (type func(appengine.Context) string) as type func("golang.org/x/net/context".Context) string in assignment
...

This can be reproduced locally via go install -v -tags appenginevm within the app to deploy. The app builds and runs fine without the appenginevm tag.

I've just followed the helloworld example and modified it, and can't find anyone else with this problem (a few Google searches yielded nothing useful).

Anyone know how to fix this / what I'm missing?

Thanks in advance. The full program is below.

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "cloud.google.com/go/storage"
)

var (
    client *storage.Client
)

func main() {
    ctx := context.Background()

    var err error
    client, err = storage.NewClient(ctx)
    if err != nil {
        log.Fatal(err)
        return
    }
    defer client.Close()

    http.HandleFunc("/_ah/health", healthCheckHandler)
    http.HandleFunc("/", indexHandler)
    log.Print("Listening on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func httpError(w http.ResponseWriter, err error) {
    log.Println(err)
    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()

    finish := time.Since(start)
    fmt.Fprintf(w, "Done %v %v", finish)
}

Here is the app.yaml

env: flex
runtime: go

Body:
You probably should use

import "golang.org/x/net/context"

instead of

import "context"


问:
Link Button in PDF Doesn't Work
I have a FileMaker Pro 11 layout containing a button with an action of "open URL." When the layout is saved as a PDF, the button appears but no longer works (clicking on it doesn't do anything). Is there a way to save as PDF with the PDF containing a working "open URL" button?

Thank you,

Ben

答: You have to be in browse mode for your button to work. You are probably in preview mode. Buttons don't work in preview mode (which makes sense as it is just a preview of what will be printed).</p>

Title: Link Button in PDF Doesn't Work


问:
Remove selected destination from dropdown list to another dropdown list
I am currently developing an airline reservation using PHP(Codeigniter). Currently the fields/radio buttons that I have:

2 radio button

1) One way

2) Round Trip

2 dropdown list

1) From

2) To

and so on..

When the user trying to book, the user can't repeat the destination he inputted  "from destination" into "to destination". Example: I have 3 destinations; 1) Country 1; 2) Country 2; 3) Country 3, then user tries to book. From: Country 1, To: Country1. The Country 1 in the "To:"  should not be display because he already use it in the From Destination.

NOTE: The thing that I do first is, call all the available destinations in my controller then call it in my view using my foreach.

```<code><div class="pure-u-1-1 fromto">
               <div class="pure-u-1-1">
                  <label for="from" class="margin2px">From</label>
                  <!-- <input type="text" class="fromto"><br> -->
                  <select class="fromto" name="flight_from">
                  <?php foreach($flight as $a):?>
                    <option value ="<?= $a->flight_name?>" ><?= $a->flight_destination?></option>
                  <?php endforeach?>

                  </select>

               </div>
                <div class="pure-u-1-1">
                  <label for="to" class="tomargin">To</label>
                  <!-- <input type="text" class="fromto"><br> -->
                  <select class="fromto" name="flight_to">
                    <?php foreach($flight as $a):?>
                      <option value ="<?= $a->flight_name?>" ><?= $a->flight_destination?></option>
                    <?php endforeach?>
                  </select>
                </div>
</code>```

Question: How can I prevent it from repeating the country I selected in my "from destination" into "to destination"?

答:
You may use jQuery:

$('select[name=flight_from]').on('change',function(){
  $("select[name=flight_to]").find('option').show();
  var from = $(this).find(":selected").val();
  $("select[name=flight_to]").val('');
  if ( from != "" ) {
      $("select[name=flight_to]").find( 'option:contains("'+from+'")' ).hide();
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="flight_from">
  <option value="">-- Please select depature --</option>
  <option>Country 1</option>
  <option>Country 2</option>
  <option>Country 3</option>
</select>

<select name="flight_to">
  <option value="">-- Please select destination --</option>
  <option>Country 1</option>
  <option>Country 2</option>
  <option>Country 3</option>
</select>

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

Body:
I am currently developing an airline reservation using PHP(Codeigniter). Currently the fields/radio buttons that I have:

2 radio button

1) One way

2) Round Trip

2 dropdown list

1) From

2) To

and so on..

When the user trying to book, the user can't repeat the destination he inputted  "from destination" into "to destination". Example: I have 3 destinations; 1) Country 1; 2) Country 2; 3) Country 3, then user tries to book. From: Country 1, To: Country1. The Country 1 in the "To:"  should not be display because he already use it in the From Destination.

NOTE: The thing that I do first is, call all the available destinations in my controller then call it in my view using my foreach.

                  From

                  <select class="fromto" name="flight_from">
                  <?php foreach($flight as $a):?>
                    <option value ="<?= $a->flight_name?>" ><?= $a->flight_destination?></option>
                  <?php endforeach?>

                  </select>

                  To

                  <select class="fromto" name="flight_to">
                    <?php foreach($flight as $a):?>
                      <option value ="<?= $a->flight_name?>" ><?= $a->flight_destination?></option>
                    <?php endforeach?>
                  </select>

Question: How can I prevent it from repeating the country I selected in my "from destination" into "to destination"?

Body:
You may use jQuery:

$('select[name=flight_from]').on('change',function(){
  $("select[name=flight_to]").find('option').show();
  var from = $(this).find(":selected").val();
  $("select[name=flight_to]").val('');
  if ( from != "" ) {
      $("select[name=flight_to]").find( 'option:contains("'+from+'")' ).hide();
  }
})

<select name="flight_from">
  <option value="">-- Please select depature --</option>
  <option>Country 1</option>
  <option>Country 2</option>
  <option>Country 3</option>
</select>

<select name="flight_to">
  <option value="">-- Please select destination --</option>
  <option>Country 1</option>
  <option>Country 2</option>
  <option>Country 3</option>
</select>

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


问:
How to find phone number in list array when you know name?
I need to write a code which finds a phone number from an array list when a name is given. Here is what i currently have:

```<code>public class Person {

    private String name;
    private String number;

    public Person(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public String getName() {
        return this.name;
    }

    public String getNumber() {
        return this.number;
    }

    public String toString() {
        return "" + getName()+ "  number: " + getNumber();
    }
}
</code>```

And here is the class for phone numbers list:

```<code>import java.util.ArrayList;

public class Numbers {
    private ArrayList<Person> memo;

    public Numbers() {
        this.memo = new ArrayList<>();
    }

    public void addnew(String name, String number) {
        Person newperson = new Person (name, number);
        this.memo.add(newperson);
    }
}
</code>```

答:
Use this method

```<code>public String FindNumber(String UserName){
   for(Person p : [ArrayList<Person>]) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}
</code>```

this object [ArrayList<Person>] Must be the reference of your list

in your case:

you need to fix the builder

```<code>public Numbers() {
    this.memo = new ArrayList<Person>();
}
</code>```

Your function will be

```<code>public String FindNumber(String UserName){
   for(Person p : this.memo ) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}
</code>```

Body:
I need to write a code which finds a phone number from an array list when a name is given. Here is what i currently have:

public class Person {

    private String name;
    private String number;

    public Person(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public String getName() {
        return this.name;
    }

    public String getNumber() {
        return this.number;
    }

    public String toString() {
        return "" + getName()+ "  number: " + getNumber();
    }
}

And here is the class for phone numbers list:

import java.util.ArrayList;

public class Numbers {
    private ArrayList<Person> memo;

    public Numbers() {
        this.memo = new ArrayList<>();
    }

    public void addnew(String name, String number) {
        Person newperson = new Person (name, number);
        this.memo.add(newperson);
    }
}

Body:
Use this method

public String FindNumber(String UserName){
   for(Person p : [ArrayList<Person>]) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}

this object [ArrayList<Person>] Must be the reference of your list

in your case:

you need to fix the builder

public Numbers() {
    this.memo = new ArrayList<Person>();
}

Your function will be

public String FindNumber(String UserName){
   for(Person p : this.memo ) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}


问:
How to install wordpress in laravel public folder
i also follow this link but this is not my solution - laravel and wordpress on the same domain(laravel in subfolder)

i want to add wordpress in my laravel site.

so i install all wordpress in my laravel's public folders. here i create one folder "blog" and in this folder i install my wordpress site.

but my problem is when i run my wordpress site like that localhost:8000/blog it work fine

But when i am try to oprn another link then laravel redirect me 404 page not found.

so how to run wordpress in laravel if make any changes in any file so please any one help me.

my laravel public folder's .htaccess look like that

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</code>```

答:
To run wordpress as subdirectory, you must change the .htaccess file inside worpress directory like below:

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

Follow this guide for more information
https://wordpress.org/support/article/giving-wordpress-its-own-directory/

Body:
i also follow this link but this is not my solution - laravel and wordpress on the same domain(laravel in subfolder)

i want to add wordpress in my laravel site.

so i install all wordpress in my laravel's public folders. here i create one folder "blog" and in this folder i install my wordpress site.

but my problem is when i run my wordpress site like that localhost:8000/blog it work fine

But when i am try to oprn another link then laravel redirect me 404 page not found.

so how to run wordpress in laravel if make any changes in any file so please any one help me.

my laravel public folder's .htaccess look like that

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Body:
To run wordpress as subdirectory, you must change the .htaccess file inside worpress directory like below:

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

Follow this guide for more information
https://wordpress.org/support/article/giving-wordpress-its-own-directory/


问:
Different ways of clearing lists
Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?

```<code>old_list = []
old_list = list()
</code>```

The reason I ask is that I just saw this in some running code:

```<code>del old_list[ 0:len(old_list) ]
</code>```

答:
Doing alist = [] does not clear the list, just creates an empty list and binds it to the variable alist. The old list will still exist if it had other variable bindings.

To actually clear a list in-place, you can use any of these ways:

alist.clear()  # Python 3.3+, most obvious

del alist[:]

alist[:] = []

alist *= 0     # fastest

See the Mutable Sequence Types documentation page for more details.

Title: Different ways of clearing lists

Body:
Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?

old_list = []
old_list = list()

The reason I ask is that I just saw this in some running code:

del old_list[ 0:len(old_list) ]


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
```<code>boolean array[100] = {true:first 15, false:rest};
shuffle(array);
while(array.size > 0)
{
    // pop first element of the array.
    if(element == true)
       do_action();
    else
       do_something_else();
}
// redo the whole thing again when no elements are left.
</code>```


问:
No provider for Router?
Im getting this error:

EXCEPTION: Error in ./AppComponent class AppComponent - inline
template:0:0 caused by: No provider for Router!

This is my app component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}
```
<p>I tried this in my app module:</p>
<pre class="lang-ts prettyprint-override"><code>import { RouterModule } from '@angular/router';

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  bootstrap: [AppComponent, RouterModule]
</code>```

But then i get this error:

Error: Error: No Directive annotation found on RouterModule

I found some examples but they use router-deprecated, and i dont have that folder. Do i need that or what? Any suggstion?

UPDATE:

This is my app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginModule } from './login/login.module';
import { RouterModule } from '@angular/router';
//import 'rxjs/Rx';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
<p>app.component:</p>
<pre class="lang-ts prettyprint-override"><code>import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}
</code>```

And then i have login.component:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

          // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
                function(response) { console.log("Success Response" + response)},
                function(error) { console.log("Error happened" + error)},
                function() {
                   console.log("the subscription is completed");
                     this.router.navigate(['/About']);

                 }
            );

           }
}
```
<p>Maybe problem is in this line:</p>
<pre class="lang-ts prettyprint-override"><code> this.router.navigate(['/home']);
</code>```

This is my login.module:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { LoginComponent } from './components/login.component';
import { RouterModule } from '@angular/router';

import { LoginService } from './services/login.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
     HttpModule,
    JsonpModule,
    RouterModule

  ],
  declarations: [
    LoginComponent
  ],

  providers: [
      LoginService
  ],

  exports:[
    LoginComponent
  ]

})
export class LoginModule {
}
```

答:
I had the error of

No provider for Router

It happens when you try to navigate in any service.ts

this.router.navigate(['/home']); like codes in services cause that error.

You should handle navigating in your components. for example: at login.component

```<code>login().subscribe(
        (res) => this.router.navigate(['/home']),
        (error: any) => this.handleError(error));
</code>```

Annoying errors happens when we are newbie :)

Title: No provider for Router?

Body:
Im getting this error:

EXCEPTION: Error in ./AppComponent class AppComponent - inline
template:0:0 caused by: No provider for Router!

This is my app component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

I tried this in my app module:

import { RouterModule } from '@angular/router';

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  bootstrap: [AppComponent, RouterModule]

But then i get this error:

Error: Error: No Directive annotation found on RouterModule

I found some examples but they use router-deprecated, and i dont have that folder. Do i need that or what? Any suggstion?

UPDATE:

This is my app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginModule } from './login/login.module';
import { RouterModule } from '@angular/router';
//import 'rxjs/Rx';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

And then i have login.component:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

          // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
                function(response) { console.log("Success Response" + response)},
                function(error) { console.log("Error happened" + error)},
                function() {
                   console.log("the subscription is completed");
                     this.router.navigate(['/About']);

                 }
            );

           }
}

Maybe problem is in this line:

 this.router.navigate(['/home']);

This is my login.module:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { LoginComponent } from './components/login.component';
import { RouterModule } from '@angular/router';

import { LoginService } from './services/login.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
     HttpModule,
    JsonpModule,
    RouterModule

  ],
  declarations: [
    LoginComponent
  ],

  providers: [
      LoginService
  ],

  exports:[
    LoginComponent
  ]

})
export class LoginModule {
}

Body:
I had the error of

No provider for Router

It happens when you try to navigate in any service.ts

this.router.navigate(['/home']); like codes in services cause that error.

You should handle navigating in your components. for example: at login.component

login().subscribe(
        (res) => this.router.navigate(['/home']),
        (error: any) => this.handleError(error));

Annoying errors happens when we are newbie :)


问:
Is it possible to auto initialize a date field in MySQL?
So I would like to auto initialize a date field (without the time), and then auto initialize a time field (without the date) in 2 separate columns (I don't want them in the same column)...

Is this possible?

I thought this would work... but it doesn't.

```<code>CREATE TABLE `account_ip_history` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned NOT NULL,
  `ip_address` varchar(39) NOT NULL,
  `created_date` date NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_time` time NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
</code>```

答:
The documentation is quite clear:

TIMESTAMP and DATETIME columns can be automatically initializated and
  updated to the current date and time (that is, the current timestamp).

If DATE could be initialized it would be included in the documentation.

So, simply do:

```<code>CREATE TABLE `account_ip_history` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned NOT NULL,
  `ip_address` varchar(39) NOT NULL,
  `created_datetime` datetim NOT NULL DEFAULT CURRENT_TIMESTAMP
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
</code>```

You can extract the date and time components when you query the table.

Body:
So I would like to auto initialize a date field (without the time), and then auto initialize a time field (without the date) in 2 separate columns (I don't want them in the same column)...

Is this possible?

I thought this would work... but it doesn't.

CREATE TABLE `account_ip_history` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned NOT NULL,
  `ip_address` varchar(39) NOT NULL,
  `created_date` date NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_time` time NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

Body:
The documentation is quite clear:

TIMESTAMP and DATETIME columns can be automatically initializated and
  updated to the current date and time (that is, the current timestamp).

If DATE could be initialized it would be included in the documentation.

So, simply do:

CREATE TABLE `account_ip_history` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned NOT NULL,
  `ip_address` varchar(39) NOT NULL,
  `created_datetime` datetim NOT NULL DEFAULT CURRENT_TIMESTAMP
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

You can extract the date and time components when you query the table.


问:
SweetAlert: Missing title argument
I'm using sweet alert and i've got the following error when the error function is called from sweet alert. It works fine when the operation from the php files is successful. How can solve this problem? Many thanks

```<code>SweetAlert: Missing "title" argument!
</code>```

This is my javascript code

```<code>function DeletePost() {
    swal({
        title: "Sei Sicuro?",
        text: "Questa operazione non è reversibile ed eliminerà la comunicazione i commenti ad essa connessi dal database!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, elimina comunicazione!",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, non procedere!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {

            $.ajax({
                url: "../delete_all.php",
                method: "POST",
                dataType: 'json',

                success: function(response) {
                  // swal('Deleted!', response.message, response.status);
                    swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    },

                    function(){

                      location.reload();

                    }

                  );

                },

                error: function(response) {

                  swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    });

                }

            });

        } else {
            swal("Annulato!", "Operazione annullata con successo!", "error");
        }
    });
}
</code>```

And this is my php file

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Prelevo l'id dell'amministratore e lo passo ad una variabile
    $userid = $_SESSION['user_id'];

    if($delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'")){

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    }else{

    // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    }

    echo json_encode($response);

}
</code>```

答:
many thanks for your help, it think the problem was in the php file I've changed it and now it works fine, the reason why i wanted to test it is so i can validate and sanitize the variable before i do a query to the database and i wanted to show an error if the query can't be performed

This is my php file

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $user_id = 'prova';

    if (!filter_var($user_id, FILTER_VALIDATE_INT)) {
        // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    echo json_encode($response);

    }else{

    // Prelevo l'id dell'amministratore e lo passo ad una variabile effettuaando un sanitize
    $user_id = filter_var($_SESSION['user_id'], FILTER_SANITIZE_NUMBER_INT);

    $delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'");

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    echo json_encode($response);

    }
</code>```

To generate the error i've set $user_id as not integer

It is now working fine without using
title: JSON.parse(response.respoonseText).title
or
response= JSON.parse(response);

Title: SweetAlert: Missing title argument

Body:
I'm using sweet alert and i've got the following error when the error function is called from sweet alert. It works fine when the operation from the php files is successful. How can solve this problem? Many thanks

SweetAlert: Missing "title" argument!

This is my javascript code

function DeletePost() {
    swal({
        title: "Sei Sicuro?",
        text: "Questa operazione non è reversibile ed eliminerà la comunicazione i commenti ad essa connessi dal database!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Si, elimina comunicazione!",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, non procedere!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {

            $.ajax({
                url: "../delete_all.php",
                method: "POST",
                dataType: 'json',

                success: function(response) {
                  // swal('Deleted!', response.message, response.status);
                    swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    },

                    function(){

                      location.reload();

                    }

                  );

                },

                error: function(response) {

                  swal({

                      title: response.title,
                      text: response.message,
                      type: response.status

                    });

                }

            });

        } else {
            swal("Annulato!", "Operazione annullata con successo!", "error");
        }
    });
}

And this is my php file

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Prelevo l'id dell'amministratore e lo passo ad una variabile
    $userid = $_SESSION['user_id'];

    if($delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'")){

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    }else{

    // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    }

    echo json_encode($response);

}

Body:
many thanks for your help, it think the problem was in the php file I've changed it and now it works fine, the reason why i wanted to test it is so i can validate and sanitize the variable before i do a query to the database and i wanted to show an error if the query can't be performed

This is my php file

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $user_id = 'prova';

    if (!filter_var($user_id, FILTER_VALIDATE_INT)) {
        // Passo messaggio di risposta se l'operazione non è andata a buon fine
    $response['title']  = 'Si è verificato un errore!';
    $response['message'] = 'Non è stato possibile eliminare i messaggi. Per favore contatta amministratore di sistema';
    $response['status']  = 'error';

    echo json_encode($response);

    }else{

    // Prelevo l'id dell'amministratore e lo passo ad una variabile effettuaando un sanitize
    $user_id = filter_var($_SESSION['user_id'], FILTER_SANITIZE_NUMBER_INT);

    $delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'");

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Passo messaggio di risposta se l'operazione è andata a buon fine
    $response['title']  = 'Messaggi eliminati!';
    $response['message'] = 'Tutti i messaggi sono stati eliminati con successo.';
    $response['status']  = 'success';

    echo json_encode($response);

    }

To generate the error i've set $user_id as not integer

It is now working fine without using
title: JSON.parse(response.respoonseText).title
or
response= JSON.parse(response);


问:
Java multithreading: cannot change thread priority
I have 2 threads whose priority has been set using setPriority() function and still it shows same priority?

Here is the code snippet:

```<code>public class threadtest  extends Thread {
    public void run() {
       System.out.println("running thread name is:" + Thread.currentThread().getName());
       System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        threadtest tt = new threadtest();
        tt.setPriority(MAX_PRIORITY);
        threadtest tt1 = new threadtest();
        tt1.setPriority(MIN_PRIORITY);
        tt1.run();
        tt.run();
    }
}
</code>```

The output if the above code in my ECLIPSE neon is.

```<code>running thread name is:main
running thread priority is:5
running thread name is:main
running thread priority is:5
</code>```

Even after having different priorities,it shows similar priorities.

答:
You should call Thread.start(), not Thread.run().

When you directly call the run() method than the code inside run() method will not be executed on a new thread, instead it will be executed on the same thread. On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method:

```<code>public class threadtest extends Thread {
    public void run() {
        System.out.println("running thread name is:" + Thread.currentThread().getName());
        System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        threadtest tt = new threadtest();
        tt.setPriority(MAX_PRIORITY);
        threadtest tt1 = new threadtest();
        tt1.setPriority(MIN_PRIORITY);
        tt1.start();
        tt.start();
    }
}
</code>```

Output:

```<code>running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1
</code>```

Body:
I have 2 threads whose priority has been set using setPriority() function and still it shows same priority?

Here is the code snippet:

public class threadtest  extends Thread {
    public void run() {
       System.out.println("running thread name is:" + Thread.currentThread().getName());
       System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        threadtest tt = new threadtest();
        tt.setPriority(MAX_PRIORITY);
        threadtest tt1 = new threadtest();
        tt1.setPriority(MIN_PRIORITY);
        tt1.run();
        tt.run();
    }
}

The output if the above code in my ECLIPSE neon is.

running thread name is:main
running thread priority is:5
running thread name is:main
running thread priority is:5

Even after having different priorities,it shows similar priorities.

Body:
You should call Thread.start(), not Thread.run().

When you directly call the run() method than the code inside run() method will not be executed on a new thread, instead it will be executed on the same thread. On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method:

public class threadtest extends Thread {
    public void run() {
        System.out.println("running thread name is:" + Thread.currentThread().getName());
        System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        threadtest tt = new threadtest();
        tt.setPriority(MAX_PRIORITY);
        threadtest tt1 = new threadtest();
        tt1.setPriority(MIN_PRIORITY);
        tt1.start();
        tt.start();
    }
}

Output:

running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1


问:
Cant access correct number of vertices for a 3d model (.OBJ) using Assimp
I am trying to access the vertices of an .Obj file and later do some operations on them. But the number of Vertices shown by assimp lib. are actually not the same as if I check them by opening the .Obj file with an text editor (e.g. notepad++). Any suggestion in this regard would be really nice, Thanks in advance.
I am using following code snippet:

```<code>   std::string path = "model.obj";
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate);
    //i've changed the parameters but the issue is same

    auto mesh = scene->mMeshes[0]; //Zero index because Im loading single model only

    ofstream outputfile; //write the vertices in a text file read by assimp
    outputfile.open("vertex file.txt");

    for (int i = 0; i < mesh->mNumVertices; i++) {

        auto& v = mesh->mVertices[i];

        outputfile << v.x <<" " ;
        outputfile << v.y << " ";
        outputfile << v.z << " "<<endl;

    }

    outputfile.close();
</code>```

Difference between the no. of vertices in both files can be seen at index value here

答: Are the additional vertices just copies of the existing ones? If that is the case, it is probably because said vertices are part of more than one face. Since Assimp stores the normals, UV mapping, etc along with the vertex position, the same vertex that is part of two different faces has two normals, two UV coordinates, etc. That is probably the reason for the additional vertices.</p>

Body:
I am trying to access the vertices of an .Obj file and later do some operations on them. But the number of Vertices shown by assimp lib. are actually not the same as if I check them by opening the .Obj file with an text editor (e.g. notepad++). Any suggestion in this regard would be really nice, Thanks in advance.
I am using following code snippet:

   std::string path = "model.obj";
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate);
    //i've changed the parameters but the issue is same

    auto mesh = scene->mMeshes[0]; //Zero index because Im loading single model only

    ofstream outputfile; //write the vertices in a text file read by assimp
    outputfile.open("vertex file.txt");

    for (int i = 0; i < mesh->mNumVertices; i++) {

        auto& v = mesh->mVertices[i];

        outputfile << v.x <<" " ;
        outputfile << v.y << " ";
        outputfile << v.z << " "<<endl;

    }

    outputfile.close();

Difference between the no. of vertices in both files can be seen at index value here


问:
Why tensor.view() is not working in pytorch?
I have the following piece of code.

```<code>embedded = self.embedding(input).view(1, 1, -1)
embedded = self.drop(embedded)
print(embedded[0].size(), hidden[0].size())
concatenated_output = torch.cat((embedded[0], hidden[0]), 1)
</code>```

The last line of the code is giving me the following error.

RuntimeError: inconsistent tensor sizes at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.9_1487344852722/work/torch/lib/THC/generic/THCTensorMath.cu:141

Please note, when I am printing the tensor shapes at line no. 3, I am getting the following output.

```<code>torch.size([1, 300]) torch.size([1, 1, 300])
</code>```

Why I am getting [1, 300] shape for embedded tensor even though I have used the view method as view(1, 1, -1)?

Any help would be appreciated!

答:
embedded was a 3d-tensor and hidden was a tuple of two elements (hidden states and cell states) where each element is a 3d-tensor. hidden was the output from LSTM layer. In PyTorch, LSTM returns hidden states [h] and cell states [c] as a tuple which made me confused about the error.

So, I updated the last line of the code as follows and it solved the problem.

```<code>concatenated_output = torch.cat((embedded, hidden[0]), 1)
</code>```

Body:
I have the following piece of code.

embedded = self.embedding(input).view(1, 1, -1)
embedded = self.drop(embedded)
print(embedded[0].size(), hidden[0].size())
concatenated_output = torch.cat((embedded[0], hidden[0]), 1)

The last line of the code is giving me the following error.

RuntimeError: inconsistent tensor sizes at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.9_1487344852722/work/torch/lib/THC/generic/THCTensorMath.cu:141

Please note, when I am printing the tensor shapes at line no. 3, I am getting the following output.

torch.size([1, 300]) torch.size([1, 1, 300])

Why I am getting [1, 300] shape for embedded tensor even though I have used the view method as view(1, 1, -1)?

Any help would be appreciated!

Body:
embedded was a 3d-tensor and hidden was a tuple of two elements (hidden states and cell states) where each element is a 3d-tensor. hidden was the output from LSTM layer. In PyTorch, LSTM returns hidden states [h] and cell states [c] as a tuple which made me confused about the error.

So, I updated the last line of the code as follows and it solved the problem.

concatenated_output = torch.cat((embedded, hidden[0]), 1)


问:
Trying to add html5shiv.js to my code so it can render with IE
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="Description" content="C.V"/>
</code>```

I have added code below to render in IE but will not work.

```<code><!--[if lt IE 9]>
<script src="Assets/html5shiv/html5shiv.js"></script>
<![endif]-->

<link rel="stylesheet" type= "text/css" href="Assets/aboutme.css"/>
</code>```

答:
if you want to target all versions of IE(except 10) use this:

```<code><!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->
</code>```

For IE 10 check this:
IE 10 Specific Styles

hope it helps.

EDIT:
and last, check this for IE 11 & 12+(EDGE) Detect Internet Explorer (IE) up to version 11 and Edge (12+)

Body:
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta name="Description" content="C.V"/>

I have added code below to render in IE but will not work.

<link rel="stylesheet" type= "text/css" href="Assets/aboutme.css"/>

Body:
if you want to target all versions of IE(except 10) use this:

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

For IE 10 check this:
IE 10 Specific Styles

hope it helps.

EDIT:
and last, check this for IE 11 & 12+(EDGE) Detect Internet Explorer (IE) up to version 11 and Edge (12+)


问:
How to obtain csrf token for a python POST request to Django server
Without the csrf token I am getting a 403 Response, so it looks like I need it. I am currently trying to do this:

```<code>import requests
import sys

URL = 'http://127.0.0.1:8000/toasterinfo'

client = requests.session()

# Retrieve the CSRF token first
client.get(URL)  # sets cookie
csrftoken = client.cookies['csrf']
r = client.post(URL, data={'number': 12524,
  'type': 'issue', 'action': 'show', "csrfmiddlewaretoken": csrftoken}, headers=dict(Referer=URL))
print(r)
</code>```

Yet I am getting an error:

```<code>    Traceback (most recent call last):
  File "django_client.py", line 10, in <module>
    csrftoken = client.cookies['csrftoken']
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 327, in __getitem__
    return self._find_no_duplicates(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 398, in _find_no_duplicates
    raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"
</code>```

What am I doing wrong?

答:
The CSRF Token is a client to server security feature to protect your users from a cross-site request forgery.

You are doing a server to server request so the CSRF is useless. You should consider removing the requirement for the CSRF and using a proper authentification method for your server to server request.

You can remove the CSRF token verification used the following decorator on your view.

@csrf_exempt

See https://docs.djangoproject.com/en/dev/_modules/django/views/decorators/csrf/#csrf_exempt

A token based authentification method with an HTTPS connexion would probably fit your case.

Body:
Without the csrf token I am getting a 403 Response, so it looks like I need it. I am currently trying to do this:

import requests
import sys

URL = 'http://127.0.0.1:8000/toasterinfo'

client = requests.session()

# Retrieve the CSRF token first
client.get(URL)  # sets cookie
csrftoken = client.cookies['csrf']
r = client.post(URL, data={'number': 12524,
  'type': 'issue', 'action': 'show', "csrfmiddlewaretoken": csrftoken}, headers=dict(Referer=URL))
print(r)

Yet I am getting an error:

    Traceback (most recent call last):
  File "django_client.py", line 10, in <module>
    csrftoken = client.cookies['csrftoken']
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 327, in __getitem__
    return self._find_no_duplicates(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py", line 398, in _find_no_duplicates
    raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"

What am I doing wrong?


问:
Bootstrap Mobile versions have space on the right side, container is also not proper size. have overflow-x:hidden.. Any ideas on how to fix it?
Bootstrap Mobile versions have space on the right side, container is also not proper size. have overflow-x:hidden..

I also double checked the container and rows to make sure the containers divs are all closed and there are no nested containers, or containers inside of rows.

You can view a sample here: http://holbrookautoparts.com/mock/index.html

答:
The problem is your input

<input type="email" class="form-control input-lg text-center font-heavy" id="contact-email" placeholder="Enter Email Address">```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media (max-width: 568px)
style.css:932
.signupform input[type="email"] {
    width: 100%;
    height: 60px;
}</code>```

change width to 100%;

and maybe the img, maybe add img-responsive.

This block made this problem in my opinion

Body:
The problem is your input

<input type="email" class="form-control input-lg text-center font-heavy" id="contact-email" placeholder="Enter Email Address">

@media (max-width: 568px)
style.css:932
.signupform input[type="email"] {
    width: 100%;
    height: 60px;
}

change width to 100%;

and maybe the img, maybe add img-responsive.

This block made this problem in my opinion


问:
Swift Firebase Email Verification always returning false
I've been trying to make this work but isEmailVerified keeps returning false... even thought I clearly verified the email.

User Creation

```<code>FIRAuth.auth()?.createUser(withEmail: Email.text!, password: Password.text!) { (user:FIRUser?, error:Error?) in
            if error == nil {

                let when = DispatchTime.now() + 1
                DispatchQueue.main.asyncAfter(deadline: when) {

                    FIRAuth.auth()?.currentUser?.sendEmailVerification(completion: { (error) in

                        let post2 = UIAlertController(title: "Verification sent", message: "A Email will be sent to activate your account.", preferredStyle: .alert)

                        post2.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in

                            self.performSegue(withIdentifier: "Sign_in", sender: nil)

                        }))

                        self.present(post2, animated: true, completion: nil)

                    })
                }

            } else {

                self.ErrorMsg.isHidden = false

                self.Password.text = ""

                print(error.debugDescription)
            }

        }
</code>```

User Verification

```<code>FIRAuth.auth()?.addStateDidChangeListener { auth, user in

            if let user = user {
                Shared.shared.User_ID = user.uid
                Shared.shared.User_Email = user.email

                if user.isEmailVerified {

                    // Email Verified
                    self.performSegue(withIdentifier: "Launch_L", sender: nil)

                } else {

                    self.logOut.isHidden = false

                }

            } else {
                self.performSegue(withIdentifier: "Launch_S", sender: nil)
            }

        }
</code>```

Thanks in advance for helping!

答:
I simply needed to refresh the profile with:</p>

```<code>FIRAuth.auth()?.currentUser?.reload()
</code>```

Body:
I've been trying to make this work but isEmailVerified keeps returning false... even thought I clearly verified the email.

User Creation

FIRAuth.auth()?.createUser(withEmail: Email.text!, password: Password.text!) { (user:FIRUser?, error:Error?) in
            if error == nil {

                let when = DispatchTime.now() + 1
                DispatchQueue.main.asyncAfter(deadline: when) {

                    FIRAuth.auth()?.currentUser?.sendEmailVerification(completion: { (error) in

                        let post2 = UIAlertController(title: "Verification sent", message: "A Email will be sent to activate your account.", preferredStyle: .alert)

                        post2.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in

                            self.performSegue(withIdentifier: "Sign_in", sender: nil)

                        }))

                        self.present(post2, animated: true, completion: nil)

                    })
                }

            } else {

                self.ErrorMsg.isHidden = false

                self.Password.text = ""

                print(error.debugDescription)
            }

        }

User Verification

FIRAuth.auth()?.addStateDidChangeListener { auth, user in

            if let user = user {
                Shared.shared.User_ID = user.uid
                Shared.shared.User_Email = user.email

                if user.isEmailVerified {

                    // Email Verified
                    self.performSegue(withIdentifier: "Launch_L", sender: nil)

                } else {

                    self.logOut.isHidden = false

                }

            } else {
                self.performSegue(withIdentifier: "Launch_S", sender: nil)
            }

        }

Thanks in advance for helping!

Body:
I simply needed to refresh the profile with:

FIRAuth.auth()?.currentUser?.reload()


问:
java.nio.file not workin in java 8
I have the following code:

```<code>import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
public class debugImageMain {
    public static void main() throws IOException {
        Path path = Paths.get("path/to/file");
        byte[] data = Files.readAllBytes(path);
    }
}
</code>```

But when I run I get:

Exception in thread "main" java.lang.NoSuchMethodException:
  pdc.conversor.debugImageMain.main([Ljava.lang.String;)    at
  java.lang.Class.getMethod(Class.java:1786)

javac -version gives: javac 1.8.0_60 and I have java VERSION 8 Update 91.

IntelliJ tell me java.nio.file imports are underlined in red and says "Usages of API which isn't available at the configured language level.

Any help please???

答:
The problem is not with java.nio.file, the problem is in the definition of main signature.

The only way to running a program in Java is with the specific public static void main (String [] args) signature.

To fix your current statement, change this:

```<code>public static void main() throws IOException {
</code>```

For this:

```<code>public static void main (String[] args) throws IOException {
</code>```

Check it out these entries first, and second

Title: java.nio.file not workin in java 8

Body:
I have the following code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
public class debugImageMain {
    public static void main() throws IOException {
        Path path = Paths.get("path/to/file");
        byte[] data = Files.readAllBytes(path);
    }
}

But when I run I get:

Exception in thread "main" java.lang.NoSuchMethodException:
  pdc.conversor.debugImageMain.main([Ljava.lang.String;)    at
  java.lang.Class.getMethod(Class.java:1786)

javac -version gives: javac 1.8.0_60 and I have java VERSION 8 Update 91.

IntelliJ tell me java.nio.file imports are underlined in red and says "Usages of API which isn't available at the configured language level.

Any help please???

Body:
The problem is not with java.nio.file, the problem is in the definition of main signature.

The only way to running a program in Java is with the specific public static void main (String [] args) signature.

To fix your current statement, change this:

public static void main() throws IOException {

For this:

public static void main (String[] args) throws IOException {

Check it out these entries first, and second


问:
Kotlin enum class in Android performance
In Java we are told to strictly avoid using enums on Android because they take up twice the memory.

Does this apply to enum class in Kotlin aswell? Will a Kotlin enum be compiled into a Java enum?

答:
It would appear so, yes.

I created this in Kotlin:

```<code>enum class Thingies {
    Red,
    Green,
    Blue
}
</code>```

And decompiled it with javap -v, and here is the header:

```<code>public final class Thingies extends java.lang.Enum<Thingies>
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM
</code>```

Bottom line: they are identical, so you probably have to treat them the same way.

Body:
It would appear so, yes.

I created this in Kotlin:

enum class Thingies {
    Red,
    Green,
    Blue
}

And decompiled it with javap -v, and here is the header:

public final class Thingies extends java.lang.Enum<Thingies>
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM

Bottom line: they are identical, so you probably have to treat them the same way.


问:
Resources for high level introduction into iCalendar rfc 5545
I am grateful to have crossed paths with the 5545 spec.  However, I found that available resources on https://icalendar.org/ & from google are either moderately dense or lacking.

I was hoping to find an iCalendar tutorial, iCalendar 101, Brief intro to iCalendar, RFC 5545 Crash Course or similarly suited resource.

What introductory resources are out there explaining how to use/implement rfc 5545?  Also, is there a suitable competing spec?

I know that some people find these questions obnoxious, so I will confirm that "yes", I did search for a wide set of combinations of the term "introduction, icalendar, rfc, 5545, tutorial" etc before asking this community :)

答: You may find the CalConnect Developer's Guide helpful.</p>


问:
Close a running program from java application
I open up an external application from my java application. How can I close this application from the same Java application?
thanks</p>

答:
The best you can do (without venturing into messy/complicated/platform specific stuff) is to call Process.kill() on the Process object you got when you started the external application.

I don't think this is guaranteed to close the application*, and there is a chance that it may cause it to close uncleanly; i.e. without giving the application a chance to save open files, etc.

* Indeed, on *NIX if you started a "setuid root" process from a non-root Java application, and the OS won't let it send any signals to to.


问:
Linker command failed with exit code 1 error in Xcode project
I was working on my project and suddenly after editing the code and compiling gave this error:

ld: warning: directory not found for option '-

  L/Users/mani/Documents/Classes/Twitter+OAuth/Libraries & Headers' ld:
  duplicate symbol _OBJC_CLASS_$_playSiew in
  /Users/mani/Library/Developer/Xcode/DerivedData/learn-aktrtiwswclovoatyweyquoxmypa/Build/Intermediates/learn.build/Debug-iphonesimulator/learn.build/Objects-normal/i386/playSiew.o
  and
  /Users/mani/Library/Developer/Xcode/DerivedData/learn-aktrtiwswclovoatyweyquoxmypa/Build/Intermediates/learn.build/Debug-iphonesimulator/learn.build/Objects-normal/i386/Thumb.o
  for architecture i386 clang: error: linker command failed with exit
  code 1 (use -v to see invocation)

I never touched the project settings, just edited the code.

What's more strange is that I took out last revised code from svn but still I got the the same error.

答: If this happens to you with CoreData generated classes, combine the +CoreDataProperties and +CoreDataClass into the +CoreDataProperties class and delete the +CoreDataClass. Make sure to search Derived Data for leftovers of the +CoreDataClass. Even after deleting the Derived Data and cleaning I sometimes had Xcode just generate the +CoreDataClass again and again. Deleting it manually in Finder and then re-bulding helped me solve this.</p>


问:
How to access index.html through Wamp localhost?
I have install Wamp on my computer but I can't see my project on my navigator, the Wamp icon is green but when I try to access the file that I put in the www folder trough the virtual LocalHost a blank page is shown.</p>

答:
Please check that there is an index page in the first root directory of your project. That is if its a PHP web application there has to be an index.php page in the first root directory of your project.

Second make sure all the services on your wamp server are turned on. Then access your project like this:

http://localhost/yourProjectName/
or
http://localhost/yourProjectName/index.php

Please also check for spelling errors, its very important.


问:
ServiceStack OrmLite: MySQL connection pool
I understand the topic is not new, I read a few posts but did not come to the answer ...

Each time the connection is opened for a very long time, but the idea was to use a connection pool, is not it?

As I understand it in MySQL you cannot specify a connection pool in the connection string.

How to do the right thing not to spend a lot of time opening the database connection?

Thanks!

```<code>    IDbConnectionFactory = connection = new OrmLiteConnectionFactory(TeleportParams.DbConnectionStr, MySqlDialectProvider.Instance)

  ...

    void function1(){
       var db = connection.Open();
       db.Select("some request");
    }

    void function2(){
       var db = connection.Open();
       db.Select("some request");
    }

...

    function1();
    function2();
</code>```

答:
As I understand it in MySQL you cannot specify a connection pool in the connection string.

You can add pooling=false to the connection string to disable Connection Pooling in MySql.

Body:
I understand the topic is not new, I read a few posts but did not come to the answer ...

Each time the connection is opened for a very long time, but the idea was to use a connection pool, is not it?

As I understand it in MySQL you cannot specify a connection pool in the connection string.

How to do the right thing not to spend a lot of time opening the database connection?

Thanks!

    IDbConnectionFactory = connection = new OrmLiteConnectionFactory(TeleportParams.DbConnectionStr, MySqlDialectProvider.Instance)

  ...

    void function1(){
       var db = connection.Open();
       db.Select("some request");
    }

    void function2(){
       var db = connection.Open();
       db.Select("some request");
    }

...

    function1();
    function2();


问:
Copy always to output directory does not work
I've got a simple console project where I'm reading two Excel-files. The Excel-files are included in the project ("add existing item") and I've marked them with "Copy to Output Directory". However, they are not copied to the debug-directory when debugging/running the code.

I feel like I've forgotten something trivial. What do I need to do more?

答:
I had an issue when some png files was renamed-excluded-added again to project. It seemed that VS2015 had lost tracking what to do with these files: although in VS the "Copy to output directory: Copy always" was set at the problematic files, CopyToOutputDirectory key was not present in csproj file. I had to change csproj manually from

<Content Include="xxx.png"/>
```
<p>to this:</p>
<pre class="lang-xml prettyprint-override"><code><Content Include="xxx.png">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</code>```

OwnerDisplayName: Jonas Lincoln

Body:
I had an issue when some png files was renamed-excluded-added again to project. It seemed that VS2015 had lost tracking what to do with these files: although in VS the "Copy to output directory: Copy always" was set at the problematic files, CopyToOutputDirectory key was not present in csproj file. I had to change csproj manually from

<Content Include="xxx.png"/>

to this:

<Content Include="xxx.png">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>


问:
Golang alternative for python/flask send_from_directory()
I have this image urls:

```<code>/book/cover/Computer_Science.png
</code>```

but the location of the image actually exists under

```<code>/uploads/img/Computer_Science.png
</code>```

I'm using Gin framework. Is there any command like Flask's send_from_directory() in Gin or in in-built Golang functions?

If not could you share a snippet of how to do it?

Thanks!

答:
Use gin's Context.File to serve file content. This method internally calls http.ServeFile builtin function. The code snippets will be:

```<code>import "path/filepath"

// ...
router := gin.Default()
// ...

router.GET("/book/cover/:filename", func(c *gin.Context) {
    rootDir := "/uploads/img/"
    name := c.Param("filename")
    filePath, err :=  filepath.Abs(rootDir + name)
    if err != nil {
        c.AbortWithStatus(404)
    }

    //Only allow access to file/directory under rootDir
    //The following code is for ilustration since HasPrefix is deprecated.
    //Replace with correct one when https://github.com/golang/dep/issues/296 fixed
    if !filepath.HasPrefix(filePath, rootDir) {
        c.AbortWithStatus(404)
    }

    c.File(filePath)
})
</code>```

Update

As pointed by zerkms, the path name must be sanitized before passing it Context.File. Simple sanitizer is added in the snippet. Please adapt to your needs.

Body:
I have this image urls:

/book/cover/Computer_Science.png

but the location of the image actually exists under

/uploads/img/Computer_Science.png

I'm using Gin framework. Is there any command like Flask's send_from_directory() in Gin or in in-built Golang functions?

If not could you share a snippet of how to do it?

Thanks!

Body:
Use gin's Context.File to serve file content. This method internally calls http.ServeFile builtin function. The code snippets will be:

import "path/filepath"

// ...
router := gin.Default()
// ...

router.GET("/book/cover/:filename", func(c *gin.Context) {
    rootDir := "/uploads/img/"
    name := c.Param("filename")
    filePath, err :=  filepath.Abs(rootDir + name)
    if err != nil {
        c.AbortWithStatus(404)
    }

    //Only allow access to file/directory under rootDir
    //The following code is for ilustration since HasPrefix is deprecated.
    //Replace with correct one when https://github.com/golang/dep/issues/296 fixed
    if !filepath.HasPrefix(filePath, rootDir) {
        c.AbortWithStatus(404)
    }

    c.File(filePath)
})

Update

As pointed by zerkms, the path name must be sanitized before passing it Context.File. Simple sanitizer is added in the snippet. Please adapt to your needs.


问:
Pandas subtracting group mean from colum value
So i have a dataset from a genechip, where 16 chips measure 1 tissue sample. I would like to subtract from each gene in each chip the mean of this gene over all the chips. Therefore I grouped by gene and calculated the mean. Now I want to take the original PM intensity value and subtract the Mean from this gene.
Thus i need to match the gene column with the the index from the table where i stored the mean value for this gene group and then subtract this value from the PM column.

```<code>totalgene  = genedata.groupby(genedata['GENE']).mean()[['PM','LOGPM']]

genedata['MEANNORM'] = genedata['PM'] - totalgene.ix[genedata['GENE']]['AVGPM']
genedata['MEANNORM'] = genedata['LOGPM'] - totalgene.ix[genedata['GENE']]['AVGLOGPM']
</code>```

results in the error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-08c1bb979f9c> in <module>()
----> 1 genedata['MEANNORM'] = genedata['PM'] - totalgene.ix[genedata['GENE'],'AVGPM']
      2 genedata['MEANNORM'] = genedata['LOGPM'] - totalgene.ix[genedata['GENE'],'AVGLOGPM']

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   2417         else:
   2418             # set column
-> 2419             self._set_item(key, value)
   2420
   2421     def _setitem_slice(self, key, value):

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   2483
   2484         self._ensure_valid_index(value)
-> 2485         value = self._sanitize_column(key, value)
   2486         NDFrame._set_item(self, key, value)
   2487

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast)
   2633
   2634         if isinstance(value, Series):
-> 2635             value = reindexer(value)
   2636
   2637         elif isinstance(value, DataFrame):

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in reindexer(value)
   2625                     # duplicate axis
   2626                     if not value.index.is_unique:
-> 2627                         raise e
   2628
   2629                     # other

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in reindexer(value)
   2620                 # GH 4107
   2621                 try:
-> 2622                     value = value.reindex(self.index)._values
   2623                 except Exception as e:
   2624

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\series.py in reindex(self, index, **kwargs)
   2360     @Appender(generic._shared_docs['reindex'] % _shared_doc_kwargs)
   2361     def reindex(self, index=None, **kwargs):
-> 2362         return super(Series, self).reindex(index=index, **kwargs)
   2363
   2364     @Appender(generic._shared_docs['fillna'] % _shared_doc_kwargs)

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in reindex(self, *args, **kwargs)
   2257         # perform the reindex on the axes
   2258         return self._reindex_axes(axes, level, limit, tolerance, method,
-> 2259                                   fill_value, copy).__finalize__(self)
   2260
   2261     def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
   2275             obj = obj._reindex_with_indexers({axis: [new_index, indexer]},
   2276                                              fill_value=fill_value,
-> 2277                                              copy=copy, allow_dups=False)
   2278
   2279         return obj

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in _reindex_with_indexers(self, reindexers, fill_value, copy, allow_dups)
   2369                                                 fill_value=fill_value,
   2370                                                 allow_dups=allow_dups,
-> 2371                                                 copy=copy)
   2372
   2373         if copy and new_data is self._data:

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\internals.py in reindex_indexer(self, new_axis, indexer, axis, fill_value, allow_dups, copy)
   3837         # some axes don't allow reindexing with dups
   3838         if not allow_dups:
-> 3839             self.axes[axis]._can_reindex(indexer)
   3840
   3841         if axis >= self.ndim:

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\indexes\base.py in _can_reindex(self, indexer)
   2492         # trying to reindex on an axis with duplicates
   2493         if not self.is_unique and len(indexer):
-> 2494             raise ValueError("cannot reindex from a duplicate axis")
   2495
   2496     def reindex(self, target, method=None, level=None, limit=None,

ValueError: cannot reindex from a duplicate axis
</code>```

And i have no clue why?
Could somebody help?

答:
Consider transform for an inline aggregate which returns a series that can be subtracted from original columns, PM and LOGPM:

```<code>genedata['MEANNORM_PM'] = genedata['PM'] - \
                            genedata.groupby(['GENE'])['PM'].transform('mean')

genedata['MEANNORM_LOGPM'] = genedata['LOGPM'] - \
                               genedata.groupby(['GENE'])['LOGPM'].transform('mean')
</code>```

Body:
So i have a dataset from a genechip, where 16 chips measure 1 tissue sample. I would like to subtract from each gene in each chip the mean of this gene over all the chips. Therefore I grouped by gene and calculated the mean. Now I want to take the original PM intensity value and subtract the Mean from this gene.
Thus i need to match the gene column with the the index from the table where i stored the mean value for this gene group and then subtract this value from the PM column.

totalgene  = genedata.groupby(genedata['GENE']).mean()[['PM','LOGPM']]

genedata['MEANNORM'] = genedata['PM'] - totalgene.ix[genedata['GENE']]['AVGPM']
genedata['MEANNORM'] = genedata['LOGPM'] - totalgene.ix[genedata['GENE']]['AVGLOGPM']

results in the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-08c1bb979f9c> in <module>()
----> 1 genedata['MEANNORM'] = genedata['PM'] - totalgene.ix[genedata['GENE'],'AVGPM']
      2 genedata['MEANNORM'] = genedata['LOGPM'] - totalgene.ix[genedata['GENE'],'AVGLOGPM']

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   2417         else:
   2418             # set column
-> 2419             self._set_item(key, value)
   2420
   2421     def _setitem_slice(self, key, value):

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   2483
   2484         self._ensure_valid_index(value)
-> 2485         value = self._sanitize_column(key, value)
   2486         NDFrame._set_item(self, key, value)
   2487

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast)
   2633
   2634         if isinstance(value, Series):
-> 2635             value = reindexer(value)
   2636
   2637         elif isinstance(value, DataFrame):

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in reindexer(value)
   2625                     # duplicate axis
   2626                     if not value.index.is_unique:
-> 2627                         raise e
   2628
   2629                     # other

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\frame.py in reindexer(value)
   2620                 # GH 4107
   2621                 try:
-> 2622                     value = value.reindex(self.index)._values
   2623                 except Exception as e:
   2624

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\series.py in reindex(self, index, **kwargs)
   2360     @Appender(generic._shared_docs['reindex'] % _shared_doc_kwargs)
   2361     def reindex(self, index=None, **kwargs):
-> 2362         return super(Series, self).reindex(index=index, **kwargs)
   2363
   2364     @Appender(generic._shared_docs['fillna'] % _shared_doc_kwargs)

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in reindex(self, *args, **kwargs)
   2257         # perform the reindex on the axes
   2258         return self._reindex_axes(axes, level, limit, tolerance, method,
-> 2259                                   fill_value, copy).__finalize__(self)
   2260
   2261     def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
   2275             obj = obj._reindex_with_indexers({axis: [new_index, indexer]},
   2276                                              fill_value=fill_value,
-> 2277                                              copy=copy, allow_dups=False)
   2278
   2279         return obj

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\generic.py in _reindex_with_indexers(self, reindexers, fill_value, copy, allow_dups)
   2369                                                 fill_value=fill_value,
   2370                                                 allow_dups=allow_dups,
-> 2371                                                 copy=copy)
   2372
   2373         if copy and new_data is self._data:

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\core\internals.py in reindex_indexer(self, new_axis, indexer, axis, fill_value, allow_dups, copy)
   3837         # some axes don't allow reindexing with dups
   3838         if not allow_dups:
-> 3839             self.axes[axis]._can_reindex(indexer)
   3840
   3841         if axis >= self.ndim:

C:\Users\timothy\Anaconda3\lib\site-packages\pandas\indexes\base.py in _can_reindex(self, indexer)
   2492         # trying to reindex on an axis with duplicates
   2493         if not self.is_unique and len(indexer):
-> 2494             raise ValueError("cannot reindex from a duplicate axis")
   2495
   2496     def reindex(self, target, method=None, level=None, limit=None,

ValueError: cannot reindex from a duplicate axis

And i have no clue why?
Could somebody help?

Body:
Consider transform for an inline aggregate which returns a series that can be subtracted from original columns, PM and LOGPM:

genedata['MEANNORM_PM'] = genedata['PM'] - \
                            genedata.groupby(['GENE'])['PM'].transform('mean')

genedata['MEANNORM_LOGPM'] = genedata['LOGPM'] - \
                               genedata.groupby(['GENE'])['LOGPM'].transform('mean')