问:
How to implement authentication with access and refresh token using retrofit in android?
I am trying to implement the token based authentication with access and refresh token. The access token expires after some limited time. Then using the refresh token it needs to be updated again. I am following this reference and this answer as well. As I am new to android I got no idea about how to implement these concepts.

This is my interface to get access token using the refresh token.

```<code>  //get access Token with Refresh Token
    @POST("/api/token")
    Call<ResponseBody> getAccessToken(@Body JSONObject jsonObject);
</code>```

This is my Retrofit Client:

```<code>public class ApiClient {
        public static final String BASE_URL = "https://lit-cove-70675.herokuapp.com";
        private static Retrofit retrofit = null;
          public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
</code>```

I have no idea where and how to implement those Service Generators and Authenticator. I have to pass "Authentication"=>ACCESSTOKEN in header with every API URL.

答:
```<code>public class ApiClient {
    public static final String BASE_URL = "https://lit-cove-70675.herokuapp.com";

    public <Service> Service buildApi(Class<Service> service, String accessToken) {

        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkkHttpClient(accessToken))
                .build()
                .create(service);
    }

    private OkHttpClient getOkkHttpClient(String accessToken) {

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(@NonNull Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();

                // ============= Your access token will go here ============
                if(accessToken != null) {
                   requestBuilder.header("Access token key", accessToken);
                }

                return chain.proceed(requestBuilder.build());
            }
        });
        return httpClient.build();
    }
}
</code>```

Body:
I am trying to implement the token based authentication with access and refresh token. The access token expires after some limited time. Then using the refresh token it needs to be updated again. I am following this reference and this answer as well. As I am new to android I got no idea about how to implement these concepts.

This is my interface to get access token using the refresh token.

  //get access Token with Refresh Token
    @POST("/api/token")
    Call<ResponseBody> getAccessToken(@Body JSONObject jsonObject);

This is my Retrofit Client:

public class ApiClient {
        public static final String BASE_URL = "https://lit-cove-70675.herokuapp.com";
        private static Retrofit retrofit = null;
          public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

I have no idea where and how to implement those Service Generators and Authenticator. I have to pass "Authentication"=>ACCESSTOKEN in header with every API URL.


来源: stackexchange

问:
How can I remove special characters from a list of elements in python?
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

```<code>out_list = ["one","two","three"]
</code>```

I cannot simply apply strip() to these items, please help.

答:
Use the str.translate() method  to apply the same translation table to all strings:

```<code>removetable = str.maketrans('', '', '@#%')
out_list = [s.translate(removetable) for s in my_list]
</code>```

The str.maketrans() static method is a helpful tool to produce the translation map; the first two arguments are empty strings because you are not replacing characters, only removing. The third string holds all characters you want to remove.

Demo:

```<code>>>> my_list = ["on@3", "two#", "thre%e"]
>>> removetable = str.maketrans('', '', '@#%')
>>> [s.translate(removetable) for s in my_list]
['on3', 'two', 'three']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

out_list = ["one","two","three"]

I cannot simply apply strip() to these items, please help.

Body:
Use the str.translate() method  to apply the same translation table to all strings:

removetable = str.maketrans('', '', '@#%')
out_list = [s.translate(removetable) for s in my_list]

The str.maketrans() static method is a helpful tool to produce the translation map; the first two arguments are empty strings because you are not replacing characters, only removing. The third string holds all characters you want to remove.

Demo:

>>> my_list = ["on@3", "two#", "thre%e"]
>>> removetable = str.maketrans('', '', '@#%')
>>> [s.translate(removetable) for s in my_list]
['on3', 'two', 'three']

ContentLicense: CC BY-SA 3.0


问:
Best way to create Observable, using from, in RxJS 5.x?
Now that we have "lettable" operators, how should we go about creating an Observable from another?

When I try to do:

import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)```
</div>
</div>
</p>

<p>I get the error <code>Observable.from is not a function</code>, which makes sense, because <code>from</code> is now something else that needs to be imported separately.</p>

<p>I don't want to do </p>

<p><code>import 'rxjs/add/observable/from'</code> anymore due to the prototypal problems there.</p>

<p>What I ended up doing was:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'

const myNewStream = from.call(
  Observable,
  someOtherStream
)</code>```

But this really feels "hacky" for some reason to me.  Does anyone have any better ways of going about this?

答:
I think this is misunderstanding what from does. It's just a function that takes a "stream" (that's Observable, Promise, array, ...) and creates an Observable from it.

This means you use it just like any other function:

```<code>import { from } from 'rxjs/observable/from'

from(someOtherStream).pipe(...).subscribe(...)
</code>```

Body:
Now that we have "lettable" operators, how should we go about creating an Observable from another?

When I try to do:

import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)

I get the error Observable.from is not a function, which makes sense, because from is now something else that needs to be imported separately.

I don't want to do

import 'rxjs/add/observable/from' anymore due to the prototypal problems there.

What I ended up doing was:

import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'

const myNewStream = from.call(
  Observable,
  someOtherStream
)

But this really feels "hacky" for some reason to me.  Does anyone have any better ways of going about this?

Body:
I think this is misunderstanding what from does. It's just a function that takes a "stream" (that's Observable, Promise, array, ...) and creates an Observable from it.

This means you use it just like any other function:

import { from } from 'rxjs/observable/from'

from(someOtherStream).pipe(...).subscribe(...)


问:
How do I import an excel spreadsheet into SQL Server?
I need to import an excel spreadsheet into SQL Server 2005.  What steps would I need to take to accomplish that?</p>

答:
you can also do it with OPENROWSET</p>

```<code>INSERT INTO SOMETABLE SELECT * FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
</code>```

OwnerDisplayName: Fiona

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Onorio Catenacci

Body:
you can also do it with OPENROWSET

INSERT INTO SOMETABLE SELECT * FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')

OwnerDisplayName: SQLMenace

LastEditorDisplayName: SQLMenace


问:
How can I send automated emails from bluehost?
I want to send newsletters and event information to my customers. Sending manual emails will take time. So, I was thinking of sending automated emails. </p>

<p>I just want to upload all my contact details to MySQL database in Bluehost where my website is placed and send automated emails. But, I don't know how to do it. Please help. </p>

答:
Use Mailchimp.com instead (or another alternative such as Sendgrid, Sendinblue, Sendpulse etc..).
They all have automatization and integration tools you need.

Sending bulk emails via hosting is not good idea.

Most of them would go to spam boxes. (becuase you don't have reliable mail server in your shared hosting website)

You can easily be blocked by the Hosting Provider because of rulebreak.

Body:
I want to send newsletters and event information to my customers. Sending manual emails will take time. So, I was thinking of sending automated emails.

I just want to upload all my contact details to MySQL database in Bluehost where my website is placed and send automated emails. But, I don't know how to do it. Please help.


问:
Concatenate huge pictures
I want to concatenate eight png-pictures each in the size of 21600px x 21600px in the form of 4 x 2 pictures using any program in windows. Trying ImageMagick or GraphicsMagick resulted in an error (due to a limitation of 65500px in any dimensions).

I also tried it with gimp, but it's too much for my computer (and gimp). I prefer a light program or even a command line program. Do you have any recommendations?

答:
Thx for your ideas!!! Finally I concatenated the pictures with vips, the main problem was actually displaying the picture since the first computer did't have enough RAM (16 GB). It always showed the final picture (with 86'400 x 21'600 pixels) with a black line at the bottom (like this https://ibb.co/bPGHnb)

To display the picture I used a computer with 32 GB RAM. Magick couldn't display it, since it couldn't allocate sufficient RAM. But irfantview finally made it.

Title: Concatenate huge pictures


问:
SqlSave Error: Unable to append to table
Code:

```<code>sqlSave(SQL,data.frame(df),tablename='Data',append = TRUE,rownames = FALSE)
</code>```

The table in which I am trying to insert the data has a primary key which is auto-increment. My table has a total of 5 columns including the primary key. In my data frame, I have 4 columns because I don't want to insert the PK myself. However, when I run the command, I get the following error:

Error in colnames<-(*tmp*, value = c("BId", "name", "Set",  :
  length of 'dimnames' [2] not equal to array extent

Also, when I insert the Primary key in the dataframe by myself, it still doesn't work.

Error in sqlSave(SQL, data.frame(df), tablename = "Data",  :
  unable to append to table ‘Data’

答:
have a try safer = FALSE

the defination of sqlSave

```<code>if (!append) {
    if (safer)
        stop("table ", sQuote(tablename), " already exists")
        ......
    }
    ......
if (safer)
    stop("unable to append to table ", sQuote(tablename))
</code>```

Body:
Code:

sqlSave(SQL,data.frame(df),tablename='Data',append = TRUE,rownames = FALSE)

The table in which I am trying to insert the data has a primary key which is auto-increment. My table has a total of 5 columns including the primary key. In my data frame, I have 4 columns because I don't want to insert the PK myself. However, when I run the command, I get the following error:

Error in colnames<-(*tmp*, value = c("BId", "name", "Set",  :
  length of 'dimnames' [2] not equal to array extent

Also, when I insert the Primary key in the dataframe by myself, it still doesn't work.

Error in sqlSave(SQL, data.frame(df), tablename = "Data",  :
  unable to append to table ‘Data’

Body:
have a try safer = FALSE

the defination of sqlSave

if (!append) {
    if (safer)
        stop("table ", sQuote(tablename), " already exists")
        ......
    }
    ......
if (safer)
    stop("unable to append to table ", sQuote(tablename))


问:
Adding days to date jquery or JS
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.</p>

```<code><input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});
</code>```

答:
Pure js approach
split date , get day,
split selected value, get integer
add above two
create date again using the updated date
update it in the input box</p>

```<code>   document.getElementById("days").onchange = function() {
        let inputValueParts = document.getElementById("startdate").value.split("/");
        let daysToIncrement = document.getElementById("days").value.split(" ")[0];
        let integerDate = parseInt(inputValueParts[1]);
        let integerIncrement = parseInt(daysToIncrement);
        integerDate += integerIncrement;
        let increasedDate = inputValueParts[0] + "/" + integerDate + "/" +inputValueParts[2];
        document.getElementById("fdate").value = increasedDate;
    }
