问:
How can I save an object to a file?
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

```<code>m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]
</code>```

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

答:
See Marshal: http://ruby-doc.org/core/classes/Marshal.html

-or-

YAML: http://www.ruby-doc.org/core/classes/YAML.html

Title: How can I save an object to a file?

Body:
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.


来源: stackexchange

问:
I want 7 days ahead of current date by using java 7 not java 8
```<code>String s= new java.util.Date().toString();
</code>```

<p>I am using java 7, I want to print one week ahead of this date I have used the calendar class but it always gives me IST 1970 and does not give correct answer and I want that date into string so please help me in this. I know this question is repeated but they cant solve my query?        </p>

答:
If you want date in string format then use Dateformat . Below is the complete code ,

```<code>    Date givenDate= new Date();
    DateFormat dateFormatter=new SimpleDateFormat("dd-MM-yy");
    Calendar c=Calendar.getInstance();
    c.setTime(givenDate);
    //This will print whole week after given date
    for(int i=1;i<8;i++){
        c.add(Calendar.DAY_OF_MONTH, 1);
        System.out.println(dateFormatter.format(c.getTime()));
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
String s= new java.util.Date().toString();

I am using java 7, I want to print one week ahead of this date I have used the calendar class but it always gives me IST 1970 and does not give correct answer and I want that date into string so please help me in this. I know this question is repeated but they cant solve my query?

Body:
If you want date in string format then use Dateformat . Below is the complete code ,

    Date givenDate= new Date();
    DateFormat dateFormatter=new SimpleDateFormat("dd-MM-yy");
    Calendar c=Calendar.getInstance();
    c.setTime(givenDate);
    //This will print whole week after given date
    for(int i=1;i<8;i++){
        c.add(Calendar.DAY_OF_MONTH, 1);
        System.out.println(dateFormatter.format(c.getTime()));
    }


问:
Error Domain=IDETestOperationsObserverErrorDomain Code=12 "Timed out trying to set AX messaging timeout
I get this error when building my iOS app on Travis CI. Can someone please help me with that?

Config: OSX 10.11.6, Xcode 8 beta 6, Swift 3.

答:
We're having the same issue on Xcode 8.1 using command line builds (not Travis). I found both links below useful. A machine reboot and test retry seems to mostly workaround the issue.

This GitHub issue on Travis suggested adding a build retry

This Fastlane GitHub issue suggests "turning it off and on again"


问:
RecyclerView - control item count by boolean
I'm using a RecyclerView where there is a boolean involved in getItemCount(). This boolean value controls the visibility of the last item in the RecyclerView, kinda like a load more view, but slightly different. From time to time, the value of this boolean changes, so the RecyclerView will know whether to include the last item.

The code looks something like this

```<code>@Override
public int getItemCount() {
    return mItemArray.size() + (shouldShow ? 1 : 0);
}
</code>```

When the value of shouldShow gets updated, I'm not calling notifyDataSetChanged() or notifyItemChanged(), but the RecyclerView still gets updated properly. But I worry it will eventually cause the RecyclerView to crash because of inconsistency. My questions are,

Is using a dynamic boolean value in getItemCount() a proper way to control RecyclerView size?

Should I call notify...() when the value of this boolean changes?

Would my RecyclerView crashes for inconsistency because of this?

答:
1.It's ok

2.If you want the last item to be shown right after your boolean variable has changed you should call notifyDataSetChanged(), because getItemCount() will not be called by the adapter until recycler view is scrolled.

3.The app can crash if you don't handle all the behaviour. For example you take some item from your mItemArray inside onBindViewHolder() method, and when getItemCount() returns the number bigger than the size of your array, the app will throw IndexOutOfBoundException. In this case you should check if position is smaller than size of your array.

```<code>if (position < mItemArray.size()){
    //you can get item from the array
} else {
    //handle your additional item
}
</code>```

Body:
I'm using a RecyclerView where there is a boolean involved in getItemCount(). This boolean value controls the visibility of the last item in the RecyclerView, kinda like a load more view, but slightly different. From time to time, the value of this boolean changes, so the RecyclerView will know whether to include the last item.

The code looks something like this

@Override
public int getItemCount() {
    return mItemArray.size() + (shouldShow ? 1 : 0);
}

When the value of shouldShow gets updated, I'm not calling notifyDataSetChanged() or notifyItemChanged(), but the RecyclerView still gets updated properly. But I worry it will eventually cause the RecyclerView to crash because of inconsistency. My questions are,

Is using a dynamic boolean value in getItemCount() a proper way to control RecyclerView size?

Should I call notify...() when the value of this boolean changes?

Would my RecyclerView crashes for inconsistency because of this?

Body:
1.It's ok

2.If you want the last item to be shown right after your boolean variable has changed you should call notifyDataSetChanged(), because getItemCount() will not be called by the adapter until recycler view is scrolled.

3.The app can crash if you don't handle all the behaviour. For example you take some item from your mItemArray inside onBindViewHolder() method, and when getItemCount() returns the number bigger than the size of your array, the app will throw IndexOutOfBoundException. In this case you should check if position is smaller than size of your array.

if (position < mItemArray.size()){
    //you can get item from the array
} else {
    //handle your additional item
}


问:
How to solve Invalid JSON Primitive error on Ajax?
I am trying to perform ajax using webmethod on Asp.net,

And I am using JQuery-3.1.1

I want to pass the value to server and get back the value. I don't know what I did wrong.

Asp.net Code

```<code><div class="row">
   <asp:Button ID="btnSave" runat="server" CssClass="btn btn-info"  Text="save" />
</div>
</code>```

Jquery Code

```<code>$(document).ready(function () {
    $('#btnSave').click(function () {
        var name= 'xxx';

        $.ajax({
            type: "POST",
            url: "AjaxWebMethod.aspx/getFileExistOrNot",
            data: '{fileName:'+name+'}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("failed ="+response.d);
            },
            error: function (response) {
                alert("error ="+response.d);  //This alert is executing
            }
        });

        function OnSuccess(response) {
            alert("Result ="+response.d.mydata);
        }
        return false;
    });
});
</code>```

C# code

```<code>public partial class AjaxWebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string mydata="ajaxworking";
        return mydata;
    }
}
</code>```

I don't know really where I did my mistake

Error message on console

{Message: "Invalid JSON primitive: xxx.",…}

ExceptionType:"System.ArgumentException"

Message:"Invalid JSON primitive: xxx."

Can you give the solution with proper reason. that will good for me to understand more, thanks

答: The jQuery call that you are making is set up to expect JSON format in the response.  It would appear that your server side code is simply returning a string which is not encoded as JSON.  You either need to change the output from the server or change what is expected from the ajax invocation.</p>

Body:
I am trying to perform ajax using webmethod on Asp.net,

And I am using JQuery-3.1.1

I want to pass the value to server and get back the value. I don't know what I did wrong.

Asp.net Code

   <asp:Button ID="btnSave" runat="server" CssClass="btn btn-info"  Text="save" />

Jquery Code

$(document).ready(function () {
    $('#btnSave').click(function () {
        var name= 'xxx';

        $.ajax({
            type: "POST",
            url: "AjaxWebMethod.aspx/getFileExistOrNot",
            data: '{fileName:'+name+'}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("failed ="+response.d);
            },
            error: function (response) {
                alert("error ="+response.d);  //This alert is executing
            }
        });

        function OnSuccess(response) {
            alert("Result ="+response.d.mydata);
        }
        return false;
    });
});

C# code

public partial class AjaxWebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string mydata="ajaxworking";
        return mydata;
    }
}

I don't know really where I did my mistake

Error message on console

{Message: "Invalid JSON primitive: xxx.",…}

ExceptionType:"System.ArgumentException"

Message:"Invalid JSON primitive: xxx."

Can you give the solution with proper reason. that will good for me to understand more, thanks


问:
Contains with a predicate (/find/search) for a java.util.concurrent.BlockingQueue?
The java.util.concurrent.BlockingQueue has a convenient contains method:

```<code>/**
 * Returns {@code true} if this queue contains the specified element.
 * More formally, returns {@code true} if and only if this queue contains
 * at least one element {@code e} such that {@code o.equals(e)}.
 *
 * @param o object to be checked for containment in this queue
 * @return {@code true} if this queue contains the specified element
 * @throws ClassCastException if the class of the specified element
 *         is incompatible with this queue
 *         (<a href="../Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if the specified element is null
 *         (<a href="../Collection.html#optional-restrictions">optional</a>)
 */
