问:
Android Google Maps API v2 - how to change marker icon
I am trying to change marker icon.
I get the image from one server directory.

When I put break point every time the "bit" result is null. And when I run the app I get java.lang.NullPointerException.

```<code>File file = new File("J:\\!!! DOCUMENTS\\!Outsourcing\\AppStore\\Benzinostancii\\Petrol\\logo.png");

Bitmap bit = BitmapFactory.decodeFile(String.valueOf(file));

double Dlat = lat.get(index);
double Dlon = lon.get(index);
String info = Arrayinfo.get(index);
String name = Arrayname.get(index);

LatLng coordinate = new LatLng(Dlat, Dlon);
map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromBitmap(bit))
    .position(coordinate)
    .title(info)
).setSnippet(name);
</code>```

答:
It's very simple :

```<code>new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.icon))
</code>```

In case you want the icon from a bitmap

```<code>new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap));
</code>```

Body:
I am trying to change marker icon.
I get the image from one server directory.

When I put break point every time the "bit" result is null. And when I run the app I get java.lang.NullPointerException.

File file = new File("J:\\!!! DOCUMENTS\\!Outsourcing\\AppStore\\Benzinostancii\\Petrol\\logo.png");

Bitmap bit = BitmapFactory.decodeFile(String.valueOf(file));

double Dlat = lat.get(index);
double Dlon = lon.get(index);
String info = Arrayinfo.get(index);
String name = Arrayname.get(index);

LatLng coordinate = new LatLng(Dlat, Dlon);
map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromBitmap(bit))
    .position(coordinate)
    .title(info)
).setSnippet(name);

Body:
It's very simple :

new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.icon))

In case you want the icon from a bitmap

new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap));


来源: stackexchange

问:
Why are all contexts executed when non specified on update?
I'm using Liquibase 3.3.5 to update my database. Having contexts is a nice way to only execute specific parts of the changelog. But I don't understand, why ALL changesets are executed, when no context is provided on update. Consider the following example:

changeset A: context=test

changeset B: no context

changeset C: context=prod

So

executing update with context=test, will execute changeset A+B.

executing update with context=prod, will execute changeset B+C.

executing update with no context, will execute changeset A+B+C.

For me, this doesn't make sense at all :).

I would expect, that only changeset B will be executed, since it doesn't define a specific context.

In the Liquibase contexts example: http://www.liquibase.org/documentation/contexts.html ("Using Contexts for Test Data") they say, that one should mark the changesets for testing with "test", and executing them with giving the context "test" to apply testdata. Fine - make sense. But

"When it comes time to migrate your production database, don’t include the “test" context, and your test data not be included. "

So, if I wouldn't specify "test" context when executing production update, it would execute the "test" changesets as well, since I didn't specify a context at all.

Again, I would expect that leaving out test on update execution, would only perform the regular changesets without the test changesets.

Or I'm missing something here :)?

答:
I will add solution from me (from my perspective the default Liquibase behavior is not intuitive). In our project to deal with the "problem" we configured liquibase context in this way:

```<code>liquibase.setChangeLog("classpath*:liquibase/master.xml");
contexts = StringUtils.isBlank(contexts) ? "none" : contexts;
liquibase.setContexts(contexts);
</code>```

It cause that liquibase will run all change-sets with context 'none' and all default change-sets (change-sets without context) - yes this is how it works.

So select the name which nobody on your team won't use ('none' in our case) as context name and then run the liquibase by default with that context (take a look at example). With that approach you will run the change-sets without any context what I assume should be default approach!

ContentLicense: CC BY-SA 3.0

Body:
I will add solution from me (from my perspective the default Liquibase behavior is not intuitive). In our project to deal with the "problem" we configured liquibase context in this way:

liquibase.setChangeLog("classpath*:liquibase/master.xml");
contexts = StringUtils.isBlank(contexts) ? "none" : contexts;
liquibase.setContexts(contexts);

It cause that liquibase will run all change-sets with context 'none' and all default change-sets (change-sets without context) - yes this is how it works.

So select the name which nobody on your team won't use ('none' in our case) as context name and then run the liquibase by default with that context (take a look at example). With that approach you will run the change-sets without any context what I assume should be default approach!


问:
Not able to select node for installation using Cloudera Manager
I am trying to install CDH using cloudera manager 5.9. When it prompts for the hosts ip's it is able to scan that node, but afterwards the "Continue" button is disabled, please see the screen shot below:

Are there any reasons why the "Continue" button isn't enabled?

FYI: I am using Virtualbox and my VM is based on CentOS. I am able to reach to VM's IP address and from VM i am able to ping the Host IP address. (I have used Bridge network, so it is working fine).

答:
You already installed cloudera agent on this node (look at the column "managed", value is yes).
So, to use it, you must have a "already managed" tab in the higher part of your screen. If you click it you could choose your node as a host for your cluster.

If you're trying to complete a previously aborted installation, first click to the Cloudera logo of this page to go to the dashboard, and delete the cluster (Action -> Delete). Next connect to your host hadoopcluster and execute as root yum remove cloudera-manager-agent.

Rerun the wizard from your Cloudera Manager and you'll be able to select your hadoopcluster machine as a new host for your cluster.


问:
division in php
```<code> $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;
</code>```

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?

答:
If youre doing number opertations then use numeric functions and varibles not strings...</p>

```<code>$voltage = (float) '0.4000'; //cast as a float, assuming this comes from user input as string
$newValue = $volatge*1000;
echo 'newvalue'.$newValue;

$newValue = $newValue/0.0125;
echo 'newvalue'.$newValue;
</code>```

ContentLicense: CC BY-SA 2.5

Title: division in php

Body:
 $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?

Body:
If youre doing number opertations then use numeric functions and varibles not strings...

$voltage = (float) '0.4000'; //cast as a float, assuming this comes from user input as string
$newValue = $volatge*1000;
echo 'newvalue'.$newValue;

$newValue = $newValue/0.0125;
echo 'newvalue'.$newValue;


问:
How to pass column name in ggplot facet_wrap in a function
How to pass column name of a data frame in ggplot facet_wrap or fill/colour in a function? I looked up lazyeval but didn't figure out a way.

```<code>x="class"
ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x)
</code>```

In this example, why didn't the points get coloured by x?

答:
I used an example from ggplot2::facet_wrap. So, you can easily replace ~class with x containing a character or a formulae. Example :

```<code>library(ggplot2)
x="class"#or ~class
ggplot(mpg, aes(displ, hwy)) +
        geom_point() +
        facet_wrap(x)
</code>```

Body:
How to pass column name of a data frame in ggplot facet_wrap or fill/colour in a function? I looked up lazyeval but didn't figure out a way.

x="class"
ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x)

In this example, why didn't the points get coloured by x?

Body:
I used an example from ggplot2::facet_wrap. So, you can easily replace ~class with x containing a character or a formulae. Example :

library(ggplot2)
x="class"#or ~class
ggplot(mpg, aes(displ, hwy)) +
        geom_point() +
        facet_wrap(x)


问:
DeepLinkDispatch - incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>
Following the tutorial on the github page I have:

added to my project's parent build.gradle:

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' <---

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
</code>```

added to my app's build.gradle:

```<code>apply plugin: 'com.neenbedankt.android-apt'

...

compile 'com.airbnb:deeplinkdispatch:3.0.0'
apt 'com.airbnb:deeplinkdispatch-processor:3.0.0'
</code>```

Created a module class and annotated it:

```<code>@DeepLinkModule
public class AppDeepLinkModule
{

}
</code>```

Now when I try to build, it displays the above error message:

```<code>Error:(12, 82) error: incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>
</code>```

It then points me towards this class which is autogenerated:

```<code>public final class AppDeepLinkModuleLoader implements Parser {
  public static final List<DeepLinkEntry> REGISTRY = Collections.unmodifiableList(Arrays.asList(
  )); <-- this line here

  @Override
  public DeepLinkEntry parseUri(String uri) {
    for (DeepLinkEntry entry : REGISTRY) {
      if (entry.matches(uri)) {
        return entry;
      }
    }
    return null;
  }
}
</code>```

I've referred to their sample app and mine seems identical. Here is a link to their class which does the same thing.

I completed further steps until I need to use the autogenerated class in case this was the issue but this didn't fix things either. AndroidManifest.xml:

```<code><activity
        android:name=".deeplink.DeepLinkActivity"
        android:theme="@android:style/Theme.NoDisplay">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:host="slackwebsocket"
                android:scheme="http"/>
        </intent-filter>
    </activity>