</code>```

Title: Adding days to date jquery or JS

Body:
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.

<input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});

Body:
Pure js approach
split date , get day,
split selected value, get integer
add above two
create date again using the updated date
update it in the input box

   document.getElementById("days").onchange = function() {
        let inputValueParts = document.getElementById("startdate").value.split("/");
        let daysToIncrement = document.getElementById("days").value.split(" ")[0];
        let integerDate = parseInt(inputValueParts[1]);
        let integerIncrement = parseInt(daysToIncrement);
        integerDate += integerIncrement;
        let increasedDate = inputValueParts[0] + "/" + integerDate + "/" +inputValueParts[2];
        document.getElementById("fdate").value = increasedDate;
    }


问:
Split date-time column into Date and time variables
I have a 'date-time column 'Start' in the format "Y-m-d H:M:S". I want to split this column into a "Date" and a "time" column.

I have tried the following:

```<code>df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1)
df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2)
</code>```

This works, however, if I use the function str(df)

```<code># 'data.frame':   18363 obs. of  19 variables:<br>
#  $ Start    : Factor w/ 67 levels "2013-09-01 08:07:41.000",..: 1 1 1 1 1 1 1 1 1 1 ...
# [snip]
</code>```

So now I only need to know how to convert the time and date from factor to 'time' and 'date'.

答:
By seeing your column format, I'd say you could use as.POSIXct to properly format your column, and then use format() to extract the desired data.

This is the code I use when splitting a DateTime column,

```<code>df$Time <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%H:%M:%S")

