问:
FusedLocationApi.requestLocationUpdates gets trigger to call onLocationChanged only after GPS is turned on
After spending lots and lots of hours of experimentation and after trying multiple combinations of calls and settings, I narrowed down to this:

Google Play services location APIs FusedLocationApi.requestLocationUpdates ideally should call onLocationChanged for specified time interval when any location service is turned on. However, the actual behavior is weired and is like this:

If all location services are turned off it never calls onLocationChanged....... Expected behavior

If only wifi/mobile network location service is turned on, it never calls onLocationChanged....... Unexpected behavior

If only GPS location service is turned on, it never calls onLocationChanged (even if we turn on wifi location service afterwards)....... Unexpected behavior

If GPS location service is turned on (after turning on first wifi/mobile location service), it calls onLocationChanged (and keeps calling even after we turn off GPS afterwards)....... Expected behavior

If wifi location service is turned on (after turning on first GPS location service), it never calls onLocationChanged ....... Unexpected behavior

In short: It calls onLocationChanged only after we turn on wifi first and then GPS. (However, GPS is no longer needed afterwards for it to call onLocationChanged)

Here is my code:

```<code>void ConnectToLocationApi()
{
    // Create an instance of GoogleAPIClient.
    if(m_GoogleApiClient == null)
    {
        // Initialize Google Api client
        m_GoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Connect to Google play service location api
        m_GoogleApiClient.connect();
    }
}

@Override
public synchronized void onConnected(Bundle bundle) // Called when m_GoogleApiClient.connect() succeeds
{
    Log.d(TAG, "GoogleApiClient connected");

    try
    {
        LocationRequest locationRequest;

        // Initialize location request
        locationRequest = new LocationRequest();
        locationRequest.setInterval(LOCATION_UPDATE_INTERVAL_IN_MILLISECONDS);
        locationRequest.setFastestInterval(FASTEST_LOCATION_UPDATE_INTERVAL_IN_MILLISECONDS);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Start receiving location updates
        LocationServices.FusedLocationApi.requestLocationUpdates(m_GoogleApiClient, locationRequest, this);

        // Get location details of last available location (if any)
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(m_GoogleApiClient);

        if (lastLocation != null)
        {
            ShowToast(this, "Last location received", Toast.LENGTH_SHORT);
            Log.i(TAG, "In onConnected. Latitude:" + m_Location.getLatitude() + ", Longitude: " + m_Location.getLongitude());
        }
        else
        {
            Log.e(TAG, "getLastLocation returned NULL value");
        }
    }
    catch (SecurityException e)
    {
        Log.e(TAG, "getLastLocation failed because of security exception (permission issue?)");
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) // Called when m_GoogleApiClient.connect fails
{
    ShowToast(this, "GoogleApiClient connection failed", Toast.LENGTH_SHORT);
    m_GoogleApiClient = null;
    Log.e(TAG, "GoogleApiClient connection failed");
}

@Override
public void onConnectionSuspended(int i) // Called when m_GoogleApiClient.connect suspended
{
    Log.e(TAG, "GoogleApiClient connection suspended");
}

@Override
public synchronized void onLocationChanged(Location location)
{
    ShowToast(this, "Location update received", Toast.LENGTH_SHORT);
    Log.i(TAG, "In location changed. Latitude:" + location.getLatitude() + ", Longitude: " + location.getLongitude());
}
</code>```

Note: I preferred Google Play services location APIs over the Android framework location APIs after I read this. Any clue please? I am badly stuck.

答:
In my case problem was in listening.
If i started GoogleApi services before i get premission for location and gps on, then OnLocationChanged never called. So
In OnPermissionGrantedResult and in reciver for android.location.PROVIDERS_CHANGED i am restarting GoogleApiServices and starting to recive location events</p>

Body:
After spending lots and lots of hours of experimentation and after trying multiple combinations of calls and settings, I narrowed down to this:

Google Play services location APIs FusedLocationApi.requestLocationUpdates ideally should call onLocationChanged for specified time interval when any location service is turned on. However, the actual behavior is weired and is like this:

If all location services are turned off it never calls onLocationChanged....... Expected behavior

If only wifi/mobile network location service is turned on, it never calls onLocationChanged....... Unexpected behavior

If only GPS location service is turned on, it never calls onLocationChanged (even if we turn on wifi location service afterwards)....... Unexpected behavior

If GPS location service is turned on (after turning on first wifi/mobile location service), it calls onLocationChanged (and keeps calling even after we turn off GPS afterwards)....... Expected behavior

If wifi location service is turned on (after turning on first GPS location service), it never calls onLocationChanged ....... Unexpected behavior

In short: It calls onLocationChanged only after we turn on wifi first and then GPS. (However, GPS is no longer needed afterwards for it to call onLocationChanged)

Here is my code:

void ConnectToLocationApi()
{
    // Create an instance of GoogleAPIClient.
    if(m_GoogleApiClient == null)
    {
        // Initialize Google Api client
        m_GoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Connect to Google play service location api
        m_GoogleApiClient.connect();
    }
}

@Override
public synchronized void onConnected(Bundle bundle) // Called when m_GoogleApiClient.connect() succeeds
{
    Log.d(TAG, "GoogleApiClient connected");

    try
    {
        LocationRequest locationRequest;

        // Initialize location request
        locationRequest = new LocationRequest();
        locationRequest.setInterval(LOCATION_UPDATE_INTERVAL_IN_MILLISECONDS);
        locationRequest.setFastestInterval(FASTEST_LOCATION_UPDATE_INTERVAL_IN_MILLISECONDS);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Start receiving location updates
        LocationServices.FusedLocationApi.requestLocationUpdates(m_GoogleApiClient, locationRequest, this);

        // Get location details of last available location (if any)
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(m_GoogleApiClient);

        if (lastLocation != null)
        {
            ShowToast(this, "Last location received", Toast.LENGTH_SHORT);
            Log.i(TAG, "In onConnected. Latitude:" + m_Location.getLatitude() + ", Longitude: " + m_Location.getLongitude());
        }
        else
        {
            Log.e(TAG, "getLastLocation returned NULL value");
        }
    }
    catch (SecurityException e)
    {
        Log.e(TAG, "getLastLocation failed because of security exception (permission issue?)");
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) // Called when m_GoogleApiClient.connect fails
{
    ShowToast(this, "GoogleApiClient connection failed", Toast.LENGTH_SHORT);
    m_GoogleApiClient = null;
    Log.e(TAG, "GoogleApiClient connection failed");
}

@Override
public void onConnectionSuspended(int i) // Called when m_GoogleApiClient.connect suspended
{
    Log.e(TAG, "GoogleApiClient connection suspended");
}

@Override
public synchronized void onLocationChanged(Location location)
{
    ShowToast(this, "Location update received", Toast.LENGTH_SHORT);
    Log.i(TAG, "In location changed. Latitude:" + location.getLatitude() + ", Longitude: " + location.getLongitude());
}

Note: I preferred Google Play services location APIs over the Android framework location APIs after I read this. Any clue please? I am badly stuck.


来源: stackexchange

问:
Producing persistent message using stompest for python
I am not able to send persistent message to AMQ queue using stompest and python.. Dont know what header to use???
Below is source code</p>

```<code>from stompest.config import StompConfig
from stompest.sync import Stomp
import os

CONFIG = StompConfig('tcp://localhost:61613')
QUEUE = '/queue/myQueue'

if __name__ == '__main__':

    try:
        client = Stomp(CONFIG)
        client.connect({'login':'#####','passcode':'#####'})
        for i in range(10):
            msg="Test Message" +str(i)
            client.send(QUEUE,msg)
        client.disconnect()
    except Exception,e:
        print e
</code>```

答:
You have to change the send line to this :</p>

```<code>client.send(QUEUE,msg, headers={'persistent' :'true'})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not able to send persistent message to AMQ queue using stompest and python.. Dont know what header to use???
Below is source code

from stompest.config import StompConfig
from stompest.sync import Stomp
import os

CONFIG = StompConfig('tcp://localhost:61613')
QUEUE = '/queue/myQueue'

if __name__ == '__main__':

    try:
        client = Stomp(CONFIG)
        client.connect({'login':'#####','passcode':'#####'})
        for i in range(10):
            msg="Test Message" +str(i)
            client.send(QUEUE,msg)
        client.disconnect()
    except Exception,e:
        print e

Body:
You have to change the send line to this :

client.send(QUEUE,msg, headers={'persistent' :'true'})


问:
Laravel package ServiceProvider not found
I have created a PHP package for laravel named zoho.

```<code>namespace rahulreghunath\zoho;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

    class ServiceProvider extends IlluminateServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            $this->publishes([
                __DIR__.'/../config/zoho.php' => config_path('zoho.php'),
            ]);

        }

        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {

        }
    }
