问:
Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable
iam getting this error message when build simple app

Getting user info from: http://localhost:9999/uaa/user
  Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=UTF-8]

however i sure the content type is json

this is the github repository https://github.com/ashraf-revo/oauth

this is server

```<code>@SpringBootApplication
public class AuthServerApplication {

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
}
}

@Order(1)
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws     Exception {
      auth.inMemoryAuthentication().withUser("ashraf").password("ashraf").roles("user");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/user").authenticated().and().formLogin();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
}

@Configuration
class OAuth2ServerConfig {
private static final String RESOURCE_IDS = "revo";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_IDS);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/user").authenticated();
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("revo")
                .resourceIds(RESOURCE_IDS)
                .authorizedGrantTypes("authorization_code", "implicit")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write")
                .secret("revo");
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
    }
}

}
</code>```

this is the client

```<code>@SpringBootApplication
public class ClientApplication {

public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
}
}

@Configuration
@EnableOAuth2Sso
class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().mvcMatchers("/home").authenticated();
}
}

 @Configuration
 class MvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/home").setViewName("home");
}
}
</code>```

答:
If you can control the server response, modify it to set the Content-type to application/json.

Please try,

```<code>@RequestMapping(value = "/user", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
</code>```

Body:
iam getting this error message when build simple app

Getting user info from: http://localhost:9999/uaa/user
  Could not fetch user details: class org.springframework.web.client.RestClientException, Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=UTF-8]

however i sure the content type is json

this is the github repository https://github.com/ashraf-revo/oauth

this is server

@SpringBootApplication
public class AuthServerApplication {

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
}
}

@Order(1)
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws     Exception {
      auth.inMemoryAuthentication().withUser("ashraf").password("ashraf").roles("user");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/user").authenticated().and().formLogin();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
}

@Configuration
class OAuth2ServerConfig {
private static final String RESOURCE_IDS = "revo";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_IDS);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/user").authenticated();
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("revo")
                .resourceIds(RESOURCE_IDS)
                .authorizedGrantTypes("authorization_code", "implicit")
                .authorities("ROLE_CLIENT")
                .scopes("read", "write")
                .secret("revo");
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
    }
}

}

this is the client

@SpringBootApplication
public class ClientApplication {

public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
}
}

@Configuration
@EnableOAuth2Sso
class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().mvcMatchers("/home").authenticated();
}
}

 @Configuration
 class MvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/home").setViewName("home");
}
}

Body:
If you can control the server response, modify it to set the Content-type to application/json.

Please try,

@RequestMapping(value = "/user", method = RequestMethod.GET,
produces = "application/json; charset=utf-8")


来源: stackexchange

问:
jenkins deletes existing work space ,when trying to clone new git repo from git scm plugin
I see in a Jenkins job log:

```<code>Cloning the remote Git repository ssh://username@systemname.eu.company.com:29418/<repo-name>.
ERROR: Failed to clean the workspace Java.io.IOException: Unable to delete ‘C:\Users\<usersname>\GitRepositorys\reponame’.
  Tried 3 times (of a maximum of 3) waiting 0.1 sec between attempts.
Error cloning remote repo ‘origin’ Hudson.plugins.git.GitException:
  Failed to delete workspace
</code>```

This above error we had got, but it had already deleted the majority of files and only files which where active was not deleted.

And no delete workspace or clean up command was active in jenkins job configuration.

答:
Try first to see if there is any process preempting those files (and blocking the deletion). Use Process Explorer ctrl+F "find process" feature.

Sometimes, I have to reboot the slave server in order to make sure those processes go away.

Then retry your job, and see if the workspace can be deleted then.

ContentLicense: CC BY-SA 3.0

Body:
I see in a Jenkins job log:

Cloning the remote Git repository ssh://username@systemname.eu.company.com:29418/<repo-name>.
ERROR: Failed to clean the workspace Java.io.IOException: Unable to delete ‘C:\Users\<usersname>\GitRepositorys\reponame’.
  Tried 3 times (of a maximum of 3) waiting 0.1 sec between attempts.
Error cloning remote repo ‘origin’ Hudson.plugins.git.GitException:
  Failed to delete workspace

This above error we had got, but it had already deleted the majority of files and only files which where active was not deleted.

And no delete workspace or clean up command was active in jenkins job configuration.


问:
Adding Web API to existing application with virtual directory
I have an existing website setup and working (kentico 10), I want to add Web API to it using a virtual directory.

I setup the web api project and it works when I map IIS to it as a normal site. However when I map the folder as a virtual directory and convert to application into my kentico site I get errors. What I dont understand is why I am getting errors originating from the kentico web config and not the new web api web.config/service:

```<code>Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0234: The type or namespace name 'Web' does not exist in the namespace 'CMS.Base' (are you missing an assembly reference?)

Source Error:

Line 47:       <namespaces>
Line 48:         <add namespace="CMS.Helpers" />
Line 49:         <add namespace="CMS.Base.Web.UI" />
Line 50:       </namespaces>
Line 51:     </pages>
</code>```

I did try adding these DLLs into the bin of the web api project which stopped this error but I couldnt retrieve data as expected from kentico in the web-api project.

Thanks

答:
Whenever you create an application within a website in IIS, the parent web.config will be inherited by the sub applications very similar to how a main website inherits the "global" web.config.  Maybe not all of the nodes will be inherited but a lot of them will be.

So what you'll want to do is add  (i.e.: <remove name="WebDAVModule" />) nodes to areas in which you want to remove namespaces or such in your newly created sub application's web.config.  I cannot say specifically which nodes will need to have those  nodes applied but trial and error should help.  If you follow the errors that come on-screen, they should help with adding those nodes in your child web.config.

Body:
I have an existing website setup and working (kentico 10), I want to add Web API to it using a virtual directory.

I setup the web api project and it works when I map IIS to it as a normal site. However when I map the folder as a virtual directory and convert to application into my kentico site I get errors. What I dont understand is why I am getting errors originating from the kentico web config and not the new web api web.config/service:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0234: The type or namespace name 'Web' does not exist in the namespace 'CMS.Base' (are you missing an assembly reference?)

Source Error:

Line 47:       <namespaces>
Line 48:         <add namespace="CMS.Helpers" />
Line 49:         <add namespace="CMS.Base.Web.UI" />
Line 50:       </namespaces>
Line 51:     </pages>

I did try adding these DLLs into the bin of the web api project which stopped this error but I couldnt retrieve data as expected from kentico in the web-api project.

Thanks


问:
How to check if an item exists in more than one listbox? ASP.NET/C#
I have three sets of listboxes, I move items from lb1 to lb2, from lb3 to lb4 and from lb5 to lb6. The listboxes on the left contains the same items and I don't want the user to be able to submit the page if one or more items from the left listboxes is added to more than one listbox to the right. For example, item A in lb1, lb3 and lb5 can only be saved in either lb2, lb4 or lb6, not in two or three of them.

I want to perform this check before submitting the page (and later on I will add validation with javascript) and I wonder what is the most efficient way to do this.

Add all items to a list and check if there are any duplicates?

Thanks in advance.

Edit:
something like this:

```<code>            List<string> groupList = new List<string>();
            foreach (ListItem item in lbFullAccess.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lbContributor.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lblReadOnly.Items)
            {
                groupList.Add(item.Value.ToString());
            }
</code>```

答:
Well, there's a hundred different ways you could do it. Absolutely nothing wrong with your suggestion of iteration.

You could have a little fun with LINQ:

```<code>public bool AreAllValuesUnique()
{
    // Build up a linq expression of all of the ListItems
    // by concatenating each sequence
    var allItems = lbFullAccess.Items.Cast<ListItem>()
        .Concat(lbContributor.Items.Cast<ListItem>())
        .Concat(lbReadOnly.Items.Cast<ListItem>());

    // Group the previous linq expression by value (so they will be in groups of "A", "B", etc)
    var groupedByValue = allItems.GroupBy(i => i.Value);

    // Finally, return that all groups must have a count of only one element
    // So each value can only appear once
    return groupedByValue.All(g => g.Count() == 1);
}
</code>```

Not really sure about the performance of calling Cast (converting each element of the ListItemCollection to a ListItem, resulting in an IEnumerable) on each collection, but it is probably negligible.

ContentLicense: CC BY-SA 2.5