df$Date <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%Y:%m:%d")
</code>```

Body:
I have a 'date-time column 'Start' in the format "Y-m-d H:M:S". I want to split this column into a "Date" and a "time" column.

I have tried the following:

df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1)
df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2)

This works, however, if I use the function str(df)

# 'data.frame':   18363 obs. of  19 variables:

#  $ Start    : Factor w/ 67 levels "2013-09-01 08:07:41.000",..: 1 1 1 1 1 1 1 1 1 1 ...
# [snip]

So now I only need to know how to convert the time and date from factor to 'time' and 'date'.

Body:
By seeing your column format, I'd say you could use as.POSIXct to properly format your column, and then use format() to extract the desired data.

This is the code I use when splitting a DateTime column,

df$Time <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%H:%M:%S")

df$Date <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%Y:%m:%d")


问:
Unable to click a link residing inside a <li element
I am not able to click on the link nestled inside a list tag.
Here is the HTML code:

```<code><div class="sideBarContent" ng-include="'routes/sidebar/sidebar.tpl.html'">
<div id="innerSidebarContent" ng-controller="SidebarController">
<div>
<ul class="menuItems bounceInDown">
<li id="menuHome" class="" ui-sref="home" ng-click="closeMobileMenu()" href="/home/">
<li id="menuConfigurator" ui-sref="configurator" ng-click="closeMobileMenu()" href="/configurator/">
<span class="menuIcon regularImage blueHighlight activated icon-selectAndTailor"></span>
<span class="menuIcon icon-selectAndTailor_active activeImage">
<p class="mainMenuLabel multiLine">Select & Tailor Methods</p>
</li>
</code>```

I tried all these ways to locate the text and click on it:

```<code>describe('Test objects in /configurator/ route', function() {
it('Click on select and tailor banner icon', function(){
    //element(by.css('ul.menuItems > li[href=/configurator/]')).click();
    //element(by.className('menuIcon icon-selectAndTailor_active activeImage')).click();
    //element(by.css("li[@id='menuConfigurator' and @href='/configurator/']")).click();
    //element(by.id('menuConfigurator')).click();
    //element(by.xpath("//div[@class='sideBarContent']/p")).click();
    //element(by.css("#menuConfigurator > p")).click();
    //element(by.partialLinkText('Select & Tailor Methods')).click();
    element(by.linkText("Select & Tailor Methods")).click();
    console.log('in the configspec ...');
})});
</code>```

Can someone help me resolve this?

答:
Just had the same issue.
It turned out that wrapping the list in a < div > block was the problem.
Once the list was moved to be outside any < div > block the < a > tags worked.</p>

Body:
I am not able to click on the link nestled inside a list tag.
Here is the HTML code:

Select & Tailor Methods

I tried all these ways to locate the text and click on it:

describe('Test objects in /configurator/ route', function() {
it('Click on select and tailor banner icon', function(){
    //element(by.css('ul.menuItems > li[href=/configurator/]')).click();
    //element(by.className('menuIcon icon-selectAndTailor_active activeImage')).click();
    //element(by.css("li[@id='menuConfigurator' and @href='/configurator/']")).click();
    //element(by.id('menuConfigurator')).click();
    //element(by.xpath("//div[@class='sideBarContent']/p")).click();
    //element(by.css("#menuConfigurator > p")).click();
    //element(by.partialLinkText('Select & Tailor Methods')).click();
    element(by.linkText("Select & Tailor Methods")).click();
    console.log('in the configspec ...');
})});

Can someone help me resolve this?


问:
Does an RSpec2 matcher for matching Hashes exist?
Note to future readers: think RSpec does not consider your Hashes equal? One might be an OrderedHash, but from the regular RSpec output you can't tell. This was the problem that prompted this post.

Original question:

Suppose I have a spec where I want to test that a method generates the appropriate Hash.

```<code>it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.should == expected
end
</code>```

This often fails, because different Hashes with the same key-value pairs may return their pairs in a different ordered. Results look like:

```<code>Failure/Error: subject.some_method_that_should_generate_the_hash.should == expected
expected: {:foo => 1, 'baz' => 2},
     got: {'baz' => 2, :foo => 1}
</code>```

For arrays, this is solved using the =~ operator. However, that does not work for Hashes. For now, I've resorted to

```<code>it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.each {|k,v|
    v.should == expected[k]
  }
end
</code>```

but that seems unnecessarily verbose. I expect there to be an obvious solution for this. Am I overlooking something in the docs or doesn't RSpec have a proper Matcher for orderless Hash equality?

答:
```<code>describe 'Hash' do
  let(:x) { { :a => 1, :b => 2 } }
  let(:y) { { :b => 2, :a => 1 } }

  it "should be equal with ==" do
    x.should == y
  end
end
</code>```

Passes. I'm not sure what's going on in your specific case. Do you have some failing examples you can share?

Programming Ruby has this to say:

Equality — Two hashes are equal if
  they have the same default value, they
  contain the same  number of keys, and
  the value corresponding to each key in
  the ﬁrst hash is equal (using ==) to
  the value for the same key in the
  second.

Body:
Note to future readers: think RSpec does not consider your Hashes equal? One might be an OrderedHash, but from the regular RSpec output you can't tell. This was the problem that prompted this post.

Original question:

Suppose I have a spec where I want to test that a method generates the appropriate Hash.

it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.should == expected
end

This often fails, because different Hashes with the same key-value pairs may return their pairs in a different ordered. Results look like:

Failure/Error: subject.some_method_that_should_generate_the_hash.should == expected
expected: {:foo => 1, 'baz' => 2},
     got: {'baz' => 2, :foo => 1}

For arrays, this is solved using the =~ operator. However, that does not work for Hashes. For now, I've resorted to

it 'should generate the Hash correctly' do
  expected = {:foo => 1, 'baz' => 2}
  subject.some_method_that_should_generate_the_hash.each {|k,v|
    v.should == expected[k]
  }
end

but that seems unnecessarily verbose. I expect there to be an obvious solution for this. Am I overlooking something in the docs or doesn't RSpec have a proper Matcher for orderless Hash equality?

Body:
describe 'Hash' do
  let(:x) { { :a => 1, :b => 2 } }
  let(:y) { { :b => 2, :a => 1 } }

  it "should be equal with ==" do
    x.should == y
  end
end

Passes. I'm not sure what's going on in your specific case. Do you have some failing examples you can share?

Programming Ruby has this to say:

Equality — Two hashes are equal if
  they have the same default value, they
  contain the same  number of keys, and
  the value corresponding to each key in
  the ﬁrst hash is equal (using ==) to
  the value for the same key in the
  second.


问:
What are virtual functions in javascript?
According to one definition of virtual functions:

In object-oriented programming, in languages such as C++, a virtual
  function or virtual method is an inheritable and overridable function
  or method for which dynamic dispatch is facilitated.

How would this look for functions in javascript?

答:
How would this look for functions in javascript?

The concept largely doesn't apply to JavaScript.

The concept of virtual and non-virtual functions (methods, really) requires the concept of a type of reference to an object, as distinct from what the object is. For instance, you might have a BaseFoo type with a bar method, and a DerivedFoo type that derives from it and overrides bar. Later, if you have a BaseFoo-typed variable b referring to a DerivedFoo object, when you call b.bar(), you'll get DerivedFoo's bar if bar is virtual, but BaseFoo's bar if bar is non-virtual. But if you have a DerivedFoo-typed variable d referring to a DerivedFoo object, d.bar() always calls bar whether it's virtual or not. The type of the variable you're using to refer to the object determines what method gets called if the method is non-virtual.

None of that exists in JavaScript. References to objects are untyped. When you call o.bar(), you get the property bar from that object and call the function it refers to.

If you wanted to stretch a point, given JavaScript's prototypical inheritance mechanism, you could say that in some sense, all JavaScript "methods" are virtual, if we very loosely say a "method" is a function attached to an object property (although in ES2015+, "method" has a more specific meaning in JavaScript than that, but still fits that definition). That's because when you look up a property on an object, if it has its own property with that name, that's the one you get; you only get the one from its prototype if it doesn't have its own. But that's probably stretching a point, perhaps too far.


问:
Nginx redirect using return 301
I need to do permanent redirect from URLs:

```<code>https://SiteName.com/shop/forklift-tires/XXX/
to
https://SiteName.com/shop/tires/forklift-tires/XXX/
</code>```

or

```<code>https://SiteName.com/shop/forklift-tires/YYY/
to
https://SiteName.com/shop/tires/forklift-tires/YYY/
</code>```

How could I do it using structure below?

```<code>location *something* {
        return 301 *something*;
}
</code>```

As I understood from article "Pitfalls and Common Mistakes" it`s best to use return instead of rewrite.