</code>```

and composer file is

```<code>{
    "name": "rahulreghunath/zoho",
    "minimum-stability": "dev",
    "require": {
    },
    "description": "PHP form validation plugin ",
    "homepage": "https://github.com/rahulreghunath/zoho-crm",
    "license": "MIT",
    "authors": [
        {
            "name": "Rahul Reghunath",
            "email": "reghunath11@gmail.com",
            "role": "developer"
        }
    ]
}
</code>```

package is working fine when I created which is not in vendor folder but when I
submitted to Packagist and install using composer and it shows the error

```<code>[Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'rahulreghunath\zoho\ServiceProvider' not found
</code>```

When running vendot:publish command
even if provider rahulreghunath\Zoho\ServiceProvider::class,
is added to config/app.php

is that any error in autoloading in composer file
anyway thanks in advance

答:
Found an answer myself

changed the composer.json to

```<code>{
    "name": "rahulreghunath/zoho",
    "description": "Zoho CRM integration for PHP-Laravel",
    "license": "MIT",
    "keywords": ["laravel", "zoho"],
    "authors": [
        {
            "name": "Rahul Reghunath",
            "email": "reghunath11@gmail.com",
            "role": "developer"
        }
    ],
    "require": {
        "php": ">=5.5.9"
    },

    "autoload": {
        "psr-4": {
            "Rahulreghunath\\Zoho\\": "src/"
        }
    },
    "minimum-stability": "dev"
}
</code>```

and service provider to

```<code>Rahulreghunath\Zoho\ServiceProvider::class,
</code>```

Body:
I have created a PHP package for laravel named zoho.

namespace rahulreghunath\zoho;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

    class ServiceProvider extends IlluminateServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            $this->publishes([
                __DIR__.'/../config/zoho.php' => config_path('zoho.php'),
            ]);

        }

        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {

        }
    }

and composer file is

{
    "name": "rahulreghunath/zoho",
    "minimum-stability": "dev",
    "require": {
    },
    "description": "PHP form validation plugin ",
    "homepage": "https://github.com/rahulreghunath/zoho-crm",
    "license": "MIT",
    "authors": [
        {
            "name": "Rahul Reghunath",
            "email": "reghunath11@gmail.com",
            "role": "developer"
        }
    ]
}

package is working fine when I created which is not in vendor folder but when I
submitted to Packagist and install using composer and it shows the error

[Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'rahulreghunath\zoho\ServiceProvider' not found

When running vendot:publish command
even if provider rahulreghunath\Zoho\ServiceProvider::class,
is added to config/app.php

is that any error in autoloading in composer file
anyway thanks in advance

Body:
Found an answer myself

changed the composer.json to

{
    "name": "rahulreghunath/zoho",
    "description": "Zoho CRM integration for PHP-Laravel",
    "license": "MIT",
    "keywords": ["laravel", "zoho"],
    "authors": [
        {
            "name": "Rahul Reghunath",
            "email": "reghunath11@gmail.com",
            "role": "developer"
        }
    ],
    "require": {
        "php": ">=5.5.9"
    },

    "autoload": {
        "psr-4": {
            "Rahulreghunath\\Zoho\\": "src/"
        }
    },
    "minimum-stability": "dev"
}

and service provider to

Rahulreghunath\Zoho\ServiceProvider::class,


问:
How to add folders in Source Safe?
I have a static site of html and css files. It has folders on my computers. I see an 'add files' option in Source Safe 8 but it only copies files from the root folder.

How can I get Source Safe to copy the whole folder tree structure and their files?

答: Yes, drag and drop the folder, check the recursive box at the bottom where you add your comment for the initial check in.  This copy all subfolders and files.</p>

ContentLicense: CC BY-SA 2.5

Title: How to add folders in Source Safe?


问:
How to save user-entered line breaks from a TextArea to a database?
How do I save user-entered line breaks from a <textarea> HTML element to a database?

It always removes the line breaks.

答: I noticed that breakable content saved normally if textarea is inside a html form. But if I use textarea without any form and try to edit a long text in it, insert line breaks and save content via ajax, it's saved as a merged text into database</p>

OwnerDisplayName: Adam Brown

ContentLicense: CC BY-SA 4.0


问:
Facebook Marketing API | Combine breakdowns
Is it possible to combine breakdowns using the facebook marketing api? So far I can breakdown my reports by Age, Gender and Region, Country.

But would be nice if I could combine this four breakdowns. Because even having 2 separate reports I will never be able to get the accurate metric values, for example: clicks by Females from 18-25 living in Texas, USA.

I can only have:

Clicks by females from 18-25

Clicks from Texas, USA

Is there any way to achieve this.

答:
you need create 2 diferent consult </p>

<p>$campaignparams['breakdowns'] = ['age','gender'];
$adsetparams ['breakdowns'] =  ['country'];</p>

Body:
you need create 2 diferent consult

$campaignparams['breakdowns'] = ['age','gender'];
$adsetparams ['breakdowns'] =  ['country'];


问:
Advantages/disadvantages of init method
What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?

```<code>public class A {
  private int x;

  public A(int x){
    this.x = x;
  }

  public void init(int x){
   this.x = x;
  }
}
</code>```

Here we can use either constructor or init method.

答:
Constructor is not a regular method. It's special in a sense that it gets always called when you invoke new A(). If you don't provide a constructor, Java creates one automatically. As a consequence, constructors do not have a return (i.e. they return this) and always have the same name as the class.

On the other hand, init is a regular method, which you can call - or not. There is no universally accepted consensus for any kind of "init" methods. So it depends on what you want to do. If you want to ensure that the new calls your logic, use constructor. If you want to have your own stuff, use plain methods. You can mix and match, just be sure to write a good documentation about how your class is supposed to be used.

Title: Advantages/disadvantages of init method

Body:
What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?

public class A {
  private int x;

  public A(int x){
    this.x = x;
  }

  public void init(int x){
   this.x = x;
  }
}

Here we can use either constructor or init method.


问:
HashMap to SQL when Key is an enum
I have the following entity class:

```<code>public class SportData {
//other attributes

 @Column(name = "POINTS")
    @ElementCollection
    private Map<NBAEvent, Integer> points;
}

public enum NBAEvent {
    THREE_POINT,
    TWO_POINT,
    FREE_THROW,
    //..
}
</code>```

When I generate the corresponding tables using ddl-auto: validate it creates the NBAEvent(which is the k) column with the data type as an integer(points_key int4 NOT NULL).

How can I generate a varchar type column for the points key column?

If I manually write the SQL like points_key CHARACTER VARYING(255) how would it affect?

I'm using Spring boot along with Spring JPA, DB is PostgreSQL.

答:
When the key of your Map is an enum then you must also add the MapKeyEnumerated annotation.

The key is to declare it with the EnumType.STRING type.

```<code>@ElementCollection
@CollectionTable(name = "colltable")
@MapKeyEnumerated(EnumType.STRING)
@Column(name="POINTS")
private Map<NBAEvent, Integer> map;
</code>```

Otherwise as per javadocs it defaults to: javax.persistence.EnumType.ORDINAL. And that results in an integer table while ddl creation.

you may also need the @CollectionTable annotation as above.

Title: HashMap to SQL when Key is an enum

Body:
I have the following entity class:

public class SportData {
//other attributes

 @Column(name = "POINTS")
    @ElementCollection
    private Map<NBAEvent, Integer> points;
}

public enum NBAEvent {
    THREE_POINT,
    TWO_POINT,
    FREE_THROW,
    //..
}

When I generate the corresponding tables using ddl-auto: validate it creates the NBAEvent(which is the k) column with the data type as an integer(points_key int4 NOT NULL).

How can I generate a varchar type column for the points key column?

If I manually write the SQL like points_key CHARACTER VARYING(255) how would it affect?

I'm using Spring boot along with Spring JPA, DB is PostgreSQL.

Body:
When the key of your Map is an enum then you must also add the MapKeyEnumerated annotation.

The key is to declare it with the EnumType.STRING type.

@ElementCollection
@CollectionTable(name = "colltable")
@MapKeyEnumerated(EnumType.STRING)
@Column(name="POINTS")
private Map<NBAEvent, Integer> map;

Otherwise as per javadocs it defaults to: javax.persistence.EnumType.ORDINAL. And that results in an integer table while ddl creation.

you may also need the @CollectionTable annotation as above.


问:
sapui5 coordinate plotting
A question regarding below process. I have a table maintained in blue box. Sample table maintenance and expected output.

How could I render the coordinates to a clickable table/grid like what is shown in red box. Which SAPUI5 control able to achieve this objective? The X will be the lot id which will be maintained in the table and it shall have an event triggered to show the detail information when user click on the cell. Some lot will have single cell and some will need to merge cell(Note: if the coordinate is not maintained, it shall leaves blank to that cell and is non-clickable).

Does this requirment able to achive using sapui5 for fiori app?

答:
There are several ways to achieve this, but not all of them offer the complete set of functionality that you describe.

The first way that comes into mind is to use a sap.m.Table with the "mergeDuplicates" properties set on the columns. Example (working fiddle here):

    <columns>
    <Column mergeDuplicates="true">

    </Column>
    <Column mergeDuplicates="true">

    </Column>
    <Column mergeDuplicates="true">

    </Column>
  </columns>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="B"/>
    <Button text="X"/>
  </ColumnListItem>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="C"/>
    <Button text="C"/>
  </ColumnListItem>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="C"/>
    <Button text="C"/>
  </ColumnListItem>

```

<p>The main downside of this is that you cannot merge cells across columns (i.e. in this example, you would get cell "C" twice: once for the second column and once for the third).</p>

<p>Another version is to use the sap.ui.layout.Grid. This has mostly the same limitation (that you can only merge "cells" in a single direction) and also has the added limitation that:</p>

<blockquote>
  <p>The Grid control is a layout which positions its child controls in a 12 column flow layout.</p>
</blockquote>

<p>Lastly, you could use a sap.ui.commons.layout.MatrixLayout (which is deprecated btw, but no "full" replacement was provided). This actually can be used to model your problem completely. Example (working fiddle here):</p>

<pre class="lang-xml prettyprint-override"><code><layout:MatrixLayout class="matrix">
    <layout:rows>
    <layout:MatrixLayoutRow height="4em">
        <layout:MatrixLayoutCell padding="None" rowSpan="3">
            <Button text="A" width="100%"/>
        </layout:MatrixLayoutCell>
      <layout:MatrixLayoutCell padding="None">
            <Button text="B" width="100%"/>
        </layout:MatrixLayoutCell>
      <layout:MatrixLayoutCell padding="None">
            <Button text="X" width="100%"/>
        </layout:MatrixLayoutCell>
    </layout:MatrixLayoutRow>
    <layout:MatrixLayoutRow height="4em">
        <layout:MatrixLayoutCell padding="None" colSpan="2" rowSpan="2" >
            <Button text="C" width="100%"/>
        </layout:MatrixLayoutCell>
    </layout:MatrixLayoutRow>
    <layout:MatrixLayoutRow height="4em">
    </layout:MatrixLayoutRow>
  </layout:rows>
</layout:MatrixLayout>
</code>```

But as you see, it is slightly more complicated and may need some CSS fiddling.

Title: sapui5 coordinate plotting

Body:
There are several ways to achieve this, but not all of them offer the complete set of functionality that you describe.

The first way that comes into mind is to use a sap.m.Table with the "mergeDuplicates" properties set on the columns. Example (working fiddle here):

<Table>
    <columns>
    <Column mergeDuplicates="true">
        <header><Label text="1" /></header>
    </Column>
    <Column mergeDuplicates="true">
        <header><Label text="2" /></header>
    </Column>
    <Column mergeDuplicates="true">
        <header><Label text="3" /></header>
    </Column>
  </columns>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="B"/>
    <Button text="X"/>
  </ColumnListItem>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="C"/>
    <Button text="C"/>
  </ColumnListItem>
  <ColumnListItem>
    <Button text="A"/>
    <Button text="C"/>
    <Button text="C"/>
  </ColumnListItem>
</Table>

The main downside of this is that you cannot merge cells across columns (i.e. in this example, you would get cell "C" twice: once for the second column and once for the third).

Another version is to use the sap.ui.layout.Grid. This has mostly the same limitation (that you can only merge "cells" in a single direction) and also has the added limitation that:

The Grid control is a layout which positions its child controls in a 12 column flow layout.

Lastly, you could use a sap.ui.commons.layout.MatrixLayout (which is deprecated btw, but no "full" replacement was provided). This actually can be used to model your problem completely. Example (working fiddle here):

<layout:MatrixLayout class="matrix">
    <layout:rows>
    <layout:MatrixLayoutRow height="4em">
        <layout:MatrixLayoutCell padding="None" rowSpan="3">
            <Button text="A" width="100%"/>
        </layout:MatrixLayoutCell>
      <layout:MatrixLayoutCell padding="None">
            <Button text="B" width="100%"/>
        </layout:MatrixLayoutCell>
      <layout:MatrixLayoutCell padding="None">
            <Button text="X" width="100%"/>
        </layout:MatrixLayoutCell>
    </layout:MatrixLayoutRow>
    <layout:MatrixLayoutRow height="4em">
        <layout:MatrixLayoutCell padding="None" colSpan="2" rowSpan="2" >
            <Button text="C" width="100%"/>
        </layout:MatrixLayoutCell>
    </layout:MatrixLayoutRow>
    <layout:MatrixLayoutRow height="4em">
    </layout:MatrixLayoutRow>
  </layout:rows>
</layout:MatrixLayout>

But as you see, it is slightly more complicated and may need some CSS fiddling.


问:
bootstrap-modal dynamic content ajax in laravel
I would like to load content in my bootstrap modal from ajax i can get it in an alert or console log but the part that i want to update disappears!

I tried it with $('.modal-content').html(data) but my modal-content disappears     or .append(data) but it dus not work!

I remade it really simple but it is still not working what im i dowing wrong?

THANKS for your time and help!!!

part off my main page

```<code><a class="btn btn-primary"  class="quickview22" href="#" data-target="#quickviewMain55" data-categorie="1" data-trigger="hover" data-toggle="modal">Trigger modal</a>
@include('bootmodal')
</code>```

my bootmodal view

```<code><div class="modal fade in " id="quickviewMain55">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Modal ffffffffffffffftitle</h4>
            </div>
            <div class="modal-body">
                <h1>{{ $quickProducts1->first()->name }}</h1>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>
</code>```

this is my script

```<code>   jQuery( document ).ready( function( $ ) {
   $('#quickviewMain55').on('show.bs.modal', function(e) {

   var category = $(e.relatedTarget).data('categorie');

     $.ajax({

           url: 'quick-view',
           data: { category : category },
           success: function(data)
           {

         $('.modal-content').html(data);

           alert(data);
           }
         });

});
});

       $.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

</script>
</code>```

my controller

```<code>class QuickViewController extends Controller
{
    public function index(Request $request)
    {

         $quickProducts1 = Product::where('category_id', $request->category)->get();

         return view('bootmodal', compact('quickProducts1'))->render();
    }

}
</code>```

答:
Are you sure you want to append it to .modal-content and not .modal-content .modal-body?

You might want to try:
$('.modal-content .modal-body').html(data)

Keep us updated!

Kenny

Body:
I would like to load content in my bootstrap modal from ajax i can get it in an alert or console log but the part that i want to update disappears!

I tried it with $('.modal-content').html(data) but my modal-content disappears     or .append(data) but it dus not work!

I remade it really simple but it is still not working what im i dowing wrong?

THANKS for your time and help!!!

part off my main page

Trigger modal
@include('bootmodal')

my bootmodal view

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal ffffffffffffffftitle

{{ $quickProducts1->first()->name }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

this is my script

   jQuery( document ).ready( function( $ ) {
   $('#quickviewMain55').on('show.bs.modal', function(e) {

   var category = $(e.relatedTarget).data('categorie');

     $.ajax({

           url: 'quick-view',
           data: { category : category },
           success: function(data)
           {

         $('.modal-content').html(data);

           alert(data);
           }
         });

});
});

       $.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

</script>

my controller

class QuickViewController extends Controller
{
    public function index(Request $request)
    {

         $quickProducts1 = Product::where('category_id', $request->category)->get();

         return view('bootmodal', compact('quickProducts1'))->render();
    }

}


问:
How to use highchart 3d with angular 5?
I am just adding to app.module.ts

```<code>import { ChartModule } from 'angular-highcharts';
</code>```

and to import

```<code>ChartModule
</code>```

Now i want to use highchart-3d
how can i do that?
Can i customize the chart to make it something like morris.js donut chart?

答:
You can check add-highcharts-modules from npm packages.

Any other modules like highcharts-3d, highcharts-exporintg and etc. can be also added in @NgModule after main chart module

```<code>...
@NgModule({
    ...
    imports: [
      BrowserModule,
      ChartModule.forRoot(
        require('highcharts'),
+       require('highcharts/highchart-3d'),
+       require('highcharts/modules/exporting')
      ],
})
</code>```

Check http://plnkr.co/edit/sz6OfccvAetQcBX8KFXy?p=preview .

If you are facing problem then add live example

Title: How to use highchart 3d with angular 5?

Body:
I am just adding to app.module.ts

import { ChartModule } from 'angular-highcharts';

and to import

ChartModule

Now i want to use highchart-3d
how can i do that?
Can i customize the chart to make it something like morris.js donut chart?

Body:
You can check add-highcharts-modules from npm packages.

Any other modules like highcharts-3d, highcharts-exporintg and etc. can be also added in @NgModule after main chart module

...
@NgModule({
    ...
    imports: [
      BrowserModule,
      ChartModule.forRoot(
        require('highcharts'),
+       require('highcharts/highchart-3d'),
+       require('highcharts/modules/exporting')
      ],
})

Check http://plnkr.co/edit/sz6OfccvAetQcBX8KFXy?p=preview .

If you are facing problem then add live example


问:
Horiztonal centered rotated text
Hello I am trying to create this in HTML + CSS.

I have everything working, except the horizontal alignement of the legend is wrong, and the whole legend is offset.

https://jsbin.com/cuzobijuqe/

.barometer-body>div {
  float: left;
  width: 12.5%;
  height: 1.3em;
  display: inline-block;
}

.barometer-body>div:nth-child(1) {
  background-color: #CC0033;
}

.barometer-body>div:nth-child(2) {
  background-color: #FF6633;
}

.barometer-body>div:nth-child(3) {
  background-color: #F49819;
}

.barometer-body>div:nth-child(4) {
  background-color: #FFCC00;
}

.barometer-body>div:nth-child(5) {
  background-color: #FFFF66;
}

.barometer-body>div:nth-child(6) {
  background-color: #99C667;
}

.barometer-body>div:nth-child(7) {
  background-color: #349937;
}

.barometer-body>div:nth-child(8) {
  background-color: #006633;
}

.barometer-legend>div {
  width: 12.5%;
  float: left;
  font-size: 2em;
  line-height: 12.5%;
  display: inline-block;
  transform: rotate(90deg);
  transform-origin: left top 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="barometer-body">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="barometer-legend">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
  <div>Five</div>
  <div>Six</div>
  <div>Seven</div>
  <div>Eight</div>
</div></code>```

What CSS method should I use for aligning the rotated text to the center position of it's associated segment?

EDIT: thanks to @ovokuro I have an almost perfect solution. I'm happy to use flexbox for this. However when I reduce the viewport, the alignment seems to switch to left rather than right which causes the text to look messy. How would I fix this?

答:
I think you could approach this layout using flexbox

updated as per comment (text not aligning on smaller screen sizes):

Replace text-align: right with justify-content: flex-end:

```<code>.barometer-legend > div {
  display: flex;
  justify-content: flex-end;
}
</code>```

I have also added a media query to reduce the font-size on smaller screens.

.wrapper,
.barometer-body,
.barometer-legend {
  display: flex;
}

.wrapper {
  flex-direction: column;
}

.barometer-body {
  border-radius: 2em;
  overflow: hidden;
}

/* create space between body and legend */

.barometer-legend {
  padding-top: 6%;
}

.barometer-body>div,
.barometer-legend>div {
  flex: 1 0 12.5%;
  width: 12.5%;
  height: 1.3em;
}

.barometer-body>div:nth-child(1) {
  background-color: #CC0033;
}

.barometer-body>div:nth-child(2) {
  background-color: #FF6633;
}

.barometer-body>div:nth-child(3) {
  background-color: #F49819;
}

.barometer-body>div:nth-child(4) {
  background-color: #FFCC00;
}

.barometer-body>div:nth-child(5) {
  background-color: #FFFF66;
}

.barometer-body>div:nth-child(6) {
  background-color: #99C667;
}

.barometer-body>div:nth-child(7) {
  background-color: #349937;
}

.barometer-body>div:nth-child(8) {
  background-color: #006633;
}

.barometer-legend>div {
  font-size: 2em;
  transform: rotate(-90deg);
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 600px) {
  .barometer-legend div {
    font-size: 1.5em
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="barometer-body">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="barometer-legend">
    <div>One</div>
    <div>Two</div>
    <div>Three</div>
    <div>Four</div>
    <div>Five</div>
    <div>Six</div>
    <div>Seven</div>
    <div>Eight</div>
  </div>
</div></code>```

Title: Horiztonal centered rotated text

Body:
Hello I am trying to create this in HTML + CSS.

I have everything working, except the horizontal alignement of the legend is wrong, and the whole legend is offset.

https://jsbin.com/cuzobijuqe/

.barometer-body>div {
  float: left;
  width: 12.5%;
  height: 1.3em;
  display: inline-block;
}

.barometer-body>div:nth-child(1) {
  background-color: #CC0033;
}

.barometer-body>div:nth-child(2) {
  background-color: #FF6633;
}

.barometer-body>div:nth-child(3) {
  background-color: #F49819;
}

.barometer-body>div:nth-child(4) {
  background-color: #FFCC00;
}

.barometer-body>div:nth-child(5) {
  background-color: #FFFF66;
}

.barometer-body>div:nth-child(6) {
  background-color: #99C667;
}

.barometer-body>div:nth-child(7) {
  background-color: #349937;
}

.barometer-body>div:nth-child(8) {
  background-color: #006633;
}

.barometer-legend>div {
  width: 12.5%;
  float: left;
  font-size: 2em;
  line-height: 12.5%;
  display: inline-block;
  transform: rotate(90deg);
  transform-origin: left top 0;
}

One

Two

Three

Four

Five

Six

Seven

Eight

What CSS method should I use for aligning the rotated text to the center position of it's associated segment?

EDIT: thanks to @ovokuro I have an almost perfect solution. I'm happy to use flexbox for this. However when I reduce the viewport, the alignment seems to switch to left rather than right which causes the text to look messy. How would I fix this?

Body:
I think you could approach this layout using flexbox

updated as per comment (text not aligning on smaller screen sizes):

Replace text-align: right with justify-content: flex-end:

.barometer-legend > div {
  display: flex;
  justify-content: flex-end;
}

I have also added a media query to reduce the font-size on smaller screens.

.wrapper,
.barometer-body,
.barometer-legend {
  display: flex;
}

.wrapper {
  flex-direction: column;
}

.barometer-body {
  border-radius: 2em;
  overflow: hidden;
}

/* create space between body and legend */

.barometer-legend {
  padding-top: 6%;
}

.barometer-body>div,
.barometer-legend>div {
  flex: 1 0 12.5%;
  width: 12.5%;
  height: 1.3em;
}

.barometer-body>div:nth-child(1) {
  background-color: #CC0033;
}

.barometer-body>div:nth-child(2) {
  background-color: #FF6633;
}

.barometer-body>div:nth-child(3) {
  background-color: #F49819;
}

.barometer-body>div:nth-child(4) {
  background-color: #FFCC00;
}

.barometer-body>div:nth-child(5) {
  background-color: #FFFF66;
}

.barometer-body>div:nth-child(6) {
  background-color: #99C667;
}

.barometer-body>div:nth-child(7) {
  background-color: #349937;
}

.barometer-body>div:nth-child(8) {
  background-color: #006633;
}

.barometer-legend>div {
  font-size: 2em;
  transform: rotate(-90deg);
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 600px) {
  .barometer-legend div {
    font-size: 1.5em
  }
}

<div class="wrapper">
  <div class="barometer-body">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="barometer-legend">
    <div>One</div>
    <div>Two</div>
    <div>Three</div>
    <div>Four</div>
    <div>Five</div>
    <div>Six</div>
    <div>Seven</div>
    <div>Eight</div>
  </div>
</div>


问:
Spring-boot @ExceptionHandler in Java8 is not reached out
I am using @ExcpetionHandler in my Java8 app. I'm unable to reach out to this function. Upon all exceptions, the HTTP response is always 500 (with the message I inserted into the exception), and it ignores the @ExceptionHandler methods.

When my colleague runs the app with java 7 compiler, it works.

Any reason why @ExceptionHandler annotation fails to be reached out with Java 8?

Controller:

validateInput() is throwing InputParameterException. InputParameterException is caught in the try/catch, which throws it again.

```<code>import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import vce.exception.InputParameterException;

@Controller
@RestController
public class VRestController {

    @Resource(name="aManager")
    AManager aManager;

    public void setAManager(AManager aManager) {
        this.aManager = aManager;
    }

    @RequestMapping(value ="/authentication/signature", method = RequestMethod.PUT)
    public ResponseEntity<Object> signature(@RequestBody final Signature signature) {

        return handle(Marker.UseCases.SIGNATURE, new Supplier<Integer>() {

            @Override
            public Integer get() {
                validateInput(signature);
                aManager.doSomething(signature);
                return 0;
            }

        });
    }

    private ResponseEntity<ErrorResponse> handle(UseCases useCase, Supplier<Integer> supplier) {

        final Marker marker = Marker.REQUEST_MARKER.get();
        marker.startUseCase().setUseCase(useCase.name()).setStartTime(DateTime.now());
        try{
            marker.setSerializationId(serializationID);

            supplier.get();
        }

        catch (Exception e) {
            marker.setException(e);

            throw e;
        }

        finally {
          ......
        }

        return ResponseEntity.ok(new ErrorResponse(200,0,"Success"));
    }

    private static void validateInput(Signature signature) {
        final String missingErr = "The request is missing the following parameter: ";

        if(signature.getData()==null) {
            throw new InputParameterException(missingErr+VConstants.DATA_FIELD_NAME, VErrorCodeEnum.MISSING_FIELD);
        }

        if(signature.getSignature()==null) {
            throw new InputParameterException(missingErr+VConstants.SIGNATURE_FIELD_NAME, VErrorCodeEnum.MISSING_FIELD);
        }
    }

    @ExceptionHandler(InputParameterException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponse handleInputParameterException(HttpServletRequest req, InputParameterException e) {
        .....
        return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getErrorCode().getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error - Any Exception")
    public void handleAnyException(HttpServletRequest req, Exception e) {

        .....
    }

    static class ErrorResponse {

        public int statusCode;
        public int errorCode;
        public String message;

        public ErrorResponse(int statusCode, int errorCode, String message) {
            this.statusCode = statusCode;
            this.errorCode = errorCode;
            this.message = message;
        }
    }
}
</code>```

Relevant part from pom.xml:

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.4.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</dependencies>
</code>```

This code fails to reach out to @ExceptionHandler with Java8. When switching to Java7, without any code changes, it works.

Update:

The error message I receive is:

```<code>{
  "timestamp": 1494863566131,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "com.nds.ch.vge.vaus.exception.InputParameterException",
  "message": "org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.nds.ch.vge.vaus.exception.InputParameterException: The request is missing the following parameter: data",
  "path": "/authentication/signature"
}
</code>```

I removed @Controller annotation and I also tried to use resolver, but it didn't work.

Code of the resolver, in the same package as the rest controller class:

```<code>@RestControllerAdvice
@EnableWebMvc
public class GlobalControllerExceptionHandler {

        @ExceptionHandler(InputParameterException.class)
        @ResponseStatus(value= HttpStatus.BAD_REQUEST)
        public ErrorResponse handleInputParameterException(HttpServletRequest req, InputParameterException e) {
            .....
            return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getErrorCode().getCode(), e.getMessage());
        }

        @ExceptionHandler(Exception.class)
        @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error - Any Exception")
        public void handleAnyException(HttpServletRequest req, Exception e) {

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

答:
The issue was importing the wrong HttpServletRequest class:

```<code>import org.apache.catalina.servlet4preview.http.HttpServletRequest;
</code>```

The import should be:

```<code>import javax.servlet.http.HttpServletRequest;
</code>```

When I changed the import, the @ExceptionHandler methods worked.

Body:
I am using @ExcpetionHandler in my Java8 app. I'm unable to reach out to this function. Upon all exceptions, the HTTP response is always 500 (with the message I inserted into the exception), and it ignores the @ExceptionHandler methods.

When my colleague runs the app with java 7 compiler, it works.

Any reason why @ExceptionHandler annotation fails to be reached out with Java 8?

Controller:

validateInput() is throwing InputParameterException. InputParameterException is caught in the try/catch, which throws it again.

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import vce.exception.InputParameterException;

@Controller
@RestController
public class VRestController {

    @Resource(name="aManager")
    AManager aManager;

    public void setAManager(AManager aManager) {
        this.aManager = aManager;
    }

    @RequestMapping(value ="/authentication/signature", method = RequestMethod.PUT)
    public ResponseEntity<Object> signature(@RequestBody final Signature signature) {

        return handle(Marker.UseCases.SIGNATURE, new Supplier<Integer>() {

            @Override
            public Integer get() {
                validateInput(signature);
                aManager.doSomething(signature);
                return 0;
            }

        });
    }

    private ResponseEntity<ErrorResponse> handle(UseCases useCase, Supplier<Integer> supplier) {

        final Marker marker = Marker.REQUEST_MARKER.get();
        marker.startUseCase().setUseCase(useCase.name()).setStartTime(DateTime.now());
        try{
            marker.setSerializationId(serializationID);

            supplier.get();
        }

        catch (Exception e) {
            marker.setException(e);

            throw e;
        }

        finally {
          ......
        }

        return ResponseEntity.ok(new ErrorResponse(200,0,"Success"));
    }

    private static void validateInput(Signature signature) {
        final String missingErr = "The request is missing the following parameter: ";

        if(signature.getData()==null) {
            throw new InputParameterException(missingErr+VConstants.DATA_FIELD_NAME, VErrorCodeEnum.MISSING_FIELD);
        }

        if(signature.getSignature()==null) {
            throw new InputParameterException(missingErr+VConstants.SIGNATURE_FIELD_NAME, VErrorCodeEnum.MISSING_FIELD);
        }
    }

    @ExceptionHandler(InputParameterException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponse handleInputParameterException(HttpServletRequest req, InputParameterException e) {
        .....
        return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getErrorCode().getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error - Any Exception")
    public void handleAnyException(HttpServletRequest req, Exception e) {

        .....
    }

    static class ErrorResponse {

        public int statusCode;
        public int errorCode;
        public String message;

        public ErrorResponse(int statusCode, int errorCode, String message) {
            this.statusCode = statusCode;
            this.errorCode = errorCode;
            this.message = message;
        }
    }
}

Relevant part from pom.xml:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.4.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</dependencies>

This code fails to reach out to @ExceptionHandler with Java8. When switching to Java7, without any code changes, it works.

Update:

The error message I receive is:

{
  "timestamp": 1494863566131,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "com.nds.ch.vge.vaus.exception.InputParameterException",
  "message": "org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.nds.ch.vge.vaus.exception.InputParameterException: The request is missing the following parameter: data",
  "path": "/authentication/signature"
}

I removed @Controller annotation and I also tried to use resolver, but it didn't work.

Code of the resolver, in the same package as the rest controller class:

@RestControllerAdvice
@EnableWebMvc
public class GlobalControllerExceptionHandler {

        @ExceptionHandler(InputParameterException.class)
        @ResponseStatus(value= HttpStatus.BAD_REQUEST)
        public ErrorResponse handleInputParameterException(HttpServletRequest req, InputParameterException e) {
            .....
            return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getErrorCode().getCode(), e.getMessage());
        }

        @ExceptionHandler(Exception.class)
        @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR, reason="Internal Server Error - Any Exception")
        public void handleAnyException(HttpServletRequest req, Exception e) {

            .....
        }
}

Body:
The issue was importing the wrong HttpServletRequest class:

import org.apache.catalina.servlet4preview.http.HttpServletRequest;

The import should be:

import javax.servlet.http.HttpServletRequest;

When I changed the import, the @ExceptionHandler methods worked.


问:
How to get first item of value in service response from array of objects in angular2
I have an empty numbers array and

```<code>public numbers :number[] =[];
</code>```

The api response is here in service :

```<code>[
{"productID":1,"productName":"Phone","price":19.96},
{"productID":3,"productName":"Phones","price":18.96},
{"productID":2,"productName":"Laptop","price":2000.96
}]
</code>```

Need to get First price value and pass to public numbers :number[] here How to do that.

```<code>export class AppComponent implements OnInit {
 @ViewChild('mycanvas')canvas:ElementRef;

public numbers :number[] =[];

 public products:IProduct[];
 constructor(private _productService:ProductService)
    {
    }

 ngOnInit():void{

    this._productService.getProducts().subscribe((response) => {
  console.log(this.numberss = response);

  for(let item of response)
    {
    console.log("ff" +item.price);
    this.numbers.push(item.price); // need to get first value and assign to
                                   array

    }
    }),(err)=> {this.errorMsg =<any>err};

  public doughnutChartLabels:string[] = ['Mobiles', 'Laptops'];
  public doughnutChartData:number[] = this.numbers;
  public doughnutChartType:string = 'doughnut';
}
</code>```

答:
Without for loop, you can simply assign as,</p>

```<code> this.numbers.push(response[0].price);
</code>```

Body:
I have an empty numbers array and

public numbers :number[] =[];

The api response is here in service :

[
{"productID":1,"productName":"Phone","price":19.96},
{"productID":3,"productName":"Phones","price":18.96},
{"productID":2,"productName":"Laptop","price":2000.96
}]

Need to get First price value and pass to public numbers :number[] here How to do that.

export class AppComponent implements OnInit {
 @ViewChild('mycanvas')canvas:ElementRef;

public numbers :number[] =[];

 public products:IProduct[];
 constructor(private _productService:ProductService)
    {
    }

 ngOnInit():void{

    this._productService.getProducts().subscribe((response) => {
  console.log(this.numberss = response);

  for(let item of response)
    {
    console.log("ff" +item.price);
    this.numbers.push(item.price); // need to get first value and assign to
                                   array

    }
    }),(err)=> {this.errorMsg =<any>err};

  public doughnutChartLabels:string[] = ['Mobiles', 'Laptops'];
  public doughnutChartData:number[] = this.numbers;
  public doughnutChartType:string = 'doughnut';
}

Body:
Without for loop, you can simply assign as,

 this.numbers.push(response[0].price);


问:
Generating an uber/fat/shade sources-jar (and javadoc-jar) using Gradle
Does anyone know how to make a uber/fat/shade sources-jar (and javadoc-jar) using Gradle?

The generated Jar should not only contain the sources of the current project but also the sources of it's dependencies. I have been looking at, among others, a vanilla way and a way using the Shadow Plugin. Both work great at creating a normal uber/fat/shade jar, but none of them seems to support a way to create a sources-jar.

答: Use Shadow Plugin. In Maven it is called shade plugin. Does same thing. It produces an executable uber jar!</p>


问:
Best continuous integration setup for multi-platform development
What is the best continuous integration setup for a Devleopment department that codes in multiple environments?

At my company we write some code in C# and some in Java, I've previously used CC.Net but I've never done CInt with Java.

I'm aware of Continuum and was recently told about Hudson, but I've never used either.

Would it be better to use two CInt services one for each platform or to use a single one for both?

答: Note this assumes you want to build the same code on multiple platforms. Hardware has gotten cheaper so use virtual machines or multiple physical servers I'd go with virtual machines and just buy one powerful server to run them on but if you have a lot of old mid range hardware that may be a cheaper option. Set up a main source control repository on one server, and set up servers with the client operating systems you want to build for. For example have a svn server containing your operating system of choice, a Linux server to do Linux builds and a Windows server to do Windows builds. Then just install what ever continuous integration software works best for the given code base and operating system.</p>

OwnerDisplayName: Omar Kooheji

OwnerDisplayName: Jared


问:
Copying Content From Multiple TextBoxes to Clipboard
I'm looking to copy content from multiple textboxes to one textarea or straight to the clipboard using HTML/JS.

E.g Text1 = 123 Text2 = 456 Text3 = 789
I need to output it as

123

456

789

Without the spaces - So Far I have

```<code> function Copy1() {
 if(window.clipboardData) {
 window.clipboardData.clearData();
 window.clipboardData.setData("Text", document.getElementById('Text3').value);
</code>```

This is okay for copying 1 textbox but I need to copy multiple textboxes and line break the content is this possible?

Thanks

答:
```<code><script type="text/javascript">
    function kopyala() {
        //Ekrandaki text vb. alanların tümü uygun formatta kopyala değişkenine atılır.
        var kopyala = "";
        kopyala = document.getElementById('metin-alani').value + '\n' +
            document.getElementById('text-alani').value + '\n' +
            document.getElementById('text2-alani').value;

        //Clipboard için kopyala değişkenindeki veriler gizli-alana atılıyor.
        document.getElementById('gizli-alan').value = "";
        document.getElementById('gizli-alan').value = kopyala;

        console.log(kopyala ? 'Panoya Atıldı' : 'Panoya Atılamadı');
        console.log(kopyala);

        try {
            //Gizli alandaki veriler clipboarda atılıyor.
            //document.getElementById('gizli-alan').select();
            document.getElementById('gizli-alan').select();
            document.execCommand('copy');

        } catch (err) {
            console.log(err);

        }

    }

</script>
</code>```

```<code><textarea id="metin-alani" cols="30" rows="10"></textarea>
<br />
<input type="text" id="text-alani" />
<br />
<input type="text" id="text2-alani" />
<br />
<button onclick="kopyala()">Panoya Kopyala</button>

<textarea id="gizli-alan" style="width:1px;height:1px" />
</code>```

Body:
I'm looking to copy content from multiple textboxes to one textarea or straight to the clipboard using HTML/JS.

E.g Text1 = 123 Text2 = 456 Text3 = 789
I need to output it as

123

456

789

Without the spaces - So Far I have

 function Copy1() {
 if(window.clipboardData) {
 window.clipboardData.clearData();
 window.clipboardData.setData("Text", document.getElementById('Text3').value);

This is okay for copying 1 textbox but I need to copy multiple textboxes and line break the content is this possible?

Thanks

Body:
<script type="text/javascript">
    function kopyala() {
        //Ekrandaki text vb. alanların tümü uygun formatta kopyala değişkenine atılır.
        var kopyala = "";
        kopyala = document.getElementById('metin-alani').value + '\n' +
            document.getElementById('text-alani').value + '\n' +
            document.getElementById('text2-alani').value;

        //Clipboard için kopyala değişkenindeki veriler gizli-alana atılıyor.
        document.getElementById('gizli-alan').value = "";
        document.getElementById('gizli-alan').value = kopyala;

        console.log(kopyala ? 'Panoya Atıldı' : 'Panoya Atılamadı');
        console.log(kopyala);

        try {
            //Gizli alandaki veriler clipboarda atılıyor.
            //document.getElementById('gizli-alan').select();
            document.getElementById('gizli-alan').select();
            document.execCommand('copy');

        } catch (err) {
            console.log(err);

        }

    }

</script>

<textarea id="metin-alani" cols="30" rows="10"></textarea>
<br />
<input type="text" id="text-alani" />
<br />
<input type="text" id="text2-alani" />
<br />
<button onclick="kopyala()">Panoya Kopyala</button>

<textarea id="gizli-alan" style="width:1px;height:1px" />


问:
Failed to enter to a docker container, created with kubernetes deployment
With minikube i created simple deployment (https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#creating-a-deployment) in the kubernetes. I'm sure that container must running , because kubernetes pod was started successfully and I can see container running in the Portainer. But I just can't enter into the container!!

(I always could do it with a simple pod, maybe with deployment something wrong)

```<code>$ docker exec -it 01a7c90b4267 /bin/bash
rpc error: code = 2 desc = oci runtime error: exec failed: dial unix /tmp/pty870274210/pty.sock: connect: connection refused
</code>```

Also I found "Error syncing pod" in the container logs, but the container status is running

答: It seems that the problem was caused by mounting to the minikubes' tmp folder minikube mount $TMP:/tmp. Without mounting I can exec the /bin/bash in the containers with no problems

Body:
With minikube i created simple deployment (https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#creating-a-deployment) in the kubernetes. I'm sure that container must running , because kubernetes pod was started successfully and I can see container running in the Portainer. But I just can't enter into the container!!

(I always could do it with a simple pod, maybe with deployment something wrong)

$ docker exec -it 01a7c90b4267 /bin/bash
rpc error: code = 2 desc = oci runtime error: exec failed: dial unix /tmp/pty870274210/pty.sock: connect: connection refused

Also I found "Error syncing pod" in the container logs, but the container status is running


问:
SQL where condition in Codeigniter
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?</p>

```<code>$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();
</code>```

答:
Right now i'm not thinking about your logic here - because Simos Fasouliotis said enough in the comments - so you get a right idea here in a syntactic way...

However, if you compile your query with get_compiled_select you get the following result:

```<code>SELECT *
FROM `igc_room_booking`
WHERE `delete_status` =0
AND `cancel_status` =0
AND `room_id` = 12
AND `checkin_date` = '2010-09-01'
AND `checkout_date` = '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` > '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` < '2010-09-01'
OR `checkin_date` = '2010-09-01'
OR `checkout_date` = '2010-09-01'
OR `checkin_date` >= '2010-09-01'
OR `checkout_date` <= '2010-09-01'
OR `checkin_date` >= '2010-10-01'
OR `checkout_date` <= '2010-10-01'
</code>```

by now you should be able to understand whats the problem...

a possible solutions could be

```<code>$bookingss = $this->db
    ->select('*')
    ->from('igc_room_booking')
    ->where('delete_status', 0)
    ->where('cancel_status', 0)
    ->where('room_id', $val->room_id)
    ->group_start()
        ->or_where($array)
        ->or_where($array2)
        ->or_where($array3)
        ->or_where($array4)
        ->or_where($array5)
    ->group_end()
    ->get()
    ->result();
</code>```

But imho that doesn't make any sense, you should clearly think about which date range you need...

Title: SQL where condition in Codeigniter

Body:
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?

$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();

Body:
Right now i'm not thinking about your logic here - because Simos Fasouliotis said enough in the comments - so you get a right idea here in a syntactic way...

However, if you compile your query with get_compiled_select you get the following result:

SELECT *
FROM `igc_room_booking`
WHERE `delete_status` =0
AND `cancel_status` =0
AND `room_id` = 12
AND `checkin_date` = '2010-09-01'
AND `checkout_date` = '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` > '2010-09-01'
OR `checkin_date` < '2010-09-01'
OR `checkout_date` < '2010-09-01'
OR `checkin_date` = '2010-09-01'
OR `checkout_date` = '2010-09-01'
OR `checkin_date` >= '2010-09-01'
OR `checkout_date` <= '2010-09-01'
OR `checkin_date` >= '2010-10-01'
OR `checkout_date` <= '2010-10-01'

by now you should be able to understand whats the problem...

a possible solutions could be

$bookingss = $this->db
    ->select('*')
    ->from('igc_room_booking')
    ->where('delete_status', 0)
    ->where('cancel_status', 0)
    ->where('room_id', $val->room_id)
    ->group_start()
        ->or_where($array)
        ->or_where($array2)
        ->or_where($array3)
        ->or_where($array4)
        ->or_where($array5)
    ->group_end()
    ->get()
    ->result();

But imho that doesn't make any sense, you should clearly think about which date range you need...


问:
Excel function to identify dependency of subsequent records
I am looking for an excel function or formula that allows me to derive the below dependency column. I have a list of processes with start and end time and want to know which subsequent processes fall in between the time interval of any previous processes e.g. Processes E starts at 15:15, while Process D is still running, hence 'E' for the row with Process Id D.</p>

```<code>Process StartTime EndTime   Dependency
A        12:00    14:00     B,C
B        12:30    13:30     C
C        12:45    14:30
D        14:45    15:30     E
E        15:15    17:00
</code>```

答:
If you have Office 365 Excel, put the following array formula in D2:

```<code>=TEXTJOIN(",",TRUE,IF(($B3:$B$7<C2)*($A3:$A$7<>""),$A3:$A$7,""))
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode. Then copy down.

To make it dynamic on the range we can use INDEX(MATCH()) to automatically set the end cell:

```<code>=TEXTJOIN(",",TRUE,IF(($B3:INDEX(B:B,MATCH("zzz",A:A)+1)<C2)*($A3:INDEX(A:A,MATCH("zzz",A:A)+1)<>""),$A3:INDEX(A:A,MATCH("zzz",A:A)+1),""))
</code>```

Still an array formula so still needs Ctrl-Shift-Enter.

If you do not have Office 365 then you can use this UDF.  Put this code in a module attached to the workbook and use the formula as described above.

```<code>Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function
</code>```

Body:
I am looking for an excel function or formula that allows me to derive the below dependency column. I have a list of processes with start and end time and want to know which subsequent processes fall in between the time interval of any previous processes e.g. Processes E starts at 15:15, while Process D is still running, hence 'E' for the row with Process Id D.

Process StartTime EndTime   Dependency
A        12:00    14:00     B,C
B        12:30    13:30     C
C        12:45    14:30
D        14:45    15:30     E
E        15:15    17:00

Body:
If you have Office 365 Excel, put the following array formula in D2:

=TEXTJOIN(",",TRUE,IF(($B3:$B$7<C2)*($A3:$A$7<>""),$A3:$A$7,""))

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode. Then copy down.

To make it dynamic on the range we can use INDEX(MATCH()) to automatically set the end cell:

=TEXTJOIN(",",TRUE,IF(($B3:INDEX(B:B,MATCH("zzz",A:A)+1)<C2)*($A3:INDEX(A:A,MATCH("zzz",A:A)+1)<>""),$A3:INDEX(A:A,MATCH("zzz",A:A)+1),""))

Still an array formula so still needs Ctrl-Shift-Enter.

If you do not have Office 365 then you can use this UDF.  Put this code in a module attached to the workbook and use the formula as described above.

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function


问:
How can I add all checked checkboxes to database?
I'm creating checkboxes dynamically by records in the database. I can successfully generate checkboxech for each record in database.

Than after I click on button, I want to add a record in different table based of checked checkboxes. I need to go throuht all checkboxes, see if it's checked and if YES, I need to pass the id to id_participant to create the record. But I'm lost how to do it.

Can you help please?

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    myDB =  new DBAdapter(getContext());
    final View root = inflater.inflate(R.layout.fragment_add_from_db, container, false);
    final LinearLayout layout = root.findViewById(R.id.check_add_layout);
    btn_ad_group = root.findViewById(R.id.btn_add_group);
    Bundle bundle = getArguments();
    if (bundle != null) {
        id_eventu = bundle.getLong("idevent");
    }
    myDB.open();
    pocet = myDB.getParticipantsCount();
    Cursor cursor = myDB.getAllRowsParticipant();
    cursor.moveToFirst();
    for(int i = 0; i < pocet; i++) {
        CheckBox cb = new CheckBox(root.getContext());
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String surname = cursor.getString(cursor.getColumnIndex("surname"));
        String text = name + " " + surname;
        cb.setText(text);
        cb.setHeight(90);
        cb.setId(cursor.getInt(cursor.getColumnIndex("_id")));
        layout.addView(cb);
        cursor.moveToNext();
    }
    myDB.close();

    btn_ad_group.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            myDB.open();
            // here I want to write into database by selected checkboxes
            // I want to read id of checked checkbox and pass it to id_participant
            myDB.insertRowRegistr(id_eventu, id_participant);
            myDB.close();

        }
    });

    return root;
}
</code>```

答:
You've not given a lot of information, so I'll assume a couple of things.

If that LinearLayout "layout" is the parent of the checkboxes, you should be able to access its children through two functions:

```<code>int numChildren = layout.getChildCount();
for(int i=0;i<numChildren;i++){
    //create a temporary checkbox variable
    //make it equal to layout.getChildAt(i);
    //if temp is checked, add it to a list or hand it straight to database
</code>```

Should work. Never used checkboxes or databases from within android, but that should let you access each checkbox and check if it is clicked.

UPDATE

this code works as I needed. Thanks for help!

```<code>btn_ad_group.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            myDB.open();
            int numChildren = layout.getChildCount();
            for(int i=0;i<numChildren;i++){
                CheckBox temp;
                temp = (CheckBox) layout.getChildAt(i);
                if (temp.isChecked()) {
                    id_participant =  (long) temp.getId();
                    myDB.insertRowRegistr(id_eventu, id_participant);
                }
            }
            myDB.close();
            fm.popBackStackImmediate();
        }
    });
</code>```

Body:
I'm creating checkboxes dynamically by records in the database. I can successfully generate checkboxech for each record in database.

Than after I click on button, I want to add a record in different table based of checked checkboxes. I need to go throuht all checkboxes, see if it's checked and if YES, I need to pass the id to id_participant to create the record. But I'm lost how to do it.

Can you help please?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    myDB =  new DBAdapter(getContext());
    final View root = inflater.inflate(R.layout.fragment_add_from_db, container, false);
    final LinearLayout layout = root.findViewById(R.id.check_add_layout);
    btn_ad_group = root.findViewById(R.id.btn_add_group);
    Bundle bundle = getArguments();
    if (bundle != null) {
        id_eventu = bundle.getLong("idevent");
    }
    myDB.open();
    pocet = myDB.getParticipantsCount();
    Cursor cursor = myDB.getAllRowsParticipant();
    cursor.moveToFirst();
    for(int i = 0; i < pocet; i++) {
        CheckBox cb = new CheckBox(root.getContext());
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String surname = cursor.getString(cursor.getColumnIndex("surname"));
        String text = name + " " + surname;
        cb.setText(text);
        cb.setHeight(90);
        cb.setId(cursor.getInt(cursor.getColumnIndex("_id")));
        layout.addView(cb);
        cursor.moveToNext();
    }
    myDB.close();

    btn_ad_group.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            myDB.open();
            // here I want to write into database by selected checkboxes
            // I want to read id of checked checkbox and pass it to id_participant
            myDB.insertRowRegistr(id_eventu, id_participant);
            myDB.close();

        }
    });

    return root;
}

Body:
You've not given a lot of information, so I'll assume a couple of things.

If that LinearLayout "layout" is the parent of the checkboxes, you should be able to access its children through two functions:

int numChildren = layout.getChildCount();
for(int i=0;i<numChildren;i++){
    //create a temporary checkbox variable
    //make it equal to layout.getChildAt(i);
    //if temp is checked, add it to a list or hand it straight to database

Should work. Never used checkboxes or databases from within android, but that should let you access each checkbox and check if it is clicked.

UPDATE

this code works as I needed. Thanks for help!

btn_ad_group.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            myDB.open();
            int numChildren = layout.getChildCount();
            for(int i=0;i<numChildren;i++){
                CheckBox temp;
                temp = (CheckBox) layout.getChildAt(i);
                if (temp.isChecked()) {
                    id_participant =  (long) temp.getId();
                    myDB.insertRowRegistr(id_eventu, id_participant);
                }
            }
            myDB.close();
            fm.popBackStackImmediate();
        }
    });


问:
jQuery IF statement not working
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

```<code>function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}
</code>```

答:
You could probably solve the problem doing what patrick dw suggested (it's likely that the ajax call has not been completed yet (i.e. div content wasn't updated) and the check returns false), but since string comparison can really bring to many errors (like string not matching because of newlines, trailing spaces, case sensitiveness, etc...) I would suggest you use another comparison method.

For example you could add a class using .addClass() if the car is found, and then checking if that div has the "found" class using .hasClass()

Title: jQuery IF statement not working

Body:
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}


问:
C Number in Python
I'm reviewing some code that utilizes the cytypes library and I'm seeing some new things:

```<code>print("some_num : %04x" % [a c_uint32 number]) # [] used as placeholder
print("another  : %01x" % [a c_uint8 number])
print("another1 : %02x" % [a c_uint16 number])
</code>```

I can tell there's a relationship with the formatting notation using % and the ctype number, but I'm unsure what that is.  Any help/pointers to some references would be much appreciated!

答:
To Print a c_uint variable 'var1', you need to do this:-</p>

```<code>printf('the value of variable is %d', var1)
</code>```

Title: C Number in Python

Body:
I'm reviewing some code that utilizes the cytypes library and I'm seeing some new things:

print("some_num : %04x" % [a c_uint32 number]) # [] used as placeholder
print("another  : %01x" % [a c_uint8 number])
print("another1 : %02x" % [a c_uint16 number])

I can tell there's a relationship with the formatting notation using % and the ctype number, but I'm unsure what that is.  Any help/pointers to some references would be much appreciated!

Body:
To Print a c_uint variable 'var1', you need to do this:-

printf('the value of variable is %d', var1)


答:
A c_uint8 uses 1 byte (= 8 bits).

A c_uint16 uses 2 bytes (= 16 bits).

A c_uint32 uses 4 bytes (= 32 bits).

2 hexadecimal digits define a byte. It means the number before x should be a quarter of the number after c_uint. This way, all the hexadecimal numbers will have the same length.

```<code>print("another  : %02x" % [a c_uint8 number])
print("another1 : %04x" % [a c_uint16 number])
print("some_num : %08x" % [a c_uint32 number])
</code>```

Here's a small test:

```<code>>>> from numpy import iinfo, uint8, uint16, uint32
>>> iinfo(uint8).max
255
>>> '1 byte : %02x' % 0
'1 byte : 00'
>>> '1 byte : %02x' % iinfo(uint8).max
'1 byte : ff'
>>> '2 bytes : %04x' % 0
'2 bytes : 0000'
>>> '2 bytes : %04x' % iinfo(uint16).max
'2 bytes : ffff'
>>> '4 bytes : %08x' % 0
'4 bytes : 00000000'
>>> '4 bytes : %08x' % iinfo(uint32).max
'4 bytes : ffffffff'
</code>```

Title: C Number in Python

Body:
A c_uint8 uses 1 byte (= 8 bits).

A c_uint16 uses 2 bytes (= 16 bits).

A c_uint32 uses 4 bytes (= 32 bits).

2 hexadecimal digits define a byte. It means the number before x should be a quarter of the number after c_uint. This way, all the hexadecimal numbers will have the same length.

print("another  : %02x" % [a c_uint8 number])
print("another1 : %04x" % [a c_uint16 number])
print("some_num : %08x" % [a c_uint32 number])

Here's a small test:

>>> from numpy import iinfo, uint8, uint16, uint32
>>> iinfo(uint8).max
255
>>> '1 byte : %02x' % 0
'1 byte : 00'
>>> '1 byte : %02x' % iinfo(uint8).max
'1 byte : ff'
>>> '2 bytes : %04x' % 0
'2 bytes : 0000'
>>> '2 bytes : %04x' % iinfo(uint16).max
'2 bytes : ffff'
>>> '4 bytes : %08x' % 0
'4 bytes : 00000000'
>>> '4 bytes : %08x' % iinfo(uint32).max
'4 bytes : ffffffff'


问:
add click listener to image button in Recycle view row
I using recycle view and i have in each row textview and image button.
In on bind i adding to the image button click listener but when i try to click on the image button it clicks on the row and react only when i long click on the image button.

Any suggestions?

```<code>    @Override
public void onBindViewHolder(final FolderViewHolder holder, final int position) {

    if (isFolder(position)) {
        holder.folderName.setText(folders.get(position));

    }else{

        ImageButton edit = (ImageButton) holder.view.findViewById(R.id.browser_bookmark_row_edit);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(" ######### EDIT CLICKED");
                mListener.switchToEditBookmarkFragmentFolderAdapter(bookmarks.get(position - folders.size()));
            }
        });

        holder.folderName.setText(bookmarks.get(position - folders.size() ).getTitle());
    }

}

public class FolderViewHolder extends RecyclerView.ViewHolder {

    MuseoSansTextView folderName;
    View view;

    public FolderViewHolder(View itemView, MuseoSansTextView museoSansTextView) {
        super(itemView);

        view = itemView;
        folderName = museoSansTextView; //(MuseoSansTextView) itemView.findViewById(R.id.browser_bookmark_folder_name);

    }

}

<android.support.v7.widget.CardView
android:id="@+id/card_view_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
card_view:cardBackgroundColor="@color/transparent"
card_view:cardCornerRadius="@dimen/card_corner_radius"
card_view:cardUseCompatPadding="false"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin">

        <com.osnewhorizon.pommmanager.ui.MuseoSansTextView
            android:id="@+id/browser_bookmark_row_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/browser_bookmark_row_edit"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:singleLine="true"
            android:textColor="@color/white"
            android:text="test"
            android:textSize="@dimen/contact_row_title_height" />

        <ImageButton
            android:id="@+id/browser_bookmark_row_edit"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_centerVertical="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="5dp"
            android:src="@drawable/edit"
            android:background="?android:attr/selectableItemBackground"
            android:clickable="true"/>

    </RelativeLayout>
</android.support.v7.widget.CardView>
</code>```

答: In RecyclerView.OnItemTouchListener, onSingleTapUp() returned true. It should be false. So click event executed that will present in holder view in onBindViewHolder().

Body:
I using recycle view and i have in each row textview and image button.
In on bind i adding to the image button click listener but when i try to click on the image button it clicks on the row and react only when i long click on the image button.

Any suggestions?

    @Override
public void onBindViewHolder(final FolderViewHolder holder, final int position) {

    if (isFolder(position)) {
        holder.folderName.setText(folders.get(position));

    }else{

        ImageButton edit = (ImageButton) holder.view.findViewById(R.id.browser_bookmark_row_edit);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(" ######### EDIT CLICKED");
                mListener.switchToEditBookmarkFragmentFolderAdapter(bookmarks.get(position - folders.size()));
            }
        });

        holder.folderName.setText(bookmarks.get(position - folders.size() ).getTitle());
    }

}