public boolean contains(Object o);
</code>```

My need is a bit more specific: to apply a predicate / search criteria. Is there any way to do this short of

```<code>  Using a ArrayBlockQueue
  Invoking toArray
</code>```

That will work .. but what if the queue were large? This could cause memory allocation issues.

答:
You could just stream over the Queue (in parallel if you'd like) and filter out your element using your predicate. BlockingQueue is a Queue, which is a Collection and thus defines stream() and parallelStream(). Something along the following:

```<code>public class SampleApplication {

    private static final int ELEMENT_COUNT = 100000;

    public static void main(String[] args) {
        Queue<Element> blockingQueue = new ArrayBlockingQueue<>(ELEMENT_COUNT);
        List<Element> elements = Stream.generate(SampleApplication::createElement).limit(ELEMENT_COUNT).collect(Collectors.toList());
        blockingQueue.addAll(elements);

        blockingQueue.stream().filter(getFilterPredicate(5)).findAny().ifPresent(System.out::println);
        blockingQueue.stream().filter(getFilterPredicate(105)).findAny().ifPresent(System.out::println);
        blockingQueue.stream().filter(getFilterPredicate(-1)).findAny().ifPresent(System.out::println);
    }

    private static Predicate<Element> getFilterPredicate(int value) {
        return e -> e.getId() == value;
    }

    private static int i = 0;
    private static Element createElement() {
        return new Element(++i);
    }

    static class Element {
        private int id;
        private String message;

        public Element(int id) {
            this.id = id;
            this.message = "Default msg";
        }

        //Getters, Setters & toString omitted
    }
}
</code>```

Having the following output the found values:

```<code>Element{id=5, message=Default msg}
Element{id=105, message=Default msg}
</code>```

Body:
The java.util.concurrent.BlockingQueue has a convenient contains method:

/**
 * Returns {@code true} if this queue contains the specified element.
 * More formally, returns {@code true} if and only if this queue contains
 * at least one element {@code e} such that {@code o.equals(e)}.
 *
 * @param o object to be checked for containment in this queue
 * @return {@code true} if this queue contains the specified element
 * @throws ClassCastException if the class of the specified element
 *         is incompatible with this queue
 *         (optional)
 * @throws NullPointerException if the specified element is null
 *         (optional)
 */
public boolean contains(Object o);

My need is a bit more specific: to apply a predicate / search criteria. Is there any way to do this short of

  Using a ArrayBlockQueue
  Invoking toArray

That will work .. but what if the queue were large? This could cause memory allocation issues.

Body:
You could just stream over the Queue (in parallel if you'd like) and filter out your element using your predicate. BlockingQueue is a Queue, which is a Collection and thus defines stream() and parallelStream(). Something along the following:

public class SampleApplication {

    private static final int ELEMENT_COUNT = 100000;

    public static void main(String[] args) {
        Queue<Element> blockingQueue = new ArrayBlockingQueue<>(ELEMENT_COUNT);
        List<Element> elements = Stream.generate(SampleApplication::createElement).limit(ELEMENT_COUNT).collect(Collectors.toList());
        blockingQueue.addAll(elements);

        blockingQueue.stream().filter(getFilterPredicate(5)).findAny().ifPresent(System.out::println);
        blockingQueue.stream().filter(getFilterPredicate(105)).findAny().ifPresent(System.out::println);
        blockingQueue.stream().filter(getFilterPredicate(-1)).findAny().ifPresent(System.out::println);
    }

    private static Predicate<Element> getFilterPredicate(int value) {
        return e -> e.getId() == value;
    }

    private static int i = 0;
    private static Element createElement() {
        return new Element(++i);
    }

    static class Element {
        private int id;
        private String message;

        public Element(int id) {
            this.id = id;
            this.message = "Default msg";
        }

        //Getters, Setters & toString omitted
    }
}

Having the following output the found values:

Element{id=5, message=Default msg}
Element{id=105, message=Default msg}


问:
Sort an ArrayList base on multiple attributes
I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?

答:
If you want sample code looks like, you can use following:</p>

```<code>Collections.sort(foos, new Comparator<Foo>{
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you want sample code looks like, you can use following:

Collections.sort(foos, new Comparator<Foo>{
    public int compare(Foo a, Foo b) {
        int dateComparison = a.date.compareTo(b.date);
        return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
    }
});


问:
Android BLE LeScanCallback get when stopped
I have a dialog that scans for BLE devices for 10 seconds. When I start my scan I enable a spinner at the footer of the list. When the scan is completed I'd like to remove that spinner. I'm trying to get this to work with the deprecated mBluetoothAdapter.stopLeScan(callback) function instead of the new startScan/stopScan functions as if the device isn't running version 21 or higher, you have to fallback to this method.

stopLeScan requires the same callback as startLeScan but I dont think I see the callback being made. I was hoping that it was a simple check to see if the BluetoohDevice was null, then the callback was made because the scan was stopped, but this didn't work.

With the old version of the SDK, how do you get when the scan has been stopped (either due to the proper device being found or the scan time completed)? I could pass another handler to the my scanLeDevice function, but that just seems silly as I'm already passing a callback.

Bluetooth scanner

```<code>public class BleDevice {
    private final static String TAG = BleDevice.class.getSimpleName();

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    public BleDevice() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mHandler = new Handler();
    }

    public void scanLeDevice(final boolean enable, final BluetoothAdapter.LeScanCallback callback) {
        if (enable == true && mScanning == false) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Turn off scanning
                    scanLeDevice(false, callback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(callback);
            Log.d(TAG, "Starting Bluetooth LE scan");
        } else if(enable == false && mScanning == true) {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(callback);
            Log.d(TAG, "Stopped Bluetooth LE scan");
        }
    }
}
</code>```

Callback in Dialog Box:

```<code>private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.d(TAG, device.getAddress() + " " + device.getName() + "");
        if(device == null) {
            Log.d(TAG, "Device is null? stop?");
        } else {
            btAdapter.add(device);
        }
    }
};
</code>```

答:
In mBluetoothAdapter.stopLeScan(callback); the callback is just used to identify which scan is to be stopped and it's not supposed to trigger any method in the callback. It's a synchronous operation.

And the BluetoothAdapter.LeScanCallback class doesn't even have any methods beyond the onLeScan() which just receives the results.

So, you can define your own method to be triggered when the scan is stopped by you:

```<code>...
} else if(enable == false && mScanning == true) {
    mScanning = false;
    mBluetoothAdapter.stopLeScan(callback);
    Log.d(TAG, "Stopped Bluetooth LE scan");
    onScanStopped(); // <--- Remove the spinner here.
}
</code>```

I'm not aware of any automatic timeout for startLeScan(), so as far as I know it should only stop by calling stopLeScan(). And onLeScan() being triggered doesn't stop the scan either.

Body:
I have a dialog that scans for BLE devices for 10 seconds. When I start my scan I enable a spinner at the footer of the list. When the scan is completed I'd like to remove that spinner. I'm trying to get this to work with the deprecated mBluetoothAdapter.stopLeScan(callback) function instead of the new startScan/stopScan functions as if the device isn't running version 21 or higher, you have to fallback to this method.

stopLeScan requires the same callback as startLeScan but I dont think I see the callback being made. I was hoping that it was a simple check to see if the BluetoohDevice was null, then the callback was made because the scan was stopped, but this didn't work.

With the old version of the SDK, how do you get when the scan has been stopped (either due to the proper device being found or the scan time completed)? I could pass another handler to the my scanLeDevice function, but that just seems silly as I'm already passing a callback.

Bluetooth scanner

public class BleDevice {
    private final static String TAG = BleDevice.class.getSimpleName();

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    public BleDevice() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mHandler = new Handler();
    }

    public void scanLeDevice(final boolean enable, final BluetoothAdapter.LeScanCallback callback) {
        if (enable == true && mScanning == false) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Turn off scanning
                    scanLeDevice(false, callback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(callback);
            Log.d(TAG, "Starting Bluetooth LE scan");
        } else if(enable == false && mScanning == true) {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(callback);
            Log.d(TAG, "Stopped Bluetooth LE scan");
        }
    }
}

Callback in Dialog Box:

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.d(TAG, device.getAddress() + " " + device.getName() + "");
        if(device == null) {
            Log.d(TAG, "Device is null? stop?");
        } else {
            btAdapter.add(device);
        }
    }
};

