问:
filter Firebase data Swift 3
I am using firebase to store info that will be presented in a table view. This is a screenshot of the database:

I am trying to only add media from a certain "createdBy uid":

```<code>    func fetchMyMedia() {
        let ref = DatabaseReference.media.reference()
        let query = ref.queryOrdered(byChild: "createdBy/uid").queryEqual(toValue: "Cdxbj1iCZUNxWRbIBllBxKqXh5P2")

        query.observe(.value,
                      with: { snapshot in
                          for childSnapshot in snapshot.children {
                              self.myMedia.insert(childSnapshot as! Media, at: 0)
                              let indexPath = IndexPath(row: 0, section: 0)
                          }
                      })
    }
</code>```

"myMedia" is an array of type Media

I'm getting an error that I cannot cast value of type FIRDataSnapshot  to XXXXXX.Media. Any help with this would be greatly appreciated.

in case it helps, without listing my entire Model class, this is how I get all the info unfiltered...

```<code>    extension Media {
        class func observeNewMedia(_ completion: @escaping (Media) -> Void) {
            DatabaseReference.media.reference().observe(.childAdded, with: { snapshot in
                let media = Media(dictionary: snapshot.value as! [String : Any])
                completion(media)
            })
        }
</code>```

and then...

```<code>    func fetchMedia() {
            Media.observeNewMedia { (media) in
                if !self.media.contains(media) {
                    self.media.insert(media, at: 0)
                    self.tableView.reloadData()
                }
            }
        }
</code>```

答:
```<code>    func fetchMyMedia() {
        let ref = DatabaseReference.media.reference()
        let query = ref.queryOrdered(byChild: "createdBy/uid").queryEqual(toValue: "Cdxbj1iCZUNxWRbIBllBxKqXh5P2")

       query.observe(.childAdded, with: { snapshot in

                let media = Media(dictionary: snapshot.value as! [String : Any])
                self.myMedia.insert(media, at: 0)
            self.tableView.reloadData()
</code>```

Title: filter Firebase data Swift 3

Body:
I am using firebase to store info that will be presented in a table view. This is a screenshot of the database:

I am trying to only add media from a certain "createdBy uid":

    func fetchMyMedia() {
        let ref = DatabaseReference.media.reference()
        let query = ref.queryOrdered(byChild: "createdBy/uid").queryEqual(toValue: "Cdxbj1iCZUNxWRbIBllBxKqXh5P2")

        query.observe(.value,
                      with: { snapshot in
                          for childSnapshot in snapshot.children {
                              self.myMedia.insert(childSnapshot as! Media, at: 0)
                              let indexPath = IndexPath(row: 0, section: 0)
                          }
                      })
    }

"myMedia" is an array of type Media

I'm getting an error that I cannot cast value of type FIRDataSnapshot  to XXXXXX.Media. Any help with this would be greatly appreciated.

in case it helps, without listing my entire Model class, this is how I get all the info unfiltered...

    extension Media {
        class func observeNewMedia(_ completion: @escaping (Media) -> Void) {
            DatabaseReference.media.reference().observe(.childAdded, with: { snapshot in
                let media = Media(dictionary: snapshot.value as! [String : Any])
                completion(media)
            })
        }

and then...

    func fetchMedia() {
            Media.observeNewMedia { (media) in
                if !self.media.contains(media) {
                    self.media.insert(media, at: 0)
                    self.tableView.reloadData()
                }
            }
        }


来源: stackexchange

问:
How do I specify exactly where a border will be postionioned?
I would like the border to be around the text area rather than inside of it.

```<code>/**
   This frame shows a data set and its statistics.
 */
public class FileGUI extends JFrame
{

    private static JPanel panel;
    private JTextArea display;
    private JButton open;
    private JButton save;
    private JButton clear;

    //declare data fields here (GUI Components and other data fields)

    public FileGUI()
    {

        //Initialize data fields and construct GUI

        open = new JButton("Open file");
        save = new JButton("Save to File");
        clear = new JButton("Clear Display");

        display = new JTextArea(30,30);
        Border border = BorderFactory.createTitledBorder("File Summary");
        display.setBorder(border);

        panel = new JPanel();
        panel.add(open);
        panel.add(save);
        panel.add(clear);
        panel.add(display);
    }

    //supporting methods here.

    public static void main(String[] args)
    {
        JFrame frame = new FileGUI();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 600);
        frame.setVisible(true);
        frame.add(panel);
    }
}
</code>```

答:
If you want the border to enclose your textfield you have to wrap it into another component (e.g. a JPanel) and set the border on that component. Borders are always rendered within the bounds of the components you assign them to.

By the way: You're creating and initializing swing components from the main thread. This is not a good way to do it. Swing is a single threaded GUI and requires all interactions to happen on the event dispatch thread. I recommend the concurrency in swing lesson

ContentLicense: CC BY-SA 3.0

Body:
I would like the border to be around the text area rather than inside of it.

/**
   This frame shows a data set and its statistics.
 */
public class FileGUI extends JFrame
{

    private static JPanel panel;
    private JTextArea display;
    private JButton open;
    private JButton save;
    private JButton clear;

    //declare data fields here (GUI Components and other data fields)

    public FileGUI()
    {

        //Initialize data fields and construct GUI

        open = new JButton("Open file");
        save = new JButton("Save to File");
        clear = new JButton("Clear Display");

        display = new JTextArea(30,30);
        Border border = BorderFactory.createTitledBorder("File Summary");
        display.setBorder(border);

        panel = new JPanel();
        panel.add(open);
        panel.add(save);
        panel.add(clear);
        panel.add(display);
    }

    //supporting methods here.

    public static void main(String[] args)
    {
        JFrame frame = new FileGUI();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 600);
        frame.setVisible(true);
        frame.add(panel);
    }
}


问:
Accessing newer APIs in a redirected assembly
If I use Assembly Binding Redirection to redirect my v1.0 referenced assembly to a v1.1 assembly, can I use reflection APIs to:

Create new classes introduced in the v1.1 assembly

Invoke new methods of existing classes introduced in the v1.1 assembly

While keeping reference to the v1.0 assembly?

答:
Mmmm,  I'm not sure if this makes sense.

You could do what you say but you would need to know the class names and methods available at 1.1 while coding against the 1.0 version so you why not to change to the 1.1 references?

You can create instances with name using the Activatior.CreateInstance().

ContentLicense: CC BY-SA 2.5


问:
Get a custom field value saved in Order items meta in a hooked function
I am able to add, validate, display on cart and checkout page a custom field on the Product Page.Please can someone tell me how can I retrieve the custom field values using woocommerce_order_status_completed hook?

I want to send an additional email including the custom field data after the confirmation email is sent to the user

```<code>static function sendCustomData($order_id) {
    $order = wc_get_order($order_id);
    $items = $order->get_items();

    foreach ($items as $item) {
        $product_id = $item['product_id'];

        $Id = get_post_meta($product_id, '_wpws_ID', true);
        $first_name = $order->get_billing_first_name();
        $billing_email = $order->get_billing_email();

        if (empty($Id))
        continue;

        $mail = new CustomMails();
        $mail->SendMailtoReaderOnWCOrderComplete($first_name, $billing_email, $Id);
    }
}
add_action('woocommerce_order_status_completed','sendCustomData');
</code>```

Saving custom order meta value

```<code>public static function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values['name_on_tshirt'] ) ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", $values['name_on_tshirt'] );
    }
}
add_action( 'woocommerce_new_order_item', 'tshirt_order_meta_handler', 1, 3 );
</code>```

答:
To get "name_on_tshirt" custom field, you need to get the order Item ID and you need to use wc_get_order_item_meta() function this way:

```<code>foreach ($order->get_items() as $item_id => $item) {
    ## HERE ==> Get your custom field value
    $name_on_tshirt wc_get_order_item_meta( $item_id, "name_on_tshirt", true );
}
</code>```

Body:
I am able to add, validate, display on cart and checkout page a custom field on the Product Page.Please can someone tell me how can I retrieve the custom field values using woocommerce_order_status_completed hook?

I want to send an additional email including the custom field data after the confirmation email is sent to the user

static function sendCustomData($order_id) {
    $order = wc_get_order($order_id);
    $items = $order->get_items();

    foreach ($items as $item) {
        $product_id = $item['product_id'];

        $Id = get_post_meta($product_id, '_wpws_ID', true);
        $first_name = $order->get_billing_first_name();
        $billing_email = $order->get_billing_email();

        if (empty($Id))
        continue;

        $mail = new CustomMails();
        $mail->SendMailtoReaderOnWCOrderComplete($first_name, $billing_email, $Id);
    }
}
add_action('woocommerce_order_status_completed','sendCustomData');

Saving custom order meta value

public static function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values['name_on_tshirt'] ) ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", $values['name_on_tshirt'] );
    }
}
add_action( 'woocommerce_new_order_item', 'tshirt_order_meta_handler', 1, 3 );

Body:
To get "name_on_tshirt" custom field, you need to get the order Item ID and you need to use wc_get_order_item_meta() function this way:

foreach ($order->get_items() as $item_id => $item) {
    ## HERE ==> Get your custom field value
    $name_on_tshirt wc_get_order_item_meta( $item_id, "name_on_tshirt", true );
}


问:
how to print inline in python strings and function
How to print a string and funtion(print) on the same line:
For example:-

```<code>def displayHand(hand):
      print({1:2,2:3})
</code>```

know how can i get a print like this ( Current Hand:{1:2,2:3} )

答:
```<code>def displayHand(hand):
    print ('Current Hand: %s'%(hand))

print displayHand({'1':2, '2':3})
</code>```

