问:
Remote persistent views with Lagom
In a classical microservice architecture, you have relevant domain events published on some messaging system which allows other parts of the system to react.

Now imagine you have three microservices: Customers, Orders and Recommendation. The Recommendation microservice needs information from Customers and Orders to provide its functionality, such as the list of all customers and all the orders, which is going to be analyzed from some machine learning algorithm. Now, you need to have the state of Customers "join" Orders on the Recommandation microservice:

You have the Recommandation microservice listen to domain events published by Customers and Orders and built its own state. This leads to logic duplication since you probably have that same logic inside Customers and Orders already

On each relevant domain message from Customers and Orders, you just go to them and ask the state of a specific customer or order. This works fine, however if you have N services rather than just one which needs to build a materialized view, you will cause a big load on Customers and Orders

You get Customers and Orders themselves publish "heavy-weight" events (not domain events) that allows any other microservice to build a materialized view without processing domain events. This allows you both a) not to duplicate the logic b) not to keep asking the same information

Has pattern n.3 some drawbacks we couldn't figure out and if not, how do you implement it in Lagom?

答:
I will try to explain a few more bits in the hope to give you some more perspective on that matter and how you can achieve it in a reliable way in Lagom.

We have a few concepts that we must keep in mind. The most important one which is the source of all is Event Sourcing itself. Event Sourcing means that any State in the system has its source in Events.

The first State that we will deal with is the State of the PersistentEntity. This State is prominent because, together with the Command and Event Handler, it defines the consistency boundary of your model.

But there other States in the system. Actually, we can create as much as we want because we have the Event Journal. A read-model is also a State and it’s also generated from the events.

There are many reasons why you shouldn’t publish the State of the PersistentEntity to other systems. The first one being a matter of avoiding coupling. You don’t want your data to leak to other services. That’s all about having an anti-corruption layer (ACL).

So, from here we could say: before publishing Order and Customer to Recommendation Service, I will transform it to OrderView and CustomerView (ACL 101).

The question now is when will you do it? If you try to publish it in Kafka after you have handled a command, you don’t have any guarantee that the State will be published. There are no XA transactions between the event journal and the Kafka topic. So, there is a chance that the events are persisted, but for some reason, the State is not published in Kafka.

If you want data to get out of a service in a reliable way and without creating coupling between services, you have the following options:

Use the broker API and publish the events to a topic. You should not publish the events as they are, but transform them into the format of your external API (ACL).
Use a read-side processor to generate a view of it, again the external API format you want to make available. If you want, you can publish that ViewState to a topic so other services can consume it directly.

That said, there is nothing wrong in publishing something in a topic that is not a real event, but some derived State. The problem is how you can guarantee that it is effectively published. Doing that from inside the PersistentEntity is risky because you have at-most-once semantics. The most reliable way of doing it is a read-side process that gives you at-least-once semantics.

Further comments inline...

Listen to domain events from customer and orders and rebuild the state
  in the recommandation service. This is a horrible idea because you
  would need to duplicate the logic that handles events across different
  bounded context

That's not a horrible idea. That's how you make your services independent from each other. The logic that you will need to implement to consume the events are not the same. As you said, it's a different bounded context, as such it only gets what it needs.

Leaking the State from a BC to another is more problematic for the reasons I mentioned above (anti-corruption layer).

To achieve decoupling you do need more coding and there is nothing wrong with that. At the end of the day, the reason for building microservices is to avoid coupling and be able to let the services evolve and scale without interfering with each other. There is a price to pay for that and the price is to write more code. You need to evaluate the thread-offs.

You can consume your own events, produce an OrderView and CustomerView and publish into Kafka, but that's the same as consuming the events directly on the Recommendation Service.

Note that you also need to store OrderView and CustomerView somewhere in the Recommendation Service. So you end up storing it three times. On the original service (view table), in Kafka and in the Recommendation Services.

That's why publishing events in a topic is the best option to propagate data between services.

Every time we receive a domain event from customers or orders, go to
  them and ask them the state. This is horrible because if you have more
  than one microservice that needs their state, you will end up
  producing load on customers and orders

That is indeed a horrible idea because you will make the Recommendation Service be dependent on the other two services. If Order or Customer is down, the Recommendation will be down as well. That's what a broker helps to solve.

Have customers and orders not only publish events but also state and
  having all the services that need to build materialized views listen
  the state they need How do you apply the last pattern with Lagom? We
  found no way to listen to state changes, just to events.  One solution
  we considered implied publishing with pubSub the state in the onEvent
  handler of a persistent entity but I am not sure this is the right
  place to make it happen.

Using pubSub in the onEvent handler is the worst solution of all. For the following reasons:

pubSub has at-most-once sematincs (see comments above)

Event handlers are called many times. Whenever you re-hydrate an Entity, the events are replayed and the the event handlers will be used for that. Which mean that you will re-publish the state each time. Actually, you would solve the at-most-once pubSub problem, but not the way you might expect/desire.

You could use the afterPersist callback for that, but that's not reliable neither because pubSub is at-most-once.

PubSub inside a PersistentEntity should not be used for something that you need to be reliable. It's a best-effort capability, that's all.

Title: Remote persistent views with Lagom


来源: stackexchange

问:
Wordpress migrated site - links and image url's not updating
hope everyone is doing well.

I’m a newbee so please excuse me.

I’ve designed a website for a client, I’ve moved the site from local to live, hosting is through Godaddy:

http://www.tangledhairstudio.co.uk

I’ve run into a few issues, some of the links on the new website are not working, I’ve been sitting in-front of my laptop trying to fix them for more than a week and to no avail.

When I hover over the tabs/ buttons that are not working I can see the url is pointing towards the WordPress local (localhost:8888/tangledhairstudio/prices), surely what I want and what it should be is http://www.tangledhairstudio/prices ????

HALF WAY DOWN THE PAGE, IN THE SERVCE “SECTION”, 3 RED TABS NAMED: “SEE ALL”

I’ve used the WordPress plugins Search & Replace, Better Search Replace, Velvet Blue as well as using sql code to search and replace to edit parts of the url’s/links. This is the exact sql code I used below:

/** update URL in posts table **/
UPDATE wp_posts SET guid = replace(guid, ‘http://localhost:8888/’,’http://www.’);

/** update URL in posts table **/
UPDATE wp_posts SET post_content = replace(post_content, ‘http://localhost:8888/’, ‘http://www.’);

/** update URL in postmeta table **/
UPDATE wp_postmeta SET meta_value = replace(meta_value,’http://localhost:8888/’,’http://www.’);

However, this worked by editing the url’s/ links in the database BUT, did nothing for the broken website links I was trying to change.

nothing seems to work whether i’ve used a plugin, snippet of code or hardcoded each and every field in the database.

ALSO, WHEN I VIEW THE WEBSITE ON MY MOBILE/ CELL, NONE OF THE IMAGES SHOW UP AND, SOME STUFF JUST SEEMS LITTLE OUT OF PLACE, I’M NOT SURE. ANY IDEAS?

please please please could I get some help and ideas how I can get this site running smoothly without any errors.

would much appreciate it,

many thanks

Leon

答:
run one more query in your live database
 and replace

```<code> UPDATE wp_options SET option_value = replace(meta_value,'http://localhost:8888/tangledhairstudio','http://www.tangledhairstudio.co.uk');
</code>```

after that you you see the widget are gone, put the content widgwets from you local you live.

hope it will help you

ContentLicense: CC BY-SA 3.0

Body:
run one more query in your live database
 and replace

 UPDATE wp_options SET option_value = replace(meta_value,'http://localhost:8888/tangledhairstudio','http://www.tangledhairstudio.co.uk');

after that you you see the widget are gone, put the content widgwets from you local you live.

hope it will help you


问:
how to fetch all the tags in particular Response array for a nested xml using groovy script for soap ui 5.3.0
I want to fetch all the values for particular array, how can we do that?

I used the below one, but it only reads the 1st parameter not the entire parameters of the array.

```<code>def ActualValue= resholder.getNodeValues("//*:Array1//*:"+context["parameter"]).toString()
</code>```

there are 10 parameters in a particular array, and after fetching value of 1st node, am getting error as "java.lang.nullpointerexception: Cannot invoke method contains () on null object"

```<code><a:Bundle>
  <a:Plans>
    <a:Quotes>
      <a:Quote>
        <a:StandardBenefits>
          <a:BenefitPeriod>
            <a:Description i:nil="true"/>
            <a:DisplayName i:nil="true"/>
            <a:Value>6 months</a:Value>
          </a:BenefitPeriod>
          <a:Coinsurance>
            <a:Description>50</a:Description>
            <a:DisplayName i:nil="true"/>
            <a:Value>50</a:Value>
          </a:Coinsurance>
          <a:OutOfPocket>
            <a:Description>5000</a:Description>
            <a:DisplayName i:nil="true"/>
            <a:Value>5000</a:Value>
          </a:OutOfPocket>
          <a:PreventiveCare i:nil="true"/>
          <a:Rx i:nil="true"/>
          <a:StopLoss>
            <a:Description i:nil="true"/>
            <a:DisplayName i:nil="true"/>
            <a:Value>10000</a:Value>
          </a:StopLoss>
        </a:StandardBenefits>
      </a:Quote>
      <a:Quote>
        //similar data like above quote
      </a:Quote>
    </a:Quotes>
  </a:Plans>
</a:Bundle>
</code>```

答:
"def ActualValue= resholder.getNodeValues("//:Array1//:"+context["parameter"])"

used the above code, for retrieving all the tag values of an array

Body:
I want to fetch all the values for particular array, how can we do that?

I used the below one, but it only reads the 1st parameter not the entire parameters of the array.

def ActualValue= resholder.getNodeValues("//*:Array1//*:"+context["parameter"]).toString()

there are 10 parameters in a particular array, and after fetching value of 1st node, am getting error as "java.lang.nullpointerexception: Cannot invoke method contains () on null object"

            6 months

            50

            50

            5000

            5000

            10000

        //similar data like above quote


问:
How to Resolve duplicate entry: com/google/gson/JsonParseException.class?
I am using android studio 3.0,no matter what i do i can't generate or build APK astonishingly it runs on emulator but build fails on real android device.

This is how the error appears when i try to build APK.

It actually works on other computers only on this system there is this issue.

答:
You must not have repeated library in your app or your dependence program
try this</p>

```<code>android {
    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
        all*.exclude group: 'com.android.support', module: 'support-annotations'
    }
}
</code>```

Body:
You must not have repeated library in your app or your dependence program
try this

android {
    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
        all*.exclude group: 'com.android.support', module: 'support-annotations'
    }
}


问:
Laravel 5.4 - send mail
i have web site make in Laravel 5.4. I have contact form and try to send mail but when send i got in mail this data

```<code>Name: {{ $name }}

Email: {{ $email }}

Message: {{ $message1 }}
</code>```

In laravel 5.1 I got the data but in Laravel 5.4 I can not pass data.

My web.php

```<code>Route::post('mailContact', 'SiteController@postEmailContact');
</code>```

My contorller:

```<code>  protected function postEmailContact() {

   Mail::send('requestContact', array(
        'name' =>Input::get("name"),
         'email' =>Input::get("email"),
          'message1' =>Input::get("message1")

    ), function ($message) {

    $message->from('myMail@gmail.com', 'Contact');

    $message->to('yourMail@gmail.com')->subject('Contact');

});
    return redirect('/');
}
</code>```

and my requestContact.blade.php

```<code> Name: {{ $name }}
 Email: {{ $email }}
 Message: {{ $message1 }}
</code>```

and contact.blade.php

```<code> {!! Form::open(array('url' => 'mailContact','class'=>'form-group')) !!}
                    <div id="content-page" class="content group">
                        <div class="hentry group">
                             <div class="usermessagea"></div>
                                            <label for="name-contact-us">
                                           Name
                                            </label>
                                            <div class="input-prepend"> {!! Form::text('name', null, array('class' => 'form-control','placeholder' => 'ime')) !!}</div>
                                            <div class="msg-error"></div>

                                            <label for="email-contact-us">
                                           Email
                                            </label>
                                           <div class="input-prepend">   {!! Form::text('name', null, array('class' => 'form-control','placeholder' => 'email')) !!}</div>
                                            <div class="msg-error"></div>

                                            <label for="message-contact-us">
                                           Message
                                            </label>
                                        <div class="input-prepend">     {!! Form::textarea('message1', null,
                    array( 'placeholder'=>'message',
                    'class'=>'form-control'
                   )) !!}</div>

                                  </br>
                                         {!! Form::submit('send' , array('class' => 'btn btn-primary')) !!}

                    </div>
                    {!! Form::close() !!}
</code>```

Any idea? How to pass data?

答:
```<code> Follow 3 step only
 1] configure in .evn file at root dir. as above
  MAIL_DRIVER=smtp
  MAIL_HOST=smtp.gmail.com
  MAIL_PORT=587
  MAIL_USERNAME=username@gmail.com
  MAIL_PASSWORD=******
  MAIL_ENCRYPTION=tls

2]create controller
  use Mail;
  class mailController extends Controller
  {
    public function send(){
       Mail::send(
          ['text' => 'post.mail'], //e.g post/mail.blade.php <view file mentioned here>
          ['name' => 'Name'],
          function($message){
              $message->to('username@gmail.com','To username');
              $message->subject('test email yagnesh');
              $message->from('username@gmail.com','from username');
          }
       );
    }
 }

AND create view file <post/mail.blade.php> set this name

3] run command at root dir. to Restart server <php artisan serve>
   And
   U can allow google less security at [https://www.google.com/settings/security/lesssecureapps][1]
   Just enabled

4] create Route
  //for send mail

       Route::get('/send','mailController@send');
  and run 'send' keyword in your url.

For more visit <https://www.youtube.com/watch?v=a08ouL3wjjQ&list=PLe30vg_FG4OQz1yZq0z19ZuWD_C3MZbA4&index=26>
Good luck!!!
</code>```

Title: Laravel 5.4 - send mail

Body:
i have web site make in Laravel 5.4. I have contact form and try to send mail but when send i got in mail this data

Name: {{ $name }}

Email: {{ $email }}

Message: {{ $message1 }}

In laravel 5.1 I got the data but in Laravel 5.4 I can not pass data.

My web.php

Route::post('mailContact', 'SiteController@postEmailContact');

My contorller:

  protected function postEmailContact() {

   Mail::send('requestContact', array(
        'name' =>Input::get("name"),
         'email' =>Input::get("email"),
          'message1' =>Input::get("message1")

    ), function ($message) {

    $message->from('myMail@gmail.com', 'Contact');

    $message->to('yourMail@gmail.com')->subject('Contact');

});
    return redirect('/');
}

and my requestContact.blade.php

 Name: {{ $name }}
 Email: {{ $email }}
 Message: {{ $message1 }}

and contact.blade.php

 {!! Form::open(array('url' => 'mailContact','class'=>'form-group')) !!}

                                           Name

 {!! Form::text('name', null, array('class' => 'form-control','placeholder' => 'ime')) !!}

                                           Email

   {!! Form::text('name', null, array('class' => 'form-control','placeholder' => 'email')) !!}

                                           Message

     {!! Form::textarea('message1', null,
                    array( 'placeholder'=>'message',
                    'class'=>'form-control'
                   )) !!}

                                         {!! Form::submit('send' , array('class' => 'btn btn-primary')) !!}

                    {!! Form::close() !!}

Any idea? How to pass data?


问:
How to create auto answering machine for Android
Is it possible to write an auto answering machine for Android? For example, when an incoming call event occurs, the application plays a voice message.

How can I do this?

答: Android applications do not have access to the in-call audio stream at this time. So, presently, your application is not possible, sorry.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Text size in dp
So I'm totally lost now I have problems with Text size ruing my UI when user sets his font size through Accessibility -> Font size to Huge so for quick fix I decided to change all text sizes to dp instead of sp that text would always be same size but on some places textviews even when textsize is set to dp resizes any idea why??

Here is button with text size set to dp which maintains font size even after changing through accessibility

```<code>    <Button
        android:id="@+id/video_button"
        android:textSize="16dp"
        android:layout_marginTop="10dp"
        android:layout_height="30dp"
        android:layout_width="180dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/webshop_button"
        android:text="@string/button_3dvideo_text"/>
</code>```

And here is textView which ignores textSize even after setting it to dp:

```<code> <TextView
        android:id="@+id/about"
        android:gravity="center"
        android:textSize="16dp"
        android:layout_above="@+id/footer"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_white"
        android:text="@string/about"/>
</code>```

答:
I have a solution for this which will make the font size non changeable in your app :

```<code> public void adjustFontScale(Configuration configuration) {
    configuration.fontScale = (float) 1;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
</code>```

Call this method in onCreate of your every Activity or you can make a Base Activity:

```<code> adjustFontScale(getResources().getConfiguration());
</code>```

You can change the fontScale according to your needs.
Hope this helps.

Title: Text size in dp

Body:
So I'm totally lost now I have problems with Text size ruing my UI when user sets his font size through Accessibility -> Font size to Huge so for quick fix I decided to change all text sizes to dp instead of sp that text would always be same size but on some places textviews even when textsize is set to dp resizes any idea why??

Here is button with text size set to dp which maintains font size even after changing through accessibility

    <Button
        android:id="@+id/video_button"
        android:textSize="16dp"
        android:layout_marginTop="10dp"
        android:layout_height="30dp"
        android:layout_width="180dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/webshop_button"
        android:text="@string/button_3dvideo_text"/>

And here is textView which ignores textSize even after setting it to dp:

 <TextView
        android:id="@+id/about"
        android:gravity="center"
        android:textSize="16dp"
        android:layout_above="@+id/footer"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/color_white"
        android:text="@string/about"/>

Body:
I have a solution for this which will make the font size non changeable in your app :

 public void adjustFontScale(Configuration configuration) {
    configuration.fontScale = (float) 1;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);
}

Call this method in onCreate of your every Activity or you can make a Base Activity:

 adjustFontScale(getResources().getConfiguration());

You can change the fontScale according to your needs.
Hope this helps.


问:
codeigniter: Send email via localhost
I have configured php.ini, sendmail.ini and also used the right port and configuration for gmail, I also enable lesssecure apps on gmail but I could see mail when i check inbox and it shows no error

Here's the controller

```<code>                   $config['protocol'] = 'smtp';
                    $config['smtp_host'] = 'ssl://smtp.googlemail.com';
// SMTP Port - the port that you is required
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $sender_password;
$this->load->library('email', $config);
$this->email->from($sender_email);
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
                    if(!$this->email->send()) {
                        show_error($this->email->print_debugger());
                    }
                    else{
                        echo 'Your email has been sent!<br/>';
                    }

                echo $message2; //send this in email
</code>```

php.ini

```<code>extension=php_openssl.dll
</code>```

sendmail.ini

```<code>smtp_server=smtp.gmail.com
smtp_port=465
auth_username= xxxx.gmail.com
auth_password= xxxx
</code>```

答:
You can use below tool to test emails on localhost. Setup is rather easy and clearly explained in the description.
Test Mail Server Tool</p>

Title: codeigniter: Send email via localhost

Body:
I have configured php.ini, sendmail.ini and also used the right port and configuration for gmail, I also enable lesssecure apps on gmail but I could see mail when i check inbox and it shows no error

Here's the controller

                   $config['protocol'] = 'smtp';
                    $config['smtp_host'] = 'ssl://smtp.googlemail.com';
// SMTP Port - the port that you is required
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $sender_password;
$this->load->library('email', $config);
$this->email->from($sender_email);
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
                    if(!$this->email->send()) {
                        show_error($this->email->print_debugger());
                    }
                    else{
                        echo 'Your email has been sent!
';
                    }

                echo $message2; //send this in email

php.ini

extension=php_openssl.dll

sendmail.ini

smtp_server=smtp.gmail.com
smtp_port=465
auth_username= xxxx.gmail.com
auth_password= xxxx


问:
PowerDNS Scripting - Getting the DNS Query's Unique ID
I'm writing lua scripts for PowerDNS.

I wish to get some kind of a unique ID for each DNS query when my script intercepts a DNS query.

I'm intercepting the DNS queries with the "preresolve" and "postresolve" functions and they don't have any unique ID that will symbolize the current DNS query it's handling.

I saw that when using the function "ipfilter", I can use the GetID() function to get the DNS query ID.
This ability is missing in the "preresolve" and "postresolve" functions.

Any ideas?

答:
After upgrading from PDNS Recursor version 3.0 to 4.0 I found my answer.

In version 4, 'preresolve' and 'postresolve' functions get the dq (DNSQuestion) object,
the dq object contains two fields that can help with the query ID.

One, you can use the original query ID by getting the value from

```<code>dq:getDH():getID()
</code>```

Two, dq can contain a custom LUA object reference that is persistent throughout the lifetime of the dq object.

```<code>local data={}
data["domaindetails"]= dq.udpAnswer
dq.data=data
</code>```

Find more details in their Scripting manual:
https://doc.powerdns.com/md/recursor/scripting/#the-dnsquestion-dq-object

Body:
After upgrading from PDNS Recursor version 3.0 to 4.0 I found my answer.

In version 4, 'preresolve' and 'postresolve' functions get the dq (DNSQuestion) object,
the dq object contains two fields that can help with the query ID.

One, you can use the original query ID by getting the value from

dq:getDH():getID()

Two, dq can contain a custom LUA object reference that is persistent throughout the lifetime of the dq object.

local data={}
data["domaindetails"]= dq.udpAnswer
dq.data=data

Find more details in their Scripting manual:
https://doc.powerdns.com/md/recursor/scripting/#the-dnsquestion-dq-object


问:
How to convert Json to CSV in php
Hi I am trying to convert a json file with differrent array structure than the normal one into csv file. I had been trying to find out a solution to convert it into a csv file but I cant find the solution.

```<code>  <?php
    $jsondata = '[{
        "accession_number_original": "2012.11.45",
        "author_birth_date": [
          "1932"
        ],
        "author_date": [
          "1932"
        ],
        "author_death_date": [
          ""
        ],
        "author_description": [
          "American"
        ],
        "author_display": [
          "Day yon"
        ],
        "author_names_first": [
          "Day"
        ],
        "author_names_last": [
          "yon"
        ],
        "author_names_middle": [
          ""
        ],
        "image_height": "12 1/2",
        "image_width": "18 1/4",
        "jp2_image_url": "",
        "location_physical_location": "Art Gallery",
        "location_shelf_locator": "Unknown",
        "master_image_url": "",
        "note_provenance": "Gift of Gary Ginsberg and Susanna Aaron",
        "object_date": "1963/2010",
        "object_depth": "",
        "object_height": "",
        "object_width": "",
        "origin_datecreated_end": "1963",
        "origin_datecreated_start": "1963",
        "physical_description_extent": [
          "12 1/2 x 18 1/4"
        ],
        "physical_description_material": [
          "Gelatin silver print"
        ],
        "physical_description_technique": [
          "Gelatin silver print"
        ],
        "pid": "bdr:123456",
        "title": "As Demonstrators"
      }]';

    $jsonDecoded = json_decode($jsondata);
    print_r('```');
    print_r($jsonDecoded);
    print_r('```');
    $fh = fopen('fileout.csv', 'w');
    if (is_array($jsonDecoded)){
      print_r('<-------- line variable output-------->');
      foreach($jsonDecoded as $line){
            print_r('```'); print_r($line); print_r('```');
        print_r('<-------- data variable output-------->');
        if (is_array($line)||is_object($line)){
          foreach($line as $data){
            fputcsv($fp,$data);
            }
          }
        }
      }
    }

   fclose($fh);
   print_r('Converted Successfully');