Body:
In mBluetoothAdapter.stopLeScan(callback); the callback is just used to identify which scan is to be stopped and it's not supposed to trigger any method in the callback. It's a synchronous operation.

And the BluetoothAdapter.LeScanCallback class doesn't even have any methods beyond the onLeScan() which just receives the results.

So, you can define your own method to be triggered when the scan is stopped by you:

...
} else if(enable == false && mScanning == true) {
    mScanning = false;
    mBluetoothAdapter.stopLeScan(callback);
    Log.d(TAG, "Stopped Bluetooth LE scan");
    onScanStopped(); // <--- Remove the spinner here.
}

I'm not aware of any automatic timeout for startLeScan(), so as far as I know it should only stop by calling stopLeScan(). And onLeScan() being triggered doesn't stop the scan either.


问:
"many to many to many" relation
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

```<code>CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);
</code>```

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?

答:
Ingredients

ID (int) (pkey) (ai)

Name (varchar)

Synonyms

ID (int) (pkey) (ai)

IngredientID (int) (foreign key maps to: Ingredients.ID)

Name (varchar)

Flag (optional; sample values: IUPAC Name, Common Name, Spanish Name, ...)

So yes, for the rules you described, you will at minimum have a primary name, and then a synonym table using the Ingredients.ID

I also introduced a Flag field so that you can programmatically choose when to use a synonym rather than just hard-coding it all the time. For example, if you're listing a product flagged as an industrial chemical, it would be programmed to pull the IUPAC* name

*IUPAC refers to conventions for naming chemicals, and is used by professional chemists almost always, but almost never used in consumer supermarkets: http://www.chem.uiuc.edu/GenChemReferences/nomenclature_rules.html

Title: "many to many to many" relation

Body:
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?


问:
google doc reader : remove the option "Open in new window"
Is there any way of removing or disabling the 'open in new window' icon of google doc reader( when used in embedded mode interface) through the embedded code(which we write for embedding documents) or javascript/jquery?</p>

答:
I don't know if there is any standard method. If you really want to do it, then you can try something like this.</p>

```<code><html>
    <body>
        <div style='position:relative;'>
            <div style='background-color:White;top:0px; height: 47px; position: absolute; left:0px; width: 100%;'></div>
            <div style='background-color:LightGray;top:47px; height: 5px; position: absolute; left:0px; width: 100%;'></div>
            <iframe src='http://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&embedded=true' width='100%' height='100%' style='border: none;'/>
        </div>
    </body>
</html>
</code>```

Body:
I don't know if there is any standard method. If you really want to do it, then you can try something like this.

<html>
    <body>
        <div style='position:relative;'>
            <div style='background-color:White;top:0px; height: 47px; position: absolute; left:0px; width: 100%;'></div>
            <div style='background-color:LightGray;top:47px; height: 5px; position: absolute; left:0px; width: 100%;'></div>
            <iframe src='http://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&embedded=true' width='100%' height='100%' style='border: none;'/>
        </div>
    </body>
</html>


问:
Javascript Uncaught TypeError: Cannot read property 'append' of null in code
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>

    <script>

function checkDistance(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 51.714236,
      "lon": 50.710236
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
];

for(var i = 0;i < data.length;i++){

    var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

    if(result <= distanceLimit){
        var resultList = document.getElementById('resultList');
        resultList.append(data[i].name + ', ');
    }
}

    </script>

</head>
<body>

   <div id="resultList"></div>

</body>
</html>
</code>```

Why I'm I getting this error and how can I fix it?

答:
Your javascript code executes even before the html is loaded, due to which it is unable to locate 'resultList' element.

Wrap your below code in some function.

```<code>function foo(){
    for(var i = 0;i < data.length;i++){
        var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);
        if(result <= distanceLimit){
            var resultList = document.getElementById('resultList');
            resultList.append(data[i].name + ', ');
        }
    }
}
</code>```

Now call this function through onload() event which will be executed only when whole page is loaded.

```<code><body onload="foo()">
   <div id="resultList"></div>