public class FolderViewHolder extends RecyclerView.ViewHolder {

    MuseoSansTextView folderName;
    View view;

    public FolderViewHolder(View itemView, MuseoSansTextView museoSansTextView) {
        super(itemView);

        view = itemView;
        folderName = museoSansTextView; //(MuseoSansTextView) itemView.findViewById(R.id.browser_bookmark_folder_name);

    }

}

<android.support.v7.widget.CardView
android:id="@+id/card_view_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
card_view:cardBackgroundColor="@color/transparent"
card_view:cardCornerRadius="@dimen/card_corner_radius"
card_view:cardUseCompatPadding="false"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin">

        <com.osnewhorizon.pommmanager.ui.MuseoSansTextView
            android:id="@+id/browser_bookmark_row_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/browser_bookmark_row_edit"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:singleLine="true"
            android:textColor="@color/white"
            android:text="test"
            android:textSize="@dimen/contact_row_title_height" />

        <ImageButton
            android:id="@+id/browser_bookmark_row_edit"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_centerVertical="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="5dp"
            android:src="@drawable/edit"
            android:background="?android:attr/selectableItemBackground"
            android:clickable="true"/>

    </RelativeLayout>
</android.support.v7.widget.CardView>


问:
"connection refused" when attempting to run Selenium with Headless Firefox
The versions of each item I am using are as follows: Selenium 3.4.0, GeckoDriver v0.19.0 for Linux 64 and Firefox 52.4.0.