?>
</code>```

I tried looking into most of the similar questions in the stackoverflow but none has a array of my kind so they are not much useful to me.

If I use single foreach I am getting error Array to String Conversion failed and Array is being printed as value instead of actual data into the csv file.

If I use two foreach I am getting error fputcsv() expects parameter 2 to be array string given

var_dump or print_r result of decoded json is as follows

```<code>Array
(
[0] => stdClass Object
    (
        [accession_number_original] => 2012.11.45
        [author_birth_date] => Array
            (
                [0] => 1932
            )

        [author_date] => Array
            (
                [0] => 1932
            )

        [author_death_date] => Array
            (
                [0] =>
            )

        [author_description] => Array
            (
                [0] => American
            )

        [author_display] => Array
            (
                [0] => Day yon
            )

        [author_names_first] => Array
            (
                [0] => Day
            )

        [author_names_last] => Array
            (
                [0] => yon
            )

        [author_names_middle] => Array
            (
                [0] =>
            )

        [image_height] => 12 1/2
        [image_width] => 18 1/4
        [jp2_image_url] =>
        [location_physical_location] => Art Gallery
        [location_shelf_locator] => Unknown
        [master_image_url] =>
        [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
        [object_date] => 1963/2010
        [object_depth] =>
        [object_height] =>
        [object_width] =>
        [origin_datecreated_end] => 1963
        [origin_datecreated_start] => 1963
        [physical_description_extent] => Array
            (
                [0] => 12 1/2 x 18 1/4
            )

        [physical_description_material] => Array
            (
                [0] => Gelatin silver print
            )

        [physical_description_technique] => Array
            (
                [0] => Gelatin silver print
            )

        [pid] => bdr:123456
        [title] => As Demonstrators
    )
)
</code>```

答:
As I mentioned in the comment, first step would be to take care of array values, so each line needs to have values converted (it only counts with the format you provided, if there is an array with 2 values, only first will be passed to csv).

Your modified source code:

```<code>$jsonDecoded = json_decode($jsondata, true); // add true, will handle as associative array
print_r('```');
print_r($jsonDecoded);
print_r('```');
$fh = fopen('fileout.csv', 'w');
if (is_array($jsonDecoded)) {
  print_r('<-------- line variable output-------->');
  foreach ($jsonDecoded as $line) {
    // with this foreach, if value is array, replace it with first array value
    foreach ($line as $key => $value) {
        if (is_array($value)) {
            $line[$key] = $value[0];
        }
    }
    print_r('```'); print_r($line); print_r('```');
    // no need for foreach, as fputcsv expects array, which we already have
    if (is_array($line)) {
      fputcsv($fh,$line);
    }
  }
}
fclose($fh);
print_r('Converted Successfully');
</code>```

Script output after execution:

```<code>[output of your print_r($jsonDecoded);]

<-------- line variable output-------->

Array
(
    [accession_number_original] => 2012.11.45
    [author_birth_date] => 1932
    [author_date] => 1932
    [author_death_date] =>
    [author_description] => American
    [author_display] => Day yon
    [author_names_first] => Day
    [author_names_last] => yon
    [author_names_middle] =>
    [image_height] => 12 1/2
    [image_width] => 18 1/4
    [jp2_image_url] =>
    [location_physical_location] => Art Gallery
    [location_shelf_locator] => Unknown
    [master_image_url] =>
    [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
    [object_date] => 1963/2010
    [object_depth] =>
    [object_height] =>
    [object_width] =>
    [origin_datecreated_end] => 1963
    [origin_datecreated_start] => 1963
    [physical_description_extent] => 12 1/2 x 18 1/4
    [physical_description_material] => Gelatin silver print
    [physical_description_technique] => Gelatin silver print
    [pid] => bdr:123456
    [title] => As Demonstrators
)

Converted Successfully
</code>```

Title: How to convert Json to CSV in php

Body:
Hi I am trying to convert a json file with differrent array structure than the normal one into csv file. I had been trying to find out a solution to convert it into a csv file but I cant find the solution.

  <?php
    $jsondata = '[{
        "accession_number_original": "2012.11.45",
        "author_birth_date": [
          "1932"
        ],
        "author_date": [
          "1932"
        ],
        "author_death_date": [
          ""
        ],
        "author_description": [
          "American"
        ],
        "author_display": [
          "Day yon"
        ],
        "author_names_first": [
          "Day"
        ],
        "author_names_last": [
          "yon"
        ],
        "author_names_middle": [
          ""
        ],
        "image_height": "12 1/2",
        "image_width": "18 1/4",
        "jp2_image_url": "",
        "location_physical_location": "Art Gallery",
        "location_shelf_locator": "Unknown",
        "master_image_url": "",
        "note_provenance": "Gift of Gary Ginsberg and Susanna Aaron",
        "object_date": "1963/2010",
        "object_depth": "",
        "object_height": "",
        "object_width": "",
        "origin_datecreated_end": "1963",
        "origin_datecreated_start": "1963",
        "physical_description_extent": [
          "12 1/2 x 18 1/4"
        ],
        "physical_description_material": [
          "Gelatin silver print"
        ],
        "physical_description_technique": [
          "Gelatin silver print"
        ],
        "pid": "bdr:123456",
        "title": "As Demonstrators"
      }]';

    $jsonDecoded = json_decode($jsondata);
    print_r('
');
    print_r($jsonDecoded);
    print_r('
');
    $fh = fopen('fileout.csv', 'w');
    if (is_array($jsonDecoded)){
      print_r('<-------- line variable output-------->');
      foreach($jsonDecoded as $line){
            print_r('
'); print_r($line); print_r('
');
        print_r('<-------- data variable output-------->');
        if (is_array($line)||is_object($line)){
          foreach($line as $data){
            fputcsv($fp,$data);
            }
          }
        }
      }
    }

   fclose($fh);
   print_r('Converted Successfully');
?>

I tried looking into most of the similar questions in the stackoverflow but none has a array of my kind so they are not much useful to me.

If I use single foreach I am getting error Array to String Conversion failed and Array is being printed as value instead of actual data into the csv file.

If I use two foreach I am getting error fputcsv() expects parameter 2 to be array string given

var_dump or print_r result of decoded json is as follows

Array
(
[0] => stdClass Object
    (
        [accession_number_original] => 2012.11.45
        [author_birth_date] => Array
            (
                [0] => 1932
            )

        [author_date] => Array
            (
                [0] => 1932
            )

        [author_death_date] => Array
            (
                [0] =>
            )

        [author_description] => Array
            (
                [0] => American
            )

        [author_display] => Array
            (
                [0] => Day yon
            )

        [author_names_first] => Array
            (
                [0] => Day
            )

        [author_names_last] => Array
            (
                [0] => yon
            )

        [author_names_middle] => Array
            (
                [0] =>
            )

        [image_height] => 12 1/2
        [image_width] => 18 1/4
        [jp2_image_url] =>
        [location_physical_location] => Art Gallery
        [location_shelf_locator] => Unknown
        [master_image_url] =>
        [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
        [object_date] => 1963/2010
        [object_depth] =>
        [object_height] =>
        [object_width] =>
        [origin_datecreated_end] => 1963
        [origin_datecreated_start] => 1963
        [physical_description_extent] => Array
            (
                [0] => 12 1/2 x 18 1/4
            )

        [physical_description_material] => Array
            (
                [0] => Gelatin silver print
            )

        [physical_description_technique] => Array
            (
                [0] => Gelatin silver print
            )

        [pid] => bdr:123456
        [title] => As Demonstrators
    )
)

Body:
As I mentioned in the comment, first step would be to take care of array values, so each line needs to have values converted (it only counts with the format you provided, if there is an array with 2 values, only first will be passed to csv).

Your modified source code:

$jsonDecoded = json_decode($jsondata, true); // add true, will handle as associative array
print_r('<pre>');
print_r($jsonDecoded);
print_r('</pre>');
$fh = fopen('fileout.csv', 'w');
if (is_array($jsonDecoded)) {
  print_r('<-------- line variable output-------->');
  foreach ($jsonDecoded as $line) {
    // with this foreach, if value is array, replace it with first array value
    foreach ($line as $key => $value) {
        if (is_array($value)) {
            $line[$key] = $value[0];
        }
    }
    print_r('<pre>'); print_r($line); print_r('</pre>');
    // no need for foreach, as fputcsv expects array, which we already have
    if (is_array($line)) {
      fputcsv($fh,$line);
    }
  }
}
fclose($fh);
print_r('Converted Successfully');

Script output after execution:

[output of your print_r($jsonDecoded);]

<-------- line variable output-------->

Array
(
    [accession_number_original] => 2012.11.45
    [author_birth_date] => 1932
    [author_date] => 1932
    [author_death_date] =>
    [author_description] => American
    [author_display] => Day yon
    [author_names_first] => Day
    [author_names_last] => yon
    [author_names_middle] =>
    [image_height] => 12 1/2
    [image_width] => 18 1/4
    [jp2_image_url] =>
    [location_physical_location] => Art Gallery
    [location_shelf_locator] => Unknown
    [master_image_url] =>
    [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
    [object_date] => 1963/2010
    [object_depth] =>
    [object_height] =>
    [object_width] =>
    [origin_datecreated_end] => 1963
    [origin_datecreated_start] => 1963
    [physical_description_extent] => 12 1/2 x 18 1/4
    [physical_description_material] => Gelatin silver print
    [physical_description_technique] => Gelatin silver print
    [pid] => bdr:123456
    [title] => As Demonstrators
)

Converted Successfully


问:
Changing xml-file using Ant
How to change existing xml-file using Ant.
For example:

```<code><test attr="0">
    ...
</test>
</code>```

to

```<code><test attr="1">
...
</test>
</code>```

答:
Use xmltask see <attr> section in particular), eg:

```<code><attr path="//test[@attr='0']/" attr="attr" value="1"/>
</code>```

Title: Changing xml-file using Ant

Body:
How to change existing xml-file using Ant.
For example:

<test attr="0">
    ...
</test>

to

<test attr="1">
...
</test>

Body:
Use xmltask see <attr> section in particular), eg:

<attr path="//test[@attr='0']/" attr="attr" value="1"/>


问:
Removing Java 8 JDK from Mac
So I installed the beta of JDK 8 a while ago to look at some of the examples. I thought for sure by now, it's easy to change between versions.

Doing some Play development with IntelliJ. For some reason, IntelliJ is compiling with 8 even though:

I have the compiler set in Preferences to use 1.6

Supposedly it's using SBT through external build, but sbt from the command line works

JAVA_HOME is pointing to JDK 6.

If I go to the Java Preferences page, it does show 8 installed, but there is no option to uninstall it and it doesn't see any of the other versions.

When I do which java, it tells me /usr/bin/java and I do /usr/bin/java -version and it returns 1.6.

Note: with a  little fiddling, you can use IntelliJ and JDK7, see here.

答:
To uninstall java of any version on mac just do: </p>

```<code>sudo rm -fr /Library/Java/JavaVirtualMachines/jdk-YOUR_ACCURATE_VERSION.jdk/
sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane
</code>```

Title: Removing Java 8 JDK from Mac

Body:
To uninstall java of any version on mac just do:

sudo rm -fr /Library/Java/JavaVirtualMachines/jdk-YOUR_ACCURATE_VERSION.jdk/
sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane


问:
Distinct count of users grouped by a column and distributed across bins
I have several users that each have a department they belong to and a integer which denotes (in days) when they last logged in.
A user can have several departments.

I am trying to group the users by department, vertically distribute them across three bins depending on when they logged in, and then uniquely count them.
If a user belongs to several departments i only want to count them once, it dosen't matter under which department they are being counted.

In my current solution a user with several departments gets counted once for
each department, which, given my solution, makes sense, but is not what I want.
If i try a distinct count it returns the same as each row is unique.

I'm using the MsSql Fiddle example except that I have added a DaysSinceLastLogin (int) column that denotes when the user last logged in.
Uncomment the first sql block to see the 6 users and which departments they belong to.
Fiddle here

答:
If it doesn't matter under which department they will be counted you can change the department inside of an CTE and the use your query:

```<code>;WITH CTE AS (
SELECT DISTINCT
  [User]
  ,CASE WHEN
    department = (SELECT top 1 department FROM yourtable y WHERE [User] = t.[User]) THEN department
    ELSE (SELECT top 1 department FROM yourtable y WHERE [User] = t.[User])
  END AS department
  ,[DaysSinceLastLogin]
FROM yourtable t
)
select Department,
COUNT(case when DaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
COUNT(case when DaysSinceLastLogin > 10 and  DaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
COUNT(case when DaysSinceLastLogin > 20  then 1 end) 'Last Login more then 20 days'
FROM CTE
GROUP BY Department
</code>```

Also HERE

Body:
If it doesn't matter under which department they will be counted you can change the department inside of an CTE and the use your query:

;WITH CTE AS (
SELECT DISTINCT
  [User]
  ,CASE WHEN
    department = (SELECT top 1 department FROM yourtable y WHERE [User] = t.[User]) THEN department
    ELSE (SELECT top 1 department FROM yourtable y WHERE [User] = t.[User])
  END AS department
  ,[DaysSinceLastLogin]
FROM yourtable t
)
select Department,
COUNT(case when DaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
COUNT(case when DaysSinceLastLogin > 10 and  DaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
COUNT(case when DaysSinceLastLogin > 20  then 1 end) 'Last Login more then 20 days'
FROM CTE
GROUP BY Department

Also HERE


问:
Traceback error while running python script
I am trying to run this script

```<code>import requests
from bs4 import BeautifulSoup

url = 'http://www.showmeboone.com/sheriff/JailResidents/JailResidents.asp'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
table = soup.find('tbody', attrs={'class': 'stripe'})
for row in table.findAll('tr'):
print (row.prettify())
</code>```

I am getting this error:

```<code>Traceback (most recent call last)
File: "C:\Users\s\Appdata\Local\Programs\Python\Python36-32\lib\site-
packages\urllib3\connection.py", line 141, in _new_conn
</code>```

答:
I tried your piece of code. Look at the complete traceback. It says timeout error. The url used by you is not responding.

Also change

```<code>soup = BeautifulSoup(html)
</code>```

to

```<code>soup = BeautifulSoup(html, 'html.parser')
</code>```

Body:
I am trying to run this script

import requests
from bs4 import BeautifulSoup

url = 'http://www.showmeboone.com/sheriff/JailResidents/JailResidents.asp'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
table = soup.find('tbody', attrs={'class': 'stripe'})
for row in table.findAll('tr'):
print (row.prettify())

I am getting this error:

Traceback (most recent call last)
File: "C:\Users\s\Appdata\Local\Programs\Python\Python36-32\lib\site-
packages\urllib3\connection.py", line 141, in _new_conn

Body:
I tried your piece of code. Look at the complete traceback. It says timeout error. The url used by you is not responding.

Also change

soup = BeautifulSoup(html)

to

soup = BeautifulSoup(html, 'html.parser')


问:
Jquery-confirm and passing POST variables to an externally loaded form
Is there a way to send POST variables to an external PHP form?
I'd like to pass, in this example, XXX and YYY using POST (not GET).
I'm using this plugin: https://github.com/craftpip/jquery-confirm

```<code><a id="btn" data-value1="XXX" data-value2="YYY">CLICK ME</a>

<script>
  $('#btn').on('click', function (e) {
   e.preventDefault();
   $.confirm({
   title: 'Title',
   content: 'url:form.php',
   buttons: {
      ......
   }
});
});
</code>```

form.php:

```<code><?php
 $value1 = $_POST['value1'];
 $value2 = $_POST['value2'];
?>
<div class="form-group">
    <label class="control-label">Default values from parent page:</label>
    <input type="text" id="value1" class="form-control" value="<?php echo $value1; ?>">
    <input type="text" id="value2" class="form-control" value="<?php echo $value2; ?>">
</div>
</code>```

UPDATE: tried this also, without success. Form doesn't load in modal:

```<code>content: function() {
        var self = this;
            return $.ajax({
              url: 'form.php',
              dataType: 'json',
              async: false,
              method: 'post',
              data: { 'value1': 'XXX', 'value2': 'YYY' }
            }).done(function (response) {
                self.setContent(response);
            });
}
</code>```

答:
You simply need to specify

```<code>dataType: 'html'
</code>```

instead of

```<code>dataType: 'json'
</code>```

This is because form.php returns a HTML string, not a JSON object. You likely have an error in your console complaining that jQuery cannot parse the response as JSON, because it isn't JSON. If you tell jQuery to expect HTML instead, it will pass the reponse through as a string instead which you can directly display on screen, without trying to turn it into an object.

Body:
Is there a way to send POST variables to an external PHP form?
I'd like to pass, in this example, XXX and YYY using POST (not GET).
I'm using this plugin: https://github.com/craftpip/jquery-confirm

CLICK ME

Body:
You simply need to specify

dataType: 'html'

instead of

dataType: 'json'

This is because form.php returns a HTML string, not a JSON object. You likely have an error in your console complaining that jQuery cannot parse the response as JSON, because it isn't JSON. If you tell jQuery to expect HTML instead, it will pass the reponse through as a string instead which you can directly display on screen, without trying to turn it into an object.


问:
Django: Testing redirections when the target URL is also a redirection
So I'm programming a site divided in sections, which are themselves divided in subsections. In my setup, when a user clicks on the link to a section (let's say for instance '/home'), they are redirected to one of its subsections (e.g. '/home/cover'). Additionally, when a user goes to the page root, they are redirected to one of the sections (in my case '/home'). With that setup, what happens when someone goes to the root, is that they are first redirected to '/home', and from there to '/home/cover'. Those redirections are implemented like this:

Main urls.py:

```<code>from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='/home')),
    url(r'^home/', include('components.home.urls', namespace='components.home')),
    ...
)
</code>```

components/home/urls.py:

```<code>from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView

from components.home import views

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='cover')),
    url(r'^cover$', views.cover, name='home_cover'),
    ...
)
</code>```

In practice, this seems to work fine: I can navigate my site and all the redirections do what they should. However, I can't figure out how to implement my unit tests for them, and in particular for the root redirection.

The test I designed originally was like:

```<code>def test_root_url_redirects_to_home_url(self):
    response = self.client.get('/')
    self.assertRedirects(response, '/home', status_code=301)