</body>
</code>```

Body:
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

<!DOCTYPE html>

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

Why I'm I getting this error and how can I fix it?

Body:
Your javascript code executes even before the html is loaded, due to which it is unable to locate 'resultList' element.

Wrap your below code in some function.

function foo(){
    for(var i = 0;i < data.length;i++){
        var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);
        if(result <= distanceLimit){
            var resultList = document.getElementById('resultList');
            resultList.append(data[i].name + ', ');
        }
    }
}

Now call this function through onload() event which will be executed only when whole page is loaded.

<body onload="foo()">
   <div id="resultList"></div>
</body>


问:
Android Color Picker
Does anyone know of a quick color picker widget that I could grab to use in my application?

I've seen one in a few different applications that have a wheel with colors, and that you tap in the center to select, but I'm not sure where to find it.

Any color picker would be fine though.

答:
You can use CommonsWare's cwac-colormixer.

It's an android library now! :)

Title: Android Color Picker


问:
Check if list view contain item
i have a listview with 3 columns (id , name, author), i use this method to add row:

```<code>     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }
</code>```

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

```<code>  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }
</code>```

Can you help me please? thank you

答:
It looks like you are storing your individual names on the SubItems property, so you'll need to query that to see if a given book name is present. You can do this using a bit of LINQ as follows:

```<code>// If your ListView doesn't contain any items that have a given book as a SubItem
// then add one
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
{
    listView1.Items.Add(lvi1);
}
</code>```

Since your edit indicates that you actually want to check for the ID instead, which is stored at the ListItem-level, then you would just need to slightly adjust your condition to check the Text property since the ListViewItem(string) constructor sets the Text property by default:

```<code>if (!listView1.Items.Any(i => i.Text == book.id))
{
     listView1.Items.Add(lvi1);
}
</code>```

Title: Check if list view contain item

Body:
i have a listview with 3 columns (id , name, author), i use this method to add row:

     public void addToLv(Book book)
    {

        //TODO: Verifier si l'item existe avant d'ajouter
        ListViewItem lvi1 = new ListViewItem(book.id.ToString());
        lvi1.Text = book.id.ToString();
        lvi1.SubItems.Add(book.name);
        lvi1.SubItems.Add(carte.author);

        listView1.Items.Add(lvi1);

    }

Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:

  (listView1.Items.ContainsKey(book.id))
         {
      listView1.Items.Add(lvi1);
         }

Can you help me please? thank you

Body:
It looks like you are storing your individual names on the SubItems property, so you'll need to query that to see if a given book name is present. You can do this using a bit of LINQ as follows:

// If your ListView doesn't contain any items that have a given book as a SubItem
// then add one
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
{
    listView1.Items.Add(lvi1);
}

Since your edit indicates that you actually want to check for the ID instead, which is stored at the ListItem-level, then you would just need to slightly adjust your condition to check the Text property since the ListViewItem(string) constructor sets the Text property by default:

if (!listView1.Items.Any(i => i.Text == book.id))
{
     listView1.Items.Add(lvi1);
}


问:
Private repo dependency installs but "Cannot Find Module"
I have a project that requires a private repo as a dependency. So, projectA has this included in the package.json as "projectB": "user/repo". This installs just fine, and is listed in projectA node_modules. The problem is, that node throws and error where I require the functions of the dependency. The error being that "Cannot find module projectB". As mentioned, projectB is listed in node_modules. Here is the structure of projectB:

```<code>.
├── README.md
├── file1.js
├── file2.js
├── file3.js
├── file4.js
└── package.json
</code>```

It also has its own node_modules, but I've left that out. Now, here is what file1.js might look like:

```<code>function getResult (a, b) {
  return a + b;
}

module.exports = { getResult }
</code>```

And here is what projectA looks like:

```<code>var calculate = require('projectB').file1.getResult; // I've tried this in several other ways too
</code>```

Calling calculate results in the "Cannot find module error". Have I done something fundamentally wrong in setting up for using a private repo as dependency and/or requiring it wrong?

Update projectB package.json

```<code>{
  "name": "projectB",
  "version": "1.0.0",
  "description": "Backend utility functions",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "Me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com//user/repo/issues"
  },
  "homepage": "https://github.com//user/repo#readme",
  "dependencies": {
    "lodash": "^4.17.4",
    "mongodb": "^2.2.25",
    "redis": "^2.7.1",
    "winston": "^2.3.1"
  }
}
</code>```

答:
projectB needs to be updated to set an appropriate main, but by default this will be index.js. You could do something like the following:

```<code>// projectB/index.js
exports.file1 = require("./file1");
exports.file2 = require("./file2");
exports.file3 = require("./file3");
exports.file4 = require("./file4");
</code>```

It's actually a pretty common pattern to have an index.js that does nothing but export from library files.

Body:
I have a project that requires a private repo as a dependency. So, projectA has this included in the package.json as "projectB": "user/repo". This installs just fine, and is listed in projectA node_modules. The problem is, that node throws and error where I require the functions of the dependency. The error being that "Cannot find module projectB". As mentioned, projectB is listed in node_modules. Here is the structure of projectB:

.
├── README.md
├── file1.js
├── file2.js
├── file3.js
├── file4.js
└── package.json

It also has its own node_modules, but I've left that out. Now, here is what file1.js might look like:

function getResult (a, b) {
  return a + b;
}

module.exports = { getResult }

And here is what projectA looks like:

var calculate = require('projectB').file1.getResult; // I've tried this in several other ways too

Calling calculate results in the "Cannot find module error". Have I done something fundamentally wrong in setting up for using a private repo as dependency and/or requiring it wrong?

Update projectB package.json

{
  "name": "projectB",
  "version": "1.0.0",
  "description": "Backend utility functions",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "Me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com//user/repo/issues"
  },
  "homepage": "https://github.com//user/repo#readme",
  "dependencies": {
    "lodash": "^4.17.4",
    "mongodb": "^2.2.25",
    "redis": "^2.7.1",
    "winston": "^2.3.1"
  }
}

Body:
projectB needs to be updated to set an appropriate main, but by default this will be index.js. You could do something like the following:

// projectB/index.js
exports.file1 = require("./file1");
exports.file2 = require("./file2");
exports.file3 = require("./file3");
exports.file4 = require("./file4");

It's actually a pretty common pattern to have an index.js that does nothing but export from library files.


问:
Postgres Proper Index for Sorting and Join
I have a simple schema and query, but am experiencing consistent awful performance with certain parameters.

Schema:

```<code>CREATE TABLE locations (
  id integer NOT NULL,
  barcode_id integer NOT NULL
);

CREATE TABLE barcodes (
  id integer NOT NULL,
  value citext NOT NULL
);

ALTER TABLE ONLY locations ADD CONSTRAINT locations_pkey PRIMARY KEY (id);
ALTER TABLE ONLY barcodes ADD CONSTRAINT barcodes_pkey PRIMARY KEY (id);
ALTER TABLE ONLY locations ADD CONSTRAINT fk_locations_barcodes FOREIGN KEY (barcode_id) REFERENCES barcodes(id);

CREATE INDEX index_barcodes_on_value ON barcodes (value);
CREATE INDEX index_locations_on_barcode_id ON locations (barcode_id);
</code>```

Query:

```<code>EXPLAIN ANALYZE
SELECT *
FROM locations
JOIN barcodes ON locations.barcode_id = barcodes.id
ORDER BY barcodes.value ASC
LIMIT 50;
</code>```

Analysis:

```<code>Limit  (cost=0.71..3564.01 rows=50 width=34) (actual time=0.043..683.025 rows=50 loops=1)
  ->  Nested Loop  (cost=0.71..4090955.00 rows=57404 width=34) (actual time=0.043..683.017 rows=50 loops=1)
        ->  Index Scan using index_barcodes_on_value on barcodes  (cost=0.42..26865.99 rows=496422 width=15) (actual time=0.023..218.775 rows=372138 loops=1)
        ->  Index Scan using index_locations_on_barcode_id on locations  (cost=0.29..5.32 rows=287 width=8) (actual time=0.001..0.001 rows=0 loops=372138)
              Index Cond: (barcode_id = barcodes.id)