Body:
I have three sets of listboxes, I move items from lb1 to lb2, from lb3 to lb4 and from lb5 to lb6. The listboxes on the left contains the same items and I don't want the user to be able to submit the page if one or more items from the left listboxes is added to more than one listbox to the right. For example, item A in lb1, lb3 and lb5 can only be saved in either lb2, lb4 or lb6, not in two or three of them.

I want to perform this check before submitting the page (and later on I will add validation with javascript) and I wonder what is the most efficient way to do this.

Add all items to a list and check if there are any duplicates?

Thanks in advance.

Edit:
something like this:

            List<string> groupList = new List<string>();
            foreach (ListItem item in lbFullAccess.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lbContributor.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lblReadOnly.Items)
            {
                groupList.Add(item.Value.ToString());
            }

Body:
Well, there's a hundred different ways you could do it. Absolutely nothing wrong with your suggestion of iteration.

You could have a little fun with LINQ:

public bool AreAllValuesUnique()
{
    // Build up a linq expression of all of the ListItems
    // by concatenating each sequence
    var allItems = lbFullAccess.Items.Cast<ListItem>()
        .Concat(lbContributor.Items.Cast<ListItem>())
        .Concat(lbReadOnly.Items.Cast<ListItem>());

    // Group the previous linq expression by value (so they will be in groups of "A", "B", etc)
    var groupedByValue = allItems.GroupBy(i => i.Value);

    // Finally, return that all groups must have a count of only one element
    // So each value can only appear once
    return groupedByValue.All(g => g.Count() == 1);
}

Not really sure about the performance of calling Cast (converting each element of the ListItemCollection to a ListItem, resulting in an IEnumerable) on each collection, but it is probably negligible.


问:
Python: for loop iteration accumulate values in string variable
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

```<code>string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
</code>```

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

答:
In order to add letter b to an existing string_y suppose, you'll have to concatenate it to the existing string_y like

```<code>string_y = string_y + 'b'
</code>```

or in the above loop, it would be

```<code>string_x = "abc"
string_y = ""
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     string_y = string_y + data
</code>```

Since strings are immutable data types in Python, concatenating two strings together actually creates a third string which is the combination of the previous two. So it's more efficient to add the letters to a list and combine it into a string.

```<code>string_x = "abc"
stringlist = []
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     stringlist.append(data)
string_y = "".join(stringlist)
</code>```

Body:
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

Body:
In order to add letter b to an existing string_y suppose, you'll have to concatenate it to the existing string_y like

string_y = string_y + 'b'

or in the above loop, it would be

string_x = "abc"
string_y = ""
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     string_y = string_y + data

Since strings are immutable data types in Python, concatenating two strings together actually creates a third string which is the combination of the previous two. So it's more efficient to add the letters to a list and combine it into a string.

string_x = "abc"
stringlist = []
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     stringlist.append(data)
string_y = "".join(stringlist)


问:
Text floats even when fixed relative to top on Jasper Reports
In the template we have assume 8 rows are there. And among last 4 rows, last one only eligible to be displayed others will be failed in the "print when" expression.

Settings of each row:

Position Type: Fixed to Top

Stretch Type: No Stretch

Horizontal Alignment: Left

Veritical Alignment: Top

Having all these settings, the last row is getting displayed on its position only and there is a blank three rows above.

Can you please help in resolving this issue?

答: Keep the position type as Float, that should help.</p>


问:
when i update angular2->4,use NoopAnimationsModule or BrowserAnimationsModule throw an error
Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead

I'm sure my module is CommonModule not BrowserModule .

If I don't import BrowserAnimationsModule , it's ok.

But I need this,help

答:
I think you are using 'NoopAnimationsModule' or 'BrowserAnimationModule', Which already contain 'BrowserModule' and loading your module lazily. SO the solution is Replace the BrowserModule with 'NoopAnimationModule or 'BrowserAnimationModule' in your 'app.module.ts'.</p>

```<code>import { Router } from '@angular/router';
import { AdminsModule } from './admins/admins.module';
import { NoopAnimationsModule } from '@angular/platform-
browser/animations';
//import { BrowserModule } from '@angular/platform-browser';
import { NgModule,OnInit } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
    //BrowserModule,
    NoopAnimationsModule,
    FormsModule
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

Body:
I think you are using 'NoopAnimationsModule' or 'BrowserAnimationModule', Which already contain 'BrowserModule' and loading your module lazily. SO the solution is Replace the BrowserModule with 'NoopAnimationModule or 'BrowserAnimationModule' in your 'app.module.ts'.

import { Router } from '@angular/router';
import { AdminsModule } from './admins/admins.module';
import { NoopAnimationsModule } from '@angular/platform-
browser/animations';
//import { BrowserModule } from '@angular/platform-browser';
import { NgModule,OnInit } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
    //BrowserModule,
    NoopAnimationsModule,
    FormsModule
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


问:
modify the css for font awesome
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/></code>```

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}```

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

答:
I'm not sure if you can do it using an input element. It is possible using a button though. Here are two examples:

1) Using a seperate element (eg; i or span, etc) within the button for the icon.

```<code><button type="button">
  <i class="fa fa-credit-card" aria-hidden="true"></i> Pre-payment
</button>
</code>```

2) Using a pseudo element which allows you to make the necessary changes for the icon via css.

```<code><button type="button" class="submitter" onClick="location.href='../test.htm'"/>Pre-payment</button>

<style>
button.submitter:before {
    font-family: FontAwesome;
    content:'\f09d';
    margin-right:4px;
}
</style>
</code>```

Title: modify the css for font awesome

Body:
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/>

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

Body:
I'm not sure if you can do it using an input element. It is possible using a button though. Here are two examples:

1) Using a seperate element (eg; i or span, etc) within the button for the icon.

<button type="button">
  <i class="fa fa-credit-card" aria-hidden="true"></i> Pre-payment
</button>

2) Using a pseudo element which allows you to make the necessary changes for the icon via css.

<button type="button" class="submitter" onClick="location.href='../test.htm'"/>Pre-payment</button>

<style>
button.submitter:before {
    font-family: FontAwesome;
    content:'\f09d';
    margin-right:4px;
}
</style>


问:
How to connect openWrt (Virtualbox) to wifi?
I'm new user of openWRT I using a internet wifi in Ubuntu 16.04, I installed openWRT in VirtualBox, I tried to connect to internet but I failed, when I try to ping google.com I get this message **bad address google.com **

 /etc/config/network">

答:
If you want to connect WiFi manually by editing file,
you need to edit mainly 3 files.

/etc/config/network

/etc/config/wireless

/etc/config/firewall

--> I would suggest adding the following portion in your network config file(/etc/config/network).
(make sure you do not have any assigned section for the wifi in the network config file)

```<code>config interface 'wifi'
    option proto 'dhcp'
</code>```

--> Also, you need to update the file (/etc/config/wireless)

```<code>config wifi-iface 'station1'
     option device 'radio0'
     option ifname 'wlan0'
     option mode 'sta'
     option network 'wifi'
     option disabled '0'
     option ssid 'name_of_the_wifi'
     option key 'password_of_the_wifi'
     option encryption 'encryption_of_wifi_generally_psk2'
</code>```

in above setup option network 'wifi' "wifi" will be the name of the interface you defines in the /etc/config/network.[make sure if you have above section you edit the existing one. Do not add new section if you do not know what you are doing]

Here, replace "wlan0" with your wireless interface.

If you already have above section in wireless file,
you can also use uci commands as following,

```<code>uci set wireless.station1.ssid=name_of_wifi
uci set wireless.station1.key=password
uci set wireless.station1.encryption=psk2
uci commit wireless
wifi down; wifi
</code>```

here, "station1" would be the name of the section.

--> In the /etc/config/firewall, find the option zone section where all the interface is defined, which looks like following

```<code>config zone
        option name             wan
        list   network          'wan'
        list   network          'wan6'
        option input            REJECT
        option output           ACCEPT
        option forward          REJECT
        option masq             0
        option mtu_fix          1
        option conntrack        1