</code>```

DeepLinkActivity:

```<code>@DeepLinkHandler({AppDeepLinkModule.class})
public class DeepLinkActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
}
</code>```

How do I fix this?

答:
This problem occurs when the application doesn't specify any deep link targets. In this case the code generator creates an empty list, which raises the compiler error.

You can syntactically fix this issue by annotating a class, e.g. an Activity, with @DeepLink:

@DeepLink("scheme://authority")
public class TargetActivity extends Activity {
}
```

The code generator will add an element to that list.

Body:
Following the tutorial on the github page I have:

added to my project's parent build.gradle:

dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' <---

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

added to my app's build.gradle:

apply plugin: 'com.neenbedankt.android-apt'

...

compile 'com.airbnb:deeplinkdispatch:3.0.0'
apt 'com.airbnb:deeplinkdispatch-processor:3.0.0'

Created a module class and annotated it:

@DeepLinkModule
public class AppDeepLinkModule
{

}

Now when I try to build, it displays the above error message:

Error:(12, 82) error: incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>

It then points me towards this class which is autogenerated:

public final class AppDeepLinkModuleLoader implements Parser {
  public static final List<DeepLinkEntry> REGISTRY = Collections.unmodifiableList(Arrays.asList(
  )); <-- this line here

  @Override
  public DeepLinkEntry parseUri(String uri) {
    for (DeepLinkEntry entry : REGISTRY) {
      if (entry.matches(uri)) {
        return entry;
      }
    }
    return null;
  }
}

I've referred to their sample app and mine seems identical. Here is a link to their class which does the same thing.

I completed further steps until I need to use the autogenerated class in case this was the issue but this didn't fix things either. AndroidManifest.xml:

<activity
        android:name=".deeplink.DeepLinkActivity"
        android:theme="@android:style/Theme.NoDisplay">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:host="slackwebsocket"
                android:scheme="http"/>
        </intent-filter>
    </activity>

DeepLinkActivity:

@DeepLinkHandler({AppDeepLinkModule.class})
public class DeepLinkActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
}

How do I fix this?

Body:
This problem occurs when the application doesn't specify any deep link targets. In this case the code generator creates an empty list, which raises the compiler error.

You can syntactically fix this issue by annotating a class, e.g. an Activity, with @DeepLink:

@DeepLink("scheme://authority")
public class TargetActivity extends Activity {
}

The code generator will add an element to that list.


问:
Zend_Dom gives you a DOMElement... how do I use it?
I'm trying to use Zend_Dom for some very light screen scraping (I want to grab a headline, some body text and a link from a small block of news items on my website) and I'm not sure how to handle the DOMElement that it gives me.

In the manual for Zend_Dom the code says:

```<code>foreach ($results as $result) {
    // $result is a DOMElement
}
</code>```

How do I make use of this DOMElement?

A detailed example (looking for the anchor elements on Google):

```<code>$url='http://google.com/';
$client = new Zend_Http_Client($url);
$response = $client->request();
$html = $response->getBody();
$dom = new Zend_Dom_Query($html);
$results = $dom->query('a');
foreach($results as $r){
     Zend_Debug::dump($r);
}
</code>```

This gives me:

```<code>object(DOMElement)#81 (0) {
}
object(DOMElement)#82 (0) {
}
object(DOMElement)#83 (0) {
}
... etc, etc...
</code>```

What I find confusing is that this looks like each element contains nothing (0)! This isn't the case but that is my first impression. So I poke around online and find I can add nodeValue to get something out of this:

```<code>Zend_Debug::dump($r->nodeValue);
</code>```

which gives me:

```<code>string(6) "Images"
string(6) "Videos"
string(4) "Maps"
...etc, etc...
</code>```

But where I run into trouble is getting specific elements and their contents.

For instance given this html:

```<code>  <div class="newsBlurb">
   <span class="newsDate">Mon, 11 October 2010</span>
   <h3 class="newsHeadline"><a href="http://foo.com/1/2/">Some text</a></h3>
   <a class="newsMore" href="http://foo.com/1/2/">More</a>
  </div>
  <div class="hr"></div>
  <div class="newsBlurb">
   <span class="newsDate">Mon, 16 August 2010</span>
   <h3 class="newsHeadline"><a href="http://bar.com/pants.html">Stuff is here</a></h3>
   <a class="newsMore" href="http://bar.com/pants.html">More</a>
  </div>
</code>```

I can grab the text from each newsBlurb, using the technique I use in the Google example, but cannot get each element by itself. I want to get the date and stick it somewhere, get the headline text and stick it somewhere and get the link to use. But all I get is the actual text in the div.

How do I get what I want from this?

EDIT
Here is another example that does not work as I expect. Any ideas why?

```<code>$url = 'http://php.net/manual/en/class.domelement.php';
$client = new Zend_Http_Client($url);
$response = $client->request();
$html = $response->getBody();
$dom = new Zend_Dom_Query($html);
$newsBlurbNode = $dom->query('div.note');
Zend_Debug::dump($newsBlurbNode);
</code>```

this gives me:

```<code>object(Zend_Dom_Query_Result)#867 (7) {
  ["_count":protected] => NULL
  ["_cssQuery":protected] => string(8) "div.note"
  ["_document":protected] => object(DOMDocument)#79 (0) {
  }
  ["_nodeList":protected] => object(DOMNodeList)#864 (0) {
  }
  ["_position":protected] => int(0)
  ["_xpath":protected] => NULL
  ["_xpathQuery":protected] => string(33) "//div[contains(@class, ' note ')]"
}
</code>```

Trying to get anything out of this I used:

```<code>$children = $newsBlurbNode->childNodes;
     foreach ($children as $child) {
       }
</code>```

Which results in an error because the foreach loop has nothing in it. Ack! What am I not getting?

答:
You can use something like this to get access to the individual nodes:

```<code>$children = $newsBlurbNode->childNodes;
foreach ($children as $child) {
    //do something with individual nodes
}
</code>```

Otherwise I would go through: http://php.net/manual/en/class.domelement.php

Body:
I'm trying to use Zend_Dom for some very light screen scraping (I want to grab a headline, some body text and a link from a small block of news items on my website) and I'm not sure how to handle the DOMElement that it gives me.

In the manual for Zend_Dom the code says:

foreach ($results as $result) {
    // $result is a DOMElement
}

How do I make use of this DOMElement?

A detailed example (looking for the anchor elements on Google):

$url='http://google.com/';
$client = new Zend_Http_Client($url);
$response = $client->request();
$html = $response->getBody();
$dom = new Zend_Dom_Query($html);
$results = $dom->query('a');
foreach($results as $r){
     Zend_Debug::dump($r);
}

This gives me:

object(DOMElement)#81 (0) {
}
object(DOMElement)#82 (0) {
}
object(DOMElement)#83 (0) {
}
... etc, etc...

What I find confusing is that this looks like each element contains nothing (0)! This isn't the case but that is my first impression. So I poke around online and find I can add nodeValue to get something out of this:

Zend_Debug::dump($r->nodeValue);

which gives me:

string(6) "Images"
string(6) "Videos"
string(4) "Maps"
...etc, etc...

But where I run into trouble is getting specific elements and their contents.

For instance given this html:

   Mon, 11 October 2010

Some text

   More

   Mon, 16 August 2010

Stuff is here

   More

I can grab the text from each newsBlurb, using the technique I use in the Google example, but cannot get each element by itself. I want to get the date and stick it somewhere, get the headline text and stick it somewhere and get the link to use. But all I get is the actual text in the div.

How do I get what I want from this?

EDIT
Here is another example that does not work as I expect. Any ideas why?