</code>```

However, when I run it, I'm faced with the error:

```<code>"AssertionError: 301 != 200 : Couldn't retrieve redirection page '/home':
response code was 301 (expected 200)."
</code>```

Now, I could easily remove all double redirections and make every redirected URL point directly to its target, but the current configuration feels cleaner and easier to maintain, so if there is some way I can properly test it that would be perfect.

I'm very new to Django and web development in general, so I'm sorry if I'm missing an obvious answer here.

答:
By default Django's assertRedirects fetches the status code of the page and tests that it's OK. You can disable this by setting fetch_redirect_response=False:

```<code>self.assertRedirects(response, reverse('app:login'), fetch_redirect_response=False)
</code>```

Body:
So I'm programming a site divided in sections, which are themselves divided in subsections. In my setup, when a user clicks on the link to a section (let's say for instance '/home'), they are redirected to one of its subsections (e.g. '/home/cover'). Additionally, when a user goes to the page root, they are redirected to one of the sections (in my case '/home'). With that setup, what happens when someone goes to the root, is that they are first redirected to '/home', and from there to '/home/cover'. Those redirections are implemented like this:

Main urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='/home')),
    url(r'^home/', include('components.home.urls', namespace='components.home')),
    ...
)

components/home/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView

from components.home import views

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='cover')),
    url(r'^cover$', views.cover, name='home_cover'),
    ...
)

In practice, this seems to work fine: I can navigate my site and all the redirections do what they should. However, I can't figure out how to implement my unit tests for them, and in particular for the root redirection.

The test I designed originally was like:

def test_root_url_redirects_to_home_url(self):
    response = self.client.get('/')
    self.assertRedirects(response, '/home', status_code=301)

However, when I run it, I'm faced with the error:

"AssertionError: 301 != 200 : Couldn't retrieve redirection page '/home':
response code was 301 (expected 200)."

Now, I could easily remove all double redirections and make every redirected URL point directly to its target, but the current configuration feels cleaner and easier to maintain, so if there is some way I can properly test it that would be perfect.

I'm very new to Django and web development in general, so I'm sorry if I'm missing an obvious answer here.

Body:
By default Django's assertRedirects fetches the status code of the page and tests that it's OK. You can disable this by setting fetch_redirect_response=False:

self.assertRedirects(response, reverse('app:login'), fetch_redirect_response=False)


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

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

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

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

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
Could it be because it cant find the controller ? If yes, may you try this using @ComponentScan ? @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers. </p>

```<code>@SpringBootApplication
@ComponentScan(basePackageClasses = TestController.class)
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {
//Your code here
}
</code>```

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

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

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

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

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

Body:
Could it be because it cant find the controller ? If yes, may you try this using @ComponentScan ? @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

@SpringBootApplication
@ComponentScan(basePackageClasses = TestController.class)
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {
//Your code here
}


问:
React remote request with authorization
I want to do a remote request using React JS. I try to do it as follows:

```<code>let username = 'some-username';
let password = 'some-password';
let url = 'some-url';
fetch(url', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic '+btoa(username + ":" + password),
    },
}).then(response => {
      debugger;
      return response.json();
}).then(json => {
      debugger;
});
</code>```

I get an error:

If I do the same request with the same credentials with postman it works:

Any idea?

UPDATE

```<code>let user = 'some-user';
let password = 'some-password';
let url = 'some-url';