答:
Update(the correct answer)

Further to your comment, try this:

```<code>location  ~ ^shop/forklift-tires/(.*) {
    return 301  /shop/tires/forklift-tires/$1 ;
}
</code>```

Previous answer (sorry for misunderstood the question)

Create another server directive like this:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name Sitename.com;
    return 301 https://$host$request_uri;
}
</code>```

All traffic for http://SiteName.com/* will be redirected to https://SiteName.com/*.

Title: Nginx redirect using return 301

Body:
I need to do permanent redirect from URLs:

https://SiteName.com/shop/forklift-tires/XXX/
to
https://SiteName.com/shop/tires/forklift-tires/XXX/

or

https://SiteName.com/shop/forklift-tires/YYY/
to
https://SiteName.com/shop/tires/forklift-tires/YYY/

How could I do it using structure below?

location *something* {
        return 301 *something*;
}

As I understood from article "Pitfalls and Common Mistakes" it`s best to use return instead of rewrite.

Body:
Update(the correct answer)

Further to your comment, try this:

location  ~ ^shop/forklift-tires/(.*) {
    return 301  /shop/tires/forklift-tires/$1 ;
}

Previous answer (sorry for misunderstood the question)

Create another server directive like this:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name Sitename.com;
    return 301 https://$host$request_uri;
}

All traffic for http://SiteName.com/* will be redirected to https://SiteName.com/*.


问:
Getting exact time in ( HH:mm:sss a) format from milliseconds
I have to print time in my app in HH:mm:sss AM/PM from milliseconds which is 24 Hours later time .

so to get 24 hours later time to current time i used the code as

```<code>  public Date roundToNext24Hour() {

    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c = new GregorianCalendar();
    c.setTime(date);
    c.add(Calendar.HOUR_OF_DAY, 24);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);

    return c.getTime();
}
</code>```

now i convert this time in HH:mm:sss am/pm format

```<code>  SimpleDateFormat df = new SimpleDateFormat("HH:mm:sss a");
  timeString = df.format(Utility.roundToNext24Hour())
</code>```

but problem is timestring is always returning time which is 12 hour later not 24 hour later.

please help..

答:
```<code>Try below code.

Date date = new Date();
          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
          String str = df.format(date);
</code>```

Body:
I have to print time in my app in HH:mm:sss AM/PM from milliseconds which is 24 Hours later time .

so to get 24 hours later time to current time i used the code as

  public Date roundToNext24Hour() {

    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c = new GregorianCalendar();
    c.setTime(date);
    c.add(Calendar.HOUR_OF_DAY, 24);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);

    return c.getTime();
}

now i convert this time in HH:mm:sss am/pm format

  SimpleDateFormat df = new SimpleDateFormat("HH:mm:sss a");
  timeString = df.format(Utility.roundToNext24Hour())

but problem is timestring is always returning time which is 12 hour later not 24 hour later.

please help..


问:
Check if method exists in a class in TypeScript
I am having a class in which a method currently doesn't exists but will be added later. I want to use that method if it exists otherwise not.
For eg.

```<code>Class A {
    public func(string s) {
        // Currently this method is not present in Class A
    }
}
</code>```

I want to check that if this method exists, then call it, otherwise do something else. I found a solution which works for JavaScript but doesn't work for TypeScript:

```<code>let objectOfA = new A();
if ( objectOfA.func === function) {
    objectOfA.func();
}
</code>```

But this somehow doesn't works in TypeScript and throws compilation error saying Operator '===' cannot be applied to types 'string' and '() => any'.

Is there a way I can check for method existence in TypeScript?

答:
You can use typeof operator to get the ty the of the operand. Although use bracket notation to get unknown properties(to avoid throwing exception).

```<code>let objectOfA = new A();
if ( typeof objectOfA['func'] === 'function') {
    objectOfA.func();
}
</code>```

Body:
I am having a class in which a method currently doesn't exists but will be added later. I want to use that method if it exists otherwise not.
For eg.

Class A {
    public func(string s) {
        // Currently this method is not present in Class A
    }
}

I want to check that if this method exists, then call it, otherwise do something else. I found a solution which works for JavaScript but doesn't work for TypeScript:

let objectOfA = new A();
if ( objectOfA.func === function) {
    objectOfA.func();
}

But this somehow doesn't works in TypeScript and throws compilation error saying Operator '===' cannot be applied to types 'string' and '() => any'.

Is there a way I can check for method existence in TypeScript?

Body:
You can use typeof operator to get the ty the of the operand. Although use bracket notation to get unknown properties(to avoid throwing exception).

let objectOfA = new A();
if ( typeof objectOfA['func'] === 'function') {
    objectOfA.func();
}


问:
Sharing user ID's as a way to find people
Is it safe to share a user's ID that Firebase creates when a new user is created? I'd like to use it as an easy way to find other people on my platform.
I don't see why it should not be safe, so if it is. Please enlighten me :)</p>

答:
I am not too familiar with your system or how Nintendo does this (not really a gamer) but you can build something like this:

You can display the list of users (using uid, displayName and photoURL which can be obtained using the Admin SDK or by a list you maintain in the Firebase Database, Firestore, etc) to an authenticated user.
Let's say that user wants to add a connection or friend, you can get that user's ID token, the friend's uid and then add that user's uid to that authenticated user's pending connection list after you verify their ID token.
On the other end, you want the other user to accept the connection request (assuming this how your people finder feature works in your app). You would show the list of pending requests. When the user accepts the request, they would send their ID token and once that's verified, you can consider the connection completed.

To summarize, you still need an ID token to confirm the user sending the request and the one confirming it. Otherwise, if you just solely rely on uids, any user can get the uid of other users and try to add them to each other's friends list, etc.

Hopefully this points you in the right direction.


问:
Avoid processing same file twice in Spring Batch
I have to write a Spring Batch job as follows:

Step 1: Load an XML file from the file system and write its contents to a database staging table

Step 2: Call Oracle PL/SQL procedure to process the staging table.

(Comments on that job structure are welcome, but not the question).

In Step 1, I want to move the XML file to another directory after I have loaded it.  I want this, as much as possible, to be "transactional" with the write to the staging table.  That is, either both the writes to staging and the file move succeed, or neither does.

I feel this necessary because if (A) the staging writes happen but the file does not move, the next run will pick up the file again and process it again and (B) if the file gets moved but the staging writes do not happen, then we will have missed that file's processing.

This interface's requirements are all about robustness.  I know I could just put a step execution listener to move all the files at the end, but I want the approach that is going to guarantee that we never miss processing data and never process the same file twice.

Part of the difficulty is that I am using a MultiResourceItemReader.  I read that ChunkListener.beforeChunk() happens as part of the chunk transaction, so I tried to make a custom chunk CompletionPolicy to force chunks to complete after each change of resource (file) name, but I could not get it to work.  In any case, I would have needed an afterChunk() listener, which is not part of the transaction anyway.

I'll take any guidance on my specific questions or an expert explanation of how to robustly process files in Spring Batch (which I am only just learning).  Thanks!

答:
This kind of process can be easy done with a job with 2 step and 1 listener:

A standard (read from XML -> process? -> write to DB) step; you don't care about restartability because SB is smart enough to avoid data read repetition

a listener attached to step 1 to move file after successfully step execution (example 1, example 2 or example 3)

A second step with data processing

#3 may may be inserted as step 1 process phase


问:
Java: is there a way to convert text into a class?
I have the input: "ListClients param1 param2"
which splits by " " to "ListClients", "param1", "param2";

and I want to call a static method from ListClients.

So it would do ListClients.someMethodThatTakesPraams(param1, param2);

is there a way to do that in java?

答:
The simple hard coded way would be to create an if/else chain and invoke the right method:

```<code>String input = "ListClients param1 param2";
String [] args = input.split(" ");
switch( args.length ) {
    case 0:
       return ListClients.someMethod();
    case 1:
       return ListClients.someMethod( args[0] );
    case 2:
        return LIstClients.someMethod( args[1] );
    default:
         return // something default
}
</code>```

While this may seem a bit antiquate, it is very safe, because you program exactly how your code should be invoked.

The other solution would involve using reflection as others mention:

```<code>String input = "ListClients param1 param2";
String [] args = input.split(" ");
Class[] types = new Classs[ args.length ];
Object[] values = new Object[ args.lenght ];
for( int i = 0 ; i < types.lenght ; i++ ) {
   types[i] = String.class;
   values [i] = args[i];
 }

ListClients.class
   .getDeclaredMethod("someMethod", types )
   .invoke( null, values );
</code>```

All that surrounded by a number of reflection checked exceptions.

You should consider how dynamic you need your application to be, and / if you would do something to prevent a wild call like this:  "System.exit(0)"  be invoked or any other sort of code injection.

Body:
The simple hard coded way would be to create an if/else chain and invoke the right method:

String input = "ListClients param1 param2";
String [] args = input.split(" ");
switch( args.length ) {
    case 0:
       return ListClients.someMethod();
    case 1:
       return ListClients.someMethod( args[0] );
    case 2:
        return LIstClients.someMethod( args[1] );
    default:
         return // something default
}

While this may seem a bit antiquate, it is very safe, because you program exactly how your code should be invoked.

The other solution would involve using reflection as others mention:

String input = "ListClients param1 param2";
String [] args = input.split(" ");
Class[] types = new Classs[ args.length ];
Object[] values = new Object[ args.lenght ];
for( int i = 0 ; i < types.lenght ; i++ ) {
   types[i] = String.class;
   values [i] = args[i];
 }

ListClients.class
   .getDeclaredMethod("someMethod", types )
   .invoke( null, values );

All that surrounded by a number of reflection checked exceptions.

You should consider how dynamic you need your application to be, and / if you would do something to prevent a wild call like this:  "System.exit(0)"  be invoked or any other sort of code injection.


问:
How can I remove special characters from a list of elements in python?
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

```<code>out_list = ["one","two","three"]
</code>```

I cannot simply apply strip() to these items, please help.

答:
try this:</p>

```<code>l_in = ["on@3", "two#", "thre%e"]
l_out = [''.join(e for e in string if e.isalnum()) for string in l_in]
print l_out
>['on3', 'two', 'three']
</code>```

Body:
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

out_list = ["one","two","three"]

I cannot simply apply strip() to these items, please help.

Body:
try this:

l_in = ["on@3", "two#", "thre%e"]
l_out = [''.join(e for e in string if e.isalnum()) for string in l_in]
print l_out
>['on3', 'two', 'three']


答:
Here is another solution:

```<code>import re
my_list= ["on@3", "two#", "thre%e"]
print [re.sub('[^a-zA-Z0-9]+', '', _) for _ in my_list]
</code>```

output:

```<code>['on3', 'two', 'three']
</code>```

Title: How can I remove special characters from a list of elements in python?

Body:
Here is another solution:

import re
my_list= ["on@3", "two#", "thre%e"]
print [re.sub('[^a-zA-Z0-9]+', '', _) for _ in my_list]

output:

['on3', 'two', 'three']


问:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo':
I have used Spring with spring data, while it's giving below error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/DecoratingProxy
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
      at org.spring
  Caused by: java.lang.ClassNotFoundException: org.springframework.core.DecoratingProxy

Spring-Servlet.xml

```<code><beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/"/>
    <beans:property name="suffix" value=".jsp"/>
</beans:bean>

<beans:bean
        id="employeeRepo" class="com.spring.crud.dao.EmployeeRepo" abstract="true"/>

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url"
                    value="jdbc:mysql://localhost:3306/crud?createDatabaseIfNotExist=true"/>
    <beans:property name="username" value="gppuser"/>
    <beans:property name="password" value="da123abc"/>
</beans:bean>

<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

</beans:bean>

<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <beans:property name="packagesToScan" value="com.spring.crud.entity"/>
    <beans:property name="jpaProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.hbm2ddl.auto}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.ejb.naming_strategy}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.show_sql}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.format_sql}</beans:prop>

        </beans:props>

    </beans:property>
</beans:bean>

<beans:bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

<beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.spring.crud.entity.Employee</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<context:component-scan base-package="com.spring.crud.*"/>

<jpa:repositories base-package="com.spring.crud" />

<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

<!--<beans:bean id="transactionManager"-->
            <!--class="org.springframework.orm.hibernate4.HibernateTransactionManager">-->
    <!--<beans:property name="sessionFactory"-->
                    <!--ref="hibernate4AnnotatedSessionFactory"/>-->
<!--</beans:bean>-->
</code>```