$url = 'http://php.net/manual/en/class.domelement.php';
$client = new Zend_Http_Client($url);
$response = $client->request();
$html = $response->getBody();
$dom = new Zend_Dom_Query($html);
$newsBlurbNode = $dom->query('div.note');
Zend_Debug::dump($newsBlurbNode);

this gives me:

object(Zend_Dom_Query_Result)#867 (7) {
  ["_count":protected] => NULL
  ["_cssQuery":protected] => string(8) "div.note"
  ["_document":protected] => object(DOMDocument)#79 (0) {
  }
  ["_nodeList":protected] => object(DOMNodeList)#864 (0) {
  }
  ["_position":protected] => int(0)
  ["_xpath":protected] => NULL
  ["_xpathQuery":protected] => string(33) "//div[contains(@class, ' note ')]"
}

Trying to get anything out of this I used:

$children = $newsBlurbNode->childNodes;
     foreach ($children as $child) {
       }

Which results in an error because the foreach loop has nothing in it. Ack! What am I not getting?

Body:
You can use something like this to get access to the individual nodes:

$children = $newsBlurbNode->childNodes;
foreach ($children as $child) {
    //do something with individual nodes
}

Otherwise I would go through: http://php.net/manual/en/class.domelement.php


问:
How to use WebSecurity adapter with Spring-Security-OAuth2
I am trying to achieve authentication system using OAuth2 as well as simple Spring Security(Web Security adapter). But as I am trying to configure, I am not able to use both the services together. As per configuration file code shared below, But It will work either OAuth2 or simple auth using spring security(Web Security adapter). I want both the authentication system should work based on URL identification.

Thanks in advance!

```<code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
public class ConfigurationClass {

    // Its working as simple auth spring security
    @EnableWebSecurity
    @Configuration
    @Order(1)
    protected static class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private TokenAuthenticationService tokenAuthenticationService;

        @Autowired
        private OtpManage OtpManage;

        @Autowired
        private RoleRepository RoleRepository;

        public StatelessAuthenticationSecurityConfig() {
            super(true);

        }

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

            // allow anonymous resource requests
            .antMatchers("/").permitAll()

            // allow anonymous POSTs to login
            .antMatchers(HttpMethod.POST, "/user/registration").permitAll()
            .antMatchers(HttpMethod.POST, "/user/changepassword").permitAll()
            .antMatchers(HttpMethod.POST, "/user/resetpassword").permitAll()
            // .antMatchers(HttpMethod.POST,
            // "/api/otpResetPassword").permitAll()
            .antMatchers(HttpMethod.POST, "/user/saveusergroup").permitAll()
            .antMatchers(HttpMethod.POST, "/user/bugreport").permitAll()
            .antMatchers(HttpMethod.POST, "/user/createtoken").permitAll()

            // .anyRequest().authenticated().and()
            .anyRequest().hasAnyRole("USER","SYSTEM_ADMIN","ADMIN").and()

            // custom JSON based authentication by POST of
            // {"username":"<name>","password":"<password>"} which sets the
            // token header upon authentication
            .addFilterBefore(new StatelessLoginFilter("/api/login", tokenAuthenticationService, userDetailsService,
                    authenticationManager(), OtpManage), UsernamePasswordAuthenticationFilter.class)

            // custom Token based authentication based on the header
            // previously given to the client
            .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
                    UsernamePasswordAuthenticationFilter.class);

        }

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

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        protected UserDetailsService userDetailsService() {
            return userDetailsService;
        }

    }

    // Its not working, But if I removed @Order(1) annotation from StatelessAuthenticationSecurityConfig class then this one will work as default
    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {
            System.out.println("@EnableResourceServer");
            http
                    .exceptionHandling()
                    .authenticationEntryPoint(customAuthenticationEntryPoint)
                    .and()
                    .logout()
                    .logoutUrl("/oauth/logout")
                    .logoutSuccessHandler(customLogoutSuccessHandler)
                    .and()
                    .csrf()
                    .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                    .disable()
                    .headers()
                    .frameOptions().disable().disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    .antMatchers("/hello/").permitAll()
                    .antMatchers("/secure/**").authenticated();

        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Autowired
        private DataSource dataSource;

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

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            System.out.println("@AuthorizationServerConfigurerAdapter");
            clients
                    .inMemory()
                    .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                    .scopes("read", "write")
                    .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                    .authorizedGrantTypes("password", "refresh_token")
                    .secret(propertyResolver.getProperty(PROP_SECRET))
                    .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
        }

        @Override
        public void setEnvironment(Environment environment) {
            this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
        }

    }

}
</code>```

Update:

I have made few changes to my code with @EnableOAuth2Client, @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) and I have achieved what exactly I want to do. But now the issue is I am not able call to post url: "/api/login" with user credentials. I am getting error as url not found. as per my code in WebSecurityConfig class, I have added filter in configure(HttpSecurity http) method for loginFilter class which extends AbstractAuthenticationProcessingFilter. But this filter which is mapped with "/api/login" url not working at all. Why this one filter is not working I don`t understand. Someone could you help me regarding the same.

#WebSecurityConfigClass

```<code>/**
 * Implementation of HttpSecurity configure method
 * Implementation custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
 * @author Santosh
 *
 */