Planning time: 0.167 ms
Execution time: 683.078 ms
</code>```

500+ ms for the number of entries in my schema (500,000 barcodes and 60,000 locations) doesn't make sense. Can I do anything to improve the performance?

Note:

Even stranger is the execution time depends on the data. In drafting this question I attempted to include seeded random data, but the seeds seem to be performant:

Seed:

```<code>INSERT INTO barcodes (id, value) SELECT seed.id, gen_random_uuid() FROM generate_series(1,500000) AS seed(id);
INSERT INTO locations (id, barcode_id) SELECT seed.id, (RANDOM() * 500000)  FROM generate_series(1,60000) AS seed(id);
</code>```

Analysis:

```<code>Limit  (cost=0.71..3602.63 rows=50 width=86) (actual time=0.089..1.123 rows=50 loops=1)
  ->  Nested Loop  (cost=0.71..4330662.42 rows=60116 width=86) (actual time=0.088..1.115 rows=50 loops=1)
        ->  Index Scan using index_barcodes_on_value on barcodes  (cost=0.42..44972.42 rows=500000 width=41) (actual time=0.006..0.319 rows=376 loops=1)
        ->  Index Scan using index_locations_on_barcode_id on locations  (cost=0.29..5.56 rows=301 width=8) (actual time=0.002..0.002 rows=0 loops=376)
              Index Cond: (barcode_id = barcodes.id)
Planning time: 0.213 ms
Execution time: 1.152 ms
</code>```

Edit:

Analysis of the tables:

```<code>ANALYZE VERBOSE barcodes;
INFO:  analyzing "public.barcodes"
INFO:  "barcodes": scanned 2760 of 2760 pages, containing 496157 live
rows and 0 dead rows; 30000 rows in sample, 496157 estimated total rows
ANALYZE
Time: 62.937 ms

ANALYZE VERBOSE locations;
INFO:  analyzing "public.locations"
INFO:  "locations": scanned 254 of 254 pages, containing 57394 live rows
and 0 dead rows; 30000 rows in sample, 57394 estimated total rows
ANALYZE
Time: 21.447 ms
</code>```

答:
The problem is that the barcodes with low values don't have matches in locations, which PostgreSQL cannot know. So its plan to fetch the barcodes in the correct output order via the index and then join values from locations until it found 50 of them is much worse than it expected.

I would ANALYZE the tables and

```<code>DROP INDEX index_barcodes_on_value;
</code>```

That should keep PostgreSQL from choosing that plan.

I don't know what plan PostgreSQL will choose then.
For a nested loop the following index might help:

```<code>CREATE INDEX ON locations(id);
</code>```

Body:
I have a simple schema and query, but am experiencing consistent awful performance with certain parameters.

Schema:

CREATE TABLE locations (
  id integer NOT NULL,
  barcode_id integer NOT NULL
);

CREATE TABLE barcodes (
  id integer NOT NULL,
  value citext NOT NULL
);

ALTER TABLE ONLY locations ADD CONSTRAINT locations_pkey PRIMARY KEY (id);
ALTER TABLE ONLY barcodes ADD CONSTRAINT barcodes_pkey PRIMARY KEY (id);
ALTER TABLE ONLY locations ADD CONSTRAINT fk_locations_barcodes FOREIGN KEY (barcode_id) REFERENCES barcodes(id);

CREATE INDEX index_barcodes_on_value ON barcodes (value);
CREATE INDEX index_locations_on_barcode_id ON locations (barcode_id);

Query:

EXPLAIN ANALYZE
SELECT *
FROM locations
JOIN barcodes ON locations.barcode_id = barcodes.id
ORDER BY barcodes.value ASC
LIMIT 50;

Analysis:

Limit  (cost=0.71..3564.01 rows=50 width=34) (actual time=0.043..683.025 rows=50 loops=1)
  ->  Nested Loop  (cost=0.71..4090955.00 rows=57404 width=34) (actual time=0.043..683.017 rows=50 loops=1)
        ->  Index Scan using index_barcodes_on_value on barcodes  (cost=0.42..26865.99 rows=496422 width=15) (actual time=0.023..218.775 rows=372138 loops=1)
        ->  Index Scan using index_locations_on_barcode_id on locations  (cost=0.29..5.32 rows=287 width=8) (actual time=0.001..0.001 rows=0 loops=372138)
              Index Cond: (barcode_id = barcodes.id)
Planning time: 0.167 ms
Execution time: 683.078 ms

500+ ms for the number of entries in my schema (500,000 barcodes and 60,000 locations) doesn't make sense. Can I do anything to improve the performance?

Note:

Even stranger is the execution time depends on the data. In drafting this question I attempted to include seeded random data, but the seeds seem to be performant:

Seed:

INSERT INTO barcodes (id, value) SELECT seed.id, gen_random_uuid() FROM generate_series(1,500000) AS seed(id);
INSERT INTO locations (id, barcode_id) SELECT seed.id, (RANDOM() * 500000)  FROM generate_series(1,60000) AS seed(id);

Analysis:

Limit  (cost=0.71..3602.63 rows=50 width=86) (actual time=0.089..1.123 rows=50 loops=1)
  ->  Nested Loop  (cost=0.71..4330662.42 rows=60116 width=86) (actual time=0.088..1.115 rows=50 loops=1)
        ->  Index Scan using index_barcodes_on_value on barcodes  (cost=0.42..44972.42 rows=500000 width=41) (actual time=0.006..0.319 rows=376 loops=1)
        ->  Index Scan using index_locations_on_barcode_id on locations  (cost=0.29..5.56 rows=301 width=8) (actual time=0.002..0.002 rows=0 loops=376)
              Index Cond: (barcode_id = barcodes.id)
Planning time: 0.213 ms
Execution time: 1.152 ms

Edit:

Analysis of the tables:

ANALYZE VERBOSE barcodes;
INFO:  analyzing "public.barcodes"
INFO:  "barcodes": scanned 2760 of 2760 pages, containing 496157 live
rows and 0 dead rows; 30000 rows in sample, 496157 estimated total rows
ANALYZE
Time: 62.937 ms

ANALYZE VERBOSE locations;
INFO:  analyzing "public.locations"
INFO:  "locations": scanned 254 of 254 pages, containing 57394 live rows
and 0 dead rows; 30000 rows in sample, 57394 estimated total rows
ANALYZE
Time: 21.447 ms

Body:
The problem is that the barcodes with low values don't have matches in locations, which PostgreSQL cannot know. So its plan to fetch the barcodes in the correct output order via the index and then join values from locations until it found 50 of them is much worse than it expected.

I would ANALYZE the tables and

DROP INDEX index_barcodes_on_value;

That should keep PostgreSQL from choosing that plan.

I don't know what plan PostgreSQL will choose then.
For a nested loop the following index might help:

CREATE INDEX ON locations(id);


问:
innerHTML with added script
I have the below code:

```<code><div id="test"></div>
<script type="text/javascript">
$(document).ready(function checker () {
    if(window.location.href.indexOf("project") > -1) {
        document.getElementById('test').innerHTML = "CONTAINS KEYWORD";
    } else {
        document.getElementById('test').innerHTML = 'no keyword';
    }
    setInterval(checker,1000);
});
</script>
</code>```

This checks to see if the URL contains the word "project" and if so displays "contains keyword". If it does not is shows "no keyword". It also keeps checking for this every second.

The problem is I need to replace "CONTAINS KEYWORD" with :

```<code> <tr>
  <td  align="right"><a onClick="javascript:addURL(this);" href="https://www.facebook.com/sharer.php?src=sp&u=" target="new"><img src="http://example.co.uk/planner-files/facebook.png"></a></td>
  <td  align="left"><a onClick="javascript:addURL(this);" href="https://twitter.com/intent/tweet?text=Check out my kitchen design http://example.co.uk/planner-files/kitchen-share.jpg&hashtags=example&url="  target="_blank"><img src="http://example.co.uk/planner-files/twitter.png"></a></td>