</code>```

and add

```<code>list network 'wwan'
</code>```

Command to check Wifi Connectivity: iwconfig

Refer the following link:
https://wiki.openwrt.org/doc/uci/wireless

NOTE: PLEASE READ FROM OPENWRT FORUM OR GOOGLE BEFORE DOING ANYTHING
The Wrong configuration may break the OpenWRT connection

Body:
If you want to connect WiFi manually by editing file,
you need to edit mainly 3 files.

/etc/config/network

/etc/config/wireless

/etc/config/firewall

--> I would suggest adding the following portion in your network config file(/etc/config/network).
(make sure you do not have any assigned section for the wifi in the network config file)

config interface 'wifi'
    option proto 'dhcp'

--> Also, you need to update the file (/etc/config/wireless)

config wifi-iface 'station1'
     option device 'radio0'
     option ifname 'wlan0'
     option mode 'sta'
     option network 'wifi'
     option disabled '0'
     option ssid 'name_of_the_wifi'
     option key 'password_of_the_wifi'
     option encryption 'encryption_of_wifi_generally_psk2'

in above setup option network 'wifi' "wifi" will be the name of the interface you defines in the /etc/config/network.[make sure if you have above section you edit the existing one. Do not add new section if you do not know what you are doing]

Here, replace "wlan0" with your wireless interface.

If you already have above section in wireless file,
you can also use uci commands as following,

uci set wireless.station1.ssid=name_of_wifi
uci set wireless.station1.key=password
uci set wireless.station1.encryption=psk2
uci commit wireless
wifi down; wifi

here, "station1" would be the name of the section.

--> In the /etc/config/firewall, find the option zone section where all the interface is defined, which looks like following

config zone
        option name             wan
        list   network          'wan'
        list   network          'wan6'
        option input            REJECT
        option output           ACCEPT
        option forward          REJECT
        option masq             0
        option mtu_fix          1
        option conntrack        1

and add

list network 'wwan'

Command to check Wifi Connectivity: iwconfig

Refer the following link:
https://wiki.openwrt.org/doc/uci/wireless

NOTE: PLEASE READ FROM OPENWRT FORUM OR GOOGLE BEFORE DOING ANYTHING
The Wrong configuration may break the OpenWRT connection


问:
How to check whether a twitter bootstrap popover is visible or not?
I have an element $('#anElement') with a potential popover attached, like

```<code><div id="anElement" data-original-title="my title" data-trigger="manual" data-content="my content" rel="popover"></div>
</code>```

I just would like to know how to check whether the popover is visible or not: how this can be accomplished with jQuery?

答:
Perhaps the most reliable option would be listening to shown/hidden events, as demonstrated below. This would eliminate the necessity of digging deep into the DOM that could be error prone.

```<code>var isMyPopoverVisible = false;//assuming popovers are hidden by default

$("#myPopoverElement").on('shown.bs.popover',function(){
isMyPopoverVisible = true;
});

$("#myPopoverElement").on('hidden.bs.popover',function(){
isMyPopoverVisible = false;
});
</code>```

These events seem to be triggered even if you hide/show/toggle the popover programmatically, without user interaction.

P. S. tested with BS3.

Body:
I have an element $('#anElement') with a potential popover attached, like

I just would like to know how to check whether the popover is visible or not: how this can be accomplished with jQuery?

Body:
Perhaps the most reliable option would be listening to shown/hidden events, as demonstrated below. This would eliminate the necessity of digging deep into the DOM that could be error prone.

var isMyPopoverVisible = false;//assuming popovers are hidden by default

$("#myPopoverElement").on('shown.bs.popover',function(){
isMyPopoverVisible = true;
});

$("#myPopoverElement").on('hidden.bs.popover',function(){
isMyPopoverVisible = false;
});

These events seem to be triggered even if you hide/show/toggle the popover programmatically, without user interaction.

P. S. tested with BS3.


问:
Transferring an SQL query from the workbench to a .java class
I'm trying to transfer an SQL query into java from my workbench.
I wrote this query in the mySQL workbench and it executed fine with the results I wanted.

SELECT committee_member.member_CAN#, member.first_name, member.last_name, committee_member.member_status, committee_member.start_year, committee_member.end_year, committee_member.added_notes
FROM committee_member LEFT JOIN member
ON committee_member.member_CAN# = CAN#

Here is my .java class code.  I am trying to print a table that displays this information.
I keep getting an error that reads "Unknown table 'committee_member' in field list" in eclipse, so i'm guessing that my query syntax is wrong.

```<code>package model;

import java.sql.*;
import java.util.ArrayList;

public class ViewCommitteeMember {

private Connection connection;
private ArrayList<CommitteeMember> members;

public ViewCommitteeMember(){
members = new ArrayList<CommitteeMember>();
makeConnection();
}

public void viewMembers(){
String query =  "SELECT `committee_member`.`member_CAN#`, `member`.`first_name`,           `member`.`last_name`, `committee_member`.`member_status`, `committee_member`.`start_year`, `committee_member`.`end_year`, `committee_member`.`added_notes` FROM committee_member LEFT JOIN member ON `committee_member`.`member_CAN#` = `CAN#`";

PreparedStatement ps;
try {
 ps = connection.prepareStatement(query);

  ResultSet rs = ps.executeQuery();

  while (rs.next()){ //while the query is running, loop through all of the members
    CommitteeMember member = new CommitteeMember(); //create a new member for each entry so info may be displayed
    member.setID(rs.getInt(1)); //pulls the ID
    member.setFirstname(rs.getString(2));
    member.setLastname(rs.getString(3));
    member.setMemStat(rs.getString(4)); //pulls the status
    member.setStartYear(rs.getInt(5)); //pulls the start year
    member.setEndYear(rs.getInt(6)); //pulls the end year
    member.setNotes(rs.getString(7)); //pulls the additional notes

    members.add(member); //add the member to the array list "members"
  }

  } catch (SQLException e) {
 // TODO Auto-generated catch block
  e.printStackTrace();

 } finally {
   this.closeConnection();
 }
 }

  private void makeConnection(){
  // get connection
  String url = "jdbc:mysql://localhost:3306/committee_database";
  String user = "root";
  String pwd = "coolman";
  try {
  connection = DriverManager.getConnection(url, user, pwd);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }

  private void closeConnection(){
 try {
  connection.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }

  /**
  * @return the agents
  */
  public ArrayList<CommitteeMember> getMembers() {  //list of all the members
  return members;
  }

  }
</code>```

答:
Use alias like:

```<code>    String query =  "SELECT cm.member_CAN#, m.first_name, m.last_name,
cm.member_status, cm.start_year, cm.end_year, cm.added_notes
FROM committee_member cm LEFT JOIN member m ON cm.member_CAN# = m.CAN#";
</code>```

Body:
I'm trying to transfer an SQL query into java from my workbench.
I wrote this query in the mySQL workbench and it executed fine with the results I wanted.

SELECT committee_member.member_CAN#, member.first_name, member.last_name, committee_member.member_status, committee_member.start_year, committee_member.end_year, committee_member.added_notes
FROM committee_member LEFT JOIN member
ON committee_member.member_CAN# = CAN#

Here is my .java class code.  I am trying to print a table that displays this information.
I keep getting an error that reads "Unknown table 'committee_member' in field list" in eclipse, so i'm guessing that my query syntax is wrong.

package model;

import java.sql.*;
import java.util.ArrayList;

public class ViewCommitteeMember {

private Connection connection;
private ArrayList<CommitteeMember> members;

public ViewCommitteeMember(){
members = new ArrayList<CommitteeMember>();
makeConnection();
}

public void viewMembers(){
String query =  "SELECT `committee_member`.`member_CAN#`, `member`.`first_name`,           `member`.`last_name`, `committee_member`.`member_status`, `committee_member`.`start_year`, `committee_member`.`end_year`, `committee_member`.`added_notes` FROM committee_member LEFT JOIN member ON `committee_member`.`member_CAN#` = `CAN#`";

PreparedStatement ps;
try {
 ps = connection.prepareStatement(query);

  ResultSet rs = ps.executeQuery();

  while (rs.next()){ //while the query is running, loop through all of the members
    CommitteeMember member = new CommitteeMember(); //create a new member for each entry so info may be displayed
    member.setID(rs.getInt(1)); //pulls the ID
    member.setFirstname(rs.getString(2));
    member.setLastname(rs.getString(3));
    member.setMemStat(rs.getString(4)); //pulls the status
    member.setStartYear(rs.getInt(5)); //pulls the start year
    member.setEndYear(rs.getInt(6)); //pulls the end year
    member.setNotes(rs.getString(7)); //pulls the additional notes

    members.add(member); //add the member to the array list "members"
  }

  } catch (SQLException e) {
 // TODO Auto-generated catch block
  e.printStackTrace();

 } finally {
   this.closeConnection();
 }
 }