@EnableOAuth2Client
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled = true, proxyTargetClass = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    @Autowired
    private MessageSource messages;

    @Autowired
    private RESTAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private RESTAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private RESTAuthenticationFailureHandler restAuthenticationFailureHandler;

    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;

    public WebSecurityConfig() {
        super(true);
    }

    /*@Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("testUser").password("testUser").roles("USER");
    }
*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // setup security
        http
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler)
        .authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .authorizeRequests()
            .anyRequest()
                .fullyAuthenticated()
                .and().httpBasic();

        http
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler)
        .authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .anonymous().and()
        .servletApi().and()
        .headers().and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/api/login").permitAll()

        .antMatchers("/admin/**").hasRole("ADMIN")
        .and()
        .authorizeRequests()
        .anyRequest().hasAnyRole("USER").and()
        //all other request need to be authenticated
        // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
        .addFilterBefore(new LoginFilter("/api/login", tokenAuthenticationService, userDetailsService, authenticationManager(), restAuthenticationSuccessHandler, restAuthenticationFailureHandler), UsernamePasswordAuthenticationFilter.class)
        // custom Token based authentication based on the header previously given to the client
        .addFilterBefore(new ApplicationFilter (tokenAuthenticationService, messages), UsernamePasswordAuthenticationFilter.class);

    }

//   To allow Pre-flight [OPTIONS] request from browser
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring()//allow anonymous GETs to API
        .antMatchers(HttpMethod.GET, "/api/status/**");
    }

    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
        return new CustomBasicAuthenticationEntryPoint();
    }

    @Bean(name="authenticationManagerBean")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
</code>```

#OAuth2ServerConfiguration

```<code>@Configuration
public class OAuth2ServerConfiguration {

    private static final String RESOURCE_ID = "restservice";
    private static final String ROLE_ADMIN = "ADMIN";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomOAuth2AccessDeniedHandler accessDeniedHandler;

        @Autowired
        private RESTOAuth2AuthenticationEntryPoint restAuthenticationEntryPoint;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(RESOURCE_ID);
        }

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

            http
            .authorizeRequests()
            .antMatchers("/api/hello").permitAll()
            .antMatchers("/users/current/**","/oauth/token","/oauth/authorize","/oauth/refresh_token").permitAll()
            .antMatchers("/api/greeting").authenticated().and().exceptionHandling()
                    .accessDeniedHandler(accessDeniedHandler)
                    .authenticationEntryPoint(restAuthenticationEntryPoint);
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private TokenStore tokenStore;

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

//      @Autowired
//      private UserApprovalHandler userApprovalHandler;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

            endpoints.tokenStore(this.tokenStore).authenticationManager(this.authenticationManager)
                    .userDetailsService(userDetailsService);
//          .userApprovalHandler(userApprovalHandler)
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//          jdbc(dataSource)
            clients.inMemory().withClient("clientapp").authorizedGrantTypes("password", "refresh_token")
                    .authorities("USER").scopes("read", "write").resourceIds(RESOURCE_ID).secret("123456")
                    .accessTokenValiditySeconds(20)// Access token is only valid
                                                    // for 2 minutes.
                    .refreshTokenValiditySeconds(1200);// Refresh token is only
                                                        // valid for 10
                                                        // minutes.;

        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }

    }

}
</code>```

答:
On your WebSecurityAdapter you want to build requestMatchers to determine on which requests that instance of HttpSecurity will invoke.

For example :

```<code>protected void configure(HttpSecurity http) throws Exception {
  http.requestMatchers().antMatchers("/secure/path", "/more/secure/path");
  // Rest of your configuration.
}
</code>```

Body:
I am trying to achieve authentication system using OAuth2 as well as simple Spring Security(Web Security adapter). But as I am trying to configure, I am not able to use both the services together. As per configuration file code shared below, But It will work either OAuth2 or simple auth using spring security(Web Security adapter). I want both the authentication system should work based on URL identification.

Thanks in advance!

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
public class ConfigurationClass {

    // Its working as simple auth spring security
    @EnableWebSecurity
    @Configuration
    @Order(1)
    protected static class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private TokenAuthenticationService tokenAuthenticationService;

        @Autowired
        private OtpManage OtpManage;

        @Autowired
        private RoleRepository RoleRepository;

        public StatelessAuthenticationSecurityConfig() {
            super(true);

        }

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

            // allow anonymous resource requests
            .antMatchers("/").permitAll()

            // allow anonymous POSTs to login
            .antMatchers(HttpMethod.POST, "/user/registration").permitAll()
            .antMatchers(HttpMethod.POST, "/user/changepassword").permitAll()
            .antMatchers(HttpMethod.POST, "/user/resetpassword").permitAll()
            // .antMatchers(HttpMethod.POST,
            // "/api/otpResetPassword").permitAll()
            .antMatchers(HttpMethod.POST, "/user/saveusergroup").permitAll()
            .antMatchers(HttpMethod.POST, "/user/bugreport").permitAll()
            .antMatchers(HttpMethod.POST, "/user/createtoken").permitAll()

            // .anyRequest().authenticated().and()
            .anyRequest().hasAnyRole("USER","SYSTEM_ADMIN","ADMIN").and()

            // custom JSON based authentication by POST of
            // {"username":"<name>","password":"<password>"} which sets the
            // token header upon authentication
            .addFilterBefore(new StatelessLoginFilter("/api/login", tokenAuthenticationService, userDetailsService,
                    authenticationManager(), OtpManage), UsernamePasswordAuthenticationFilter.class)

            // custom Token based authentication based on the header
            // previously given to the client
            .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
                    UsernamePasswordAuthenticationFilter.class);

        }

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

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        protected UserDetailsService userDetailsService() {
            return userDetailsService;
        }

    }

    // Its not working, But if I removed @Order(1) annotation from StatelessAuthenticationSecurityConfig class then this one will work as default
    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {
            System.out.println("@EnableResourceServer");
            http
                    .exceptionHandling()
                    .authenticationEntryPoint(customAuthenticationEntryPoint)
                    .and()
                    .logout()
                    .logoutUrl("/oauth/logout")
                    .logoutSuccessHandler(customLogoutSuccessHandler)
                    .and()
                    .csrf()
                    .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                    .disable()
                    .headers()
                    .frameOptions().disable().disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    .antMatchers("/hello/").permitAll()
                    .antMatchers("/secure/**").authenticated();

        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Autowired
        private DataSource dataSource;

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

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            System.out.println("@AuthorizationServerConfigurerAdapter");
            clients
                    .inMemory()
                    .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                    .scopes("read", "write")
                    .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                    .authorizedGrantTypes("password", "refresh_token")
                    .secret(propertyResolver.getProperty(PROP_SECRET))
                    .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
        }

        @Override
        public void setEnvironment(Environment environment) {
            this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
        }

    }

}

Update:

I have made few changes to my code with @EnableOAuth2Client, @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) and I have achieved what exactly I want to do. But now the issue is I am not able call to post url: "/api/login" with user credentials. I am getting error as url not found. as per my code in WebSecurityConfig class, I have added filter in configure(HttpSecurity http) method for loginFilter class which extends AbstractAuthenticationProcessingFilter. But this filter which is mapped with "/api/login" url not working at all. Why this one filter is not working I don`t understand. Someone could you help me regarding the same.

#WebSecurityConfigClass

/**
 * Implementation of HttpSecurity configure method
 * Implementation custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
 * @author Santosh
 *
 */