EmployeeService.java

```<code>@Service("employeeService")
public class EmployeeService {

    @Autowired
    private EmployeeRepo employeeRepo;

    @Transactional
    public List<Employee> getAllEmployee() {
        return (List<Employee>) employeeRepo.findAll();
    }
}
</code>```

EmployeeRepo

```<code>@Repository
public interface EmployeeRepo extends CrudRepository<Employee,Long>{

}
</code>```

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.crud</groupId>
    <artifactId>springMvcAssignment</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- Apache Commons DBCP -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- Spring ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Kay-M4</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>

        <!-- AspectJ -->
        <!--<dependency>-->
            <!--<groupId>org.aspectj</groupId>-->
            <!--<artifactId>aspectjrt</artifactId>-->
            <!--<version>${org.aspectj-version}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>

    </build>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <security.version>4.0.3.RELEASE</security.version>
        <jdk.version>1.7</jdk.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
    </properties>
</project>
</code>```

mvn dependency:tree

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springMvcAssignment 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ springMvcAssignment ---
[INFO] com.spring.crud:springMvcAssignment:war:0.0.1-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] +- org.springframework:spring-core:jar:4.2.1.RELEASE:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.2:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile
[INFO] |  |     \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:4.2.1.RELEASE:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.1:compile
[INFO] +- org.hibernate:hibernate-core:jar:4.3.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  +- org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:4.0.4.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  \- org.jboss:jandex:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:4.3.5.Final:compile
[INFO] +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] |  \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-jdbc:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-tx:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.11.1.RELEASE:provided
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.13.1.RELEASE:provided
[INFO] |  +- org.aspectj:aspectjrt:jar:1.8.10:provided
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.24:provided
[INFO] |  \- org.slf4j:jcl-over-slf4j:jar:1.7.24:provided
[INFO] +- org.springframework.data:spring-data-releasetrain:pom:Kay-M4:provided
[INFO] +- mysql:mysql-connector-java:jar:5.1.6:compile
[INFO] \- jstl:jstl:jar:1.2:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.661s
[INFO] Finished at: Tue Nov 14 18:06:45 IST 2017
[INFO] Final Memory: 10M/244M
[INFO] --------------------------------------------------------------------
</code>```

答:
Thanks all for your support..!

i have found the solution, it's by updating spring-core version to latest it start creating bean :)

Body:
I have used Spring with spring data, while it's giving below error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/DecoratingProxy
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
      at org.spring
  Caused by: java.lang.ClassNotFoundException: org.springframework.core.DecoratingProxy

Spring-Servlet.xml

<beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/"/>
    <beans:property name="suffix" value=".jsp"/>
</beans:bean>

<beans:bean
        id="employeeRepo" class="com.spring.crud.dao.EmployeeRepo" abstract="true"/>

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url"
                    value="jdbc:mysql://localhost:3306/crud?createDatabaseIfNotExist=true"/>
    <beans:property name="username" value="gppuser"/>
    <beans:property name="password" value="da123abc"/>
</beans:bean>

<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

</beans:bean>

<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <beans:property name="packagesToScan" value="com.spring.crud.entity"/>
    <beans:property name="jpaProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.hbm2ddl.auto}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.ejb.naming_strategy}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.show_sql}</beans:prop>
            <beans:prop key="hibernate.dialect">${hibernate.format_sql}</beans:prop>

        </beans:props>

    </beans:property>
</beans:bean>

<beans:bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

<beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"/>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.spring.crud.entity.Employee</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<context:component-scan base-package="com.spring.crud.*"/>

<jpa:repositories base-package="com.spring.crud" />

EmployeeService.java

@Service("employeeService")
public class EmployeeService {

    @Autowired
    private EmployeeRepo employeeRepo;

    @Transactional
    public List<Employee> getAllEmployee() {
        return (List<Employee>) employeeRepo.findAll();
    }
}

EmployeeRepo

@Repository
public interface EmployeeRepo extends CrudRepository<Employee,Long>{

}

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.crud</groupId>
    <artifactId>springMvcAssignment</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Kay-M4</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>

    </build>
    <properties>
        <spring.version>4.2.1.RELEASE</spring.version>
        <security.version>4.0.3.RELEASE</security.version>
        <jdk.version>1.7</jdk.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
    </properties>
</project>

mvn dependency:tree

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springMvcAssignment 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ springMvcAssignment ---
[INFO] com.spring.crud:springMvcAssignment:war:0.0.1-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] +- org.springframework:spring-core:jar:4.2.1.RELEASE:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.2:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile
[INFO] |  |     \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:4.2.1.RELEASE:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.1:compile
[INFO] +- org.hibernate:hibernate-core:jar:4.3.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  +- org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:4.0.4.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  \- org.jboss:jandex:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:4.3.5.Final:compile
[INFO] +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] |  \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-jdbc:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-tx:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.11.1.RELEASE:provided
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.13.1.RELEASE:provided
[INFO] |  +- org.aspectj:aspectjrt:jar:1.8.10:provided
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.24:provided
[INFO] |  \- org.slf4j:jcl-over-slf4j:jar:1.7.24:provided
[INFO] +- org.springframework.data:spring-data-releasetrain:pom:Kay-M4:provided
[INFO] +- mysql:mysql-connector-java:jar:5.1.6:compile
[INFO] \- jstl:jstl:jar:1.2:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.661s
[INFO] Finished at: Tue Nov 14 18:06:45 IST 2017
[INFO] Final Memory: 10M/244M
[INFO] --------------------------------------------------------------------


问:
It's possible to replace existing html code with jQuery
Example current html code

```<code><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

I want use jQuery to replace it to be

```<code><a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

Let me know

答:
So it seems to me that you want to put the following code

```<code><a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a>
</code>```

before any links with the class tag-link-php.  You can use the before function for this:

```<code>$('a.tag-link-php').before('<a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a>');
</code>```

Body:
Example current html code

php

I want use jQuery to replace it to be

php

Let me know

Body:
So it seems to me that you want to put the following code

<a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a>

before any links with the class tag-link-php.  You can use the before function for this:

$('a.tag-link-php').before('<a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a>');