let req = new XMLHttpRequest();
let body = '';

if ('withCredentials' in req) {
    req.open('GET', url, true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.setRequestHeader('Authorization', 'Basic '+ btoa(user + ":" + password));
    req.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    req.onreadystatechange = () => {
        debugger;
        if (req.readyState === 4) {
            ///////////////// it comes here but req.status is 0
            if (req.status >= 200 && req.status < 400) {
                debugger;
                // JSON.parse(req.responseText) etc.
            } else {
                // Handle error case
            }
        }
    };
    req.send(body);
}
</code>```

This is what I see in network tab:

答:
You are having CORS problems. This is why it's working with Postman, it skips that check (OPTIONS call to the same request instead the GET one) and your React App (or any Javascript Ajax call ) fails, because your browser is checking it before launch the request..

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

This post shows how to deal with CORS
https://www.eriwen.com/javascript/how-to-cors/

Title: React remote request with authorization

Body:
I want to do a remote request using React JS. I try to do it as follows:

let username = 'some-username';
let password = 'some-password';
let url = 'some-url';
fetch(url', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic '+btoa(username + ":" + password),
    },
}).then(response => {
      debugger;
      return response.json();
}).then(json => {
      debugger;
});

I get an error:

If I do the same request with the same credentials with postman it works:

Any idea?

UPDATE

let user = 'some-user';
let password = 'some-password';
let url = 'some-url';

let req = new XMLHttpRequest();
let body = '';

if ('withCredentials' in req) {
    req.open('GET', url, true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.setRequestHeader('Authorization', 'Basic '+ btoa(user + ":" + password));
    req.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    req.onreadystatechange = () => {
        debugger;
        if (req.readyState === 4) {
            ///////////////// it comes here but req.status is 0
            if (req.status >= 200 && req.status < 400) {
                debugger;
                // JSON.parse(req.responseText) etc.
            } else {
                // Handle error case
            }
        }
    };
    req.send(body);
}

This is what I see in network tab:


问:
Eclipse 4.7.1a - open file in editor from code/programatically
I want to add capability to my eclipse plug-in to open specified file in new Eclipse editor. I found solution based on org.eclipse.ui.ide.IDE and import org.eclipse.core.filesystem.EFS:

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}
```

Unfortunately, that solution is no longer supported in 4th versions of Eclipse and only works with older IDEs.

Is there any possibility to open editor on specified file programatically in Eclipse 4.x.x or make workaround/deal with compatibility?

答: Solution was quite trivial - when I wanted to import earlier listed classes, Eclipse didn't recognize those imports, so at the first time I thought it is not compatible at all. I make one more research, to find Fix project setup... option in quick fix menu. That option just added required dependencies to my feature project, so now they are visible, and there is no more errors.

Body:
I want to add capability to my eclipse plug-in to open specified file in new Eclipse editor. I found solution based on org.eclipse.ui.ide.IDE and import org.eclipse.core.filesystem.EFS:

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}