  private void makeConnection(){
  // get connection
  String url = "jdbc:mysql://localhost:3306/committee_database";
  String user = "root";
  String pwd = "coolman";
  try {
  connection = DriverManager.getConnection(url, user, pwd);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }

  private void closeConnection(){
 try {
  connection.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }

  /**
  * @return the agents
  */
  public ArrayList<CommitteeMember> getMembers() {  //list of all the members
  return members;
  }

  }

Body:
Use alias like:

    String query =  "SELECT cm.member_CAN#, m.first_name, m.last_name,
cm.member_status, cm.start_year, cm.end_year, cm.added_notes
FROM committee_member cm LEFT JOIN member m ON cm.member_CAN# = m.CAN#";


问:
Show Results on View
Im triyng to make some calculation on my View, but i cant show the result out of my @{} block

I have this table.

```<code>    <!--Table to display registered products-->
    <table class="table table-condensed table-hover">
        <thead>
            <tr>
                <th>CODIGO</th>
                <th>NOME</th>
                <th>PRECO</th>
                <th>QUANTIDADE</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @if (Model != null)
            {
                double sum = 0;
                for (int i = 0; i < Model.Item2.Count; i++)
                {
                    <tr>
                        @using (Html.BeginForm("AddProduct", "Sale", FormMethod.Post))
                        {
                            <td>
                                @Html.DisplayFor(modelItem => Model.Item2[i].idProduct)
                            </td>

                            <td>@Html.DisplayFor(model => Model.Item2[i].nameProduct)</td>
                            <td>
                                <p>R$@Html.DisplayFor(model => Model.Item2[i].pricesaleProduct)</p>
                            </td>
                            <td>@Html.DisplayFor(model => Model.Item2[i].quantityProduct)</td>
                            <td>
                                <input type="submit" class="btn btn-danger" value="Deletar">
                            </td>
                            sum += Model.Item2[i].pricesaleProduct * Model.Item2[i].quantityProduct;
                        }
                    </tr>
                }
            }
        </tbody>
    </table>

<!--I want display "sum" here-->
Total Value: @sum
</code>```

I want to show "sum" out of my table, but trying several variations and a get error!

How can i make it?

答:
You have declared sum inside if(){} block and hence you're not able to access it. Move it outside like this and it'll work

```<code> double sum = 0;

 @if (Model != null)
 {

      ............
      ............
 }
</code>```

Title: Show Results on View

Body:
Im triyng to make some calculation on my View, but i cant show the result out of my @{} block

I have this table.

                CODIGO
                NOME
                PRECO
                QUANTIDADE

            @if (Model != null)
            {
                double sum = 0;
                for (int i = 0; i < Model.Item2.Count; i++)
                {

                        @using (Html.BeginForm("AddProduct", "Sale", FormMethod.Post))
                        {

                                @Html.DisplayFor(modelItem => Model.Item2[i].idProduct)

                            @Html.DisplayFor(model => Model.Item2[i].nameProduct)

R$@Html.DisplayFor(model => Model.Item2[i].pricesaleProduct)

                            @Html.DisplayFor(model => Model.Item2[i].quantityProduct)

                                <input type="submit" class="btn btn-danger" value="Deletar">

                            sum += Model.Item2[i].pricesaleProduct * Model.Item2[i].quantityProduct;
                        }

                }
            }

Total Value: @sum

I want to show "sum" out of my table, but trying several variations and a get error!

How can i make it?

Body:
You have declared sum inside if(){} block and hence you're not able to access it. Move it outside like this and it'll work

 double sum = 0;

 @if (Model != null)
 {

      ............
      ............
 }


问:
Printing the patterns using only one loop
I have printed this pattern using one loop:

```<code>*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}
</code>```

Now i want how to print following patterns using only one loop.

```<code>1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * *
   * * * *
    * * *
     * *
      *

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

and other similar patterns using only one loop, I have done all of them using more than one loop.

答:
to make star pyramid with single loop</p>

```<code>for(i=0; i<a; i++)
{
    for(j=0; j<a-i-1; j++)
        printf(" ");
    for(j=0; j<2*i+1; j++)
        printf("*");
    printf("\n");
}
</code>```

Body:
I have printed this pattern using one loop:

*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}

Now i want how to print following patterns using only one loop.

1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * *
   * * * *
    * * *
     * *
      *

3)
   1 2 3 4 5
   1 2 3 4
   1 2 3
   1 2
   1

and other similar patterns using only one loop, I have done all of them using more than one loop.

Body:
to make star pyramid with single loop

for(i=0; i<a; i++)
{
    for(j=0; j<a-i-1; j++)
        printf(" ");
    for(j=0; j<2*i+1; j++)
        printf("*");
    printf("\n");
}


问:
RETURN values in PHP
I have 2 functions in PHP and i want to return a value to one function to another. this is my functions

```<code> public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);

}

function payment_log_exists($icasl_no, $exam_session) {
        $this->db->where('icasl_no', $icasl_no);
        $this->db->where('exam_session', $exam_session);
        $query = $this->db->get('exm_paymentlog');
        if ($query->num_rows() > 0) {
            $pl = $query->row();
            $pay_id = $pl->paylog_id;
            return $pay_id;
        } else {
            return false;
        }
    }
</code>```

I want to return $pay_id to the save_payment_log_data() function but in here $pay_id didn't return to that function. I think it's return from the function payment_log_exists()
so how can I return $pay_id to the  save_payment_log_data() function

答:
your are only assigning a value to the $paylog_av your "save_payment_log_data" function should be:</p>

```<code>public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);
return $paylog_av;

}
</code>```

Title: RETURN values in PHP

Body:
I have 2 functions in PHP and i want to return a value to one function to another. this is my functions

 public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);

}

function payment_log_exists($icasl_no, $exam_session) {
        $this->db->where('icasl_no', $icasl_no);
        $this->db->where('exam_session', $exam_session);
        $query = $this->db->get('exm_paymentlog');
        if ($query->num_rows() > 0) {
            $pl = $query->row();
            $pay_id = $pl->paylog_id;
            return $pay_id;
        } else {
            return false;
        }
    }

I want to return $pay_id to the save_payment_log_data() function but in here $pay_id didn't return to that function. I think it's return from the function payment_log_exists()
so how can I return $pay_id to the  save_payment_log_data() function

Body:
your are only assigning a value to the $paylog_av your "save_payment_log_data" function should be:

public function save_payment_log_data($icasl_number, $exam_session) {

$paylog_av = $this->payment_log_exists($icasl_number, $exam_session);
return $paylog_av;

}


问:
Overflow of levels for factor columns of data frame in RStudio
Try this code

```<code>f <- factor(sample.int(1000, 100))
df <- data.frame(F = f)
View(df)
</code>```

Now when you mouse over F column in the RStudio View() tab, it shows "factor with 1 levels". But when you look at the definition of f separately, it will have all levels. I have tried with different levels. It shows correctly until 64 levels after that it behaves weird. Please let me know how to fix this. I already tried "nmax" that has not effect.

Below code works correctly

```<code>f <- factor(sample.int(1000, 64))
df <- data.frame(F = f)
View(df)
</code>```

答:
It's not an R bug but an RStudio bug. It's all correct looking at nlevels() or str() and checking the Environment pane in RStudio (it says Factor w/ 314 levels for me), but the one place it's wrong as you noted is when you mouse-over/tooltip over the column name in View() and it says "factor with 1 levels"

Someone has reported the bug as of Feb 2017 and RStudio is looking into it. https://support.rstudio.com/hc/en-us/community/posts/115001084508-Factor-levels-differ-in-view-mode-and-environment-tab?input_string=View()%20bug%20when%20viewing%20factors%20with%20%3E64%20levels

Body:
Try this code

f <- factor(sample.int(1000, 100))
df <- data.frame(F = f)
View(df)

Now when you mouse over F column in the RStudio View() tab, it shows "factor with 1 levels". But when you look at the definition of f separately, it will have all levels. I have tried with different levels. It shows correctly until 64 levels after that it behaves weird. Please let me know how to fix this. I already tried "nmax" that has not effect.

Below code works correctly

f <- factor(sample.int(1000, 64))
df <- data.frame(F = f)
View(df)


问:
linq to xml duplicate namespace gives empty attribute
```<code><ftc:XX version="1.1"
  xmlns:ftc="urn:v1"
  xmlns="urn:v1">
  <ftc:YY>
    <SIN>000000</SIN>
    <Country>CA</Country>
  </ftc:YY>