问:
Unity - Android 6.0 - Crash with java.lang.IllegalAccessException: java.lang.Class<com.unity3d.player.n$1> is not accessible
I have a game developed with Unity and getting crash logs that I can not reproduce on any of my devices as follows:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{fab.gameofwords/com.unity3d.player.UnityPlayerNativeActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.unity3d.player.n$1: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.access$900(ActivityThread.java:150)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.unity3d.player.n$1: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.Fragment.instantiate(Fragment.java:628)
    at android.app.FragmentState.instantiate(Fragment.java:106)
    at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1858)
    at android.app.FragmentController.restoreAllState(FragmentController.java:122)
    at android.app.Activity.onCreate(Activity.java:923)
    at android.app.NativeActivity.onCreate(NativeActivity.java:184)
    at com.unity3d.player.UnityPlayerNativeActivity.onCreate(Unknown Source)
    at android.app.Activity.performCreate(Activity.java:6285)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    ... 9 more
Caused by: java.lang.IllegalAccessException: java.lang.Class<com.unity3d.player.n$1> is not accessible from java.lang.Class<android.app.Fragment>
    at java.lang.Class.newInstance(Native Method)
    at android.app.Fragment.instantiate(Fragment.java:613)
    ... 18 more
</code>```

And here is my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fab.gameofwords" android:installLocation="preferExternal" android:theme="@android:style/Theme.NoTitleBar" android:versionCode="1" android:versionName="1.0">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application
      android:icon="@drawable/app_icon"
      android:label="@string/app_name"
      android:debuggable="true">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="fb577464905719222" />
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="fab.gameofwords.fileprovider" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
    </provider>
    <activity android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name">
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.unity.FBUnityLoginActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityDialogsActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.LoginActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityDeepLinkingActivity" android:exported="true" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
    <activity android:name="com.androidnative.AndroidNativeProxy" android:launchMode="singleTask" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="oauth" android:host="fab.gameofwords" />
      </intent-filter>
    </activity>
    <activity android:name="com.outlinegames.unibill.PurchaseActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:screenOrientation="portrait" />
    <!--Parse-->
    <receiver android:name="com.parse.ParsePushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="fab.gameofwords" />
      </intent-filter>
    </receiver>
    <service android:name="com.parse.ParsePushService" />
    <!--End-->
    <!--Google Analytics-->
    <service android:name="com.google.analytics.tracking.android.CampaignTrackingService" />
    <receiver android:name="com.google.analytics.tracking.android.CampaignTrackingReceiver" android:exported="true">
      <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
      </intent-filter>
    </receiver>
    <!--End-->
    <!--Tune-->
    <receiver android:name="com.tune.TuneTracker" android:exported="true">
      <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
      </intent-filter>
    </receiver>
    <!--End-->
    <activity android:name="com.outlinegames.unibill.PurchaseActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityAppLinkActivity" android:exported="true" />
    <activity android:name="com.facebook.unity.FBUnityGameRequestActivity" />
    <activity android:name="com.facebook.unity.FBUnityCreateGameGroupActivity" />
    <activity android:name="com.facebook.unity.FBUnityJoinGameGroupActivity" />
    <activity android:name="com.facebook.unity.AppInviteDialogActivity" />
    <provider android:name="com.facebook.FacebookContentProvider" android:authorities="com.facebook.app.FacebookContentProvider577464905719222" android:exported="true" />
    <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
  </application>
  <!-- Settings for GCM -->
  <permission
    android:name="fab.gameofwords.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="fab.gameofwords.permission.C2D_MESSAGE" />
  <uses-permission android:name="com.android.vending.BILLING" />
</manifest>
</code>```

Seems that the crash only occurs on Android 6.0.
What can be wrong here, what am I missing?

Thanks in advance.

答:
check this post out:

https://forum.unity.com/threads/crash-reports-caused-by-android-app-fragment-instantiationexception.472522/

this is a bug that Unity Team is going to fix in 5.6.4p3

Body:
I have a game developed with Unity and getting crash logs that I can not reproduce on any of my devices as follows:

java.lang.RuntimeException: Unable to start activity ComponentInfo{fab.gameofwords/com.unity3d.player.UnityPlayerNativeActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.unity3d.player.n$1: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.access$900(ActivityThread.java:150)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.unity3d.player.n$1: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.Fragment.instantiate(Fragment.java:628)
    at android.app.FragmentState.instantiate(Fragment.java:106)
    at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1858)
    at android.app.FragmentController.restoreAllState(FragmentController.java:122)
    at android.app.Activity.onCreate(Activity.java:923)
    at android.app.NativeActivity.onCreate(NativeActivity.java:184)
    at com.unity3d.player.UnityPlayerNativeActivity.onCreate(Unknown Source)
    at android.app.Activity.performCreate(Activity.java:6285)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    ... 9 more
Caused by: java.lang.IllegalAccessException: java.lang.Class<com.unity3d.player.n$1> is not accessible from java.lang.Class<android.app.Fragment>
    at java.lang.Class.newInstance(Native Method)
    at android.app.Fragment.instantiate(Fragment.java:613)
    ... 18 more

And here is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fab.gameofwords" android:installLocation="preferExternal" android:theme="@android:style/Theme.NoTitleBar" android:versionCode="1" android:versionName="1.0">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application
      android:icon="@drawable/app_icon"
      android:label="@string/app_name"
      android:debuggable="true">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="fb577464905719222" />
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="fab.gameofwords.fileprovider" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
    </provider>
    <activity android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name">
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.unity.FBUnityLoginActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityDialogsActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.LoginActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityDeepLinkingActivity" android:exported="true" />
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
    <activity android:name="com.androidnative.AndroidNativeProxy" android:launchMode="singleTask" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="oauth" android:host="fab.gameofwords" />
      </intent-filter>
    </activity>
    <activity android:name="com.outlinegames.unibill.PurchaseActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:screenOrientation="portrait" />

    <receiver android:name="com.parse.ParsePushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="fab.gameofwords" />
      </intent-filter>
    </receiver>
    <service android:name="com.parse.ParsePushService" />

    <service android:name="com.google.analytics.tracking.android.CampaignTrackingService" />
    <receiver android:name="com.google.analytics.tracking.android.CampaignTrackingReceiver" android:exported="true">
      <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
      </intent-filter>
    </receiver>

    <receiver android:name="com.tune.TuneTracker" android:exported="true">
      <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
      </intent-filter>
    </receiver>

    <activity android:name="com.outlinegames.unibill.PurchaseActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
    <activity android:name="com.facebook.unity.FBUnityAppLinkActivity" android:exported="true" />
    <activity android:name="com.facebook.unity.FBUnityGameRequestActivity" />
    <activity android:name="com.facebook.unity.FBUnityCreateGameGroupActivity" />
    <activity android:name="com.facebook.unity.FBUnityJoinGameGroupActivity" />
    <activity android:name="com.facebook.unity.AppInviteDialogActivity" />
    <provider android:name="com.facebook.FacebookContentProvider" android:authorities="com.facebook.app.FacebookContentProvider577464905719222" android:exported="true" />
    <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
  </application>

  <permission
    android:name="fab.gameofwords.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="fab.gameofwords.permission.C2D_MESSAGE" />
  <uses-permission android:name="com.android.vending.BILLING" />