Unfortunately, that solution is no longer supported in 4th versions of Eclipse and only works with older IDEs.

Is there any possibility to open editor on specified file programatically in Eclipse 4.x.x or make workaround/deal with compatibility?


问:
Detecting word between specific words with PHP
for example,

```<code><form method="post">
    <textarea name="content" id="editor"></textarea>
    <input type="submit" value="submit" name="alltext">
<form>
</code>```

Then I type: Humans have ==brain== and it helps them learn things.
After that, I want this thing to find the word between == and ==.

```<code>$all_text = $_POST["alltext"];
if (a word is between '==' and '==') {
    $special_word = the word between '==' and '==';
} else {
    do nothing
}
</code>```

and the output I desire is the variable $special_word is set to brain.

It is more like stackoverflow.com where words between # and # is heading 1 and words between ## and ## is heading 2.

Please help me solve this puzzle.

答:
You can use this Regex to match the string, then you can simply extract it and put it into a variable.

Here is the regex:

```<code>/\w+/
</code>```

You can use PHP regex function to match or extract from strings.

Here is the reference to PHP regex functions:

PHP PCRE functions

P.S: preg_match() should do well here in your scenario.

P.S: If you are trying to extract the word brain form a sentence you should use regex like this:

```<code>/==(.*?)==/
</code>```