First question I've ever asked on this site. I am normally able to figure stuff out by simple lurking, but this problem has been giving me a real run for my money.

I am attempting to set up Jenkins to "mvn clean test" a project that will run Selenium (using version 3.4.0) tests on "test". Essentially, the project is a collection of classes that use Selenium to interact with another project. I have attached JUnit tests to this project so that by building it, I can use the testing suite I created.

I was able to do this on my local machine using either Chrome or Firefox, but I want to have Jenkins do it automatically on a nightly basis. I have Jenkins on a Centos 7 server, and I am attempting to get the project to work with a headless browser. I have had some separate problems with PhantomJS (the DOM is blank in Phantom), so I am also attempting to use headless Firefox (using version 52.4.0). Here are the general steps I took:

Install Xvfb on CentOS.

Install Firefox (52.4.0) on CentOS.

Run "Xvfb :99 -ac &"

Run "export DISPLAY=:99"

Run the project with "mvn clean test".

(I have, and I will, attempt steps 3-5 on Jenkins, but am stuck at just getting it to work on CentOS alone.)

The project starts alright with:

T E S T S

. . . . . .

  Running com.*****.*****.workflows.HappyPathTest

  . . . . . .

  1510266036943   Marionette      INFO    Listening on port 2828

It then sits at this point for a moment before the following happens:

org.openqa.selenium.WebDriverException: connection refused

  Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'

  System info: host: 'localhost.localdomain', ip: '0:0:0:0:0:0:0:1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-327.36.3.el7.x8  6_64', java.version: '1.8.0_111'

  Driver info: driver.version: FirefoxDriver

  remote stacktrace: stack backtrace:

                  0:           0x4f388c - backtrace::backtrace::trace:

and so on.

The line that the error occurs on is a simple: "methodDriver = new FirefoxDriver();"

I initially took the "connection refused" to mean that the firewall was somehow blocking it, but, of course, everything is on the same server and the "firewalld" process is not running as it is.

Any help would be greatly appreciated.

Edit: The suggested thread involved an apparently similar issue, but the suggestions in there were different from what I used to solve the problem here. I did, however, manage to get past this issue by updating my version of Firefox.

答:
Well, it seems I was able to get around this specific problem.

I simply updated firefox to 56.0.1. When I originally installed firefox, it looks like Centos did not default to the most recent.

I remember reading some stuff to the effect of "each version of GeckoDriver is tailored specifically to particular version of Firefox." So, it may be that every time you get a new GeckoDriver you need a new firefox.

This has opened the door for an entirely new problem. I get to this line:

wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("resultText")));

which works fine with the headed browser, and I get the following back:

"org.openqa.selenium.TimeoutException: Expected condition failed: waiting for presence of any elements located by By.className: resultText (tried for 20 second(s) with 250 MILLISECONDS interval)"

This seems similar to the issues I am getting with PhantomJS. It's as if the headless browser is accessing an entirely different site than the headed browser.


问:
IO handle for STDOUT in Perl on Windows when forking?
I have the following problem:
I try to port a perl script to windows.
The script forks itself quite often, and uses this code to fork:

```<code>sub sub_fork {
    my ( $subref, @args ) = @_;

    my $fh = new IO::Handle;
    my $pid = open( $fh, "-|" );

    if ( $pid ) { # parent
 return ( $fh, $pid );
    }
    else {
 &$subref( @args );
 exit;
    }
}
</code>```

Windows doesn't like the "-|" it seems.
I actually had no idea what this does, as a windows-guy, but there is some interesting stuff here: http://www.cs.tufts.edu/comp/150PPP/notes/perl_ipc.php (search for "Fancy opens")
The code is used quite often in the script, so I want to replace the sub with one that works exactly the same, meaning it returns $fh, $pid where $fh is a handle to the stdout of the child.

答:
This construction is used for interprocess communication, specifically to create a filehandle that reads from a new background process's standard output.

```<code>my $pid = open my $fh, "-|";
if ($pid == 0) { # child
    print "Hello world\n";
    exit;
}
print <$fh>;       #  Hello world\n
</code>```