</manifest>

Seems that the crash only occurs on Android 6.0.
What can be wrong here, what am I missing?

Thanks in advance.


问:
How to upload Images in codeigniter with mysql database
Note is that : All data is inserted properly.
               But if i'm upload an image with the help of
               $this->upload->do_upload();and validate id,

               this is not properly working. can u suggest..

```<code>//Controller

public function saveEmployeea()
    {

      $config = [ 'upload_path'=>'./uploads',
          'allowed_types'=>'gif|jpg|png|jpeg'];

      $this->load->library('upload', $config);

      $this->form_validation->set_rules('dept_name', 'Department', 'required');

      $this->form_validation->set_rules('firstname', 'First Name','required');

      $this->form_validation->set_rules('middlename', 'Middle Name','required');

      $this->form_validation->set_rules('lastname', 'Last Name','required');

      $this->form_validation->set_rules('gendar', 'Gendar','required');

      $this->form_validation->set_rules('address1', 'Local Address','required');

      $this->form_validation->set_rules('address2', 'Permant Address','required');

      $this->form_validation->set_rules('nationality', 'Nationality','required');

      $this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');

      $this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');

      // $this->form_validation->set_rules('profile_image', 'Please Upload image','required');

      $this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');

      $this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
      $this->form_validation->set_rules('personal_no', 'Personal Contact No','required');

      $this->form_validation->set_rules('emergency_no', 'Emergency No','required');

      $this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');

      $this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');

      $this->form_validation->set_rules('university', 'University','required');

      $this->form_validation->set_rules('no_experience', 'No Experience','required');

      $this->form_validation->set_rules('pre_compony', 'Previus Compony','required');

      $this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
      $this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');

      if ( $this->form_validation->run() && $this->upload->do_upload())
      {

        $data = $this->input->post();

        // insert images in data variables by using upload object oprater.
        $upload_info = $this->upload->data();

        //set path for images store
        $path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);

        $data['profile_image'] = $path;

        // echo '```';
        // print_r($data);
        // echo '```';
        // var_dump($data);
        // exit();

        // Load Model to Call Model class
        $this->load->model('Loginm');

        if($this->Loginm->insertEmployee($data))
        {
          $this->session->set_flashdata('employee_details','Employee Details Added Successfully');
        }
        else
        {
          $this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
        }
          return redirect('Employee/EmployeeList');

      }
      else
      {
        $upload_error = $this->upload->display_errors();
        $this->createEmployee();
      }
    }

// Model

public function insertEmployee($data)
{
    return $this->db->insert('employee',$data);
}`enter code here`
</code>```

答:
First,

```<code>     $this->upload->do_upload('userfile')
</code>```

here 'userfile' in the name attribute in the input element.

```<code>     <form action="url" enctype="multipart/form-data" method="post">
     <input type="file" name="userfile" accept="image/*">
</code>```

make sure you use:
enctype="multipart/form-data"
or
CI 3 counterpart:
echo form_open_multipart();

second,

The Upload Directory

You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter installation called uploads and set its file permissions to 777.

you may have file permission issue in the upload directory that you set. You should set proper permissions to the upload directory.

References:

https://www.codeigniter.com/userguide3/libraries/file_uploading.html

Body:
Note is that : All data is inserted properly.
               But if i'm upload an image with the help of
               $this->upload->do_upload();and validate id,

               this is not properly working. can u suggest..

//Controller

public function saveEmployeea()
    {

      $config = [ 'upload_path'=>'./uploads',
          'allowed_types'=>'gif|jpg|png|jpeg'];

      $this->load->library('upload', $config);

      $this->form_validation->set_rules('dept_name', 'Department', 'required');

      $this->form_validation->set_rules('firstname', 'First Name','required');

      $this->form_validation->set_rules('middlename', 'Middle Name','required');

      $this->form_validation->set_rules('lastname', 'Last Name','required');

      $this->form_validation->set_rules('gendar', 'Gendar','required');

      $this->form_validation->set_rules('address1', 'Local Address','required');

      $this->form_validation->set_rules('address2', 'Permant Address','required');

      $this->form_validation->set_rules('nationality', 'Nationality','required');

      $this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');

      $this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');

      // $this->form_validation->set_rules('profile_image', 'Please Upload image','required');

      $this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');

      $this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
      $this->form_validation->set_rules('personal_no', 'Personal Contact No','required');

      $this->form_validation->set_rules('emergency_no', 'Emergency No','required');

      $this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');

      $this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');

      $this->form_validation->set_rules('university', 'University','required');

      $this->form_validation->set_rules('no_experience', 'No Experience','required');

      $this->form_validation->set_rules('pre_compony', 'Previus Compony','required');

      $this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
      $this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');

      if ( $this->form_validation->run() && $this->upload->do_upload())
      {

        $data = $this->input->post();

        // insert images in data variables by using upload object oprater.
        $upload_info = $this->upload->data();

        //set path for images store
        $path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);

        $data['profile_image'] = $path;

        // echo '
';
        // print_r($data);
        // echo '
';
        // var_dump($data);
        // exit();

        // Load Model to Call Model class
        $this->load->model('Loginm');

        if($this->Loginm->insertEmployee($data))
        {
          $this->session->set_flashdata('employee_details','Employee Details Added Successfully');
        }
        else
        {
          $this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
        }
          return redirect('Employee/EmployeeList');

      }
      else
      {
        $upload_error = $this->upload->display_errors();
        $this->createEmployee();
      }
    }

// Model

public function insertEmployee($data)
{
    return $this->db->insert('employee',$data);
}`enter code here`

Body:
First,

     $this->upload->do_upload('userfile')

here 'userfile' in the name attribute in the input element.

     <form action="url" enctype="multipart/form-data" method="post">
     <input type="file" name="userfile" accept="image/*">

make sure you use:
enctype="multipart/form-data"
or
CI 3 counterpart:
echo form_open_multipart();

second,

The Upload Directory

You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter installation called uploads and set its file permissions to 777.

you may have file permission issue in the upload directory that you set. You should set proper permissions to the upload directory.

References:

https://www.codeigniter.com/userguide3/libraries/file_uploading.html