Body:
for example,

<form method="post">
    <textarea name="content" id="editor"></textarea>
    <input type="submit" value="submit" name="alltext">
<form>

Then I type: Humans have ==brain== and it helps them learn things.
After that, I want this thing to find the word between == and ==.

$all_text = $_POST["alltext"];
if (a word is between '==' and '==') {
    $special_word = the word between '==' and '==';
} else {
    do nothing
}

and the output I desire is the variable $special_word is set to brain.

It is more like stackoverflow.com where words between # and # is heading 1 and words between ## and ## is heading 2.

Please help me solve this puzzle.

Body:
You can use this Regex to match the string, then you can simply extract it and put it into a variable.

Here is the regex:

/\w+/

You can use PHP regex function to match or extract from strings.

Here is the reference to PHP regex functions:

PHP PCRE functions

P.S: preg_match() should do well here in your scenario.

P.S: If you are trying to extract the word brain form a sentence you should use regex like this:

/==(.*?)==/


问:
Call function from activity to close the soft keyboard android
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

```<code>public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

```<code>    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();
</code>```

答:
I managed to find a simple solution that works for me:

http://discuss.appium.io/t/can-we-hide-android-soft-keyboard/6956/4

I just added in these 2 capabilities:

```<code>capabilities.setCapability("unicodeKeyboard", true);
capabilities.setCapability("resetKeyboard", true);
</code>```

Body:
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();

Body:
I managed to find a simple solution that works for me:

http://discuss.appium.io/t/can-we-hide-android-soft-keyboard/6956/4

I just added in these 2 capabilities:

capabilities.setCapability("unicodeKeyboard", true);
capabilities.setCapability("resetKeyboard", true);


问:
http connection timeout issues
I'm running into an issue when i try to use the HttpClient connecting
to a url. The http connection is taking a longer time to timeout, even after i set
a connection timeoout.

```<code>int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
</code>```

It works perfect most of the time. However, every once in while, the http  connection runs for ever and ignore the setconnectiontimeout, especailly when the phone is connected to wifi, and the phone was idling.

So after the phone is idling, the first time i try to connect, the http connection ignores the setconnectiontimeout and runs forever, after i cancel it and try again, it works like charm everytime. But that one time that doesn't work it creates a threadtimeout error, i tried using a different thread, it works, but i know that the thread is running for long time.

I understand that the wifi goes to sleep on idle, but i dont understand why its ignoring the setconnectiontimeout.

Anyone can help, id really appreciated.

答: Although I haven't seen this on the Android platform, I've seen similar things on other platforms and the solution in these cases is to manage the timeout yourself. Kick off another thread (the timeout thread) when your make your request. The timeout thread counts down the requisite time. If the timeout expires before you receive any data, the timeout thread cancels the original request and you retry with a new request. Harder to code, but at least you know it will work.</p>

Title: http connection timeout issues

Body:
I'm running into an issue when i try to use the HttpClient connecting
to a url. The http connection is taking a longer time to timeout, even after i set
a connection timeoout.

int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

It works perfect most of the time. However, every once in while, the http  connection runs for ever and ignore the setconnectiontimeout, especailly when the phone is connected to wifi, and the phone was idling.

So after the phone is idling, the first time i try to connect, the http connection ignores the setconnectiontimeout and runs forever, after i cancel it and try again, it works like charm everytime. But that one time that doesn't work it creates a threadtimeout error, i tried using a different thread, it works, but i know that the thread is running for long time.

I understand that the wifi goes to sleep on idle, but i dont understand why its ignoring the setconnectiontimeout.

Anyone can help, id really appreciated.


问:
Find a phrase in defined list with a file
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

```<code>fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")
</code>```

and when I execute it, I get the following

```<code>Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list
</code>```

答:
You could also join the terms in my to a regular expression like \b(cbs is down|abnormal)\b and use re.findall or re.search to find the terms. This way, you can also enclose the pattern in word-boundaries \b...\b so it does not match parts of longer words, and you also see which term was matched, and where.

```<code>>>> import re
>>> my = ['cbs is down', 'abnormal']
>>> line = "notacbs is downright abnormal"
>>> p = re.compile(r"\b(" + "|".join(map(re.escape, my)) + r")\b")
>>> p.findall(line)
['abnormal']
>>> p.search(line).span()
(21, 29)
</code>```

Body:
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")

and when I execute it, I get the following

Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list

Body:
You could also join the terms in my to a regular expression like \b(cbs is down|abnormal)\b and use re.findall or re.search to find the terms. This way, you can also enclose the pattern in word-boundaries \b...\b so it does not match parts of longer words, and you also see which term was matched, and where.

>>> import re
>>> my = ['cbs is down', 'abnormal']
>>> line = "notacbs is downright abnormal"
>>> p = re.compile(r"\b(" + "|".join(map(re.escape, my)) + r")\b")
>>> p.findall(line)
['abnormal']
>>> p.search(line).span()
(21, 29)


问:
how to set target printer in PrinterJob in javafx
I have a situation that need to print order bill in cash counter and packing area(warehouse ).

Technically, how to print javafx.print.PrinterJob by saying printer name.

1) Sample print

```<code>public static void PrintSample() {
    Label lbl = new Label("This is sample \n\n\n\n\n\nprint");
    PrinterJob job = PrinterJob.createPrinterJob();
    if (job != null  ) {

        boolean success = job.printPage(lbl);
        if (success) {
            job.endJob();
        }
    }
}
</code>```

2) Get list of printers

```<code>public static void GetListOfPrinters() {
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
    System.out.println("Number of print services: " + printServices.length);

    for (PrintService printer : printServices) {
        System.out.println("Printer: " + printer.getName());
    }

}
</code>```

答:
PrinterJob job = PrinterJob.createPrinterJob(myPrinter);
this line is not working give error The method createPrinterJob(Printer) is undefined for the type PrinterJob</p>

Body:
I have a situation that need to print order bill in cash counter and packing area(warehouse ).

Technically, how to print javafx.print.PrinterJob by saying printer name.

1) Sample print

public static void PrintSample() {
    Label lbl = new Label("This is sample \n\n\n\n\n\nprint");
    PrinterJob job = PrinterJob.createPrinterJob();
    if (job != null  ) {

        boolean success = job.printPage(lbl);
        if (success) {
            job.endJob();
        }
    }
}

2) Get list of printers

public static void GetListOfPrinters() {
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
    System.out.println("Number of print services: " + printServices.length);

    for (PrintService printer : printServices) {
        System.out.println("Printer: " + printer.getName());
    }

}


问:
Angular 2 app on Apache server
I have an angular 2 app served on Angular 2. On the host, it is located at the document root and everything is working fine. I have an .htaccess file with:

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

Problem:
On my laptop, i have an Apache server (xampp) with document root as "
c:\users...\WebProjects

When i develop the site, i put the files in c:\users...\Projects\Projects1\dist
In this directory, i cannot get the website to work due to files/folders called not being in the root. ie Server is trying to load \css\app.css when it should be loading Projects1\dist\css\app.css

Can i write a specific .htaccess to be able to serve the app from that directory? (or something else without having to change the httpd.conf document root?)

thanks

答:
you need to add the path in your .htaccess file and your index.html file like so:

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

In index.html, you need to update the base href aswell to reflect the path like so:

<base href="/your/path/here/">

And that should do the trick :)

Title: Angular 2 app on Apache server

Body:
I have an angular 2 app served on Angular 2. On the host, it is located at the document root and everything is working fine. I have an .htaccess file with:

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

Problem:
On my laptop, i have an Apache server (xampp) with document root as "
c:\users...\WebProjects

When i develop the site, i put the files in c:\users...\Projects\Projects1\dist
In this directory, i cannot get the website to work due to files/folders called not being in the root. ie Server is trying to load \css\app.css when it should be loading Projects1\dist\css\app.css

Can i write a specific .htaccess to be able to serve the app from that directory? (or something else without having to change the httpd.conf document root?)

thanks

Body:
you need to add the path in your .htaccess file and your index.html file like so:

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

In index.html, you need to update the base href aswell to reflect the path like so:

<base href="/your/path/here/">

And that should do the trick :)


问:
Salesforce custom objects accessing using selenium webdriver with java
Each time SalesForce does a new release, most of the ID's of the elements on the salesforce webpage change(I use the ID property of the element to locate it with my automation code). This breaks my automation scripts.

In my case one text box named as "Question Name" i want to enter a value in this text box.

recent html:

```<code><label class="label inputLabel uiLabel-left form-element__label uiLabel" for="7:1781;a" data-aura-rendered-by="1040:0" data-aura-class="uiLabel">
<span class="" data-aura-rendered-by="1041:0">Question Name</span>
<span class="required " data-aura-rendered-by="8:1781;a">*</span>
</label>
<input id="7:1781;a" class=" input" maxlength="80" aria-describedby="" placeholder="" required="" data-aura-rendered-by="11:1781;a"
data-interactive-lib-uid="5" aria-required="true" type="text">
</code>```

my existing xpath :

```<code>driver.findElement(By.xpath("//input[@id='6:2634;a']")).sendKeys("test");
</code>```

Salesforce application all ID's are dynamically changed for every new release, my test script failed with the above xpath with Id, so please suggest me alternate solution.

how should i get the input id value in runtime? or let me know is there any other possible.

答:
To enter a value in the text box named as "Question Name" you can use the following line of code :

```<code>driver.findElement(By.xpath("//label[@class='label inputLabel uiLabel-left form-element__label uiLabel']/span[text()='Question Name']//following::input")).sendKeys("test");
</code>```

Body:
Each time SalesForce does a new release, most of the ID's of the elements on the salesforce webpage change(I use the ID property of the element to locate it with my automation code). This breaks my automation scripts.

In my case one text box named as "Question Name" i want to enter a value in this text box.

recent html:

Question Name
*

<input id="7:1781;a" class=" input" maxlength="80" aria-describedby="" placeholder="" required="" data-aura-rendered-by="11:1781;a"
data-interactive-lib-uid="5" aria-required="true" type="text">

my existing xpath :

driver.findElement(By.xpath("//input[@id='6:2634;a']")).sendKeys("test");

Salesforce application all ID's are dynamically changed for every new release, my test script failed with the above xpath with Id, so please suggest me alternate solution.

how should i get the input id value in runtime? or let me know is there any other possible.

Body:
To enter a value in the text box named as "Question Name" you can use the following line of code :

driver.findElement(By.xpath("//label[@class='label inputLabel uiLabel-left form-element__label uiLabel']/span[text()='Question Name']//following::input")).sendKeys("test");