Body:
How to print a string and funtion(print) on the same line:
For example:-

def displayHand(hand):
      print({1:2,2:3})

know how can i get a print like this ( Current Hand:{1:2,2:3} )


问:
Create a Directory in PhoneGap Application
Trying to figure out how to create a directory on the file system using PhoneGap.

I want to create a directory for my PhoneGap application, so I can store images the user creates there and load them back up in the app.

答:
This code works for me (based on version 7 Cordova documentation - https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html):

```<code>window.resolveLocalFileSystemURL('cdvfile://localhost/persistent/',
  function fileEntryCallback(fileEntry) {
    fileEntry.getDirectory('my_directory', { create: true });
  }
);
</code>```

If the code above doesn't work, you may need to reinstall the File and File Transfer plugins. A command like console.log(window.resolveLocalFileSystemUrl) is one way to test that the plugins are working.

Also, if you're using Content Security Policy (CSP) be sure your default-src allows cdvfile: paths:

default-src cdvfile:

Body:
This code works for me (based on version 7 Cordova documentation - https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html):

window.resolveLocalFileSystemURL('cdvfile://localhost/persistent/',
  function fileEntryCallback(fileEntry) {
    fileEntry.getDirectory('my_directory', { create: true });
  }
);

If the code above doesn't work, you may need to reinstall the File and File Transfer plugins. A command like console.log(window.resolveLocalFileSystemUrl) is one way to test that the plugins are working.

Also, if you're using Content Security Policy (CSP) be sure your default-src allows cdvfile: paths:

default-src cdvfile:


问:
Save stdout, stderr and stdout+stderr synchronously
For testing purposes, I would like to save stdout and stderr separately for inspection by subsequent code. For example, a test run with erroneous input should result in output to stderr, but nothing on stdout, while a test run with correct input should result in output to stdout, but nothing to stderr. The saving has to be synchronous, to avoid race conditions with the tests (so I can't use process substitution).

To be able to debug the test after the fact, I also need to see stdout and stderr in the sequence they were output. So I have to either save them both to the same file/variable/whatever or send them to the terminal at the same time as saving them separately.

To test which error happened, I also need the exit code of the command.

For reasons of efficiency and accuracy, I of course cannot run each test twice.

Is it for example possible to redirect stdout to stdout.log, stderr to stderr.log, and both of them to output.log in the same command? Or to use a synchronous tee command separately for stdout and stderr? Or to save a copy of stdout and stderr to separate variables?

Update: It looks like tim's solution almost works (modified to output on terminal instead of logging to all.log):

```<code>$ set -o pipefail
$ {
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
foo
$ cat stderr.log
$ {
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
$ cat stderr.log
foo
$ bar=$({
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ echo "$bar"
foo
$ cat stdout.log
foo
$ cat stderr.log
$ bar=$({
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ cat stdout.log
$ cat stderr.log
foo
$ echo "$bar"
foo
</code>```

This seems to work except for the last iteration, where the value of bar is set to the contents of stderr. Any suggestions for all of these to work?

答:
This sounds like a task for multitee.

To test for synchronous output or disk writes without using process substitution you may want to play around with Bash shell redirection tricks and tee(1) similar to the following:

```<code>echos() { echo "hello on stdout"; echo "hello on stderr" 1>&2; return 0; }

   {
  {
     echos 3>&- |
        tee stdout.log 2>&3 3>&-
  } 2>&1 >&4 4>&- |
        tee  stderr.log 2>&3 3>&-
} 3>&2 4>&1 2>&1 | tee /dev/stderr > all.log

open -e stdout.log stderr.log all.log   # Mac OS X
</code>```

For more information see: http://codesnippets.joyent.com/posts/show/8769

To get the exit code of the command you may want to check out pipefail or PIPESTATUS respectively (in addition to the last-exit-code variable "$?"):

```<code>help set | grep -i pipefail
man bash | less -p pipefail
man bash | less -p PIPESTATUS
</code>```

Body:
For testing purposes, I would like to save stdout and stderr separately for inspection by subsequent code. For example, a test run with erroneous input should result in output to stderr, but nothing on stdout, while a test run with correct input should result in output to stdout, but nothing to stderr. The saving has to be synchronous, to avoid race conditions with the tests (so I can't use process substitution).

To be able to debug the test after the fact, I also need to see stdout and stderr in the sequence they were output. So I have to either save them both to the same file/variable/whatever or send them to the terminal at the same time as saving them separately.

To test which error happened, I also need the exit code of the command.

For reasons of efficiency and accuracy, I of course cannot run each test twice.

Is it for example possible to redirect stdout to stdout.log, stderr to stderr.log, and both of them to output.log in the same command? Or to use a synchronous tee command separately for stdout and stderr? Or to save a copy of stdout and stderr to separate variables?

Update: It looks like tim's solution almost works (modified to output on terminal instead of logging to all.log):

$ set -o pipefail
$ {
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
foo
$ cat stderr.log
$ {
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1
foo
$ cat stdout.log
$ cat stderr.log
foo
$ bar=$({
    {
        echo foo | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ echo "$bar"
foo
$ cat stdout.log
foo
$ cat stderr.log
$ bar=$({
    {
        echo foo >&2 | tee stdout.log 2>&3 3>&-
    } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&-
} 3>&2 4>&1)
$ cat stdout.log
$ cat stderr.log
foo
$ echo "$bar"
foo

This seems to work except for the last iteration, where the value of bar is set to the contents of stderr. Any suggestions for all of these to work?

Body:
This sounds like a task for multitee.

To test for synchronous output or disk writes without using process substitution you may want to play around with Bash shell redirection tricks and tee(1) similar to the following:

echos() { echo "hello on stdout"; echo "hello on stderr" 1>&2; return 0; }

   {
  {
     echos 3>&- |
        tee stdout.log 2>&3 3>&-
  } 2>&1 >&4 4>&- |
        tee  stderr.log 2>&3 3>&-
} 3>&2 4>&1 2>&1 | tee /dev/stderr > all.log

open -e stdout.log stderr.log all.log   # Mac OS X

For more information see: http://codesnippets.joyent.com/posts/show/8769

To get the exit code of the command you may want to check out pipefail or PIPESTATUS respectively (in addition to the last-exit-code variable "$?"):

help set | grep -i pipefail
man bash | less -p pipefail
man bash | less -p PIPESTATUS


问:
Converting a dict into a OrderedDict
I have a hashtable and a lambda for sort like this:

```<code> h = {"hlllleleo": 9, "hello": 5, "fgfgggf" : 7, "abcdefgh": 8}
 lbda = lambda x : h[x]
 from collections import OrderedDict as od
 od({x:h[x] for x in sorted(h, key=lbda)})
 #Outputs:
 OrderedDict([('abcdefgh', 8), ('hlllleleo', 9), ('fgfgggf', 7),
 ('hello', 5)])
</code>```

Why is the ordered dict not coming out sorted as it is built? If I loop over sorted() it is sorted:

```<code> for x in sorted(h, key=lbda):
   print x, h[x]

 # Outputs:
 hello 5
 fgfgggf 7
 abcdefgh 8
 hlllleleo 9
</code>```

答:
The reason is simple. You sort the dictionary by keys, and create a new dictionary using a comprehension. However, by the time the dictionary is created and passed to the OrderedDict constructor for creation, it has already forgotten the order.

Let's convert your dict comprehension into a list comprehension:

```<code>In [413]: [(x, h[x]) for x in sorted(h, key=lambda x : h[x])]
Out[413]: [('hello', 5), ('fgfgggf', 7), ('abcdefgh', 8), ('hlllleleo', 9)]
</code>```

And now, the same thing with a dictionary:

```<code>In [414]: {x : h[x] for x in sorted(h, key=lambda x : h[x])}
Out[414]: {'abcdefgh': 8, 'fgfgggf': 7, 'hello': 5, 'hlllleleo': 9}
</code>```

As you can see, the dictionary you generate bears no resemblance to the list comprehension in terms of ordering, since the generated dict has already forgotten its ordering.

Title: Converting a dict into a OrderedDict

Body:
I have a hashtable and a lambda for sort like this:

 h = {"hlllleleo": 9, "hello": 5, "fgfgggf" : 7, "abcdefgh": 8}
 lbda = lambda x : h[x]
 from collections import OrderedDict as od
 od({x:h[x] for x in sorted(h, key=lbda)})
 #Outputs:
 OrderedDict([('abcdefgh', 8), ('hlllleleo', 9), ('fgfgggf', 7),
 ('hello', 5)])

Why is the ordered dict not coming out sorted as it is built? If I loop over sorted() it is sorted:

 for x in sorted(h, key=lbda):
   print x, h[x]

 # Outputs:
 hello 5
 fgfgggf 7
 abcdefgh 8
 hlllleleo 9

Body:
The reason is simple. You sort the dictionary by keys, and create a new dictionary using a comprehension. However, by the time the dictionary is created and passed to the OrderedDict constructor for creation, it has already forgotten the order.

Let's convert your dict comprehension into a list comprehension:

In [413]: [(x, h[x]) for x in sorted(h, key=lambda x : h[x])]
Out[413]: [('hello', 5), ('fgfgggf', 7), ('abcdefgh', 8), ('hlllleleo', 9)]

And now, the same thing with a dictionary:

In [414]: {x : h[x] for x in sorted(h, key=lambda x : h[x])}
Out[414]: {'abcdefgh': 8, 'fgfgggf': 7, 'hello': 5, 'hlllleleo': 9}

As you can see, the dictionary you generate bears no resemblance to the list comprehension in terms of ordering, since the generated dict has already forgotten its ordering.


问:
How do I auto-resize dimensions for a named google sheet
My Java Google Sheet API method to auto-resize dimensions of a Google sheet is working but only on the default sheet that had gid = 0. A particular spreadsheetId that identifies a Google Sheet can have several tabs each with a particular gid.

I wish to only target a particular sheet with a different gid than gid = 0 when I auto-resize dimensions. How do I adjust my code for that to happen?

```<code>public static void setAutoResizeDimensions(String spreadsheetId, int startindex, int endindex) throws IOException {

    List<Request> requests = new ArrayList<>();

    AutoResizeDimensionsRequest autoResizeDimensions = new AutoResizeDimensionsRequest();
    DimensionRange dimensions = new DimensionRange().setDimension("COLUMNS").setStartIndex(startindex).setEndIndex(endindex);

    requests.add(new Request()
            .setAutoResizeDimensions(autoResizeDimensions
                    .setDimensions(dimensions)));

    BatchUpdateSpreadsheetRequest batchUpdateRequest = new BatchUpdateSpreadsheetRequest()
            .setRequests(requests);
    SHEETS.spreadsheets().batchUpdate(spreadsheetId, batchUpdateRequest)
            .execute();
}
</code>```

I'm currently using the following version:

```<code>        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-sheets</artifactId>
            <version>v4-rev21-1.22.0</version>
        </dependency>
</code>```

Regards,
Conteh

答:
You can get the gid by inspecting each sheet and confirming if that is the sheet that has to be modified either by looking at title or any field value:
You can do that by:

```<code>Get get = SHEETS.Spreadsheets.get(spreadsheetId);
Spreadsheet file = sheets.execute();
Sheet sheetToUpdate=null;
for(Sheet sheet: file.getSheets()){
   int index = sheet.getProperties().getIndex();
   //if this is the sheet you want to update
   sheetToUpdate = sheet;
}
int gid = sheetToUpdate.getProperties.getSheetId();
</code>```

Once you have the gid you can use the code in the update block to update that specific sheet within the spreadsheet.

Update:

If you know the gid you can pass the gid as an argument as

```<code>DimensionRange dimensions = new DimensionRange().setDimension("COLUMNS")
.setStartIndex(0).setEndIndex(2).setSheetId(gidNum);
</code>```

Body:
My Java Google Sheet API method to auto-resize dimensions of a Google sheet is working but only on the default sheet that had gid = 0. A particular spreadsheetId that identifies a Google Sheet can have several tabs each with a particular gid.

I wish to only target a particular sheet with a different gid than gid = 0 when I auto-resize dimensions. How do I adjust my code for that to happen?

public static void setAutoResizeDimensions(String spreadsheetId, int startindex, int endindex) throws IOException {

    List<Request> requests = new ArrayList<>();

    AutoResizeDimensionsRequest autoResizeDimensions = new AutoResizeDimensionsRequest();
    DimensionRange dimensions = new DimensionRange().setDimension("COLUMNS").setStartIndex(startindex).setEndIndex(endindex);

    requests.add(new Request()
            .setAutoResizeDimensions(autoResizeDimensions
                    .setDimensions(dimensions)));

    BatchUpdateSpreadsheetRequest batchUpdateRequest = new BatchUpdateSpreadsheetRequest()
            .setRequests(requests);
    SHEETS.spreadsheets().batchUpdate(spreadsheetId, batchUpdateRequest)
            .execute();
}

I'm currently using the following version:

        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-sheets</artifactId>
            <version>v4-rev21-1.22.0</version>
        </dependency>

Regards,
Conteh

Body:
You can get the gid by inspecting each sheet and confirming if that is the sheet that has to be modified either by looking at title or any field value:
You can do that by:

Get get = SHEETS.Spreadsheets.get(spreadsheetId);
Spreadsheet file = sheets.execute();
Sheet sheetToUpdate=null;
for(Sheet sheet: file.getSheets()){
   int index = sheet.getProperties().getIndex();
   //if this is the sheet you want to update
   sheetToUpdate = sheet;
}
int gid = sheetToUpdate.getProperties.getSheetId();

Once you have the gid you can use the code in the update block to update that specific sheet within the spreadsheet.

Update:

If you know the gid you can pass the gid as an argument as

DimensionRange dimensions = new DimensionRange().setDimension("COLUMNS")
.setStartIndex(0).setEndIndex(2).setSheetId(gidNum);


问:
Rails - How to delete associated attributes while updating a parent?
I have two models namely Invoice and InvoiceDetails and:

```<code>class Invoice < ActiveRecord::Base

  has_many :invoice_details
</code>```

Now an User has the ability to edit an invoice, so he can remove the invoiceDetails attributes from the invoice.
So how can I delete those nested attributes of the invoiceDetails model while updating the invoice(parent) model.

I'm using AngularJS for client side.

The Update Action :

```<code>  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end
</code>```

The Invoice Model

```<code>class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end
</code>```

The InvoiceDetails Model

```<code>class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end
</code>```

答:
In case someone is stalled on this, here is what I did. I added an attribute is_hide in InvoiceDetails(child) model.
When a user deletes an InvoiceDetails attribute, the is_hide property is set to true.

In the Invoice(parent) model, I used the before_save callback and iterated through the InvoiceDetails attributes and called mark_for_destruction where is_hide = true.

This is how my Invoice model looks :

```<code>class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy, autosave: true
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails

  before_save :mark_children_for_removal

  def mark_children_for_removal
    invoiceDetails.each do |child|
      child.mark_for_destruction if child.is_hide?
    end
  end

end
</code>```

Body:
I have two models namely Invoice and InvoiceDetails and:

class Invoice < ActiveRecord::Base

  has_many :invoice_details

Now an User has the ability to edit an invoice, so he can remove the invoiceDetails attributes from the invoice.
So how can I delete those nested attributes of the invoiceDetails model while updating the invoice(parent) model.

I'm using AngularJS for client side.

The Update Action :

  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end

The Invoice Model

class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end

The InvoiceDetails Model

class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end

Body:
In case someone is stalled on this, here is what I did. I added an attribute is_hide in InvoiceDetails(child) model.
When a user deletes an InvoiceDetails attribute, the is_hide property is set to true.

In the Invoice(parent) model, I used the before_save callback and iterated through the InvoiceDetails attributes and called mark_for_destruction where is_hide = true.

This is how my Invoice model looks :

class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy, autosave: true
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails

  before_save :mark_children_for_removal

  def mark_children_for_removal
    invoiceDetails.each do |child|
      child.mark_for_destruction if child.is_hide?
    end
  end

end


问:
Trying to hide again line with code of string in Android Studio
my question is hard to explain in text, but easy in screenshot :)
When i click on lane, which value in string.xml Android Studio show to user what is there. Something like this:

My question is: how to hide again this text in Anrdoid Studio ?

Thanks for your answers.

答:
Command+ to expand and Command- to collapse for anyone who uses a Mac.

Full list of commands for Windows/Linux and Mac here.


问:
Redirect to foreign page by embedding request
How to call/redirect to the foreign page by embedding request object from the servlet?</p>

答:
That's not possible. You need the response object.</p>

```<code>response.sendRedirect("http://google.com");
</code>```

Body:
That's not possible. You need the response object.

response.sendRedirect("http://google.com");


问:
How to make QtLinguist shipped with Qt 5.9.1 work?
Goal: Generate/update the *.ts files of a Qt widgets app using lupdate.

Setup:

Windows 7 Pro 64 (tried on Windows 10 Home as well)

Qt 5.9.1 Prebult Components for msvc2017 64-bit,

Visual Studio Community 2017.

The problem: I have run lupdate from the QtCreator, as well as manually from the console, but in neither case it is working. The message is:

Starting external tool
  "C:\Qt\Qt5.9.1\5.9.1\msvc2017_64\bin\lupdate.exe"
  C:/Documents/Projects/untitled1/untitled1.pro WARNING: Project ERROR:
  Cannot run compiler 'cl'. Maybe you forgot to setup the environment?

"C:\Qt\Qt5.9.1\5.9.1\msvc2017_64\bin\lupdate.exe" finished

Otherwise the project is compiled, run and debugged without problems with the kit: Desktop Qt 5.9.1 MSVC2017 64bit (default), which is the reason I think the environment is properly set up.

I can't find any information regarding this issue. Any ideas how to make lupdate work?

EDIT: I am adding screenshots of the current setup (which is made by the Qt installer) in attempt to clarify why I believe the environment is properly set up:

kits

cmake configuration

答:
The solution

Here is the solution I've found (rather hack-ish, but not too much), based on the info and advices kindly provided by n.m. in the comments under the question:

Create a translate.bat with the following single-line content:

"%programfiles(x86)%\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat" & lupdate.exe %1

and put it under %{CurrentProject:QT_INSTALL_BINS} (in my case C:\Qt\Qt5.9.1\5.9.1\msvc2017_64\bin). Make sure that the translate.bat contains the correct path to vcvars64.bat on your machine. You may as well put another version of vcvars if you need.

In Qt Creator select Tools/Options/Environment/External Tools and then Add Tool under Linguist category. Name it something like Create/Update TS files. Setup the fields for this entry as follows:

Executable: %{CurrentProject:QT_INSTALL_BINS}\translate.bat,

Arguments: %{CurrentProject:FilePath},

Working directory: %{CurrentProject:QT_INSTALL_BINS},

as shown here: External Tools, then apply the changes and close the Options window.

Go to Tools/External/Linguist, select Create/Update TS files and now it should do the job as usual.

The background

Here is once again the link, provided by n.m. in the comments, which served as a base for this solution. Here is also n.m.'s explaination:

Running lupdate from the console most definitely requires that you run
  vcbars*.bat as described in the link I gave you. That's because
  lupdate wants to run the compiler and it has no idea where to find it.
  vcbars*.bat tweaks your PATH and other environment variables. In
  theory the GUI should set up the environment for you, but in practice
  it probably doesn't.

ContentLicense: CC BY-SA 4.0


问:
why is strcmp not working in c?
I've just started to learn c and i wanted to try the strcmp function, but it somehow always gives me the result "1", if I run it. Doesn't matter what strings I type in. Since the first string is shorter than the second, i expected "-1" as a result.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}
</code>```

I also already tried to get rid of the i variable and just write "printf(" %d", strcmp(array1, array2)); and replacing the %d by a %u, but also not working. I've already searched the web and tried figuring it out for myself, probably just a simple mistake, would be glad if anyone could help. :)

答:
strcmp in libc's is almost always coded with some equivalent of the following:

```<code>int strcmp(char *s1, char *s2)
{
    for(; *s1 && *s2; s1++, s2++)
    {
        int res = *s1-*s2;
        if (res)
            return res;
    }
    return *s1-*s2;
}
</code>```

It returns the difference between the first different compared char, this ensure that the result is compliant with the two strings relation == < >.

When the strings length is different the return is the difference between the \0 string ending of the shorter one and the position corresponding char of the other string. So the the result shall reflect also the length difference.

Simply don't expect 0, 1 and -1.

Title: why is strcmp not working in c?

Body:
I've just started to learn c and i wanted to try the strcmp function, but it somehow always gives me the result "1", if I run it. Doesn't matter what strings I type in. Since the first string is shorter than the second, i expected "-1" as a result.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}

I also already tried to get rid of the i variable and just write "printf(" %d", strcmp(array1, array2)); and replacing the %d by a %u, but also not working. I've already searched the web and tried figuring it out for myself, probably just a simple mistake, would be glad if anyone could help. :)

Body:
strcmp in libc's is almost always coded with some equivalent of the following:

int strcmp(char *s1, char *s2)
{
    for(; *s1 && *s2; s1++, s2++)
    {
        int res = *s1-*s2;
        if (res)
            return res;
    }
    return *s1-*s2;
}

It returns the difference between the first different compared char, this ensure that the result is compliant with the two strings relation == < >.

When the strings length is different the return is the difference between the \0 string ending of the shorter one and the position corresponding char of the other string. So the the result shall reflect also the length difference.

Simply don't expect 0, 1 and -1.


问:
How to refresh wordpress variation thumbnail?
Whenever a user is selecting a different product attribute I am generating a new photo and setting it for variation. The problem I have is that I do not know how to show a newly generated photo? If I reload the page and select the same attributes I get the needed image, but I want this to happen instantly after the user selects the attributes (and after the photo is generated).

Here are the fragments of the code I am using. Uploading an external link

```<code>$upload = wp_upload_bits( basename( $mockImageUrl), null, $response['body'] );
</code>```

Generating an attachment and returning a new url:

```<code>$attachment_id = wp_insert_attachment( $attachment, $upload["file"] );

    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload["file"]);   // we can think about removing this later
    wp_update_attachment_metadata( $attachment_id, $attachment_data );
    set_post_thumbnail( $variation_id, $attachment_id );

    echo json_encode($mockImageUrl);
</code>```

Now new photo for variation is set, but the user still sees an old photo until refresh.

答:
You can update the current DOM without refreshing the page. you will have to upload image by using wordpress ajax. see below link.
WordPress image upload Using ajax?</p>

Body:
Whenever a user is selecting a different product attribute I am generating a new photo and setting it for variation. The problem I have is that I do not know how to show a newly generated photo? If I reload the page and select the same attributes I get the needed image, but I want this to happen instantly after the user selects the attributes (and after the photo is generated).

Here are the fragments of the code I am using. Uploading an external link

$upload = wp_upload_bits( basename( $mockImageUrl), null, $response['body'] );

Generating an attachment and returning a new url:

$attachment_id = wp_insert_attachment( $attachment, $upload["file"] );

    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload["file"]);   // we can think about removing this later
    wp_update_attachment_metadata( $attachment_id, $attachment_data );
    set_post_thumbnail( $variation_id, $attachment_id );

    echo json_encode($mockImageUrl);

Now new photo for variation is set, but the user still sees an old photo until refresh.


问:
can websocket exhaust webserver's connection pool
I have seen a lot of people have written Ajax(polling) vs websocket. I have not seen anyone mentioned below disadvantage of websocket.

As we know for each http request web-server needs connection.There are maximum number of concurrent connections web-server can support,beyond that if a request comes,request will have to wait till any connection is fee.

I case of simple http request(poll based),when a request is served by server connection is put in pool and that connection can be used for next request,so it is very unlikely in simple http request,a request will be waiting for a connection.

But in websocket connection is never put back in pool of webserver,so it is going to very frequent that next request will have to keep waiting for ever for connection.

So,I want to know,Am i thinking correctly or missing something. I am correct,how this is solved?does this issue ever occur?

答:
Browser can pool HTTP connections by using Connection: Keep-Alive header and then reuse them for further requests to the same host.

But WebSockets are not about requests and it's connections are not shared. You connect to WebSocket server and then control communication in your code. And that's all. If you want another connection, then you should create it.

Also, existing HTTP connections from pool can be upgraded to WebSocket connections.


问:
Sending E-mail using C#
I need to send email via my C# app.

I come from a VB 6 background and had a lot of bad experiences with the MAPI control.
First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.

If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?

答:
Use the namespace System.Net.Mail.  Here is a link to the MSDN page

You can send emails using SmtpClient class.

I paraphrased the code sample, so checkout MSDNfor details.

```<code>MailMessage message = new MailMessage(
   "fromemail@contoso.com",
   "toemail@contoso.com",
   "Subject goes here",
   "Body goes here");

SmtpClient client = new SmtpClient(server);
client.Send(message);
</code>```

The best way to send many emails would be to put something like this in forloop and send away!

OwnerDisplayName: Shaun

Title: Sending E-mail using C#

LastEditorDisplayName: Can Berk Güder

Body:
Use the namespace System.Net.Mail.  Here is a link to the MSDN page

You can send emails using SmtpClient class.

I paraphrased the code sample, so checkout MSDNfor details.

MailMessage message = new MailMessage(
   "fromemail@contoso.com",
   "toemail@contoso.com",
   "Subject goes here",
   "Body goes here");

SmtpClient client = new SmtpClient(server);
client.Send(message);

The best way to send many emails would be to put something like this in forloop and send away!

OwnerDisplayName: blarggstar


问:
Django Rest Framework filtering calculated model property
Sorry for a newbie question. I have a following model:

```<code>class WeightSlip(models.Model):

    grossdate = models.DateTimeField(auto_now=False, auto_now_add=False)
    grossweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    taredate = models.DateTimeField(auto_now=False, auto_now_add=False)
    tareweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    vehicle = models.CharField(max_length=12)

    @property
    def netweight(self):
        return self.grossweight - self.tareweight

    @property
    def slipdate(self):
        if self.grossdate > self.taredate:
           return grossdate.date()
        else:
           return taredate.date()
</code>```

Serializer:

```<code>class WeightSlipSerializer(serializers.ModelSerializer):

   class Meta:
      model = models.WeightSlip
      fields = ('grossdate', 'grossweight', 'taredate', 'tareweight', 'slipdate', 'netweight', 'vehicle')
      read_only_fields = ('slipdate', 'netweight')
</code>```

I am trying to use the django-rest-framework-filters to filter on the calculated 'netweight' and 'slipdate' properties:

```<code>class WeightSlipFilter(FilterSet):

   class Meta:
       model = WeightSlip
       fields = ('slipdate', 'netweight', 'vehicle')
</code>```

This gives me an error:

```<code>TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: slipdate, netweight
</code>```

Is there a workaround to this problem other than adding the calculated fields to the database ?

Thanks in advance.

答:
You can create custom filter for slipdate, netweight that will evaluate and filter this fields in db. For this you can use conditional expressions and F expression

```<code>from django.db.models import F, Case, When

class WeightSlipFilter(FilterSet):
    slipdate = DateTimeFilter(method='filter_slipdate')
    netweight = NumberFilter(method='filter_netweight')

    class Meta:
        model = WeightSlip
        fields = ('slipdate', 'netweight', 'vehicle')

    def filter_netweight(self, queryset, value):
        if value:
            queryset = queryset.annotate(netweight=F('grossweight') - F('tareweight')).filter(netweight=value)
        return queryset

    def filter_slipdate(self, queryset, value):
        if value:
            queryset = queryset.annotate(slipdate=Case(When(grossdate__gt=F('taredate'), then=F('grossdate')), default=F('taredate')).filter(slipdate=value)
        return queryset
</code>```

Body:
Sorry for a newbie question. I have a following model:

class WeightSlip(models.Model):

    grossdate = models.DateTimeField(auto_now=False, auto_now_add=False)
    grossweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    taredate = models.DateTimeField(auto_now=False, auto_now_add=False)
    tareweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    vehicle = models.CharField(max_length=12)

    @property
    def netweight(self):
        return self.grossweight - self.tareweight

    @property
    def slipdate(self):
        if self.grossdate > self.taredate:
           return grossdate.date()
        else:
           return taredate.date()

Serializer:

class WeightSlipSerializer(serializers.ModelSerializer):

   class Meta:
      model = models.WeightSlip
      fields = ('grossdate', 'grossweight', 'taredate', 'tareweight', 'slipdate', 'netweight', 'vehicle')
      read_only_fields = ('slipdate', 'netweight')

I am trying to use the django-rest-framework-filters to filter on the calculated 'netweight' and 'slipdate' properties:

class WeightSlipFilter(FilterSet):

   class Meta:
       model = WeightSlip
       fields = ('slipdate', 'netweight', 'vehicle')

This gives me an error:

TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: slipdate, netweight

Is there a workaround to this problem other than adding the calculated fields to the database ?

Thanks in advance.

Body:
You can create custom filter for slipdate, netweight that will evaluate and filter this fields in db. For this you can use conditional expressions and F expression

from django.db.models import F, Case, When

class WeightSlipFilter(FilterSet):
    slipdate = DateTimeFilter(method='filter_slipdate')
    netweight = NumberFilter(method='filter_netweight')

    class Meta:
        model = WeightSlip
        fields = ('slipdate', 'netweight', 'vehicle')

    def filter_netweight(self, queryset, value):
        if value:
            queryset = queryset.annotate(netweight=F('grossweight') - F('tareweight')).filter(netweight=value)
        return queryset

    def filter_slipdate(self, queryset, value):
        if value:
            queryset = queryset.annotate(slipdate=Case(When(grossdate__gt=F('taredate'), then=F('grossdate')), default=F('taredate')).filter(slipdate=value)
        return queryset


问:
Copy Paste data from columns of dynamic length
In an Excel file, I have 2 tabs: Input and Output.

In the tab Input, I have in column A, a list of codes like: code001, and it goes indefinitely, since I am adding more and more.

In column B I have a list of keywords like: blue dress, red pencil, white scarf, ... again I don't have the number of keywords since I am adding more and more.

On columns C and D, I have the same structure as A and B.
(The file structure cannot be changed!)

I want to put on the tab Output, on Column A, the codes (column A and column C from tab Input) and on column B, the keywords (column B and column D from the tab Input).

How can I go through all the columns and the rows, with a while cycle/function?

答:
Admittedly I am  5 year late to offer a solution.... here's my approach to address it</p>

```<code>Sub consol
 Dim maxi as long, restrtrow as long, i as long
 For i = 1 to 4
   If i = 1 or i = 3 then
       Maxi= sheets ("input").cells (1000000,i).end (xlup).row
       Restrtrow = sheets ("output").cells (1000000,1).end (xlup).row+1
       Sheets ("input").select
       Range (Cells (2 ,i),cells ( maxi,i)).copy
       Sheets ("output").select
       Cells(Restrtrow,1).SELECT
       Selection.pastespecial paste:= xlpastevalues
     Elseif i =2 or i=4 then
         Sheets ("input").select
         Range (cells (2,i),cells (maxi,i)).select
         Selection.copy
         Sheets ("output").select
         Cells (2,restrtrow).select
         Selection.pastespecial paste:= xlpastevalues
     End if

   next
 end sub
</code>```

Body:
Admittedly I am  5 year late to offer a solution.... here's my approach to address it

Sub consol
 Dim maxi as long, restrtrow as long, i as long
 For i = 1 to 4
   If i = 1 or i = 3 then
       Maxi= sheets ("input").cells (1000000,i).end (xlup).row
       Restrtrow = sheets ("output").cells (1000000,1).end (xlup).row+1
       Sheets ("input").select
       Range (Cells (2 ,i),cells ( maxi,i)).copy
       Sheets ("output").select
       Cells(Restrtrow,1).SELECT
       Selection.pastespecial paste:= xlpastevalues
     Elseif i =2 or i=4 then
         Sheets ("input").select
         Range (cells (2,i),cells (maxi,i)).select
         Selection.copy
         Sheets ("output").select
         Cells (2,restrtrow).select
         Selection.pastespecial paste:= xlpastevalues
     End if

   next
 end sub


问:
Getting text from XPath but want elements?
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

```<code><node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>
</code>```

I wish to copy the content of node 2 including the tags, which is:

```<code><node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>
</code>```

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

答:
to select node2 elements and everything inside of it use:

xPath: //node2/descendant-or-self::*

css: node2,node2 *

to select only inner content without node2 tag by itself:

xPath: //node2/descendant::*

css: node2 *

Body:
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

<node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>

I wish to copy the content of node 2 including the tags, which is:

<node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).


问:
Inserting multiple values in a table, in C#
I have 98 columns in a table named 'molasses_analysis' and I need to insert records using my c# desktop application.

Sample of my code is as below.

```<code>    string insert_sql = @"insert into molasses_analysis(mo_entry_date, mo_entry_time, mo_code, mo_brix, mo_pol, mo_purity, mo_crtd_by) " +
    " values(@entry_date, @entry_time, @mol_code, @brix, @pol, @purity, @crtd_by)";
    try
        {
         List<SqlParameter> param = new List<SqlParameter>();
         param.Add(new SqlParameter("@entry_date", entry_date));
         param.Add(new SqlParameter("@entry_time", entry_time));
         param.Add(new SqlParameter("@mol_code", mol_code));
         param.Add(new SqlParameter("@brix", brix));
         param.Add(new SqlParameter("@pol", pol));
         param.Add(new SqlParameter("@purity", purity));
         param.Add(new SqlParameter("@crtd_by", crtd_by));
        int inserted_rows = SqlHelper.ExecuteNonQuery(dbConn.sqlConn(),CommandType.Text, insert_sql, param.ToArray());
        }
catch (Exception ex)
      {
        MessageBox.Show("Data not saved!\nError message - "+ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
</code>```

Here I just used seven fields/columns only but it will be quite hectic and painful to write such code for 98 columns and assign Sql Parameter for each column.
My question is, is there any cleaner and good code to insert multiple columns using c# code?

答:
The short answer is no; Not with the way you're using local variables to populate each SqlParameter.

One solution would be if each of those local variables was instead stored in a Dictionary (key/value pairs) you could use a StringBuilder and iterate your dictionary keys to build the SQL query string. During that same loop you could add each SqlParameter.

```<code>using System.Collections.Generic; // for dictionary
using System.Text; // for stringbuilder

// ...

// create a dictionary then use a literal to make it easier to populate
Dictionary<string, string> data = new Dictionary<string, string>
{
    { "entry_date", "SOMEVALUE1" },
    { "entry_time", "SOMEVALUE2" }
    // add more params and values here...
};

// start our query and params list
StringBuilder query = new StringBuilder("YOUR QUERY STARTS HERE");
List<SqlParameter> params = new List<SqlParameter>();

// iterate over each key/value pair, appending to the query and params list
foreach (KeyValuePair<string, string> pair in data) {
    query.Append("@" + pair.Key);
    params.Add(new SqlParameter(pair.Key, pair.Value));
}
</code>```

NOTE: The above code is an EXAMPLE to demonstrate using dictionaries and stringbuilders; It should be studied, not be copy-pasted.

Body:
I have 98 columns in a table named 'molasses_analysis' and I need to insert records using my c# desktop application.

Sample of my code is as below.

    string insert_sql = @"insert into molasses_analysis(mo_entry_date, mo_entry_time, mo_code, mo_brix, mo_pol, mo_purity, mo_crtd_by) " +
    " values(@entry_date, @entry_time, @mol_code, @brix, @pol, @purity, @crtd_by)";
    try
        {
         List<SqlParameter> param = new List<SqlParameter>();
         param.Add(new SqlParameter("@entry_date", entry_date));
         param.Add(new SqlParameter("@entry_time", entry_time));
         param.Add(new SqlParameter("@mol_code", mol_code));
         param.Add(new SqlParameter("@brix", brix));
         param.Add(new SqlParameter("@pol", pol));
         param.Add(new SqlParameter("@purity", purity));
         param.Add(new SqlParameter("@crtd_by", crtd_by));
        int inserted_rows = SqlHelper.ExecuteNonQuery(dbConn.sqlConn(),CommandType.Text, insert_sql, param.ToArray());
        }
catch (Exception ex)
      {
        MessageBox.Show("Data not saved!\nError message - "+ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }

Here I just used seven fields/columns only but it will be quite hectic and painful to write such code for 98 columns and assign Sql Parameter for each column.
My question is, is there any cleaner and good code to insert multiple columns using c# code?

Body:
The short answer is no; Not with the way you're using local variables to populate each SqlParameter.

One solution would be if each of those local variables was instead stored in a Dictionary (key/value pairs) you could use a StringBuilder and iterate your dictionary keys to build the SQL query string. During that same loop you could add each SqlParameter.

using System.Collections.Generic; // for dictionary
using System.Text; // for stringbuilder

// ...

// create a dictionary then use a literal to make it easier to populate
Dictionary<string, string> data = new Dictionary<string, string>
{
    { "entry_date", "SOMEVALUE1" },
    { "entry_time", "SOMEVALUE2" }
    // add more params and values here...
};

// start our query and params list
StringBuilder query = new StringBuilder("YOUR QUERY STARTS HERE");
List<SqlParameter> params = new List<SqlParameter>();

// iterate over each key/value pair, appending to the query and params list
foreach (KeyValuePair<string, string> pair in data) {
    query.Append("@" + pair.Key);
    params.Add(new SqlParameter(pair.Key, pair.Value));
}

NOTE: The above code is an EXAMPLE to demonstrate using dictionaries and stringbuilders; It should be studied, not be copy-pasted.


问:
Can Jooq simulate window functions in MySql
My company is using mysql as their database layer. We are creating very complex reports that will be much easier if MySql had Window functions. I couldnt find any where in the documentation that Jooq supports window functions for mysql. Just want to know if its possible to do this with Jooq. If not, will this feature be added later?</p>

答:
There's a pending feature request to emulate window functions on databases that do not support them: https://github.com/jOOQ/jOOQ/issues/1715

It will certainly not be part of jOOQ 3.10, though.

Most window functions can indeed be emulated using correlated subqueries, although native support is quite likely to be much faster.

Do note that there is work on window functions being done for a future MySQL release. In the meantime, perhaps you could run your complex reports on a different database, e.g. PostgreSQL.


问:
How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?
Let's say I have two entities: Group and User. Every user can be member of many groups and every group can have many users.

```<code>@Entity
public class User {
    @ManyToMany
    Set<Group> groups;
    //...
}

@Entity
public class Group {
    @ManyToMany(mappedBy="groups")
    Set<User> users;
    //...
}
</code>```

Now I want to remove a group (let's say it has many members).

Problem is that when I call EntityManager.remove() on some Group, JPA provider (in my case Hibernate) does not remove rows from join table and delete operation fails due to foreign key constrains. Calling remove() on User works fine (I guess this has something to do with owning side of relationship).

So how can I remove a group in this case?

Only way I could come up with is to load all users in the group, then for every user remove current group from his groups and update user. But it seems ridiculous to me to call update() on every user from the group just to be able to delete this group.

答:
This is a good solution. The best part is on the SQL side – fine tuning to any level is easy.

I used MySql and MySql Workbench to Cascade on delete for the Required Foreign KEY.

```<code>ALTER TABLE schema.joined_table
ADD CONSTRAINT UniqueKey
FOREIGN KEY (key2)
REFERENCES schema.table1 (id)
ON DELETE CASCADE;
</code>```

Body:
Let's say I have two entities: Group and User. Every user can be member of many groups and every group can have many users.

@Entity
public class User {
    @ManyToMany
    Set<Group> groups;
    //...
}

@Entity
public class Group {
    @ManyToMany(mappedBy="groups")
    Set<User> users;
    //...
}

Now I want to remove a group (let's say it has many members).

Problem is that when I call EntityManager.remove() on some Group, JPA provider (in my case Hibernate) does not remove rows from join table and delete operation fails due to foreign key constrains. Calling remove() on User works fine (I guess this has something to do with owning side of relationship).

So how can I remove a group in this case?

Only way I could come up with is to load all users in the group, then for every user remove current group from his groups and update user. But it seems ridiculous to me to call update() on every user from the group just to be able to delete this group.

Body:
This is a good solution. The best part is on the SQL side – fine tuning to any level is easy.

I used MySql and MySql Workbench to Cascade on delete for the Required Foreign KEY.

ALTER TABLE schema.joined_table
ADD CONSTRAINT UniqueKey
FOREIGN KEY (key2)
REFERENCES schema.table1 (id)
ON DELETE CASCADE;


问:
Tensorflow: Weird broadcasting behavior
I did not quite well understand how the broadcasting mechanism works in Tensorflow. Assume that we have the following code:

```<code>W1_shape = [5, 5, 1, 32]
b1_shape = [32]
x = tf.placeholder(tf.float32)
initial_W1 = tf.truncated_normal(shape=W1_shape, stddev=0.1)
W1 = tf.Variable(initial_W1)
initial_b1 = tf.constant(0.1, shape=b1_shape)
b1 = tf.Variable(initial_b1)
conv1 = tf.nn.conv2d(x, W1, strides=[1, 1, 1, 1], padding='SAME')
conv1_sum = conv1 + b1
y = tf.placeholder(tf.float32)
z = conv1 + y

sess = tf.Session()
# Run init ops
init = tf.global_variables_initializer()
sess.run(init)

while True:
    samples, labels, indices = dataset.get_next_batch(batch_size=1000)
    samples = samples.reshape((1000, MnistDataSet.MNIST_SIZE, MnistDataSet.MNIST_SIZE, 1))
    y_data = np.ones(shape=(1000, 32))
    conv1_res, conv1_sum_res, b1_res, z_res=\
    sess.run([conv1, conv1_sum, b1, z], feed_dict={x: samples, y: y_data})

if dataset.isNewEpoch:
    break
</code>```

So, I load the MNIST dataset, which consists of 28x28 sized images. The convolution operator uses 32 filters of 5x5 size. I use a batch size of 1000, so data tensor x has the shape (1000,28,28,1). The tf.nn.conv2d operation outputs a tensor of the shape (1000,28,28,32). y is a placeholder, a variable which I add to check Tensorflow's broadcasting mechanism by adding it to (1000,28,28,32) shaped conv1 tensor. In the line y_data = np.ones(shape=(1000, 32)), I experiment with various tensor shapes for y. The shapes (28,28), (1000,28) and (1000,32) won't add to conv1, with the errors of the type:

InvalidArgumentError (see above for traceback): Incompatible shapes: [1000,28,28,32] vs. [28,28]

The shapes (28,32) and (28,28,32) work and broadcast correctly. But according to the broadcasting semantics explained in https://www.tensorflow.org/performance/xla/broadcasting , the first three shapes have to work as well, since they are of the correct order by matching dimensions with the 4D conv1 tensor. For example, (28,28) matches (1000,28,28,32) in the dimensions 1 and 2, (1000,32) matches in the dimensions 0 and 3, just as mentioned in the link. Am I missing or misunderstanding something here? What is the correct broadcasting behavior of Tensorflow in such cases?

答:
Its true the documentation seems to be suggesting what you say. But it looks like it follows numpy broadcsting rules:

When operating on two arrays, NumPy compares their shapes
  element-wise. It starts with the trailing dimensions, and works its
  way forward. Two dimensions are compatible when :

they are equal, or

one of them is 1

So by the above definition:

(28, 28) cannot broadcast to (1000, 28, 28, 32) but (28, 28, 1) can be.

(1000,28) cannot but (1000, 1, 28, 1) or (1000, 28, 1, 1) can

(28, 32) works because the trailing dimensions match.

Title: Tensorflow: Weird broadcasting behavior

Body:
I did not quite well understand how the broadcasting mechanism works in Tensorflow. Assume that we have the following code:

W1_shape = [5, 5, 1, 32]
b1_shape = [32]
x = tf.placeholder(tf.float32)
initial_W1 = tf.truncated_normal(shape=W1_shape, stddev=0.1)
W1 = tf.Variable(initial_W1)
initial_b1 = tf.constant(0.1, shape=b1_shape)
b1 = tf.Variable(initial_b1)
conv1 = tf.nn.conv2d(x, W1, strides=[1, 1, 1, 1], padding='SAME')
conv1_sum = conv1 + b1
y = tf.placeholder(tf.float32)
z = conv1 + y

sess = tf.Session()
# Run init ops
init = tf.global_variables_initializer()
sess.run(init)

while True:
    samples, labels, indices = dataset.get_next_batch(batch_size=1000)
    samples = samples.reshape((1000, MnistDataSet.MNIST_SIZE, MnistDataSet.MNIST_SIZE, 1))
    y_data = np.ones(shape=(1000, 32))
    conv1_res, conv1_sum_res, b1_res, z_res=\
    sess.run([conv1, conv1_sum, b1, z], feed_dict={x: samples, y: y_data})

if dataset.isNewEpoch:
    break

So, I load the MNIST dataset, which consists of 28x28 sized images. The convolution operator uses 32 filters of 5x5 size. I use a batch size of 1000, so data tensor x has the shape (1000,28,28,1). The tf.nn.conv2d operation outputs a tensor of the shape (1000,28,28,32). y is a placeholder, a variable which I add to check Tensorflow's broadcasting mechanism by adding it to (1000,28,28,32) shaped conv1 tensor. In the line y_data = np.ones(shape=(1000, 32)), I experiment with various tensor shapes for y. The shapes (28,28), (1000,28) and (1000,32) won't add to conv1, with the errors of the type:

InvalidArgumentError (see above for traceback): Incompatible shapes: [1000,28,28,32] vs. [28,28]

The shapes (28,32) and (28,28,32) work and broadcast correctly. But according to the broadcasting semantics explained in https://www.tensorflow.org/performance/xla/broadcasting , the first three shapes have to work as well, since they are of the correct order by matching dimensions with the 4D conv1 tensor. For example, (28,28) matches (1000,28,28,32) in the dimensions 1 and 2, (1000,32) matches in the dimensions 0 and 3, just as mentioned in the link. Am I missing or misunderstanding something here? What is the correct broadcasting behavior of Tensorflow in such cases?


问:
Get and display the values for product attribute in WooCommerce
In WooCommerce, I have this code to show product attributes slugs on archives pages like shop pages :

```<code>if (!function_exists('shop_attributes_in_loop')) {
    function shop_attributes_in_loop(){
        global $product;
        $attributes = $product->get_attributes();
        if(!empty($attributes)){
            $attribute_single = array_keys($attributes);
            $myArray = array();
            echo '<div class="product_attributes">';
            foreach ($attribute_single as $attribute => $value) {
                $myArray[] = ucfirst($value);
            }
            echo implode(', ', $myArray).'</div>';
        }
    }
}
add_action('woocommerce_after_shop_loop_item', 'shop_attributes_in_loop');
</code>```

They only show atributes field name  as pa_size, pa_color

How can I get and display the values for that product attributes (like 2kg, 3kg or blue, green)?

Thanks.

答:
It's simple with this code (Example 1):

```<code>function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = ( object ) array (
        'color'              => $product->get_attribute( 'pa_color' ),
        'size'            => $product->get_attribute( 'pa_size' ),
        );
    return $attributes;
    }
}
</code>```

Usage:

```<code>$attributes = nt_product_attributes();
echo $attributes->color;
echo $attributes->size;
</code>```

OR (Example 2)

```<code>function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = array (
        'color'              => $product->get_attribute('pa_color'),
        'size'            => $product->get_attribute('pa_size'),
        );
    return $attributes;
    }
}
</code>```

Usage:

```<code>$attributes = nt_product_attributes();
echo $attributes['color'];
echo $attributes['size'];
</code>```

Body:
In WooCommerce, I have this code to show product attributes slugs on archives pages like shop pages :

if (!function_exists('shop_attributes_in_loop')) {
    function shop_attributes_in_loop(){
        global $product;
        $attributes = $product->get_attributes();
        if(!empty($attributes)){
            $attribute_single = array_keys($attributes);
            $myArray = array();
            echo '
';
            foreach ($attribute_single as $attribute => $value) {
                $myArray[] = ucfirst($value);
            }
            echo implode(', ', $myArray).'
';
        }
    }
}
add_action('woocommerce_after_shop_loop_item', 'shop_attributes_in_loop');

They only show atributes field name  as pa_size, pa_color

How can I get and display the values for that product attributes (like 2kg, 3kg or blue, green)?

Thanks.

Body:
It's simple with this code (Example 1):

function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = ( object ) array (
        'color'              => $product->get_attribute( 'pa_color' ),
        'size'            => $product->get_attribute( 'pa_size' ),
        );
    return $attributes;
    }
}

Usage:

$attributes = nt_product_attributes();
echo $attributes->color;
echo $attributes->size;

OR (Example 2)

function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = array (
        'color'              => $product->get_attribute('pa_color'),
        'size'            => $product->get_attribute('pa_size'),
        );
    return $attributes;
    }
}

Usage:

$attributes = nt_product_attributes();
echo $attributes['color'];
echo $attributes['size'];


问:
how to print inline in python strings and function
How to print a string and funtion(print) on the same line:
For example:-

```<code>def displayHand(hand):
      print({1:2,2:3})
</code>```

know how can i get a print like this ( Current Hand:{1:2,2:3} )

答:
Add an end=" " to your first print call:

```<code>print('Current Hand:', end=" ")
</code>```

Full code:

```<code>In [416]: def displayHand(hand):
     ...:       print(hand)
     ...:

In [417]: hand = {1:2, 2:3}
     ...: print('Current Hand:', end=" ")
     ...: displayHand(hand)
     ...:
Current Hand: {1: 2, 2: 3}
</code>```

If you're using python 2, you'd need:

```<code>print 'Current Hand:',
</code>```

Body:
How to print a string and funtion(print) on the same line:
For example:-

def displayHand(hand):
      print({1:2,2:3})

know how can i get a print like this ( Current Hand:{1:2,2:3} )

Body:
Add an end=" " to your first print call:

print('Current Hand:', end=" ")

Full code:

In [416]: def displayHand(hand):
     ...:       print(hand)
     ...:

In [417]: hand = {1:2, 2:3}
     ...: print('Current Hand:', end=" ")
     ...: displayHand(hand)
     ...:
Current Hand: {1: 2, 2: 3}

If you're using python 2, you'd need:

print 'Current Hand:',


问:
ZF2 - inputFilter -> set value to null
In my ZF2 app I've got a form with several optional fields. If user decide to leave that field blank then it should set it as NULL in db, however - it doesn't work.

Example field:

```<code>$this->add(array(
  'name' => 'productId',
  'type' => 'select',
  'options' => array(
    'value_options' => array(
      'global' => 'Global option', // this should be null
      'mobile' => 'Another option'
    )
  ),
));
</code>```

And filter:

```<code>$inputFilter->add(array(
    'name' => 'productId',
    'validators' => array(
        array(
            'name' => 'Callback',
            'options' => array(
              // 'messages' => array(
              //     \Zend\Validator\Callback::INVALID_VALUE => $value,
              // ),
              'callback' => function ($value) {
                  if($value === 'global')
                  {
                    $value = null;
                    //return true;
                    // echo '```' . var_export($value, true) . '```';
                    // die();
                  }
                }

            ),
        ),
    ),
));
</code>```

This piece of code works when "mobile" option is selected. However, with 'global' option it doesn't work.
As you can see, I've done some basic debugging to make sure that value is overrided on callback and it indeed returns NULL. Regardless of that validator says:

array (
    'productId' =>
    array (
      'callbackValue' => 'The input is not valid',
    ),
  )

So I tried to return true on callback which resulted in below error:

Statement could not be executed (23000 - 1452 - Cannot add or update a child row: a foreign key constraint fails (app.codes, CONSTRAINT fk_products_id FOREIGN KEY (productId) REFERENCES products (id)))

How am I supposed to pass null param to my db? If I cut this field completly from form then it is ignored and everything works.

答:
Found solution, it's pretty simple actually.

I can set desired select options to some specific value and then use ToNull filter to convert it into null -
https://framework.zend.com/manual/2.4/en/modules/zend.filter.null.html

Code for $inputFilter:

```<code>$inputFilter->add(array(
    'name' => 'productId',
    'required'          => false,
    'filters' => array(
      array('name' => 'ToNull', 'options' => array('type' => \Zend\Filter\ToNull::TYPE_STRING)),
    ),
));
</code>```

Title: ZF2 - inputFilter -> set value to null

Body:
In my ZF2 app I've got a form with several optional fields. If user decide to leave that field blank then it should set it as NULL in db, however - it doesn't work.

Example field:

$this->add(array(
  'name' => 'productId',
  'type' => 'select',
  'options' => array(
    'value_options' => array(
      'global' => 'Global option', // this should be null
      'mobile' => 'Another option'
    )
  ),
));

And filter:

$inputFilter->add(array(
    'name' => 'productId',
    'validators' => array(
        array(
            'name' => 'Callback',
            'options' => array(
              // 'messages' => array(
              //     \Zend\Validator\Callback::INVALID_VALUE => $value,
              // ),
              'callback' => function ($value) {
                  if($value === 'global')
                  {
                    $value = null;
                    //return true;
                    // echo '
' . var_export($value, true) . '
';
                    // die();
                  }
                }

            ),
        ),
    ),
));

This piece of code works when "mobile" option is selected. However, with 'global' option it doesn't work.
As you can see, I've done some basic debugging to make sure that value is overrided on callback and it indeed returns NULL. Regardless of that validator says:

array (
    'productId' =>
    array (
      'callbackValue' => 'The input is not valid',
    ),
  )

So I tried to return true on callback which resulted in below error:

Statement could not be executed (23000 - 1452 - Cannot add or update a child row: a foreign key constraint fails (app.codes, CONSTRAINT fk_products_id FOREIGN KEY (productId) REFERENCES products (id)))

How am I supposed to pass null param to my db? If I cut this field completly from form then it is ignored and everything works.

Body:
Found solution, it's pretty simple actually.

I can set desired select options to some specific value and then use ToNull filter to convert it into null -
https://framework.zend.com/manual/2.4/en/modules/zend.filter.null.html

Code for $inputFilter:

$inputFilter->add(array(
    'name' => 'productId',
    'required'          => false,
    'filters' => array(
      array('name' => 'ToNull', 'options' => array('type' => \Zend\Filter\ToNull::TYPE_STRING)),
    ),
));


问:
No domain values in CL_SALV_TABLE column. Why?
I have 2 rows shown in the ALV list, one of this column has domain values.

If I click on the search help right it doesn't show any values at all.

Do I have to activate something in the class to see the values of any domain?

答:
Automatic search help (aka domain values) will be showed only when creating ALV via Dictionary structure, and that's why it is impossible with cl_salv_table, because it accepts only internal table.
However, it have special method set_ddic_reference for assigning F4 values.

```<code>DATA: lr_column   TYPE REF TO cl_salv_column_table,
       lr_columns TYPE REF TO cl_salv_columns_table.
DATA: ls_ddic type salv_s_ddic_reference.
lr_columns = o_alv->get_columns( ).
lr_column ?= lr_columns->get_column( columnname = 'MANDT' ).
ls_ddic-table = 'T001'.
ls_ddic-field = 'MANDT'.
lr_column->set_ddic_reference( ls_ddic ).
lr_column->set_f4( abap_true ).
</code>```

This code should be called after the factory constructor and before the display() method.

Body:
Automatic search help (aka domain values) will be showed only when creating ALV via Dictionary structure, and that's why it is impossible with cl_salv_table, because it accepts only internal table.
However, it have special method set_ddic_reference for assigning F4 values.

DATA: lr_column   TYPE REF TO cl_salv_column_table,
       lr_columns TYPE REF TO cl_salv_columns_table.
DATA: ls_ddic type salv_s_ddic_reference.
lr_columns = o_alv->get_columns( ).
lr_column ?= lr_columns->get_column( columnname = 'MANDT' ).
ls_ddic-table = 'T001'.
ls_ddic-field = 'MANDT'.
lr_column->set_ddic_reference( ls_ddic ).
lr_column->set_f4( abap_true ).

This code should be called after the factory constructor and before the display() method.


问:
Using c++ typedef/using type alias
I am reading C++ primer book and completely don't understand one line:

```<code> using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }
</code>```

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

答:
Both type aliases are the same:

Type alias, alias template (since C++11):

Type alias is a name that refers to a previously defined type (similar to typedef):

```<code>using identifier attr(optional) = type-id ;
</code>```

so you may use:

```<code>typedef int int_array[4];
</code>```

or  you may just use (it is the same as above):

```<code>using int_array = int[4];
</code>```

When you need to address the memory with 4*sizeof(int) steps, e.g. if the system int size is 4 bytes, then the memory step size is 4*4=16 bytes. even you may use int_array *p; in this case ++p advances p by one memory step e.g. 16 bytes.
see:

1- working sample with using int_array = int[4];:

```<code>#include <iostream>
using std::cout; using std::endl;

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration
    // use type alias
    using int_array = int[4];
    for (int_array& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers.
    // use type alias
    for (int_array* p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}
</code>```

output 1:

```<code>0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
</code>```

2- working sample using typedef int int_array[4];:

```<code>#include <iostream>
using std::cout; using std::endl;

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration
    // use type alias
    typedef int int_array[4];
    for (int_array& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers.
    // use type alias
    for (int_array* p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}
</code>```

output 2(same):

```<code>0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
</code>```

Ref: https://github.com/Mooophy/Cpp-Primer/blob/master/ch03/ex3_44.cpp

Note: use -std=c++11 for compile/link.

Title: Using c++ typedef/using type alias

Body:
I am reading C++ primer book and completely don't understand one line:

 using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

Body:
Both type aliases are the same:

Type alias, alias template (since C++11):

Type alias is a name that refers to a previously defined type (similar to typedef):

using identifier attr(optional) = type-id ;

so you may use:

typedef int int_array[4];

or  you may just use (it is the same as above):

using int_array = int[4];

When you need to address the memory with 4*sizeof(int) steps, e.g. if the system int size is 4 bytes, then the memory step size is 4*4=16 bytes. even you may use int_array *p; in this case ++p advances p by one memory step e.g. 16 bytes.
see:

1- working sample with using int_array = int[4];:

#include <iostream>
using std::cout; using std::endl;

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration
    // use type alias
    using int_array = int[4];
    for (int_array& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers.
    // use type alias
    for (int_array* p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}

output 1:

0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11

2- working sample using typedef int int_array[4];:

#include <iostream>
using std::cout; using std::endl;

int main()
{
    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    // a range for to manage the iteration
    // use type alias
    typedef int int_array[4];
    for (int_array& p : ia)
        for (int q : p)
            cout << q << " ";
    cout << endl;

    // ordinary for loop using subscripts
    for (size_t i = 0; i != 3; ++i)
        for (size_t j = 0; j != 4; ++j)
            cout << ia[i][j] << " ";
    cout << endl;

    // using pointers.
    // use type alias
    for (int_array* p = ia; p != ia + 3; ++p)
        for (int *q = *p; q != *p + 4; ++q)
            cout << *q << " ";
    cout << endl;

    return 0;
}

output 2(same):

0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11

Ref: https://github.com/Mooophy/Cpp-Primer/blob/master/ch03/ex3_44.cpp

Note: use -std=c++11 for compile/link.


问:
Aws ip range ssh restrictions
I'm studying for my aws cert and I'm trying understand the below section of the documentation on EC2 instances:

In the Source field, choose My IPto automatically populate the field with the public IPv4 address of your local computer. Alternatively, choose Custom and specify the public IPv4 address of your computer or network in CIDR notation. For example, if your IPv4 address is 203.0.113.25, specify 203.0.113.25/32 to list this single IPv4 address in CIDR notation. If your company allocates addresses from a range, specify the entire range, such as203.0.113.0/24.

What I want to do is restrict access to my EC2 instance to the people on my home network so let's just say that's 192.168.X.X. How would I go about doing that? The documentation is not clear enough to me. Thanks. Maybe a couple of different examples would help.

答:
You can only restrict access to your local network's public IP. Local addresses such as 192.168.x.x don't route over the internet so your EC2 instance will never see them. On a home network you usually only have one public IP which is outside IP of your router.

I should add that in your router, you should see your public IP and subnet mask. There are plenty of places on line to convert an IP/subnet combo to CIDR notation if you don't know how to do it manually.

Title: Aws ip range ssh restrictions


问:
Xcode template to import file by file path
I have a Xcode template file like so:

```<code>#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___
@end
</code>```

This will create an example file like so:

```<code>#import "ExampleFile.h"

@implementation ExampleFile
@end
</code>```

However due to some complexity in our build system, I need to import files by their file path.

For example, if I was creating ExampleFile.m inside of Path/To/ folder. Then my desired output would be:

```<code>// Desired template output
#import "Path/To/ExampleFile.h"
</code>```

I tried looking through some Apple example templates, but didn't seem to find a way to make it work.

I also stumpled upon ___DIRECTORY___ referenced here, but it doesn't seem to work for me when I attempted to use it.

Does anyone know if there is a way to accomplish this?

答:
Try enabling "Use custom working directory" option, it will let you choose the base directory.
How to enable this is answered in the following question.
Xcode: How to set current working directory to a relative path for an executable?

Hope this helps

Body:
I have a Xcode template file like so:

#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___
@end

This will create an example file like so:

#import "ExampleFile.h"

@implementation ExampleFile
@end

However due to some complexity in our build system, I need to import files by their file path.

For example, if I was creating ExampleFile.m inside of Path/To/ folder. Then my desired output would be:

// Desired template output
#import "Path/To/ExampleFile.h"

I tried looking through some Apple example templates, but didn't seem to find a way to make it work.

I also stumpled upon ___DIRECTORY___ referenced here, but it doesn't seem to work for me when I attempted to use it.

Does anyone know if there is a way to accomplish this?


问:
Creating dictionary with tuple keys with a loop
I'm trying to create a dictionary with tuples as keys.

For example, if my range is (0, 3), I want to create a dictionary with mappings of every combination. E.g. {(0,0):1, (0,1):2, (0,2):1 ...}, where the value is an int that does not exist in the tuple.

If the range were (0, 4) the dictionary would look something like this:

```<code>{(0,1,2):3, (0,0,0):1, (0,0,1):2...}
</code>```

The only rule being that the key must be a value that is not contained in the tuple and is within the given range.

Hopefully, that makes sense. I've been trying to figure out how to write code in python to do this, but I'm not sure how to go about this.

Edit Complete Example:
Range: (0, 3)

Dict Created:

```<code>{(0,0):1, (0,1):2, (0,2):1, (1,0):2, (1,1):2, (1,2): 0, (2,0): 1, (2,1):0, (2:2):1}
</code>```

And yes, for some combinations e.g. (1,1) there are multiple possible values. It could be (1,1): 0 or (1,1): 2. I just need one though.

答:
With itertools.product you could create all the keys. Then you just need to find one value that is in your range but not in the key, which could be solved using set.difference:

```<code>>>> import itertools

>>> the_range = range(0, 3)
>>> possible = set(the_range)

>>> {key: possible.difference(key).pop() for key in itertools.product(the_range, repeat=len(the_range)-1)}
{(0, 1): 2, (1, 2): 0, (0, 0): 1, (2, 0): 1, (1, 0): 2, (2, 2): 0, (0, 2): 1, (2, 1): 0, (1, 1): 0}
</code>```

It should work as long as you don't expect a specific value from the difference. Sets are un-ordered so the set.pop approach will always give a "random" value from the "remaining" ones.

Body:
I'm trying to create a dictionary with tuples as keys.

For example, if my range is (0, 3), I want to create a dictionary with mappings of every combination. E.g. {(0,0):1, (0,1):2, (0,2):1 ...}, where the value is an int that does not exist in the tuple.

If the range were (0, 4) the dictionary would look something like this:

{(0,1,2):3, (0,0,0):1, (0,0,1):2...}

The only rule being that the key must be a value that is not contained in the tuple and is within the given range.

Hopefully, that makes sense. I've been trying to figure out how to write code in python to do this, but I'm not sure how to go about this.

Edit Complete Example:
Range: (0, 3)

Dict Created:

{(0,0):1, (0,1):2, (0,2):1, (1,0):2, (1,1):2, (1,2): 0, (2,0): 1, (2,1):0, (2:2):1}

And yes, for some combinations e.g. (1,1) there are multiple possible values. It could be (1,1): 0 or (1,1): 2. I just need one though.

Body:
With itertools.product you could create all the keys. Then you just need to find one value that is in your range but not in the key, which could be solved using set.difference:

>>> import itertools

>>> the_range = range(0, 3)
>>> possible = set(the_range)

>>> {key: possible.difference(key).pop() for key in itertools.product(the_range, repeat=len(the_range)-1)}
{(0, 1): 2, (1, 2): 0, (0, 0): 1, (2, 0): 1, (1, 0): 2, (2, 2): 0, (0, 2): 1, (2, 1): 0, (1, 1): 0}

It should work as long as you don't expect a specific value from the difference. Sets are un-ordered so the set.pop approach will always give a "random" value from the "remaining" ones.


问:
Android - how to inflate a view with multiple EditText fields and read their values?
For my Android application, I want to have a view which allows a user to click a plus button to add EditText fields, and next to the EditText fields, I want to have minus buttons that will remove them from the view. In essence, something that is very similar to adding multiple phone numbers/email addresses in the edit Contact interface on Android.

I imagine I will need to do this by inflating my main view with a separate one that contains the EditText and button I want to add each time. However, I have no idea how I will manage identifying each EditText and button with a unique ID, and thus, I have no idea how I would manage to grab the values of each EditText for saving to my database. Can someone advise me on what I need to do? Thank you.

答:
If you have inflated a sub-layout, then you should now have a View object.

You can then call findViewById(R.id.edit_text_1) on that View — assuming that you supplied IDs in the sub-layout XML.

So long as you keep track of each of the parent Views, you can always use findViewById() on them.  Or after inflation, if you really want you can set a new, globally-unique ID on each EditText using setId().