@EnableOAuth2Client
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled = true, proxyTargetClass = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    @Autowired
    private MessageSource messages;

    @Autowired
    private RESTAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private RESTAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private RESTAuthenticationFailureHandler restAuthenticationFailureHandler;

    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;

    public WebSecurityConfig() {
        super(true);
    }

    /*@Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("testUser").password("testUser").roles("USER");
    }
*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // setup security
        http
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler)
        .authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .authorizeRequests()
            .anyRequest()
                .fullyAuthenticated()
                .and().httpBasic();

        http
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler)
        .authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .anonymous().and()
        .servletApi().and()
        .headers().and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/api/login").permitAll()

        .antMatchers("/admin/**").hasRole("ADMIN")
        .and()
        .authorizeRequests()
        .anyRequest().hasAnyRole("USER").and()
        //all other request need to be authenticated
        // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
        .addFilterBefore(new LoginFilter("/api/login", tokenAuthenticationService, userDetailsService, authenticationManager(), restAuthenticationSuccessHandler, restAuthenticationFailureHandler), UsernamePasswordAuthenticationFilter.class)
        // custom Token based authentication based on the header previously given to the client
        .addFilterBefore(new ApplicationFilter (tokenAuthenticationService, messages), UsernamePasswordAuthenticationFilter.class);

    }

//   To allow Pre-flight [OPTIONS] request from browser
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring()//allow anonymous GETs to API
        .antMatchers(HttpMethod.GET, "/api/status/**");
    }

    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
        return new CustomBasicAuthenticationEntryPoint();
    }

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

#OAuth2ServerConfiguration

@Configuration
public class OAuth2ServerConfiguration {

    private static final String RESOURCE_ID = "restservice";
    private static final String ROLE_ADMIN = "ADMIN";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomOAuth2AccessDeniedHandler accessDeniedHandler;

        @Autowired
        private RESTOAuth2AuthenticationEntryPoint restAuthenticationEntryPoint;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(RESOURCE_ID);
        }

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

            http
            .authorizeRequests()
            .antMatchers("/api/hello").permitAll()
            .antMatchers("/users/current/**","/oauth/token","/oauth/authorize","/oauth/refresh_token").permitAll()
            .antMatchers("/api/greeting").authenticated().and().exceptionHandling()
                    .accessDeniedHandler(accessDeniedHandler)
                    .authenticationEntryPoint(restAuthenticationEntryPoint);
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private TokenStore tokenStore;

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

//      @Autowired
//      private UserApprovalHandler userApprovalHandler;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

            endpoints.tokenStore(this.tokenStore).authenticationManager(this.authenticationManager)
                    .userDetailsService(userDetailsService);
//          .userApprovalHandler(userApprovalHandler)
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//          jdbc(dataSource)
            clients.inMemory().withClient("clientapp").authorizedGrantTypes("password", "refresh_token")
                    .authorities("USER").scopes("read", "write").resourceIds(RESOURCE_ID).secret("123456")
                    .accessTokenValiditySeconds(20)// Access token is only valid
                                                    // for 2 minutes.
                    .refreshTokenValiditySeconds(1200);// Refresh token is only
                                                        // valid for 10
                                                        // minutes.;

        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }

    }

}

Body:
On your WebSecurityAdapter you want to build requestMatchers to determine on which requests that instance of HttpSecurity will invoke.

For example :

protected void configure(HttpSecurity http) throws Exception {
  http.requestMatchers().antMatchers("/secure/path", "/more/secure/path");
  // Rest of your configuration.
}


问:
xaml how center text in a templated button
I am not able to center text in the templated button. "OK" stays at bottom center or even goes bellow the button border.</p>

```<code> <Window.Resources>
    <ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
        <Grid>
            <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FF4363EA" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
            <Viewbox>
                <ContentControl Margin="10" Content="{TemplateBinding Content}"/>
            </Viewbox>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid Margin="0,0,0,2.4">

    <Button
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="75" Margin="189.6,24.6,0,0"
            Template="{DynamicResource BT_Kids}"  FontSize="15">OK</Button>

</Grid>
</code>```

答:
Try this:</p>

```<code><Button ...>
  <Button.Content>
            <StackPanel Padding="0" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="OK"/>
            </StackPanel>
        </Button.Content>
</Button>
</code>```

Body:
I am not able to center text in the templated button. "OK" stays at bottom center or even goes bellow the button border.

 <Window.Resources>
    <ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
        <Grid>
            <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FF4363EA" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
            <Viewbox>
                <ContentControl Margin="10" Content="{TemplateBinding Content}"/>
            </Viewbox>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid Margin="0,0,0,2.4">

    <Button
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="75" Margin="189.6,24.6,0,0"
            Template="{DynamicResource BT_Kids}"  FontSize="15">OK</Button>

</Grid>

Body:
Try this:

<Button ...>
  <Button.Content>
            <StackPanel Padding="0" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="OK"/>
            </StackPanel>
        </Button.Content>
</Button>


问:
How to read words from text file and store into 2 dimensional array
```<code>#include <iostream>
using namespace std;

int main(){

string Firstname,Surname;

cout << "Full name:" <<endl;
cin >> Firstname >> Surname;

return 0;
</code>```

<p>I want the commands to work if the user only has first name, normally if the user doesn't input the surname it keeps continuously asking them again and again..... </p>

答:
I have commented my code and make a code to read names from file and store them into 2D string array as you want.

Text File

```<code>James
Will
Bruce
Wayne
Harry
Potter
</code>```

Code:

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str;
    int count=0;
    ifstream in("File.txt");
    while (!in.eof())
    {
        getline(in, str);
        count++; //counting names
    }
    in.close();
    count = count / 2; //dividing count by 2
    //SYNTAX FOR 2D ARRAY
    string **nameArray = new string*[count]; //making array of count/2
    for (int i = 0; i < count; i++)
        nameArray[i] = new string[2]; //evvery index have 2 column one for first name and second for last name
    //2D array done
    in.open("File.txt");
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
                   // getline(in,nameArray[i][j]; // if you want to read sentence.not a single word.
            //in >> nameArray[i][j]; //if you want to read name or a single word.
        }
    }
    in.close();
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cout<<nameArray[i][j]<<" "; //Printing [i,j] with first and second name
        }
        cout << endl;
    }
    for (int i = 0; i < count; i++)
        delete[] nameArray[i];
    delete[] nameArray;
    system("pause");
    return 0;
}
</code>```

Output

```<code>James Will
Bruce Wayne
Harry Potter
</code>```

Body:
#include <iostream>
using namespace std;

int main(){

string Firstname,Surname;

cout << "Full name:" <<endl;
cin >> Firstname >> Surname;

return 0;

I want the commands to work if the user only has first name, normally if the user doesn't input the surname it keeps continuously asking them again and again.....

Body:
I have commented my code and make a code to read names from file and store them into 2D string array as you want.

Text File

James
Will
Bruce
Wayne
Harry
Potter

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str;
    int count=0;
    ifstream in("File.txt");
    while (!in.eof())
    {
        getline(in, str);
        count++; //counting names
    }
    in.close();
    count = count / 2; //dividing count by 2
    //SYNTAX FOR 2D ARRAY
    string **nameArray = new string*[count]; //making array of count/2
    for (int i = 0; i < count; i++)
        nameArray[i] = new string[2]; //evvery index have 2 column one for first name and second for last name
    //2D array done
    in.open("File.txt");
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
                   // getline(in,nameArray[i][j]; // if you want to read sentence.not a single word.
            //in >> nameArray[i][j]; //if you want to read name or a single word.
        }
    }
    in.close();
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cout<<nameArray[i][j]<<" "; //Printing [i,j] with first and second name
        }
        cout << endl;
    }
    for (int i = 0; i < count; i++)
        delete[] nameArray[i];
    delete[] nameArray;
    system("pause");
    return 0;
}

Output

James Will
Bruce Wayne
Harry Potter


问:
Use async react-select with redux-saga
I try to implement a async react-select (Select.Async). The problem is, we want to do the fetch in redux-saga. So if a user types something, the fetch-action should be triggered. Saga then fetches the record and saved them to the store. This works so far.
Unfortunately loadOptions has to return a promise or the callback should be called. Since the newly retrieved options get propagated with a changing property, I see no way to use Select.Async together with saga to do the async fetch call. Any suggestions?

```<code> <Select.Async
   multi={false}
   value={this.props.value}
   onChange={this.onChange}
   loadOptions={(searchTerm) =>  this.props.options.load(searchTerm)}
  />
</code>```

I had a hack where i assigned the callback to a class variable and resolve it on componentWillReceiveProps. That way ugly and did not work properly so i look for a better solution.

Thanks

答:
redux-saga is for handling side effects like asynchronously receiving options for react-select. That's why you should leave the async stuff to redux-saga. I have never used react-select but by just looking at the documentation I would solve it this way:

Your component gets very simple. Just get value and options from your redux store. optionsRequested is an action creator for the OPTIONS_REQUESTED action:

```<code>const ConnectedSelect = ({ value, options, optionsRequested }) => (
  <Select
    value={value}
    options={options}
    onInputChange={optionsRequested}
  />
)

export default connect(store => ({
  value: selectors.getValue(store),
  options: selectors.getOptions(store),
}), {
  optionsRequested: actions.optionsRequested,
})(ConnectedSelect)
</code>```

A saga definition watches for OPTIONS_REQUESTED action that is trigged by onInputChange, loads the data with given searchTerm from server and dispatches OPTIONS_RECEIVED action to update redux store.

```<code>function* watchLoadOptions(searchTerm) {
  const options = yield call(api.getOptions, searchTerm)
  yield put(optionsReceived(options))
}
</code>```

In other words: Make your Component as pure as possible and handle all side-effect/async calls in redux-saga

I hope this answer was useful for you.

Title: Use async react-select with redux-saga

Body:
I try to implement a async react-select (Select.Async). The problem is, we want to do the fetch in redux-saga. So if a user types something, the fetch-action should be triggered. Saga then fetches the record and saved them to the store. This works so far.
Unfortunately loadOptions has to return a promise or the callback should be called. Since the newly retrieved options get propagated with a changing property, I see no way to use Select.Async together with saga to do the async fetch call. Any suggestions?

 <Select.Async
   multi={false}
   value={this.props.value}
   onChange={this.onChange}
   loadOptions={(searchTerm) =>  this.props.options.load(searchTerm)}
  />

I had a hack where i assigned the callback to a class variable and resolve it on componentWillReceiveProps. That way ugly and did not work properly so i look for a better solution.

Thanks

Body:
redux-saga is for handling side effects like asynchronously receiving options for react-select. That's why you should leave the async stuff to redux-saga. I have never used react-select but by just looking at the documentation I would solve it this way:

Your component gets very simple. Just get value and options from your redux store. optionsRequested is an action creator for the OPTIONS_REQUESTED action:

const ConnectedSelect = ({ value, options, optionsRequested }) => (
  <Select
    value={value}
    options={options}
    onInputChange={optionsRequested}
  />
)

export default connect(store => ({
  value: selectors.getValue(store),
  options: selectors.getOptions(store),
}), {
  optionsRequested: actions.optionsRequested,
})(ConnectedSelect)

A saga definition watches for OPTIONS_REQUESTED action that is trigged by onInputChange, loads the data with given searchTerm from server and dispatches OPTIONS_RECEIVED action to update redux store.

function* watchLoadOptions(searchTerm) {
  const options = yield call(api.getOptions, searchTerm)
  yield put(optionsReceived(options))
}

In other words: Make your Component as pure as possible and handle all side-effect/async calls in redux-saga

I hope this answer was useful for you.


问:
Why doesn't this searchbox work?
```<code>  <!--got this from http://www.getgooglesearch.com/-->
  <fieldset id="searchbox">
    <form method="get" action="http://www.google.com/search">
      <input type="text"   name="q" size="25" maxlength="255" value="" />
      <input type="image" src="../media/google.gif" alt="Submit button" title="Submit" /><br />
      <input type="checkbox"  name="sitesearch" value="arenanewbs.com" checked="checked" />Only search Areneanewbs.com<br />
    </form>
  </fieldset>
</code>```

If you uncheck the box the google site search works, but on my actual site it doesn't work. Can anyone help me?

答: I think the name should be site instead of sitesearch</p>

Title: Why doesn't this searchbox work?

Body:
  <fieldset id="searchbox">
    <form method="get" action="http://www.google.com/search">
      <input type="text"   name="q" size="25" maxlength="255" value="" />
      <input type="image" src="../media/google.gif" alt="Submit button" title="Submit" />

      <input type="checkbox"  name="sitesearch" value="arenanewbs.com" checked="checked" />Only search Areneanewbs.com

    </form>
  </fieldset>

If you uncheck the box the google site search works, but on my actual site it doesn't work. Can anyone help me?


问:
Binary search tree throwing error while adding node
I have this binary search tree that I wrote in Java. It seems to be working fine. However, upon calling multiple add calls, I am getting StackOverFlow error. I am learning to write in Java. Can someone please tell me what I am doing wrong?</p>

```<code> public class TreeApp<E extends Comparable<E>>
{
    private Node<E> root=null;
    private int size=0;

    private static class Node<E>
    {
        private E e;
        private Node<E> left;
        private Node<E> right;
        private Node<E> parent;

        public Node(E e,Node<E> parent,Node<E> left,Node<E> right)
        {
            this.e=e;
            this.left=left;
            this.right=right;
            this.parent=parent;
        }

        public Node(E e)
        {
            this.e=e;
        }

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }

        public Node<E> getLeft() {
            return left;
        }

        public void setLeft(Node<E> left) {
            this.left = left;
        }

        public Node<E> getRight() {
            return right;
        }

        public void setRight(Node<E> right) {
            this.right = right;
        }

        public Node<E> getParent() {
            return parent;
        }

        public void setParent(Node<E> parent) {
            this.parent = parent;
        }

    }//end of Node<E> class

    public TreeApp()
    {

    }

    public Node<E> createRoot(E e,Node<E> l,Node<E> r)
    {
        if(!(root==null))
        System.out.println("Root is already present");
        root=new Node<E>(e,root,l,r);
        size++;
        return root;

    }

    public Node<E> addNode(Node<E> left,E e)
    {

        //lets start with root
        if(root==null)
            createRoot(e,null,null);
        Node<E> focusNode=root;

        //Node<E> newLeft
        Node<E> newNode=new Node<E>(e);

        //while(true)
        if(e.compareTo(focusNode.e) < 0)
        {
            if(focusNode.getLeft()==null)
            {
                focusNode.setLeft(newNode);
                size++;
            }
            else
            {
                focusNode=focusNode.getLeft();
                //addNode(focusNode,e);
            }

        }else if(e.compareTo(focusNode.e) >= 0)
        {
            if(focusNode.getRight()==null)
            {
                focusNode.setRight(newNode);
                size++;
            }
            else
            {
                focusNode=focusNode.getRight();

                //addNode(focusNode,e);
            }
        }
        return focusNode;
    }

    public void preorderTraverseTree(Node<E> focusNode) {

        if (focusNode != null) {

            System.out.println("starting traversal: " + focusNode.getE());

            preorderTraverseTree(focusNode.getLeft());
            preorderTraverseTree(focusNode.getRight());

        }

    }

    public String toString() {
        if (root == null) {
          return "";
        } else {
          return root.toString();
        }
      }

    public static void main(String args[])
    {
        //Node<String> p=new Node<String>();
        TreeApp<String> ta=new TreeApp<String>();
        System.out.println("size before: " + ta.size);

        ta.createRoot("3",null,null);
        Integer i=1;
        Integer j=2;
        System.out.println("comparison " + i.compareTo(j));
        //System.out.println("size after: " + ta.size);
        ta.addNode(ta.root,"2");
        ta.addNode(ta.root,"4");
        ta.addNode(ta.root,"1");
        ta.addNode(ta.root,"6");

        //ta.addNode(ta.root,"5");
        ta.preorderTraverseTree(ta.root);
        //System.out.println("size after: " + ta.size);

    }

}
</code>```

答:
The stackoverflow happens because of an infinite recursive loop, caused by the left argument being ignored in favor of the root node.

The error occurs in your case when adding node 1, because the root node 3 already has a left child 2 and right child 4. Hence, the method does a recursive call to try and add node 1 as a left or right child of node 2, but when it reenters the method it ignores node 2 and tries to fit node 1 under the root node 3 again and this keeps going on and on.

```<code>public Node<E> addNode(Node<E> left, E e) {
    //lets start with root
    // if (root == null)
    //     createRoot(e, null, null);
    // Node<E> focusNode = root;        // <-- wrong
    Node<E> focusNode = left;           // <-- correct

    //Node<E> newLeft
    Node<E> newNode = new Node<E>(e);

    //while(true)
    if (e.compareTo(focusNode.e) < 0) {
        if (focusNode.getLeft() == null) {
            focusNode.setLeft(newNode);
            size++;
        } else {
            focusNode = focusNode.getLeft();
            addNode(focusNode,e);       // <-- uncomment this line
        }

    } else if (e.compareTo(focusNode.e) >= 0) {
        if (focusNode.getRight() == null) {
            focusNode.setRight(newNode);
            size++;
        } else {
            focusNode = focusNode.getRight();
            addNode(focusNode,e);       // <-- uncomment this line
        }
    }
    return focusNode;
}
</code>```

Body:
I have this binary search tree that I wrote in Java. It seems to be working fine. However, upon calling multiple add calls, I am getting StackOverFlow error. I am learning to write in Java. Can someone please tell me what I am doing wrong?

 public class TreeApp<E extends Comparable<E>>
{
    private Node<E> root=null;
    private int size=0;

    private static class Node<E>
    {
        private E e;
        private Node<E> left;
        private Node<E> right;
        private Node<E> parent;

        public Node(E e,Node<E> parent,Node<E> left,Node<E> right)
        {
            this.e=e;
            this.left=left;
            this.right=right;
            this.parent=parent;
        }

        public Node(E e)
        {
            this.e=e;
        }

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }

        public Node<E> getLeft() {
            return left;
        }

        public void setLeft(Node<E> left) {
            this.left = left;
        }

        public Node<E> getRight() {
            return right;
        }

        public void setRight(Node<E> right) {
            this.right = right;
        }

        public Node<E> getParent() {
            return parent;
        }

        public void setParent(Node<E> parent) {
            this.parent = parent;
        }

    }//end of Node<E> class

    public TreeApp()
    {

    }

    public Node<E> createRoot(E e,Node<E> l,Node<E> r)
    {
        if(!(root==null))
        System.out.println("Root is already present");
        root=new Node<E>(e,root,l,r);
        size++;
        return root;

    }

    public Node<E> addNode(Node<E> left,E e)
    {

        //lets start with root
        if(root==null)
            createRoot(e,null,null);
        Node<E> focusNode=root;

        //Node<E> newLeft
        Node<E> newNode=new Node<E>(e);

        //while(true)
        if(e.compareTo(focusNode.e) < 0)
        {
            if(focusNode.getLeft()==null)
            {
                focusNode.setLeft(newNode);
                size++;
            }
            else
            {
                focusNode=focusNode.getLeft();
                //addNode(focusNode,e);
            }

        }else if(e.compareTo(focusNode.e) >= 0)
        {
            if(focusNode.getRight()==null)
            {
                focusNode.setRight(newNode);
                size++;
            }
            else
            {
                focusNode=focusNode.getRight();

                //addNode(focusNode,e);
            }
        }
        return focusNode;
    }

    public void preorderTraverseTree(Node<E> focusNode) {

        if (focusNode != null) {

            System.out.println("starting traversal: " + focusNode.getE());

            preorderTraverseTree(focusNode.getLeft());
            preorderTraverseTree(focusNode.getRight());

        }

    }

    public String toString() {
        if (root == null) {
          return "";
        } else {
          return root.toString();
        }
      }

    public static void main(String args[])
    {
        //Node<String> p=new Node<String>();
        TreeApp<String> ta=new TreeApp<String>();
        System.out.println("size before: " + ta.size);

        ta.createRoot("3",null,null);
        Integer i=1;
        Integer j=2;
        System.out.println("comparison " + i.compareTo(j));
        //System.out.println("size after: " + ta.size);
        ta.addNode(ta.root,"2");
        ta.addNode(ta.root,"4");
        ta.addNode(ta.root,"1");
        ta.addNode(ta.root,"6");

        //ta.addNode(ta.root,"5");
        ta.preorderTraverseTree(ta.root);
        //System.out.println("size after: " + ta.size);

    }

}

Body:
The stackoverflow happens because of an infinite recursive loop, caused by the left argument being ignored in favor of the root node.

The error occurs in your case when adding node 1, because the root node 3 already has a left child 2 and right child 4. Hence, the method does a recursive call to try and add node 1 as a left or right child of node 2, but when it reenters the method it ignores node 2 and tries to fit node 1 under the root node 3 again and this keeps going on and on.

public Node<E> addNode(Node<E> left, E e) {
    //lets start with root
    // if (root == null)
    //     createRoot(e, null, null);
    // Node<E> focusNode = root;        // <-- wrong
    Node<E> focusNode = left;           // <-- correct

    //Node<E> newLeft
    Node<E> newNode = new Node<E>(e);

    //while(true)
    if (e.compareTo(focusNode.e) < 0) {
        if (focusNode.getLeft() == null) {
            focusNode.setLeft(newNode);
            size++;
        } else {
            focusNode = focusNode.getLeft();
            addNode(focusNode,e);       // <-- uncomment this line
        }

    } else if (e.compareTo(focusNode.e) >= 0) {
        if (focusNode.getRight() == null) {
            focusNode.setRight(newNode);
            size++;
        } else {
            focusNode = focusNode.getRight();
            addNode(focusNode,e);       // <-- uncomment this line
        }
    }
    return focusNode;
}


问:
NGINX reverse proxy to a host with no root subdirectory
Usually, when doing a reverse proxy setup, you have a server on your backend which looks like this:

http://localhost:8084/app-root

and you can proxy_pass

location /app-root {
  proxy_pass http://localhost:8084;
}

It will proxy www.my-domain.com/app-root to  the internal server http://localhost:8084/app-root.

Great!

Can someone explain what needs to be done if the server insists on hosting from the root as so:

http://localhost:8084/index.html
http://localhost:8084/images/image1.jpg

I want this to be accessible via

http://www.my-domain.com/app/index.html

http://www.my-domain.com/app/images/image1.jpg

答:
You can use rewrite of nginx. Something like this should work</p>

```<code>location  /app/ {
  rewrite /app/(.*) /$1  break;
  proxy_pass         http://localhost:8084;
}
</code>```

Body:
You can use rewrite of nginx. Something like this should work

location  /app/ {
  rewrite /app/(.*) /$1  break;
  proxy_pass         http://localhost:8084;
}


问:
How to check if the name is in a list that is recognized by its similar term in a predicate?
Suppose, I have a prolog predicate such as:

```<code>name(music,[jazz,blues,classical]).
</code>```

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

```<code>ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).
</code>```

But it isn't working.

```<code>?- ismember(jazz,music).
false.
</code>```

And it isn't writing the write(Z) part.

答:
the ismember/2 predicate second parameter is a list , and you are not passing a list

here is a trace

```<code>[trace]  ?- ismember(jazz,music).
   Call: (8) ismember(jazz, music) ? creep
   Call: (9) imember(jazz, name(music, _6828)) ? creep
   Fail: (9) imember(jazz, name(music, _6828)) ? creep
   Fail: (8) ismember(jazz, music) ? creep
false.
</code>```

@coder answer is a correct way

or you can simply use the member/2 predicate as follows:

first define your list in the database:

music([jazz,blues,classical]).

now we have our music types list , next we write the rule

ismusicmember(X) :- music(L) , member(X,L),write(L).

music(L) to assign the variable L to our music list

member(X,L)   the member/2 predicate check whether X is in the list or not

and running a query

```<code>?- ismusicmember(jazz).
[jazz,blues,classical]
true .
</code>```

a trace:

```<code>    [trace]  ?- ismusicmember(jazz).
   Call: (8) ismusicmember(jazz) ? creep
   Call: (9) music(_7376) ? creep
   Exit: (9) music([jazz, blues, classical]) ? creep
   Call: (9) lists:member(jazz, [jazz, blues, classical]) ? creep
   Exit: (9) lists:member(jazz, [jazz, blues, classical]) ? creep
   Call: (9) write([jazz, blues, classical]) ? creep
[jazz,blues,classical]
   Exit: (9) write([jazz, blues, classical]) ? creep
   Exit: (8) ismusicmember(jazz) ? creep
true .
</code>```

Body:
Suppose, I have a prolog predicate such as:

name(music,[jazz,blues,classical]).

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).

But it isn't working.

?- ismember(jazz,music).
false.

And it isn't writing the write(Z) part.

Body:
the ismember/2 predicate second parameter is a list , and you are not passing a list

here is a trace

[trace]  ?- ismember(jazz,music).
   Call: (8) ismember(jazz, music) ? creep
   Call: (9) imember(jazz, name(music, _6828)) ? creep
   Fail: (9) imember(jazz, name(music, _6828)) ? creep
   Fail: (8) ismember(jazz, music) ? creep
false.

@coder answer is a correct way

or you can simply use the member/2 predicate as follows:

first define your list in the database:

music([jazz,blues,classical]).

now we have our music types list , next we write the rule

ismusicmember(X) :- music(L) , member(X,L),write(L).

music(L) to assign the variable L to our music list

member(X,L)   the member/2 predicate check whether X is in the list or not

and running a query

?- ismusicmember(jazz).
[jazz,blues,classical]
true .

a trace:

    [trace]  ?- ismusicmember(jazz).
   Call: (8) ismusicmember(jazz) ? creep
   Call: (9) music(_7376) ? creep
   Exit: (9) music([jazz, blues, classical]) ? creep
   Call: (9) lists:member(jazz, [jazz, blues, classical]) ? creep
   Exit: (9) lists:member(jazz, [jazz, blues, classical]) ? creep
   Call: (9) write([jazz, blues, classical]) ? creep
[jazz,blues,classical]
   Exit: (9) write([jazz, blues, classical]) ? creep
   Exit: (8) ismusicmember(jazz) ? creep
true .


问:
Connecting MySql with Android Studio
Well I have some errors when I put the MySQL connector and I don`t know why.

I have researched in here(stackoverflow) and I've tried  to change the build.gradle app or the modules and it doesn't working. If anyone knows what's the problem it would help me a lot.. Thank You..

Errors:

```<code>Error:Error converting bytecode to dex:
Cause: Dex cannot parse version 52 byte code.
This is caused by library dependencies that have been compiled using Java 8 or above.
If you are using the 'java' gradle plugin in a library submodule add
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
to that submodule's build.gradle file.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: Return code 1 for dex process
</code>```

Errors in Android Studio

I add my code to:

build.gradle app:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.example.informatica.xabiagame"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
    compile 'com.android.support:design:24.2.1'
    compile 'com.google.android.gms:play-services-maps:9.6.1'
    compile 'com.google.android.gms:play-services-ads:9.6.1'
    compile 'com.google.android.gms:play-services:9.6.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-auth:9.6.1'
    compile project(':MySQL')
}

apply plugin: 'com.google.gms.google-services'
</code>```

Project module:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

MySQL module:

```<code>configurations.maybeCreate("default")
artifacts.add("default", file('mysql-connector-java-5.1.37-bin.jar'))
</code>```

答:
My be a bit late, but I have just found the solution for this problem:

MySQL connector 5.1 is compiled with Java 8.

Even now Android Studio 2.3 is not directly supporting Java 8.

You could write in the app/build.gradle this code:

```<code>android {
  defaultConfig
  {
      jackOptions
      {
        enabled true
      }
     compileOptions
     {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
     }
  }
</code>```

https://developer.android.com/guide/platform/j8-jack.html

Title: Connecting MySql with Android Studio

Body:
Well I have some errors when I put the MySQL connector and I don`t know why.

I have researched in here(stackoverflow) and I've tried  to change the build.gradle app or the modules and it doesn't working. If anyone knows what's the problem it would help me a lot.. Thank You..

Errors:

Error:Error converting bytecode to dex:
Cause: Dex cannot parse version 52 byte code.
This is caused by library dependencies that have been compiled using Java 8 or above.
If you are using the 'java' gradle plugin in a library submodule add
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
to that submodule's build.gradle file.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: Return code 1 for dex process

Errors in Android Studio

I add my code to:

build.gradle app:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.example.informatica.xabiagame"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
    compile 'com.android.support:design:24.2.1'
    compile 'com.google.android.gms:play-services-maps:9.6.1'
    compile 'com.google.android.gms:play-services-ads:9.6.1'
    compile 'com.google.android.gms:play-services:9.6.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-auth:9.6.1'
    compile project(':MySQL')
}

apply plugin: 'com.google.gms.google-services'

Project module:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

MySQL module:

configurations.maybeCreate("default")
artifacts.add("default", file('mysql-connector-java-5.1.37-bin.jar'))

Body:
My be a bit late, but I have just found the solution for this problem:

MySQL connector 5.1 is compiled with Java 8.

Even now Android Studio 2.3 is not directly supporting Java 8.

You could write in the app/build.gradle this code:

android {
  defaultConfig
  {
      jackOptions
      {
        enabled true
      }
     compileOptions
     {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
     }
  }

https://developer.android.com/guide/platform/j8-jack.html


问:
Why does $("body") == $("body") return false?
How come the equation in the title is false? How do check if two jQuery selectors point to the same DOM object?</p>

答:
Use $.is()

http://api.jquery.com/is/

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments...

Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers...


问:
How to delete quotation marks from a text file using batch file?
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

```<code>echo %name%>./User_Records/%username%.txt
</code>```

in the text file it is saving as

```<code>"Firstname Lastname"
</code>```

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

```<code>Firstname Lastname
</code>```

答:
```<code>echo %name:"=%>.\User_Records\%username%.txt
</code>```

should strip the quotes before they are recorded, if that's what your question is.

Note that path-separators in windows are \ not /.

But - if your question is about files that already exist then probably the easiest way is to use your editor. Depends a little on quite how many files you have to process - which you haven't specified.

Body:
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

echo %name%>./User_Records/%username%.txt

in the text file it is saving as

"Firstname Lastname"

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

Firstname Lastname

Body:
echo %name:"=%>.\User_Records\%username%.txt

should strip the quotes before they are recorded, if that's what your question is.

Note that path-separators in windows are \ not /.

But - if your question is about files that already exist then probably the easiest way is to use your editor. Depends a little on quite how many files you have to process - which you haven't specified.


问:
How can I animate these two things on one div?
Here is a live version http://lucasdebelder.be/googledoodle/

First of all I kinda want to fix it without using javascript/jquery, I want to keep it pure HTML & CSS based :)

Focus on the portals, I want to make them open and shrink after my ufo passed them. I've tried it multiple things but it doesn't want to work. How can I make a transition without using a :hover statement? I have a glowing, which is the box-shadows already on it, to make it look interactive, but how can I make them shrink?

(Portaal stands for portal, links stands for left and rechts stands for right, it's dutch)

HTML:

```<code><!-- portaal links en rechts -->
            <div class="portaal portaal_links_glow"></div>
            <div class="portaal portaal_rechts_glow"></div>
</code>```

CSS:

```<code>/*portaal algemeen*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: 2;
    animation-timing-function: ease-in-out;
}
/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_rechts;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; }
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}
</code>```

Thanks for all the effort and time.

答:
you can use this to shrink the portal :

```<code>transform: scale(0.2);
transition: 0.3s;
</code>```

or maybe this :/

```<code>background-size: 100%;
/* background-size: 50%; */
background-repeat: no-repeat;
background-position: 50% 50%;
transition: 0.3s;
</code>```

i don't know how to get it full HTML + CSS :/
but you can use js to set a new style when it's needed

for example on your HTML page you can add this below :

```<code><style>