</ftc:XX>
</code>```

this is the what i need to create. but when i create this, it shows empty namespace in the SIN and Country tag. i need to remove that. can anyone guide me?

this is the code which i use,

```<code>XNamespace ftc = "urn:v1";
XElement XX = new XElement(ftc + "XX",
  new XAttribute(XNamespace.Xmlns + "ftc", ftc.NamespaceName),
  new XAttribute("xmlns", ftc.NamespaceName),
  new XAttribute("version","1.1"),

  new XElement(ftc + "YY",
    XElement("SIN", "000000"),
    new XElement("Country", "CA")
  )
)
</code>```

with this, what i get is like this.

```<code><ftc:XX version="1.1"
  xmlns:ftc="urn:v1"
  xmlns="urn:v1">
  <ftc:YY>
    <SIN xmlns="">000000</SIN>
    <Country xmlns="">CA</Country>
  </ftc:YY>
</ftc:XX>
</code>```

but i need without this part.

xmlns=""

答:
SIN and Country belong to the urn:v1 namespace. Your document has a default namespace of urn:v1 so all elements without an explicit namespace prefix will belong to that namespace.

When you created those elements, they were in the empty namespace, so that extra namespace declaration needed to be generated.

```<code>XNamespace ftc = "urn:v1";
var doc = new XDocument(
    new XElement(ftc + "XX",
        new XAttribute("version", "1.1"),
        new XAttribute(XNamespace.Xmlns + "ftc", ftc),
        new XAttribute("xmlns", ftc),
        new XElement(ftc + "YY",
            new XElement(ftc + "SIN", "000000"),
            new XElement(ftc + "Country", "CA")
        )
    )
);
</code>```

```<code><XX version="1.1" xmlns:ftc="urn:v1" xmlns="urn:v1">
  <YY>
    <SIN>000000</SIN>
    <Country>CA</Country>
  </YY>
</XX>
</code>```

Note that since your explicit namespace ftc and the default namespace are equal, none of the prefixes will be generated as you expect. This isn't configurable on a per element level as far as I know.

Body:
<ftc:XX version="1.1"
  xmlns:ftc="urn:v1"
  xmlns="urn:v1">
  <ftc:YY>
    <SIN>000000</SIN>
    <Country>CA</Country>
  </ftc:YY>
</ftc:XX>

this is the what i need to create. but when i create this, it shows empty namespace in the SIN and Country tag. i need to remove that. can anyone guide me?

this is the code which i use,

XNamespace ftc = "urn:v1";
XElement XX = new XElement(ftc + "XX",
  new XAttribute(XNamespace.Xmlns + "ftc", ftc.NamespaceName),
  new XAttribute("xmlns", ftc.NamespaceName),
  new XAttribute("version","1.1"),

  new XElement(ftc + "YY",
    XElement("SIN", "000000"),
    new XElement("Country", "CA")
  )
)

with this, what i get is like this.

<ftc:XX version="1.1"
  xmlns:ftc="urn:v1"
  xmlns="urn:v1">
  <ftc:YY>
    <SIN xmlns="">000000</SIN>
    <Country xmlns="">CA</Country>
  </ftc:YY>
</ftc:XX>

but i need without this part.

xmlns=""

Body:
SIN and Country belong to the urn:v1 namespace. Your document has a default namespace of urn:v1 so all elements without an explicit namespace prefix will belong to that namespace.

When you created those elements, they were in the empty namespace, so that extra namespace declaration needed to be generated.

XNamespace ftc = "urn:v1";
var doc = new XDocument(
    new XElement(ftc + "XX",
        new XAttribute("version", "1.1"),
        new XAttribute(XNamespace.Xmlns + "ftc", ftc),
        new XAttribute("xmlns", ftc),
        new XElement(ftc + "YY",
            new XElement(ftc + "SIN", "000000"),
            new XElement(ftc + "Country", "CA")
        )
    )
);

<XX version="1.1" xmlns:ftc="urn:v1" xmlns="urn:v1">
  <YY>
    <SIN>000000</SIN>
    <Country>CA</Country>
  </YY>
</XX>

Note that since your explicit namespace ftc and the default namespace are equal, none of the prefixes will be generated as you expect. This isn't configurable on a per element level as far as I know.


问:
Comparing hashes and delete files with same hash in powershell not working
I am doing a script that identifies the hashes of all the files of a path (and recursively). This is alright.

My problem comes when, after I have identified which hashes are the same, I want to save them into an array so later I can delete these files that have the same Hash (if I want to), or just print the duplicate files. And I have been all afternoon and evening trying to figure out how to do it.
My code at the moment:

```<code>Write-Host "Write a path: "
$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | where { !$_.PSIsContainer }
$files | % {(Get-FileHash -Path $_.FullName -Algorithm MD5)}

#Creating an array for all the values and an array for the duplicates
$originals=@()
$copies=@()

 #grouping the hashes that are duplicated cmdlet Group-Object:
$Duplicates = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $Duplicates)
{
    Write-Host "These files share hash : $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
    $copies+=$Duplicates

}
</code>```

So the last part "$copies+=$Duplicates" does not work properly.

In the begining I was thinking of saving the first file in the "original" array. If the second one has the same hash, save that 2nd in the "copies" array. But I am not sure if I can do that in the 1st part of the script when getting the hashes.

After that, the second array would have the duplicates, so it would be easy to delete them from the computer.

答:
I think you should filter the items. I did it and I have a list with only one item of duplicate files and a list with all duplicated files.

You can use the SHA1 algorithm instead of MD5

SHA1 is much more faster than the MD5 algorithm

```<code>$fileHashes = Get-ChildItem -Path $myFilePath -Recurse -File | Get-Filehash -Algorithm SHA1
$duplicates = $fileHashes | Group hash | ? {$_.count -gt 1} | % {$_.Group}

$uniqueItems = @{}
$doubledItems = @()

foreach($item in $duplicates) {

  if(-not $uniqueItems.ContainsKey($item.Hash)){
    $uniqueItems.Add($item.Hash,$item)
  }else{
    $doubledItems += $item
  }
}

# all duplicates files
$doubledItems

# Remove the duplicate files
# $doubledItems | % {Remove-Item $_.path} -Verbose

# one of the duplicate files
$uniqueItems
</code>```

Set the seach root folder

```<code>$myFilePath = ''
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing a script that identifies the hashes of all the files of a path (and recursively). This is alright.

My problem comes when, after I have identified which hashes are the same, I want to save them into an array so later I can delete these files that have the same Hash (if I want to), or just print the duplicate files. And I have been all afternoon and evening trying to figure out how to do it.
My code at the moment:

Write-Host "Write a path: "
$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | where { !$_.PSIsContainer }
$files | % {(Get-FileHash -Path $_.FullName -Algorithm MD5)}

#Creating an array for all the values and an array for the duplicates
$originals=@()
$copies=@()

 #grouping the hashes that are duplicated cmdlet Group-Object:
$Duplicates = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $Duplicates)
{
    Write-Host "These files share hash : $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
    $copies+=$Duplicates

}

So the last part "$copies+=$Duplicates" does not work properly.

In the begining I was thinking of saving the first file in the "original" array. If the second one has the same hash, save that 2nd in the "copies" array. But I am not sure if I can do that in the 1st part of the script when getting the hashes.

After that, the second array would have the duplicates, so it would be easy to delete them from the computer.

Body:
I think you should filter the items. I did it and I have a list with only one item of duplicate files and a list with all duplicated files.

You can use the SHA1 algorithm instead of MD5

SHA1 is much more faster than the MD5 algorithm

$fileHashes = Get-ChildItem -Path $myFilePath -Recurse -File | Get-Filehash -Algorithm SHA1
$duplicates = $fileHashes | Group hash | ? {$_.count -gt 1} | % {$_.Group}

$uniqueItems = @{}
$doubledItems = @()

foreach($item in $duplicates) {

  if(-not $uniqueItems.ContainsKey($item.Hash)){
    $uniqueItems.Add($item.Hash,$item)
  }else{
    $doubledItems += $item
  }
}