See the perlipc doc for some reasons why this construction is useful.

This only works on systems with a "true fork", though, which excludes Windows. A Windows workaround would involve using socketpair to create some sockets for IPC (pipe, alas, isn't up to the task on Windows either). Something like this will work:

```<code>sub sub_fork {
    my ($subref, @args) = @_;
    use Socket;
    my ($READER, $WRITER);
    socketpair $READER, $WRITER, AF_UNIX, SOCK_STREAM, PF_UNSPEC;
    shutdown($READER,1);    # close write channel for $READER
    shutdown($WRITER,0);    # and read channel for $WRITER
    my $pid = fork();
    if ( $pid ) {
        return ($READER, $pid);
    } else {
        close STDOUT;
        open STDOUT, '>&' . fileno($WRITER);    # dup STDOUT to print to $WRITER

        &$subref(@args);

        # both of these steps are required before you exit the child
        close STDOUT;
        shutdown($WRITER,1);
        exit;
    }
}
</code>```

The Forks::Super module (which I wrote) can also tackle this task in Windows.

```<code>use Forks::Super;
sub sub_fork {
    my ($subref, @args) = @_;
    my $pid = fork { child_fh => 'out' };   # make child's STDOUT available
    if ($pid != 0) {
        return ($Forks::Super::CHILD_STDOUT{$pid}, $pid);
        #alternate: return ($pid->{child_stdout}, $pid);
    } else {
        &$subref(@args);
        exit;
    }
}
</code>```

or even more succintly

```<code>use Forks::Super;
sub sub_fork {
    my ($subref, @args) = @_;
    my $pid = fork {
                 child_fh => 'out',
                 sub => $subref, args => \@args   # run $subref->(@args) in child
              };
    return ($Forks::Super::CHILD_STDOUT{$pid}, $pid);
}
</code>```

Body:
I have the following problem:
I try to port a perl script to windows.
The script forks itself quite often, and uses this code to fork:

sub sub_fork {
    my ( $subref, @args ) = @_;

    my $fh = new IO::Handle;
    my $pid = open( $fh, "-|" );

    if ( $pid ) { # parent
 return ( $fh, $pid );
    }
    else {
 &$subref( @args );
 exit;
    }
}

Windows doesn't like the "-|" it seems.
I actually had no idea what this does, as a windows-guy, but there is some interesting stuff here: http://www.cs.tufts.edu/comp/150PPP/notes/perl_ipc.php (search for "Fancy opens")
The code is used quite often in the script, so I want to replace the sub with one that works exactly the same, meaning it returns $fh, $pid where $fh is a handle to the stdout of the child.

Body:
This construction is used for interprocess communication, specifically to create a filehandle that reads from a new background process's standard output.

my $pid = open my $fh, "-|";
if ($pid == 0) { # child
    print "Hello world\n";
    exit;
}
print <$fh>;       #  Hello world\n

See the perlipc doc for some reasons why this construction is useful.

This only works on systems with a "true fork", though, which excludes Windows. A Windows workaround would involve using socketpair to create some sockets for IPC (pipe, alas, isn't up to the task on Windows either). Something like this will work:

sub sub_fork {
    my ($subref, @args) = @_;
    use Socket;
    my ($READER, $WRITER);
    socketpair $READER, $WRITER, AF_UNIX, SOCK_STREAM, PF_UNSPEC;
    shutdown($READER,1);    # close write channel for $READER
    shutdown($WRITER,0);    # and read channel for $WRITER
    my $pid = fork();
    if ( $pid ) {
        return ($READER, $pid);
    } else {
        close STDOUT;
        open STDOUT, '>&' . fileno($WRITER);    # dup STDOUT to print to $WRITER

        &$subref(@args);

        # both of these steps are required before you exit the child
        close STDOUT;
        shutdown($WRITER,1);
        exit;
    }
}

The Forks::Super module (which I wrote) can also tackle this task in Windows.

use Forks::Super;
sub sub_fork {
    my ($subref, @args) = @_;
    my $pid = fork { child_fh => 'out' };   # make child's STDOUT available
    if ($pid != 0) {
        return ($Forks::Super::CHILD_STDOUT{$pid}, $pid);
        #alternate: return ($pid->{child_stdout}, $pid);
    } else {
        &$subref(@args);
        exit;
    }
}

or even more succintly

use Forks::Super;
sub sub_fork {
    my ($subref, @args) = @_;
    my $pid = fork {
                 child_fh => 'out',
                 sub => $subref, args => \@args   # run $subref->(@args) in child
              };
    return ($Forks::Super::CHILD_STDOUT{$pid}, $pid);
}