/*the closing animation of the portal*/

.portal_style1 {
    /*your code ...* /
    animation: animation1;
}

.portal_style2 {
    /*your code ...* /
    animation: animation2;
}

</style>
</code>```

the js :

```<code>function change_style(){
    var obj=document.getElementById("portal2");
    obj.className=".portal_style2";

}
</code>```

and you can call the change_style() function when you want without the hover event

Body:
Here is a live version http://lucasdebelder.be/googledoodle/

First of all I kinda want to fix it without using javascript/jquery, I want to keep it pure HTML & CSS based :)

Focus on the portals, I want to make them open and shrink after my ufo passed them. I've tried it multiple things but it doesn't want to work. How can I make a transition without using a :hover statement? I have a glowing, which is the box-shadows already on it, to make it look interactive, but how can I make them shrink?

(Portaal stands for portal, links stands for left and rechts stands for right, it's dutch)

HTML:

CSS:

/*portaal algemeen*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: 2;
    animation-timing-function: ease-in-out;
}
/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_rechts;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; }
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}

Thanks for all the effort and time.

Body:
you can use this to shrink the portal :

transform: scale(0.2);
transition: 0.3s;

or maybe this :/

background-size: 100%;
/* background-size: 50%; */
background-repeat: no-repeat;
background-position: 50% 50%;
transition: 0.3s;

i don't know how to get it full HTML + CSS :/
but you can use js to set a new style when it's needed

for example on your HTML page you can add this below :

<style>

/*the closing animation of the portal*/

.portal_style1 {
    /*your code ...* /
    animation: animation1;
}

.portal_style2 {
    /*your code ...* /
    animation: animation2;
}

</style>

the js :

function change_style(){
    var obj=document.getElementById("portal2");
    obj.className=".portal_style2";

}

and you can call the change_style() function when you want without the hover event


问:
How to output stdout and stderr from an exec program script in monit
I have a python script that I use as to check certain system conditions to alert on using monit.
This script prints a buch of stuff during execution to stdout which I want to capture in a log file.
How should I configure the monit conf script, such that I can capture both the stdout and stderr of this script and at the same time alerting on the exit status of the script. The monit alert should also included the stdout/stderr for the alert events.

This is what I tried

```<code>#/etc/monit/conf/myprogram.conf

check program my_program with path "/usr/bin/python -u /opt/program/my_program.py > my_prgoram.log 2&>1"
 if status !=0 alert
</code>```

But I see that the monit always thinks that the program is reporting status=0 even when then it exists with error code 1.

What am i doing wrong?

答: $MONIT_DESCRIPTION contains stderr</p>

Body:
I have a python script that I use as to check certain system conditions to alert on using monit.
This script prints a buch of stuff during execution to stdout which I want to capture in a log file.
How should I configure the monit conf script, such that I can capture both the stdout and stderr of this script and at the same time alerting on the exit status of the script. The monit alert should also included the stdout/stderr for the alert events.

This is what I tried

#/etc/monit/conf/myprogram.conf

check program my_program with path "/usr/bin/python -u /opt/program/my_program.py > my_prgoram.log 2&>1"
 if status !=0 alert

But I see that the monit always thinks that the program is reporting status=0 even when then it exists with error code 1.

What am i doing wrong?

Body: $MONIT_DESCRIPTION contains stderr