# all duplicates files
$doubledItems

# Remove the duplicate files
# $doubledItems | % {Remove-Item $_.path} -Verbose

# one of the duplicate files
$uniqueItems

Set the seach root folder

$myFilePath = ''


问:
inserting an element to a binary search tree and find its level
I have written such the code below that ;

I have an array list which has 3 objects . each object has 2 fields 1)digit2)level

I want to insert each object to a binary search tree and after inserting each element to the tree ,I need to find its level.

Code:

```<code>private void greedyMethod(ArrayList<Element> array) {
    //it will print the objects in the array list.
    System.out.println(array.toString());

    array.get(0).setLevel(1);
    root = new DNode(array.get(0), null, null);
    for (int i = 1; i < array.size(); i++) {
        insert(array.get(i));
    }
}

private void insert(Element e) {
    root = makeBST(root, e);
}

private DNode makeBST(DNode root, Element e) {
    if (root == null) {
        root = new DNode(e, null, null);
        // This will print wrong objects.
        System.out.println(root.getElement().toString());
    } else if (e.getDigit() < root.getElement().getDigit()) {
        e.setDigit(root.getElement().getLevel() + 1);
        root.prev = makeBST(root.prev, e);
    } else if (e.getDigit() > root.getElement().getDigit()) {
        e.setLevel(root.getElement().getLevel() + 1);
        root.next = makeBST(root.next, e);
    }

    System.out.println(averageAccessTime);
    return root;
}
</code>```

my array list is :

```<code>[digit :25   level:0, digit :27   level:0, digit :26   level:0]
</code>```

but as I mentioned in the code above,the line :
    System.out.println(root.getElement().toString()); prints wrong objects (I mean wrong digit or wrong level!!!!)-->

```<code>digit :27  probability: 0.2 level:2
digit :3  probability: 0.1 level:2
</code>```

please help me to find my mistake ,thanks

答:
This is wrong:</p>

```<code>e.setDigit(root.getElement().getLevel() + 1);
</code>```

Body:
I have written such the code below that ;

I have an array list which has 3 objects . each object has 2 fields 1)digit2)level

I want to insert each object to a binary search tree and after inserting each element to the tree ,I need to find its level.

Code:

private void greedyMethod(ArrayList<Element> array) {
    //it will print the objects in the array list.
    System.out.println(array.toString());

    array.get(0).setLevel(1);
    root = new DNode(array.get(0), null, null);
    for (int i = 1; i < array.size(); i++) {
        insert(array.get(i));
    }
}

private void insert(Element e) {
    root = makeBST(root, e);
}

private DNode makeBST(DNode root, Element e) {
    if (root == null) {
        root = new DNode(e, null, null);
        // This will print wrong objects.
        System.out.println(root.getElement().toString());
    } else if (e.getDigit() < root.getElement().getDigit()) {
        e.setDigit(root.getElement().getLevel() + 1);
        root.prev = makeBST(root.prev, e);
    } else if (e.getDigit() > root.getElement().getDigit()) {
        e.setLevel(root.getElement().getLevel() + 1);
        root.next = makeBST(root.next, e);
    }

    System.out.println(averageAccessTime);
    return root;
}

my array list is :

[digit :25   level:0, digit :27   level:0, digit :26   level:0]

but as I mentioned in the code above,the line :
    System.out.println(root.getElement().toString()); prints wrong objects (I mean wrong digit or wrong level!!!!)-->

digit :27  probability: 0.2 level:2
digit :3  probability: 0.1 level:2

please help me to find my mistake ,thanks

Body:
This is wrong:

e.setDigit(root.getElement().getLevel() + 1);


问:
Java mail error in webllogic server
I am trying to send mail(outlook) through weblogic 12c using java mail api
and i am getting this error so please help with this....

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [BMXPR01CA0016.INDPRD01.PROD.OUTLOOK.COM]

```<code>at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2203)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1694)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1194)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at roomBooking.sendMail.(sendMail.java:89)
at jsp_servlet.__booking._jspService(__booking.java:163)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:35)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:286)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:260)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:137)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:350)
at weblogic.servlet.internal.ServletStubImpl.onAddToMapException(ServletStubImpl.java:489)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:376)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:141)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:649)
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:124)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:232)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:94)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:224)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3654)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3620)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2423)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2280)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2258)
at weblogic.servlet.internal.ServletRequestImpl.runInternal(ServletRequestImpl.java:1626)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1586)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:270)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
</code>```

答: You probably need to authenticate to your mail server.</p>

Title: Java mail error in webllogic server

Body:
I am trying to send mail(outlook) through weblogic 12c using java mail api
and i am getting this error so please help with this....

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [BMXPR01CA0016.INDPRD01.PROD.OUTLOOK.COM]

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2203)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1694)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1194)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at roomBooking.sendMail.(sendMail.java:89)
at jsp_servlet.__booking._jspService(__booking.java:163)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:35)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:286)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:260)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:137)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:350)
at weblogic.servlet.internal.ServletStubImpl.onAddToMapException(ServletStubImpl.java:489)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:376)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:141)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:649)
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:124)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:232)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:94)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:224)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:78)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3654)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3620)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2423)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2280)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2258)
at weblogic.servlet.internal.ServletRequestImpl.runInternal(ServletRequestImpl.java:1626)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1586)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:270)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)


问:
custom error page for virto commerce storefront
in customErrors for virto commerce storefront, exist defaultRedirect="~/ServerMaintenance.aspx".
 so in statusCode="500" show ServerMaintenance.
but in statusCode="500" i need to show C500.aspx
I change webconfig to

```<code><customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/ServerMaintenance.aspx">
<error statusCode="500" redirect="~/Status/C500.aspx"/>
</customErrors>
</code>```

But in statusCode="500" do not show C500.aspx, and show And shows  page with following error :

```<code>Server Error in '/' Application.

Runtime Error

Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
</code>```

Where is my mistake ?

答:
The message on your response says there is an error on your custom error page, that's why you can't see it. Try to switch off custom errors

```<code><system.web>
   <customErrors mode="Off"...
</code>```

and make a request to C500.aspx directly - you should see what's wrong with it.

Body:
in customErrors for virto commerce storefront, exist defaultRedirect="~/ServerMaintenance.aspx".
 so in statusCode="500" show ServerMaintenance.
but in statusCode="500" i need to show C500.aspx
I change webconfig to

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/ServerMaintenance.aspx">
<error statusCode="500" redirect="~/Status/C500.aspx"/>
</customErrors>

But in statusCode="500" do not show C500.aspx, and show And shows  page with following error :

Server Error in '/' Application.

Runtime Error

Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

Where is my mistake ?

Body:
The message on your response says there is an error on your custom error page, that's why you can't see it. Try to switch off custom errors

<system.web>
   <customErrors mode="Off"...

and make a request to C500.aspx directly - you should see what's wrong with it.


问:
Deleting String Pointers Memory in Struct
With the struct declaration:

```<code>struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}
</code>```

And then I built files like so:

```<code>buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}
</code>```

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.

答: you shuld used refrence in buildFiles(int argc, char *argv[], Dat &my) like this, otherwise  it will copy a my object from main function, but there is no copy constructor in Dat,so it's not safe, the destructor will be called twice. ps:you should jugge if pointer is NULL before delete it and set ad nullptr atfer.</p>

Body:
With the struct declaration:

struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}

And then I built files like so:

buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.


问:
How to get last inserted date of a certain record using php and mysql?
Below I have a working code:

```<code>$p_code = "R-BIGANTE-010";
$date = date("m/d/Y");
$statement=$pdo->prepare("SELECT * FROM items WHERE p_code=? AND date=?");
$statement->execute(array($p_code, $date));
</code>```

And what it does is to get a certain item with p_code and date equal to TODAY. What I want to know is how can I query a specific item with the last latest update?

For example, in my items table I have

As you can see, I have two p_code with value "R-BIGANTE-010". Let's say the current date today is 05/06/2017 and I want to get the highlighted one because the date field is much latest than the other value.

How can I query it? By the way the date value is in varchar since the code is old and I will clean everything later.

Any help would be much appreciated.