</tr>
</code>```

I'm used to php where you would add e.g. a / before the " etc but I don't know how I can get around this with .

Any ideas? If possible, please include examples.

答:
It would be much easier for you to toggle the visibility of the markup you want instead of rendering it each time the condition is evaluated.

I'd create a class that hides by default:

```<code><style type="text/css">.hidden{ display: none; }</style>
</code>```

Then all you need to do is add or remove the class from the test div:

```<code>var testDiv = document.getElementById('test');
var hasProjectInURL = location.href.indexOf('project') > -1;
testDiv.className = hasProjectInURL ? '' : 'hidden';
</code>```

Title: innerHTML with added script

Body:
I have the below code:

This checks to see if the URL contains the word "project" and if so displays "contains keyword". If it does not is shows "no keyword". It also keeps checking for this every second.

The problem is I need to replace "CONTAINS KEYWORD" with :

I'm used to php where you would add e.g. a / before the " etc but I don't know how I can get around this with .

Any ideas? If possible, please include examples.

Body:
It would be much easier for you to toggle the visibility of the markup you want instead of rendering it each time the condition is evaluated.

I'd create a class that hides by default:

<style type="text/css">.hidden{ display: none; }</style>

Then all you need to do is add or remove the class from the test div:

var testDiv = document.getElementById('test');
var hasProjectInURL = location.href.indexOf('project') > -1;
testDiv.className = hasProjectInURL ? '' : 'hidden';


问:
Ordering of atomics with `memory_order_seq_cst`
My reading of the C11 spec with regards to atomic operation ordering suggests that memory_order_seq_cst applies to operations on a specific atomic object.

Mostly, the descriptions are of the form "If a A and B are applied to M, then the order is maintained on M"

My question is specifically what happens if we have two operations that apply to different atomic objects. Something like the following:

```<code>atomic_store(&a, 20);
atomic_store(&b, 30);
</code>```

where a and b are atomic (volatile) types (and atomic_store implies memory_order_seq_cst).

This problem is relevant to a memory mapped situation where the memory map represents the registers of some peripheral.

It's perfectly normal to have requirements about the ordering of the write. Let's say a = 20 is setting up the target for our missile peripheral and setting b = 30 is the launch command. Clearly, we don't want to launch until the missile is targeted properly.

If it makes a difference to anything, this is on ARM Linux with GCC.

答:
Two memory accesses in the same thread are always sequenced, if they happen, and if there is a sequence point between them.

The part for "if they happen" is guaranteed here if the two objects are declared volatile. This forces the compiler to effectively emit the load or store to memory. How the compiler does this, and how he gives guarantees for that, is completely implementation dependent.Read your platform documentation for that.

The sequencing of statements has not much to do with volatile or atomics. It is implied by syntax. A good rule of thumb is that there is a sequence point at each ;, ,, {, }, ?, || and &&. (there are more than that, but things become complicated if you want to reason with them).

Nothing of that is about atomics. These are to guarantee indivisibility of operations and data consistency inbetween threads and with signal handlers. The big deal here is to have provable visibility of side effects of operations. This is relatively involved, but doesn't help you anything when you want to discuss things that happen in the same thread. In the contrary, the "happens before" relation between threads, relies on the "sequenced before" relation within the individual threads.

Body:
My reading of the C11 spec with regards to atomic operation ordering suggests that memory_order_seq_cst applies to operations on a specific atomic object.

Mostly, the descriptions are of the form "If a A and B are applied to M, then the order is maintained on M"

My question is specifically what happens if we have two operations that apply to different atomic objects. Something like the following:

atomic_store(&a, 20);
atomic_store(&b, 30);

where a and b are atomic (volatile) types (and atomic_store implies memory_order_seq_cst).

This problem is relevant to a memory mapped situation where the memory map represents the registers of some peripheral.

It's perfectly normal to have requirements about the ordering of the write. Let's say a = 20 is setting up the target for our missile peripheral and setting b = 30 is the launch command. Clearly, we don't want to launch until the missile is targeted properly.

If it makes a difference to anything, this is on ARM Linux with GCC.


问:
awk split column into multiple columns in staggered manner
I have a text file containing a single column of data as below :

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

I want to split this into multiple columns using awk or sed command as follows:

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

How can I do this? Thanks in advance

答:
Using rs - reshape a data array:

```<code>$ cat file | rs -C' ' 2 3
1 2 3
4 5 6
</code>```

rs reads the standard input

-C output column separator

2 3 rows and columns

Use -t to transpose the input:

```<code>$ cat file | rs -C' ' -t 2 3
1 3 5
2 4 6
</code>```

Body:
I have a text file containing a single column of data as below :

1
2
3
4
5
6

I want to split this into multiple columns using awk or sed command as follows:

1 2 3
4 5 6

How can I do this? Thanks in advance

Body:
Using rs - reshape a data array:

$ cat file | rs -C' ' 2 3
1 2 3
4 5 6

rs reads the standard input

-C output column separator

2 3 rows and columns

Use -t to transpose the input:

$ cat file | rs -C' ' -t 2 3
1 3 5
2 4 6


问:
How to use Google Custom Search Element with existing form element?
I'm trying to use my current search form with Google's custom search element and so far I am unable to get it to work. This is my current search form.

```<code><form class="search-form" action="/search/">
    <p class="inputs">
        <label for="search-q">Search</label>
        <input type="search" id="search-q" name="search" data-gname="search"placeholder="Find what you're looking for..." value="#formatted_query#">
        <input type="submit" value="Go" class="button postfix brand-orange-bk">
    </p>
</form>
</code>```

The Google CSE code snippet I use is shown below:

```<code>(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];

    s.parentNode.insertBefore(gcse, s);

  })();
  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');
</code>```

In the result (which is on the same page), I have the following:

```<code><div class="row">
    <div class="small-12 medium-5 medium-push-7 large-5 large-push-7 columns" id="search-rightcol">
        <section data-searchtab="our-own-knowledgebase" class="search-panel brand-white-bk"></section>
    </div>
    <div class="small-12 medium-7 medium-pull-5 large-7 large-pull-5 columns">
        <div id="google-search-results"></div>
    </div>
</div>
</code>```

I can use the gcse:searchbox-only tag instead of my current form and then I'll style it; however, when I press the search button, it goes to a different page and the result is not display in the google-search-results div. If I use the gcse:search tag then the result replaces everything on the current page and disregard this line of code:

```<code>$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');
</code>```

I have looked at the HTML5-valid div tags, Custom Search Element Control API (V2), and  Using the JavaScript API to render elements but I'm unclear as to how I would go about modifying the code in my situation so I can simply pass whatever value is in the input element to the Google CSE code to do the search and then I'll put the result in the google-search-results div. In the example of the Custom Search Element Control API (V2), it showed this code:

```<code>var element = google.search.cse.element.getElement('element1);
element.execute('news');
</code>```

So I tried the following code but it didn't work...no result is showing/returning.

```<code>(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    //var s = document.getElementsByTagName('script')[0];
    var s = google.search.cse.element.getElement('search');

    // do the search:
    var searchTerm = $('##search-q').val();
    s.execute(searchTerm);

    s.parentNode.insertBefore(gcse, s);

  })();

  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');