答:
```<code> Try this:
     $p_code = "R-BIGANTE-010";
     $date = date("m/d/Y");
     $statement=$pdo->prepare("SELECT * FROM items WHERE p_code=? AND date=?");
     $statement->execute(array($p_code, $date));
     $id = $statement->lastInsertId();

If you want to do it with SQL instead of the PDO API query:

    $stmt = $pdo->query("SELECT LAST_INSERT_ID()");
    $lastId = $stmt->fetchColumn();
</code>```

Body:
Below I have a working code:

$p_code = "R-BIGANTE-010";
$date = date("m/d/Y");
$statement=$pdo->prepare("SELECT * FROM items WHERE p_code=? AND date=?");
$statement->execute(array($p_code, $date));

And what it does is to get a certain item with p_code and date equal to TODAY. What I want to know is how can I query a specific item with the last latest update?

For example, in my items table I have

As you can see, I have two p_code with value "R-BIGANTE-010". Let's say the current date today is 05/06/2017 and I want to get the highlighted one because the date field is much latest than the other value.

How can I query it? By the way the date value is in varchar since the code is old and I will clean everything later.

Any help would be much appreciated.


问:
replace values of keys in json1 from Json2
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code> one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.
</code>```

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

```<code> second JSON --> for ex: {"blog_heading":"def"}
</code>```

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code>  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.
</code>```

So i am trying as below,

```<code>$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);
</code>```

id5 data is : $id5

```<code>  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================
</code>```

Log of $id :

```<code>stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )
</code>```

Please suggest me how can i achieve this... Anything i am doing wrong here

答:
```<code><?php
$json1='{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$json2='{"blog_heading":"def"}';

$json1=json_decode($json1);
$json2=json_decode($json2);
foreach ($json1 as $key => $value) {
    if($json2->$key){
        $json1->$key=$json2->$key;
    }
}

$json1=json_encode($json1);
$json2=json_encode($json2);
</code>```

Body:
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

 one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

 second JSON --> for ex: {"blog_heading":"def"}

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.

So i am trying as below,

$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);

id5 data is : $id5

  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================

Log of $id :

stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )

Please suggest me how can i achieve this... Anything i am doing wrong here


问:
Laravel5.3 - Create certain number of related models - when a model is created
I have two models:

Model1 with relationship:

```<code>public function model2()
{
    return $this->hasMany('App\Model2');
}
</code>```

Model2 with relationship:

```<code>public function model1()
{
    return $this->belongsTo('App\Model1');
}
</code>```

I need to create a certain number (4) of Model2's with different kind of settings(so, not random Models2, just related to Model1), when the Model1 is created. It is important to be able to access the Model1's parameters, when creating the Model2's.
Is there any elegant/automatic way?
My first idea was to create a method for the Model1, but I suspect there is a more elegant way.

答:
You can use created event for the first model.

https://laravel.com/docs/5.3/eloquent#events

Events allow you to easily execute code each time a specific model class is saved or updated in the database.

Body:
I have two models:

Model1 with relationship:

public function model2()
{
    return $this->hasMany('App\Model2');
}

Model2 with relationship:

public function model1()
{
    return $this->belongsTo('App\Model1');
}

I need to create a certain number (4) of Model2's with different kind of settings(so, not random Models2, just related to Model1), when the Model1 is created. It is important to be able to access the Model1's parameters, when creating the Model2's.
Is there any elegant/automatic way?
My first idea was to create a method for the Model1, but I suspect there is a more elegant way.


问:
Wanted: pdfprinter without interaction
I need to export a asp.net document to a pdf-file. The design of the page is final and printing via pdfprinter works.
Using itextsharp or other tools, which require redesigning the page are not an option.
Opening the page in WebBrowserControl and printing to pdf works fine, but not without user interaction.

Do you know a free pdfprinter, which requires no interaction from the user (no popups, no "enter filename"-dialogs, just print instantaneous like in the old days)?
Options like target pdf name and path should be configurable via config file or little tool, but not at printtime.

Since the printing will take place on a server the "no user interaction"-requirement is very important.

Thx

Frank

答:
Yes it is possible I have crearted on console app which print any document without user Interaction and you can also set the Printer name here.

below is the code for my Github link:-

https://github.com/yadavparveen/Print-silently

I know I am late but it will save other person Time.

Title: Wanted: pdfprinter without interaction


问:
Left join same table twice but one column is repeat
The main table want to join two time with the reffrence table twice with the same column.
The main table column is insert with integer and need to join with the refference table to get the character back to show back for user.
it show none of records by the sql below, why?

main table BD_BRAND

```<code>Sports_BR  Leather_BR
   2          1
</code>```

Reffrence table BD_REF

```<code>ID   NME         REF_TYPE
1    NIKE      Sports_Brand
2    ADIDAS    Sports_Brand
3    PUMA      Sports_Brand
1    CLACKS    Leather_Brand
2    LOTTUSSE  Leather_Brand
3    CHEANEY   Leather_Brand

   SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
    FROM BD_BRAND A
    LEFT JOIN BD_REF B on B.ID =  A.Sports_BR
    LEFT JOIN BD_REF C on C.ID =  A.Leather_BR
</code>```

The Result i want as below:

```<code>Sports_BR  Leather_BR
 ADIDAS     CLACKS
</code>```

答:
I think you're looking for:

```<code>SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
FROM BD_BRAND A
LEFT JOIN BD_REF B on B.ID =  A.Sports_BR and B.REF_TYPE = 'Sports_Brand'
LEFT JOIN BD_REF C on C.ID =  A.Leather_BR and B.REF_TYPE = 'Leather_Brand'
</code>```

Your ID's are present multiple times due to the different reference types, so you need to specify which ID to grab by the reference type.

Body:
The main table want to join two time with the reffrence table twice with the same column.
The main table column is insert with integer and need to join with the refference table to get the character back to show back for user.
it show none of records by the sql below, why?

main table BD_BRAND

Sports_BR  Leather_BR
   2          1

Reffrence table BD_REF

ID   NME         REF_TYPE
1    NIKE      Sports_Brand
2    ADIDAS    Sports_Brand
3    PUMA      Sports_Brand
1    CLACKS    Leather_Brand
2    LOTTUSSE  Leather_Brand
3    CHEANEY   Leather_Brand

   SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
    FROM BD_BRAND A
    LEFT JOIN BD_REF B on B.ID =  A.Sports_BR
    LEFT JOIN BD_REF C on C.ID =  A.Leather_BR

The Result i want as below:

Sports_BR  Leather_BR
 ADIDAS     CLACKS

Body:
I think you're looking for:

SELECT B.NME AS Sports_BR, C.NME AS Leather_BR
FROM BD_BRAND A
LEFT JOIN BD_REF B on B.ID =  A.Sports_BR and B.REF_TYPE = 'Sports_Brand'
LEFT JOIN BD_REF C on C.ID =  A.Leather_BR and B.REF_TYPE = 'Leather_Brand'

Your ID's are present multiple times due to the different reference types, so you need to specify which ID to grab by the reference type.


问:
JS : Show Pop up box position exactly above tr in table
I have a table with certain TRs.
What I want is , when I click on any tr then a popup is opened. but I can't manipulate its position to the exact above tr on which it is clicked.

var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("tr_1");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close_div")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    margin-top: 10%
}

.container .m-t {
    margin-top: 15px
}

.container .m-t-xs {
    margin-top: 5px
}

.container .m-t-sm {
    margin-top: 10px
}

.container .cursor_pointer {
    cursor: pointer
}

.container .v-middle {
    vertical-align: middle
}

.container .table_div {
    border: thin red solid
}

.container .modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: #000;
    background-color: rgba(0, 0, 0, 0.4)
}

.container .modal-content {
    background-color: #fefefe;
    margin: 0 30px;
    padding: 20px;
    border: 1px solid #888;
    width: 100%;
}

.container .modal-content .form-group label {
    font-size: 12px;
    font-weight: 300
}

.container .modal-content:after {
    content: '';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 10px #fff;
    border-left: solid 10px transparent;
    border-right: solid 10px transparent
}

.container .close_div {
    width: 20px;
    height: 20px;
    position: absolute;
    border-radius: 50px;
    border: thin white solid;
    top: -7px;
    right: -7px;
    text-align: center;
    background: #000000
}