</code>```

I have found a similar thread (How to use custom search box for google custom search?) but there is no resolution to that thread. I have also found another thread (How to style Google Custom Search Engine so that it doesn't display as a block element) but the problem I have with that solution is whenever I clicked to search, it would go to a different page disregard this code:

```<code>$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');
</code>```

Any help is much appreciated. Thank you.

答:
Okay, thanks to colleagues of mine, this is how we resolved it. I'm putting it here perhaps it might help others.</p>

```<code>searchhelper.perform_google = function(){

    if(typeof(google)!='undefined'){
        google.search.cse.element.render({
            div: "google-search-results",
            tag: 'searchresults-only',
            gname: 'google-results-gname'
        });
        var element = google.search.cse.element.getElement('google-results-gname');
        var query = $('##search-q').val();
        element.execute(query);
    }
};

(function(){
    // add the google custom stuff:
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

window.__gcse = {
  parsetags: 'explicit',
  callback: function(){
    searchhelper.search('all');
  }
};
</code>```

Body:
I'm trying to use my current search form with Google's custom search element and so far I am unable to get it to work. This is my current search form.

<form class="search-form" action="/search/">

        Search
        <input type="search" id="search-q" name="search" data-gname="search"placeholder="Find what you're looking for..." value="#formatted_query#">
        <input type="submit" value="Go" class="button postfix brand-orange-bk">

</form>

The Google CSE code snippet I use is shown below:

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];

    s.parentNode.insertBefore(gcse, s);

  })();
  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

In the result (which is on the same page), I have the following:

I can use the gcse:searchbox-only tag instead of my current form and then I'll style it; however, when I press the search button, it goes to a different page and the result is not display in the google-search-results div. If I use the gcse:search tag then the result replaces everything on the current page and disregard this line of code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have looked at the HTML5-valid div tags, Custom Search Element Control API (V2), and  Using the JavaScript API to render elements but I'm unclear as to how I would go about modifying the code in my situation so I can simply pass whatever value is in the input element to the Google CSE code to do the search and then I'll put the result in the google-search-results div. In the example of the Custom Search Element Control API (V2), it showed this code:

var element = google.search.cse.element.getElement('element1);
element.execute('news');

So I tried the following code but it didn't work...no result is showing/returning.

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    //var s = document.getElementsByTagName('script')[0];
    var s = google.search.cse.element.getElement('search');

    // do the search:
    var searchTerm = $('##search-q').val();
    s.execute(searchTerm);

    s.parentNode.insertBefore(gcse, s);

  })();

  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have found a similar thread (How to use custom search box for google custom search?) but there is no resolution to that thread. I have also found another thread (How to style Google Custom Search Engine so that it doesn't display as a block element) but the problem I have with that solution is whenever I clicked to search, it would go to a different page disregard this code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

Any help is much appreciated. Thank you.

Body:
Okay, thanks to colleagues of mine, this is how we resolved it. I'm putting it here perhaps it might help others.

searchhelper.perform_google = function(){

    if(typeof(google)!='undefined'){
        google.search.cse.element.render({
            div: "google-search-results",
            tag: 'searchresults-only',
            gname: 'google-results-gname'
        });
        var element = google.search.cse.element.getElement('google-results-gname');
        var query = $('##search-q').val();
        element.execute(query);
    }
};

(function(){
    // add the google custom stuff:
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

window.__gcse = {
  parsetags: 'explicit',
  callback: function(){
    searchhelper.search('all');
  }
};


问:
Null Pointer Expection - Null Object Refrence
Pretty new to Android Studio and Currently creating a planner app, and I get this error when viewing trying to view my customers activity.

The error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.user.planner, PID: 21140
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.planner/com.example.user.planner.Customer}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                      at android.app.ActivityThread.-wrap14(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at com.example.user.planner.Customer.AddData(Customer.java:68)
                      at com.example.user.planner.Customer.onCreate(Customer.java:44)
                      at android.app.Activity.performCreate(Activity.java:6912)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                      at android.app.ActivityThread.-wrap14(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

This is my code:

```<code>    package com.example.user.planner;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Customer extends AppCompatActivity {
    DatabaseHelper myDb;
    EditText editName, editSurname, editAddress, editContact;
    Button addDataBtn;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer);
        myDb = new DatabaseHelper(this);

        editName = (EditText)findViewById(R.id.firstEntry);
        editSurname = (EditText)findViewById(R.id.surnameEntry);
        editAddress = (EditText)findViewById(R.id.addressEntry);
        editContact = (EditText)findViewById(R.id.contactEntry);
        addDataBtn = (Button)findViewById(R.id.addBtn);
        AddData();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    public void AddData() {
        addDataBtn.setOnClickListener(
                new View.OnClickListener(){
                    public void onClick(View v) {
                     boolean isInserted = myDb.insertData(
                              editName.getText().toString(),
                              editSurname.getText().toString(),
                              editAddress.getText().toString(),
                              editContact.getText().toString());
                        if(isInserted =true)
                            Toast.makeText(Customer.this, "Data Inserted", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(Customer.this, "Data not Inserted", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_customer, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            if(getArguments().getInt(ARG_SECTION_NUMBER)==1)
            {
                View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
                return rootView;
            }
            else if(getArguments().getInt(ARG_SECTION_NUMBER)==2)
            {
                View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
                return rootView;
            }
            else
            {
                View rootView = inflater.inflate(R.layout.fragment_customer, container, false);
                TextView textView = (TextView) rootView.findViewById(R.id.section_label);
                textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
                return rootView;
            }

        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Add Customer";
                case 1:
                    return "View Customer";
            }
            return null;
        }
    }
}
</code>```

and this is the XML

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.SubPage01"
android:textAlignment="center">

<!-- TODO: Update blank fragment layout -->

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/firstEntry"
    android:hint="First Name"
    android:textAlignment="center" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/addressEntry"
    android:hint="Address"
    android:textAlignment="center"
    android:layout_below="@+id/surnameEntry"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/surnameEntry"
    android:hint="Surname"
    android:textAlignment="center"
    android:layout_below="@+id/firstEntry"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/contactEntry"
    android:hint="Contact"
    android:textAlignment="center"
    android:layout_below="@+id/addressEntry"
    android:layout_alignParentStart="true" />

<Button
    android:text="Add Customer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/addBtn"
    android:layout_marginBottom="81dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true" />
</code>```

Im guessing the error is coming from where the AddData method however, I can't see what's wrong. Or I'm miles offtrack. Any help will be great.

答:
You exception means that addDataBtn object is null when you are invoking method public void AddData();

Pay attention to the line:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                  at com.example.user.planner.Customer.AddData(Customer.java:68)
</code>```

Body:
Pretty new to Android Studio and Currently creating a planner app, and I get this error when viewing trying to view my customers activity.

The error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.user.planner, PID: 21140
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.planner/com.example.user.planner.Customer}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                      at android.app.ActivityThread.-wrap14(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at com.example.user.planner.Customer.AddData(Customer.java:68)
                      at com.example.user.planner.Customer.onCreate(Customer.java:44)
                      at android.app.Activity.performCreate(Activity.java:6912)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                      at android.app.ActivityThread.-wrap14(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

This is my code:

    package com.example.user.planner;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Customer extends AppCompatActivity {
    DatabaseHelper myDb;
    EditText editName, editSurname, editAddress, editContact;
    Button addDataBtn;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer);
        myDb = new DatabaseHelper(this);

        editName = (EditText)findViewById(R.id.firstEntry);
        editSurname = (EditText)findViewById(R.id.surnameEntry);
        editAddress = (EditText)findViewById(R.id.addressEntry);
        editContact = (EditText)findViewById(R.id.contactEntry);
        addDataBtn = (Button)findViewById(R.id.addBtn);
        AddData();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    public void AddData() {
        addDataBtn.setOnClickListener(
                new View.OnClickListener(){
                    public void onClick(View v) {
                     boolean isInserted = myDb.insertData(
                              editName.getText().toString(),
                              editSurname.getText().toString(),
                              editAddress.getText().toString(),
                              editContact.getText().toString());
                        if(isInserted =true)
                            Toast.makeText(Customer.this, "Data Inserted", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(Customer.this, "Data not Inserted", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_customer, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            if(getArguments().getInt(ARG_SECTION_NUMBER)==1)
            {
                View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
                return rootView;
            }
            else if(getArguments().getInt(ARG_SECTION_NUMBER)==2)
            {
                View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
                return rootView;
            }
            else
            {
                View rootView = inflater.inflate(R.layout.fragment_customer, container, false);
                TextView textView = (TextView) rootView.findViewById(R.id.section_label);
                textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
                return rootView;
            }

        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Add Customer";
                case 1:
                    return "View Customer";
            }
            return null;
        }
    }
}

and this is the XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.SubPage01"
android:textAlignment="center">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/firstEntry"
    android:hint="First Name"
    android:textAlignment="center" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/addressEntry"
    android:hint="Address"
    android:textAlignment="center"
    android:layout_below="@+id/surnameEntry"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/surnameEntry"
    android:hint="Surname"
    android:textAlignment="center"
    android:layout_below="@+id/firstEntry"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/contactEntry"
    android:hint="Contact"
    android:textAlignment="center"
    android:layout_below="@+id/addressEntry"
    android:layout_alignParentStart="true" />

<Button
    android:text="Add Customer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/addBtn"
    android:layout_marginBottom="81dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true" />

Im guessing the error is coming from where the AddData method however, I can't see what's wrong. Or I'm miles offtrack. Any help will be great.

Body:
You exception means that addDataBtn object is null when you are invoking method public void AddData();

Pay attention to the line:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                  at com.example.user.planner.Customer.AddData(Customer.java:68)


问:
Alexa Skill Certification - Validating amazon request
I have submitted a skill for certification to Alexa and they replied with issue saying that my server is ignoring invalid SSL certificates.  Amazon has a strict requirement to make sure that the server properly verify the incoming request SSL certificate.

My setup is Nginx + Nodejs + Alexa-skills-app where I use letsencrypt to have a proper SSL certificates for nginx. My server is able to send and receive all response without any issues, but for the skill to be certified, nginx has to make sure that incoming requests from amazon are properly verified.

Does anyone know which nginx configuration I should use to force proper SSL verification on incoming requests?

答:
Https SSL certificate files(*.pem) need to attach on both Nodejs and Nginx server

Then only all the request will come from https://

which they will be consider safe.


问:
How do I cancel a FirebaseObjectObservable subscription?
I know in other cases I can turn off an observable with unsubscribe() but as far as I can tell a FirebaseObjectObservable doesn't seem to have that function. How can I turn it off?</p>

```<code>this.rock = this.af.database.object('/rocks/'+ rockKey);
this.rock.subscribe(obj=>{
  console.log("Can't stop the rock");
});
</code>```

答:
You don't unsubscribe the observable; you unsubscribe the subscription. This has nothing to do with Firebase observables.</p>

```<code>this.subscription = this.rock.subscribe(obj=>{
  console.log("Can't stop the rock");
});

this.subscription.unsubscribe();
</code>```

Body:
I know in other cases I can turn off an observable with unsubscribe() but as far as I can tell a FirebaseObjectObservable doesn't seem to have that function. How can I turn it off?

this.rock = this.af.database.object('/rocks/'+ rockKey);
this.rock.subscribe(obj=>{
  console.log("Can't stop the rock");
});

Body:
You don't unsubscribe the observable; you unsubscribe the subscription. This has nothing to do with Firebase observables.

this.subscription = this.rock.subscribe(obj=>{
  console.log("Can't stop the rock");
});

this.subscription.unsubscribe();


问:
Java Loop for n integer sum
I have problem with the following question:

Write a program that prompts the user to enter an integer, n. The
  program will print the following results:

Sum of all even numbers between 1 and n (inclusive)

Sum of all odd numbers between 1 and n (inclusive)

Here the code I have so far, when I hit run I am getting exponentially large numbers that keep multiplying. I am aware my code is wrong. I dont know what I am doing wrong. Thank you.

```<code>package assig;

import java.util.Scanner;

public class Assignment4_Question1 {

public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
int evenSum = 0;
int oddSum= 0;

for (int i = 1; 1<=n; i++){
    if(i % 2 == 0){
    evenSum = evenSum + i;
    } else if (i % 2 != 0){
    oddSum = oddSum + i;
    }
    System.out.println(evenSum);
    System.out.println(oddSum);
    }
}
</code>```

答:
You must change :

```<code>for (int i = 1; 1<=n; i++)
</code>```

to:

```<code>for (int i = 1; i<=n; i++)
</code>```

Title: Java Loop for n integer sum

Body:
I have problem with the following question:

Write a program that prompts the user to enter an integer, n. The
  program will print the following results:

Sum of all even numbers between 1 and n (inclusive)

Sum of all odd numbers between 1 and n (inclusive)

Here the code I have so far, when I hit run I am getting exponentially large numbers that keep multiplying. I am aware my code is wrong. I dont know what I am doing wrong. Thank you.

package assig;

import java.util.Scanner;

public class Assignment4_Question1 {

public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
int evenSum = 0;
int oddSum= 0;

for (int i = 1; 1<=n; i++){
    if(i % 2 == 0){
    evenSum = evenSum + i;
    } else if (i % 2 != 0){
    oddSum = oddSum + i;
    }
    System.out.println(evenSum);
    System.out.println(oddSum);
    }
}

Body:
You must change :

for (int i = 1; 1<=n; i++)

to:

for (int i = 1; i<=n; i++)


问:
differences between MVCarray and array
I have been looking up the differences between MVCArray and Array for Google map API, but I haven't found any concrete.

I kind of get that MVCArray is a better option since it keeps track of changes (somehow) and have some kind of special events. And some of the same methods have slightly different names, e.g. array.length and MVCarray.getLength().

But can someone please explain in layman's term the explicit differences between the two? and it would be great if you could give some simple examples to make it easier to understand.

Thank you!

答:
To explain MVCArrays it's important to understand MVCObjects.

MVCObject is one of the "keystone" classes google maps is built on. It's like a plain object with setters and getters for its properties (nothing special so far), but what makes it special is that:

You can add a listener to detect when any property is changed (with the set method) and execute a callback function

You can bind any of its properties to another property of other MVCObject (or any class that inherits from this one)

Other MVCObjects (or any class that inherit from this one) can have its properties binded to the ones in the current one.

So, basically, MVCObjects are observable-bindable objetcs.

An MVCArray inherits from MVCObject so you can set or get its properties, bind some of them, be binded by other objects, etc. But also, it implements some extras

It implements several of the methods you could use in a native javascript array, like push, pop, forEach, etc, so several google.maps methods can accept either an MVCArray or a native array, since it will use the same methods to traverse them.

It has an array property (that you can access with getArray method) that is a native js array. array-like methods as mentioned above are forwarded to this array.

It implements a set of events so you can detect when an element in the underlying array is set, removed or changed.

So, basically, MVCArrays are observable arrays. And since it inherits from MVCObject, their properties are also bindable

Title: differences between MVCarray and array