.container .close_div span {
    color: white;
    position: absolute;
    left: 3px;
    top: -1px
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="CSS/style.css" type="text/css" rel="stylesheet">

                All
                Name
                Department

                    <input type="checkbox" name="">

                    Bradley Stephen

                    Sales

                    <input type="checkbox" name="">

                    John Doe

                    Marketing

      ✕

              First Name
              <input type="text" name="first_name" value="" class="form-control">

              Last Name
              <input type="text" name="last_name" value="" class="form-control">

            <button type="button" name="button" class="m-t-xs">Update</button>

```

When I click on any of the tr , then a popup box should be above the respective tr with pointing the tr using bottom triangle.

I have searched a lot , but it could not work for me.
Any help would be great.
Thank You.

答:
Instead of modal, use bootstrap popover. Along with the explained content in the link, in the click function of tr, pass placement parameters to popover method like below:

```<code>$('tr').popover({
         content: //Your Html with textbox and button
         , container: 'body'
         , placement: 'auto top'
         , html: true
      });
$(selector).popover('show');
</code>```

Update: Complete working html is given below, removed the entire bootstrap modal html and changed the placement to auto top. With 'AUTO' if there is no space above, the popover will be shown below.

```<code><!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
      crossorigin="anonymous">
   <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
      crossorigin="anonymous"></script>
   <title>Bootstrap Popover</title>
   <style>
      .container .table_div {
         border: thin red solid
      }

      header {
         padding-top: 160px;
      }
   </style>
   <script>
      $(document).ready(function () {
         var html = '<div class="form-group"><div class="row"><div class="col-lg-8 col-md-9 col-sm-9 col-xs-9"><label>First Name</label><input type="text" name="first_name" value="" class="form-control"></div></div><div class="row m-t"><div class="col-lg-8 col-md-9 col-sm-9 col-xs-9"><label>Last Name</label><input type="text" name="last_name" value="" class="form-control"></div><div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"><label for=""></label><button type="button" name="button" class="m-t-xs">Update</button></div></div></div>'
         $('tbody tr').attr({
            "data-toggle": 'popover'
            , "data-placement": 'auto top'
            , "data-trigger": 'click'
            , "data-html": 'true'
            , "title": function () {
               return $(this).children('td:nth-of-type(2)').html();
            }
            , "data-content": html
            , "data-container": 'body'
         });

         $('tbody tr').popover();
         $('tbody tr').on('show.bs.popover', function () {
            $('tbody tr').not(this).popover('hide');
         });
      });
   </script>
</head>

<body>
   <header></header>
   <div class="container">
      <div class="row">
         <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="table_div table-responsive">
               <table class="table">
                  <thead>
                     <th>All</th>
                     <th>Name</th>
                     <th>Department</th>
                  </thead>
                  <tbody>
                     <tr class="cursor_pointer" id="tr_1">
                        <td>
                           <input type="checkbox" name="">
                        </td>
                        <td>
                           Bradley Stephen
                        </td>
                        <td>
                           Sales
                        </td>
                     </tr>

                     <tr class="cursor_pointer">
                        <td>
                           <input type="checkbox" name="">
                        </td>
                        <td>
                           John Doe
                        </td>
                        <td>
                           Marketing
                        </td>
                     </tr>
                  </tbody>
               </table>
            </div>
         </div>
      </div>
   </div>
</body>

</html>
</code>```

Body:
I have a table with certain TRs.
What I want is , when I click on any tr then a popup is opened. but I can't manipulate its position to the exact above tr on which it is clicked.

var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("tr_1");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close_div")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

.container {
    margin-top: 10%
}

.container .m-t {
    margin-top: 15px
}

.container .m-t-xs {
    margin-top: 5px
}

.container .m-t-sm {
    margin-top: 10px
}

.container .cursor_pointer {
    cursor: pointer
}

.container .v-middle {
    vertical-align: middle
}

.container .table_div {
    border: thin red solid
}

.container .modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: #000;
    background-color: rgba(0, 0, 0, 0.4)
}

.container .modal-content {
    background-color: #fefefe;
    margin: 0 30px;
    padding: 20px;
    border: 1px solid #888;
    width: 100%;
}

.container .modal-content .form-group label {
    font-size: 12px;
    font-weight: 300
}

.container .modal-content:after {
    content: '';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 10px #fff;
    border-left: solid 10px transparent;
    border-right: solid 10px transparent
}

.container .close_div {
    width: 20px;
    height: 20px;
    position: absolute;
    border-radius: 50px;
    border: thin white solid;
    top: -7px;
    right: -7px;
    text-align: center;
    background: #000000
}

.container .close_div span {
    color: white;
    position: absolute;
    left: 3px;
    top: -1px
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="CSS/style.css" type="text/css" rel="stylesheet">

                All
                Name
                Department

                    <input type="checkbox" name="">

                    Bradley Stephen

                    Sales

                    <input type="checkbox" name="">

                    John Doe

                    Marketing

      ✕

              First Name
              <input type="text" name="first_name" value="" class="form-control">

              Last Name
              <input type="text" name="last_name" value="" class="form-control">

            <button type="button" name="button" class="m-t-xs">Update</button>

When I click on any of the tr , then a popup box should be above the respective tr with pointing the tr using bottom triangle.

I have searched a lot , but it could not work for me.
Any help would be great.
Thank You.

Body:
Instead of modal, use bootstrap popover. Along with the explained content in the link, in the click function of tr, pass placement parameters to popover method like below:

$('tr').popover({
         content: //Your Html with textbox and button
         , container: 'body'
         , placement: 'auto top'
         , html: true
      });
$(selector).popover('show');

Update: Complete working html is given below, removed the entire bootstrap modal html and changed the placement to auto top. With 'AUTO' if there is no space above, the popover will be shown below.

<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
      crossorigin="anonymous">
   <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
      crossorigin="anonymous"></script>
   <title>Bootstrap Popover</title>
   <style>
      .container .table_div {
         border: thin red solid
      }

      header {
         padding-top: 160px;
      }
   </style>
   <script>
      $(document).ready(function () {
         var html = '<div class="form-group"><div class="row"><div class="col-lg-8 col-md-9 col-sm-9 col-xs-9"><label>First Name</label><input type="text" name="first_name" value="" class="form-control"></div></div><div class="row m-t"><div class="col-lg-8 col-md-9 col-sm-9 col-xs-9"><label>Last Name</label><input type="text" name="last_name" value="" class="form-control"></div><div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"><label for=""></label><button type="button" name="button" class="m-t-xs">Update</button></div></div></div>'
         $('tbody tr').attr({
            "data-toggle": 'popover'
            , "data-placement": 'auto top'
            , "data-trigger": 'click'
            , "data-html": 'true'
            , "title": function () {
               return $(this).children('td:nth-of-type(2)').html();
            }
            , "data-content": html
            , "data-container": 'body'
         });

         $('tbody tr').popover();
         $('tbody tr').on('show.bs.popover', function () {
            $('tbody tr').not(this).popover('hide');
         });
      });
   </script>
</head>

<body>
   <header></header>
   <div class="container">
      <div class="row">
         <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="table_div table-responsive">
               <table class="table">
                  <thead>
                     <th>All</th>
                     <th>Name</th>
                     <th>Department</th>
                  </thead>
                  <tbody>
                     <tr class="cursor_pointer" id="tr_1">
                        <td>
                           <input type="checkbox" name="">
                        </td>
                        <td>
                           Bradley Stephen
                        </td>
                        <td>
                           Sales
                        </td>
                     </tr>

                     <tr class="cursor_pointer">
                        <td>
                           <input type="checkbox" name="">
                        </td>
                        <td>
                           John Doe
                        </td>
                        <td>
                           Marketing
                        </td>
                     </tr>
                  </tbody>
               </table>
            </div>
         </div>
      </div>
   </div>
</body>

</html>


答:
If your date is in m/d/y format, you'll have to sort differently by converting the varchar dates to real dates using the STR_TO_DATE() function.

```<code>SELECT * from tablename
WHERE p_code = ?
ORDER BY STR_TO_DATE(date, '%m/%d/%Y') DESC
LIMIT 1
</code>```

You should really use DATE data type for dates, not VARCHAR.

Title: How to get last inserted date of a certain record using php and mysql?

Body:
If your date is in m/d/y format, you'll have to sort differently by converting the varchar dates to real dates using the STR_TO_DATE() function.

SELECT * from tablename
WHERE p_code = ?
ORDER BY STR_TO_DATE(date, '%m/%d/%Y') DESC
LIMIT 1

You should really use DATE data type for dates, not VARCHAR.