问:
How do I remove the light grey border around my Canvas widget?
I've been messing with the Tkinter Canvas widget in order to see if I could make some aesthetically pleasing widgets, and I have a few questions.

First, why is there a light grey border around my Canvas widget, and how do I get rid of it?

Secondly, why is the top left most position in the Canvas (2,2)? It seems like it should be (0,0).

My current script:

```<code>from Tkinter import *

master = Tk()
master.configure(bg='black')
master.wm_attributes("-topmost", 1)

w = Canvas(master, width=150, height=40, bd=0,relief='ridge',)
w.pack()

color = 100
x0 = 2
y0 = 2
x1 = 151
y1 = 2

while y0 < 20 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color - 2
    y0 = y0 + 1
    y1 = y1 + 1

color = 10

while y0 < 40 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color + 4
    y0 = y0 + 1
    y1 = y1 + 1

mainloop()
</code>```

答:
Section 6.8 Why doesn't the canvas seem to start at 0,0? of the Tk Usage FAQ describes the phenomenon.

I was able to eliminate the border artefact with slight changes to the posted source...

Change this:

```<code>w = Canvas(master, width=150, height=40, bd=0, relief='ridge')
w.pack()
</code>```

to:

```<code>w = Canvas(master, width=150, height=40, bd=0, highlightthickness=0, relief='ridge')
w.pack()
</code>```

and this:

```<code>x0 = 2
y0 = 2
x1 = 151
y1 = 2
</code>```

to:

```<code>x0 = 0
y0 = 0
x1 = 150
y1 = 0
</code>```

Interestingly enough, the "borderwidth" attribute did not make a difference, but I left it in per the FAQ.

Running w.config() immediately after the Canvas initialization statement showed the defaults to be 2 for highlightthickness and 0 for border width.

Body:
I've been messing with the Tkinter Canvas widget in order to see if I could make some aesthetically pleasing widgets, and I have a few questions.

First, why is there a light grey border around my Canvas widget, and how do I get rid of it?

Secondly, why is the top left most position in the Canvas (2,2)? It seems like it should be (0,0).

My current script:

from Tkinter import *

master = Tk()
master.configure(bg='black')
master.wm_attributes("-topmost", 1)

w = Canvas(master, width=150, height=40, bd=0,relief='ridge',)
w.pack()

color = 100
x0 = 2
y0 = 2
x1 = 151
y1 = 2

while y0 < 20 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color - 2
    y0 = y0 + 1
    y1 = y1 + 1

color = 10

while y0 < 40 :
    r = color
    g = color
    b = color
    rgb = r, g, b
    Hex = '#%02x%02x%02x' % rgb
    w.create_line(x0, y0, x1, y1,fill=str(Hex), width=1)
    color = color + 4
    y0 = y0 + 1
    y1 = y1 + 1

mainloop()

Body:
Section 6.8 Why doesn't the canvas seem to start at 0,0? of the Tk Usage FAQ describes the phenomenon.

I was able to eliminate the border artefact with slight changes to the posted source...

Change this:

w = Canvas(master, width=150, height=40, bd=0, relief='ridge')
w.pack()

to:

w = Canvas(master, width=150, height=40, bd=0, highlightthickness=0, relief='ridge')
w.pack()

and this:

x0 = 2
y0 = 2
x1 = 151
y1 = 2

to:

x0 = 0
y0 = 0
x1 = 150
y1 = 0

Interestingly enough, the "borderwidth" attribute did not make a difference, but I left it in per the FAQ.

Running w.config() immediately after the Canvas initialization statement showed the defaults to be 2 for highlightthickness and 0 for border width.


来源: stackexchange

问:
Passing argument 1 of 'strcpy' makes pointer from integer without a cast
There's a few students in a class.
I need to sort the students in alphabetical order.
Teacher sorts a number, which is a student number. I need to print the student's name.  But I'm receiving the following errors:
[Note] expected 'const char * restrict' but argument is of type 'char'
[Warning] passing argument 1 of 'strcmp' makes pointer from integer without a cast
The warning repeats for argument 2 of 'strcmp' and all arguments from 'strcpy'.

Code:

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

int main() {
int N, K, k, i, j;
//students names
scanf("%d", &N);
//vector with students names
char vetor[N];
char aux[N];

//get string e load it on vetor
for(i=0; i<N; i++)
    scanf("%s", vetor[i]);

//alphabetic order
for(i=0; i<N; i++) {
    for(j=0; j<N; j++) {
        //string comparison
        if(strcmp(vetor[i], vetor[j]) < 0) {
        //string copy
        strcpy(aux[i], vetor[i]);
        strcpy(vetor[i], vetor[j]);
        strcpy(vetor[j], aux[i]);
        }
    }
}
//get sorted number
scanf("%d", &K);
K=vetor[K];
//print sorted student name
printf("%s", vetor[K]);

return 0;
}
</code>```

答:
You're using char arrays of N size, but you're trying to use a syscall that copies strings from one array to another, not single char.

As far as your code respect, you can do:

```<code>if(strcmp(vetor, vetor) < 0) {
    //string copy
    strcpy(aux, vetor);
    strcpy(vetor, vetor);
    strcpy(vetor, aux);
}
</code>```

Note that an array is like a pointer: it points at the first element of the array.

ContentLicense: CC BY-SA 3.0

Body:
There's a few students in a class.
I need to sort the students in alphabetical order.
Teacher sorts a number, which is a student number. I need to print the student's name.  But I'm receiving the following errors:
[Note] expected 'const char * restrict' but argument is of type 'char'
[Warning] passing argument 1 of 'strcmp' makes pointer from integer without a cast
The warning repeats for argument 2 of 'strcmp' and all arguments from 'strcpy'.

Code:

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

int main() {
int N, K, k, i, j;
//students names
scanf("%d", &N);
//vector with students names
char vetor[N];
char aux[N];

//get string e load it on vetor
for(i=0; i<N; i++)
    scanf("%s", vetor[i]);

//alphabetic order
for(i=0; i<N; i++) {
    for(j=0; j<N; j++) {
        //string comparison
        if(strcmp(vetor[i], vetor[j]) < 0) {
        //string copy
        strcpy(aux[i], vetor[i]);
        strcpy(vetor[i], vetor[j]);
        strcpy(vetor[j], aux[i]);
        }
    }
}
//get sorted number
scanf("%d", &K);
K=vetor[K];
//print sorted student name
printf("%s", vetor[K]);

return 0;
}

Body:
You're using char arrays of N size, but you're trying to use a syscall that copies strings from one array to another, not single char.

As far as your code respect, you can do:

if(strcmp(vetor, vetor) < 0) {
    //string copy
    strcpy(aux, vetor);
    strcpy(vetor, vetor);
    strcpy(vetor, aux);
}

Note that an array is like a pointer: it points at the first element of the array.


问:
Unicode characters not displayed in TextView.setText
I can't get a TextView to correctly dynamically display unicode characters, and it's driving me batty.  I've stripped it down to the bare minimum, but the TextView populated by setText still shows diamonds with question marks inside them for the unicode characters.  The version populated from strings.xml shows the multibyte characters perfectly.  Here's the activity:

```<code>public class TestMultibyteActivity extends Activity
{
  /** Called when the activity is first created. */
  @Override
  public void onCreate( Bundle savedInstanceState )
  {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main );
    TextView textField = (TextView) findViewById( R.id.text_field );
    String str = "Tübingen systemportefølje";
    Log.d( "MULTIBYTE", str ); //note that this prints the multibyte chars correctly.
    //EDIT: oh crap, no it doesn't.  might be onto something here...
    textField.setText( str );
  }
}
</code>```

And here's the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
  <TextView android:id="@+id/text_field"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/unicodechars"/>
</LinearLayout>
</code>```

Here's strings.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">TestMultibyteActivity</string>
  <string name="unicodechars">Tübingen systemportefølje</string>
</resources>
</code>```

I'm building with ant.  Here's my default.properties:

```<code>target=Google Inc.:Google APIs:8
</code>```

And here's my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.mycompany.android.multibyte"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:icon="@drawable/icon">
        <activity android:name="TestMultibyteActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

I've tinkered with everything I can think of, but it seems like unicode characters are getting split by the CharSequence interface, and I can't figure out why.

答:
The accepted answer is correct but Html.fromHtml is deprecated now. So you'll need to use:

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        textView.setText(Html.fromHtml(user.getInput(), Html.FROM_HTML_MODE_LEGACY));
    } else {
        textView.setText(Html.fromHtml(user.getInput()));
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I can't get a TextView to correctly dynamically display unicode characters, and it's driving me batty.  I've stripped it down to the bare minimum, but the TextView populated by setText still shows diamonds with question marks inside them for the unicode characters.  The version populated from strings.xml shows the multibyte characters perfectly.  Here's the activity:

public class TestMultibyteActivity extends Activity
{
  /** Called when the activity is first created. */
  @Override
  public void onCreate( Bundle savedInstanceState )
  {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main );
    TextView textField = (TextView) findViewById( R.id.text_field );
    String str = "Tübingen systemportefølje";
    Log.d( "MULTIBYTE", str ); //note that this prints the multibyte chars correctly.
    //EDIT: oh crap, no it doesn't.  might be onto something here...
    textField.setText( str );
  }
}

And here's the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
  <TextView android:id="@+id/text_field"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/unicodechars"/>
</LinearLayout>

Here's strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">TestMultibyteActivity</string>
  <string name="unicodechars">Tübingen systemportefølje</string>
</resources>

I'm building with ant.  Here's my default.properties:

target=Google Inc.:Google APIs:8

And here's my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.mycompany.android.multibyte"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:icon="@drawable/icon">
        <activity android:name="TestMultibyteActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

I've tinkered with everything I can think of, but it seems like unicode characters are getting split by the CharSequence interface, and I can't figure out why.

Body:
The accepted answer is correct but Html.fromHtml is deprecated now. So you'll need to use:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        textView.setText(Html.fromHtml(user.getInput(), Html.FROM_HTML_MODE_LEGACY));
    } else {
        textView.setText(Html.fromHtml(user.getInput()));
    }


问:
Why does javax MimeType not implement equals?
The javax.activation.MimeType class does not compare intuitively (to me) due to a lack of an overridden equals-method. Consider the following snippet;

```<code>MimeType a = new MimeType("image/png");
MimeType b = new MimeType("image/png");

a.equals(b);                            // false

a.toString().equals(b.toString());      // true
a.getBaseType().equals(b.getBaseType());// true
a.getSubType().equals(b.getSubType());  // true
a.getParameters().size();               // 0
b.getParameters().size();               // 0
</code>```

It seems to me that a and b are equal in every aspect and that a.equals(b) should return true.

Is there a reason that this class does not implement an equals-method?

Update: There exists a match-method which does exactly what I want, but I only found out after posting this question which kind-of confirms the not-so-intuitiveness of this class.

答:
I can only speculate as this decision is not documented, but when checking the MimeType class, there are two match methods: match(MimeType) and match(String). The second does it's job by constructing a MimeType object from the string argument and then calling the first match method.

So by implementing the match methods, it is possible to compare to MimeType and String objects. This would not be possible by implementing the equals(Object)method. Of course you could implement the equals method so that it can compare to both a MimeType and a String, but this would violate the contract that is specified by the equalsdocumentation:

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

This would only work if String.equals(Object o) would use o.toString() to do the comparison, but String doc states:

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

So you could only implement equals to compare to a different MimeType, and if you want to compare to a String, you would have to fall back to the match(String) method.

And I think the reason for not implementing equals in this class is just to keep the method you use for comparing consistent for different objects to compare to.

Body:
The javax.activation.MimeType class does not compare intuitively (to me) due to a lack of an overridden equals-method. Consider the following snippet;

MimeType a = new MimeType("image/png");
MimeType b = new MimeType("image/png");

a.equals(b);                            // false

a.toString().equals(b.toString());      // true
a.getBaseType().equals(b.getBaseType());// true
a.getSubType().equals(b.getSubType());  // true
a.getParameters().size();               // 0
b.getParameters().size();               // 0

It seems to me that a and b are equal in every aspect and that a.equals(b) should return true.

Is there a reason that this class does not implement an equals-method?

Update: There exists a match-method which does exactly what I want, but I only found out after posting this question which kind-of confirms the not-so-intuitiveness of this class.


问:
Waiting for localhost, forever!
I have a gridview on my homepage with a view and an edit link that use query strings to display table data in read-only and editable pages, respectively. I get no error messages from my code, it's simple enough that it doesn't seem to be missing anything, but when I try to debug or view in browser, I get the permanent pinwheel on my status bar and the message "waiting for localhost". What am I missing? Does anyone out there have some experience with this particular issue? I'm using C# and ASP.NET in visual studios with sql server 2008. </p>

答: I shut down iis, stopped debugging the site in visual studio, and restarted with F5 ;-)</p>

Title: Waiting for localhost, forever!


问:
Unload iFrame before jQuery UI tabs removal
I have group of jQuery Tabs that are created dynamically.  Each tab has an iFrame with it.  Here is a stripped down version of the code:

```<code>$tabs = $('#myTabs').tabs({
    tabTemplate: '<li class="myTabClass"><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-close">Remove Tab</span></li>',
    add: function (event, ui) {
      $(ui.tab.hash).append('<iframe src="BlankTabHTML.htm" id="tabFrame' + GLOBALTabIndex + '" class="tabIFrames" frameBorder="no"></iframe>');
    },
    remove: function (event, ui) {
      GLOBALTabIndex --;
    }
  });
</code>```

My problem is this: When a user clicks the 'x' to remove a tab, the tab and iFrame are removed but onbeforeunload isn't fired.

I to unload the iframe by setting the frame to a dummy page, then find out if the user clicks "ok" or "cancel" on the onbeforeunload dialog so I know if the tab should be closed.

If they click cancel I need to cancel the tab removal.  I have looked through jQuery's documentation and can't seem to find a way to cancel the tab removal once it is called.  I know this is really a couple questions in one, any ideas?

答:
Don't call tab().remove() directly by clicking on the span.

Just remove the iframe as you said(changing the src).

First onbeforeunload will fire. Later, if the user chooses "yes", onunload will fire, where you can remove the tab too.(There is no way to determine directly, what the user chooses in beforeunload, you have to observe unload, it's clear that the user chooses "yes" if onunload fires)

Body:
I have group of jQuery Tabs that are created dynamically.  Each tab has an iFrame with it.  Here is a stripped down version of the code:

$tabs = $('#myTabs').tabs({
    tabTemplate: '
#{label} Remove Tab
',
    add: function (event, ui) {
      $(ui.tab.hash).append('');
    },
    remove: function (event, ui) {
      GLOBALTabIndex --;
    }
  });

My problem is this: When a user clicks the 'x' to remove a tab, the tab and iFrame are removed but onbeforeunload isn't fired.

I to unload the iframe by setting the frame to a dummy page, then find out if the user clicks "ok" or "cancel" on the onbeforeunload dialog so I know if the tab should be closed.

If they click cancel I need to cancel the tab removal.  I have looked through jQuery's documentation and can't seem to find a way to cancel the tab removal once it is called.  I know this is really a couple questions in one, any ideas?


问:
Is there a class/template in std library to perform a task when out of scope?
We have some resource, which need to be manually released. Except explicitly writing a RAII wrapper for managing its resource, is any built-in template or class in std library to automatically perform a lambda task?

```<code>{
    auto resource = InitResource();
    GuardedTask task ([&resource]{ FreeUp(resource); }); // Simply bind a clean up lambda
    ...
    if(failed_condition_met) { return false; } // Free up
    ...
    if(another_failed_condition_met) { return false; } // Free up

} // Free up
</code>```

The class may behavior like the following, but I am wondering that wheel may be already built in std library, or I should write my own one.

```<code>struct GuardedTask
{
    std::function<void()> task;
    GuardedTask(std::function<void()> f): task(f) {}
    ~GuardedTask(){ task(); }
};
</code>```

答: This pattern is called a scope guard and has many other uses than RAII cleanup such as transaction safe functions. Unfortunately, there is no standardized scope guard but there is proposal P0052 that intended to implement this.</p>

Body:
We have some resource, which need to be manually released. Except explicitly writing a RAII wrapper for managing its resource, is any built-in template or class in std library to automatically perform a lambda task?

{
    auto resource = InitResource();
    GuardedTask task ([&resource]{ FreeUp(resource); }); // Simply bind a clean up lambda
    ...
    if(failed_condition_met) { return false; } // Free up
    ...
    if(another_failed_condition_met) { return false; } // Free up

} // Free up

The class may behavior like the following, but I am wondering that wheel may be already built in std library, or I should write my own one.

struct GuardedTask
{
    std::function<void()> task;
    GuardedTask(std::function<void()> f): task(f) {}
    ~GuardedTask(){ task(); }
};


问:
Postgresql dynamic function with current table name
I have a function (audit.create_audit_table()) that accepts an array of table names. It creates a single function audit.if_modified_func() and then loops through each table name and creates an audit table and applies a trigger to the main table. The function compiles and is created with no errors. When I run the function

```<code>select audit.create_audit_table(ARRAY['organization'])
</code>```

I keep getting the following error and I am not sure why because I thought that TG_TABLE_NAME is a automatic variable which will give me access to the current table that is executing audit.if_modified_func()

ERROR:

```<code>ERROR:  column "tg_table_name" does not exist
LINE 3:   audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
                                           ^
</code>```

Here's the function:

```<code>    CREATE OR REPLACE FUNCTION audit.create_audit_table(table_names character varying[])
RETURNS character varying AS
$BODY$
    DECLARE
    table_name varchar;
    i int;
BEGIN
    EXECUTE 'CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
    DECLARE
        audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
        include_values boolean;
        log_diffs boolean;
        h_old hstore;
        h_new hstore;
        excluded_cols text[] = ARRAY[]::text[];
    BEGIN
        IF TG_WHEN <> ''AFTER'' THEN
            RAISE EXCEPTION ''audit.if_modified_func() may only run as an AFTER trigger'';
        END IF;

        audit_row = ROW(
            nextval(''audit.'|| quote_ident(TG_TABLE_NAME::text) ||'_event_id_seq''), -- event_id
            TG_TABLE_SCHEMA::text,                        -- schema_name
            TG_TABLE_NAME::text,                          -- table_name
            TG_RELID,                                     -- relation OID for much quicker searches
            session_user::text,                           -- session_user_name
            current_timestamp,                            -- action_tstamp_tx
            statement_timestamp(),                        -- action_tstamp_stm
            clock_timestamp(),                            -- action_tstamp_clk
            txid_current(),                               -- transaction ID
            current_setting(''application_name''),          -- client application
            inet_client_addr(),                           -- client_addr
            inet_client_port(),                           -- client_port
            current_query(),                              -- top-level query or queries (if multistatement) from client
            substring(TG_OP,1,1),                         -- action
            NULL, NULL,                                   -- row_data, changed_fields
            ''f''                                           -- statement_only
            );

        IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM ''f''::boolean THEN
            audit_row.client_query = NULL;
        END IF;

        IF TG_ARGV[1] IS NOT NULL THEN
            excluded_cols = TG_ARGV[1]::text[];
        END IF;

        IF (TG_OP = ''UPDATE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
            audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
            IF audit_row.changed_fields = hstore('''') THEN
                -- All changed fields are ignored. Skip this update.
                RETURN NULL;
            END IF;
        ELSIF (TG_OP = ''DELETE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
        ELSIF (TG_OP = ''INSERT'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(NEW.*) - excluded_cols;
        ELSIF (TG_LEVEL = ''STATEMENT'' AND TG_OP IN (''INSERT'',''UPDATE'',''DELETE'',''TRUNCATE'')) THEN
            audit_row.statement_only = ''t'';
        ELSE
            RAISE EXCEPTION ''[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %%, %%'',TG_OP, TG_LEVEL;
            RETURN NULL;
        END IF;
        INSERT INTO audit.'|| quote_ident(TG_TABLE_NAME::TEXT) ||' VALUES (audit_row.*);
    RETURN null;
    END;
    $$
    LANGUAGE plpgsql;
    ALTER FUNCTION audit.if_modified_func()
    OWNER TO postgres;';

    FOR i in 1..array_upper(table_names, 1) LOOP

        EXECUTE format('
        DROP TABLE IF EXISTS audit.%1$s;
        CREATE TABLE audit.%1$s (
        event_id bigserial primary key,
        schema_name text not null,
        table_name text not null,
        relid oid not null,
        session_user_name text,
        action_tstamp_tx TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_stm TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_clk TIMESTAMP WITH TIME ZONE NOT NULL,
        transaction_id bigint,
        application_name text,
        client_addr inet,
        client_port integer,
        client_query text,
        action TEXT NOT NULL CHECK (action IN (''I'',''D'',''U'', ''T'')),
        row_data hstore,
        changed_fields hstore,
        statement_only boolean not null
        );

        REVOKE ALL ON audit.%1$s FROM public;

        COMMENT ON TABLE audit.%1$s IS ''History of auditable actions on audited tables, from audit.if_modified_func()'';
        COMMENT ON COLUMN audit.%1$s.event_id IS ''Unique identifier for each auditable event'';
        COMMENT ON COLUMN audit.%1$s.schema_name IS ''Database schema audited table for this event is in'';
        COMMENT ON COLUMN audit.%1$s.table_name IS ''Non-schema-qualified table name of table event occured in'';
        COMMENT ON COLUMN audit.%1$s.relid IS ''Table OID. Changes with drop/create. Get with ''''tablename''''::regclass'';
        COMMENT ON COLUMN audit.%1$s.session_user_name IS ''Login / session user whose statement caused the audited event'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_tx IS ''Transaction start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_stm IS ''Statement start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_clk IS ''Wall clock time at which audited event''''s trigger call occurred'';
        COMMENT ON COLUMN audit.%1$s.transaction_id IS ''Identifier of transaction that made the change. May wrap, but unique paired with action_tstamp_tx.'';
        COMMENT ON COLUMN audit.%1$s.client_addr IS ''IP address of client that issued query. Null for unix domain socket.'';
        COMMENT ON COLUMN audit.%1$s.client_port IS ''Remote peer IP port address of client that issued query. Undefined for unix socket.'';
        COMMENT ON COLUMN audit.%1$s.client_query IS ''Top-level query that caused this auditable event. May be more than one statement.'';
        COMMENT ON COLUMN audit.%1$s.application_name IS ''Application name set when this audit event occurred. Can be changed in-session by client.'';
        COMMENT ON COLUMN audit.%1$s.action IS ''Action type; I = insert, D = delete, U = update, T = truncate'';
        COMMENT ON COLUMN audit.%1$s.row_data IS ''Record value. Null for statement-level trigger. For INSERT this is the new tuple. For DELETE and UPDATE it is the old tuple.'';
        COMMENT ON COLUMN audit.%1$s.changed_fields IS ''New values of fields changed by UPDATE. Null except for row-level UPDATE events.'';
        COMMENT ON COLUMN audit.%1$s.statement_only IS ''''''t'''' if audit event is from an FOR EACH STATEMENT trigger, ''''f'''' for FOR EACH ROW'';

        CREATE INDEX %1$s_relid_idx ON audit.%1$s(relid);
        CREATE INDEX %1$s_action_tstamp_tx_stm_idx ON audit.%1$s(action_tstamp_stm);
        CREATE INDEX %1$s_action_idx ON audit.%1$s(action);
        ', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_row ON %1$s;
        CREATE TRIGGER audit_trigger_row
        AFTER INSERT OR UPDATE OR DELETE
        ON public.%1$s
        FOR EACH ROW
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_stm ON %1$s;
        CREATE TRIGGER audit_trigger_stm
        AFTER TRUNCATE
        ON public.%1$s
        FOR EACH STATEMENT
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

    END LOOP;

RETURN 'SUCCESS';
END;
$BODY$
LANGUAGE plpgsql;
ALTER FUNCTION audit.create_audit_table(character varying[])
OWNER TO postgres;
</code>```

UPDATE 03/31:

Ok, so I created the if_modified_func() function without the dynamic sql and I declared the audit_row as audit_row RECORD; I am not sure about the part of "needing a cast upon inserting the values". I am also not sure if this is the correct way to do the insert

EXECUTE format($string$INSERT INTO audit.%1$s VALUES (audit_row.*);$string$, TG_TABLE_NAME::text);

I am now getting this error when I run select audit.create_audit_table(ARRAY['organization'])

ERROR:

```<code>ERROR:  record "audit_row" has no field "row_data"
CONTEXT:  PL/pgSQL function audit.if_modified_func() line 42 at assignment
</code>```

Here's the updated function:

```<code>CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
        DECLARE
            audit_row RECORD;
            include_values boolean;
            log_diffs boolean;
            h_old hstore;
            h_new hstore;
            excluded_cols text[] = ARRAY[]::text[];
        BEGIN
            IF TG_WHEN <> 'AFTER' THEN
                RAISE EXCEPTION 'audit.if_modified_func() may only run as an AFTER trigger';
            END IF;

            audit_row = ROW(
                nextval(format('audit.%1$s_event_id_seq',TG_TABLE_NAME::text)), -- event_id
                TG_TABLE_SCHEMA::text,                        -- schema_name
                TG_TABLE_NAME::text,                          -- table_name
                TG_RELID,                                     -- relation OID for much quicker searches
                session_user::text,                           -- session_user_name
                current_timestamp,                            -- action_tstamp_tx
                statement_timestamp(),                        -- action_tstamp_stm
                clock_timestamp(),                            -- action_tstamp_clk
                txid_current(),                               -- transaction ID
                current_setting('application_name'),          -- client application
                inet_client_addr(),                           -- client_addr
                inet_client_port(),                           -- client_port
                current_query(),                              -- top-level query or queries (if multistatement) from client
                substring(TG_OP,1,1),                         -- action
                NULL, NULL,                                   -- row_data, changed_fields
                'f'                                           -- statement_only
                );

            IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN
                audit_row.client_query = NULL;
            END IF;

            IF TG_ARGV[1] IS NOT NULL THEN
                excluded_cols = TG_ARGV[1]::text[];
            END IF;

            IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
                audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
                IF audit_row.changed_fields = hstore('') THEN
                    -- All changed fields are ignored. Skip this update.
                    RETURN NULL;
                END IF;
            ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
            ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(NEW.*) - excluded_cols;
            ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
                audit_row.statement_only = 't';
            ELSE
                RAISE EXCEPTION '[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
                RETURN NULL;
            END IF;
            EXECUTE format('INSERT INTO audit.%1$s VALUES (audit_row.*)', TG_TABLE_NAME::text);

        RETURN null;
        END;
        $$
        LANGUAGE plpgsql;
        ALTER FUNCTION audit.if_modified_func()
        OWNER TO postgres;
</code>```

答:
quote_ident(TG_TABLE_NAME::TEXT) will apply necessary actions to correcty quote the argument as relation name.

I would recommend using execute format('statement') instead of concatinations, eg:

```<code>t=# do $$ begin raise info '%',format('I am %I, now is %L',current_user,now()); end;$$;
INFO:  I am postgres, now is '2017-03-30 07:33:53.579476+00'
DO
</code>```

Instead of:

```<code>t=# do $$ begin raise info '%','I am '||quote_ident(current_user)||', now is '||quote_ident(now()::text); end;$$;
INFO:  I am postgres, now is "2017-03-30 07:36:20.495887+00"
DO
</code>```

Body:
I have a function (audit.create_audit_table()) that accepts an array of table names. It creates a single function audit.if_modified_func() and then loops through each table name and creates an audit table and applies a trigger to the main table. The function compiles and is created with no errors. When I run the function

select audit.create_audit_table(ARRAY['organization'])

I keep getting the following error and I am not sure why because I thought that TG_TABLE_NAME is a automatic variable which will give me access to the current table that is executing audit.if_modified_func()

ERROR:

ERROR:  column "tg_table_name" does not exist
LINE 3:   audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
                                           ^

Here's the function:

    CREATE OR REPLACE FUNCTION audit.create_audit_table(table_names character varying[])
RETURNS character varying AS
$BODY$
    DECLARE
    table_name varchar;
    i int;
BEGIN
    EXECUTE 'CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
    DECLARE
        audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
        include_values boolean;
        log_diffs boolean;
        h_old hstore;
        h_new hstore;
        excluded_cols text[] = ARRAY[]::text[];
    BEGIN
        IF TG_WHEN <> ''AFTER'' THEN
            RAISE EXCEPTION ''audit.if_modified_func() may only run as an AFTER trigger'';
        END IF;

        audit_row = ROW(
            nextval(''audit.'|| quote_ident(TG_TABLE_NAME::text) ||'_event_id_seq''), -- event_id
            TG_TABLE_SCHEMA::text,                        -- schema_name
            TG_TABLE_NAME::text,                          -- table_name
            TG_RELID,                                     -- relation OID for much quicker searches
            session_user::text,                           -- session_user_name
            current_timestamp,                            -- action_tstamp_tx
            statement_timestamp(),                        -- action_tstamp_stm
            clock_timestamp(),                            -- action_tstamp_clk
            txid_current(),                               -- transaction ID
            current_setting(''application_name''),          -- client application
            inet_client_addr(),                           -- client_addr
            inet_client_port(),                           -- client_port
            current_query(),                              -- top-level query or queries (if multistatement) from client
            substring(TG_OP,1,1),                         -- action
            NULL, NULL,                                   -- row_data, changed_fields
            ''f''                                           -- statement_only
            );

        IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM ''f''::boolean THEN
            audit_row.client_query = NULL;
        END IF;

        IF TG_ARGV[1] IS NOT NULL THEN
            excluded_cols = TG_ARGV[1]::text[];
        END IF;

        IF (TG_OP = ''UPDATE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
            audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
            IF audit_row.changed_fields = hstore('''') THEN
                -- All changed fields are ignored. Skip this update.
                RETURN NULL;
            END IF;
        ELSIF (TG_OP = ''DELETE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
        ELSIF (TG_OP = ''INSERT'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(NEW.*) - excluded_cols;
        ELSIF (TG_LEVEL = ''STATEMENT'' AND TG_OP IN (''INSERT'',''UPDATE'',''DELETE'',''TRUNCATE'')) THEN
            audit_row.statement_only = ''t'';
        ELSE
            RAISE EXCEPTION ''[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %%, %%'',TG_OP, TG_LEVEL;
            RETURN NULL;
        END IF;
        INSERT INTO audit.'|| quote_ident(TG_TABLE_NAME::TEXT) ||' VALUES (audit_row.*);
    RETURN null;
    END;
    $$
    LANGUAGE plpgsql;
    ALTER FUNCTION audit.if_modified_func()
    OWNER TO postgres;';

    FOR i in 1..array_upper(table_names, 1) LOOP

        EXECUTE format('
        DROP TABLE IF EXISTS audit.%1$s;
        CREATE TABLE audit.%1$s (
        event_id bigserial primary key,
        schema_name text not null,
        table_name text not null,
        relid oid not null,
        session_user_name text,
        action_tstamp_tx TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_stm TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_clk TIMESTAMP WITH TIME ZONE NOT NULL,
        transaction_id bigint,
        application_name text,
        client_addr inet,
        client_port integer,
        client_query text,
        action TEXT NOT NULL CHECK (action IN (''I'',''D'',''U'', ''T'')),
        row_data hstore,
        changed_fields hstore,
        statement_only boolean not null
        );

        REVOKE ALL ON audit.%1$s FROM public;

        COMMENT ON TABLE audit.%1$s IS ''History of auditable actions on audited tables, from audit.if_modified_func()'';
        COMMENT ON COLUMN audit.%1$s.event_id IS ''Unique identifier for each auditable event'';
        COMMENT ON COLUMN audit.%1$s.schema_name IS ''Database schema audited table for this event is in'';
        COMMENT ON COLUMN audit.%1$s.table_name IS ''Non-schema-qualified table name of table event occured in'';
        COMMENT ON COLUMN audit.%1$s.relid IS ''Table OID. Changes with drop/create. Get with ''''tablename''''::regclass'';
        COMMENT ON COLUMN audit.%1$s.session_user_name IS ''Login / session user whose statement caused the audited event'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_tx IS ''Transaction start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_stm IS ''Statement start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_clk IS ''Wall clock time at which audited event''''s trigger call occurred'';
        COMMENT ON COLUMN audit.%1$s.transaction_id IS ''Identifier of transaction that made the change. May wrap, but unique paired with action_tstamp_tx.'';
        COMMENT ON COLUMN audit.%1$s.client_addr IS ''IP address of client that issued query. Null for unix domain socket.'';
        COMMENT ON COLUMN audit.%1$s.client_port IS ''Remote peer IP port address of client that issued query. Undefined for unix socket.'';
        COMMENT ON COLUMN audit.%1$s.client_query IS ''Top-level query that caused this auditable event. May be more than one statement.'';
        COMMENT ON COLUMN audit.%1$s.application_name IS ''Application name set when this audit event occurred. Can be changed in-session by client.'';
        COMMENT ON COLUMN audit.%1$s.action IS ''Action type; I = insert, D = delete, U = update, T = truncate'';
        COMMENT ON COLUMN audit.%1$s.row_data IS ''Record value. Null for statement-level trigger. For INSERT this is the new tuple. For DELETE and UPDATE it is the old tuple.'';
        COMMENT ON COLUMN audit.%1$s.changed_fields IS ''New values of fields changed by UPDATE. Null except for row-level UPDATE events.'';
        COMMENT ON COLUMN audit.%1$s.statement_only IS ''''''t'''' if audit event is from an FOR EACH STATEMENT trigger, ''''f'''' for FOR EACH ROW'';

        CREATE INDEX %1$s_relid_idx ON audit.%1$s(relid);
        CREATE INDEX %1$s_action_tstamp_tx_stm_idx ON audit.%1$s(action_tstamp_stm);
        CREATE INDEX %1$s_action_idx ON audit.%1$s(action);
        ', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_row ON %1$s;
        CREATE TRIGGER audit_trigger_row
        AFTER INSERT OR UPDATE OR DELETE
        ON public.%1$s
        FOR EACH ROW
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_stm ON %1$s;
        CREATE TRIGGER audit_trigger_stm
        AFTER TRUNCATE
        ON public.%1$s
        FOR EACH STATEMENT
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

    END LOOP;

RETURN 'SUCCESS';
END;
$BODY$
LANGUAGE plpgsql;
ALTER FUNCTION audit.create_audit_table(character varying[])
OWNER TO postgres;

UPDATE 03/31:

Ok, so I created the if_modified_func() function without the dynamic sql and I declared the audit_row as audit_row RECORD; I am not sure about the part of "needing a cast upon inserting the values". I am also not sure if this is the correct way to do the insert

EXECUTE format($string$INSERT INTO audit.%1$s VALUES (audit_row.*);$string$, TG_TABLE_NAME::text);

I am now getting this error when I run select audit.create_audit_table(ARRAY['organization'])

ERROR:

ERROR:  record "audit_row" has no field "row_data"
CONTEXT:  PL/pgSQL function audit.if_modified_func() line 42 at assignment

Here's the updated function:

CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
        DECLARE
            audit_row RECORD;
            include_values boolean;
            log_diffs boolean;
            h_old hstore;
            h_new hstore;
            excluded_cols text[] = ARRAY[]::text[];
        BEGIN
            IF TG_WHEN <> 'AFTER' THEN
                RAISE EXCEPTION 'audit.if_modified_func() may only run as an AFTER trigger';
            END IF;

            audit_row = ROW(
                nextval(format('audit.%1$s_event_id_seq',TG_TABLE_NAME::text)), -- event_id
                TG_TABLE_SCHEMA::text,                        -- schema_name
                TG_TABLE_NAME::text,                          -- table_name
                TG_RELID,                                     -- relation OID for much quicker searches
                session_user::text,                           -- session_user_name
                current_timestamp,                            -- action_tstamp_tx
                statement_timestamp(),                        -- action_tstamp_stm
                clock_timestamp(),                            -- action_tstamp_clk
                txid_current(),                               -- transaction ID
                current_setting('application_name'),          -- client application
                inet_client_addr(),                           -- client_addr
                inet_client_port(),                           -- client_port
                current_query(),                              -- top-level query or queries (if multistatement) from client
                substring(TG_OP,1,1),                         -- action
                NULL, NULL,                                   -- row_data, changed_fields
                'f'                                           -- statement_only
                );

            IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN
                audit_row.client_query = NULL;
            END IF;

            IF TG_ARGV[1] IS NOT NULL THEN
                excluded_cols = TG_ARGV[1]::text[];
            END IF;

            IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
                audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
                IF audit_row.changed_fields = hstore('') THEN
                    -- All changed fields are ignored. Skip this update.
                    RETURN NULL;
                END IF;
            ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
            ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(NEW.*) - excluded_cols;
            ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
                audit_row.statement_only = 't';
            ELSE
                RAISE EXCEPTION '[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
                RETURN NULL;
            END IF;
            EXECUTE format('INSERT INTO audit.%1$s VALUES (audit_row.*)', TG_TABLE_NAME::text);

        RETURN null;
        END;
        $$
        LANGUAGE plpgsql;
        ALTER FUNCTION audit.if_modified_func()
        OWNER TO postgres;

Body:
quote_ident(TG_TABLE_NAME::TEXT) will apply necessary actions to correcty quote the argument as relation name.

I would recommend using execute format('statement') instead of concatinations, eg:

t=# do $$ begin raise info '%',format('I am %I, now is %L',current_user,now()); end;$$;
INFO:  I am postgres, now is '2017-03-30 07:33:53.579476+00'
DO

Instead of:

t=# do $$ begin raise info '%','I am '||quote_ident(current_user)||', now is '||quote_ident(now()::text); end;$$;
INFO:  I am postgres, now is "2017-03-30 07:36:20.495887+00"
DO


问:
Print characters as a Matrix
Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.

```<code>list: a b c d e f g
colums: 3

Wrong:
a b c
d e f
g

Wrong:
a d g
b e
c f

Correct:
a d f
b e g
c
</code>```

I have tried below:

```<code>public static void printPatern(List<Character> list, int cols) {

    for (int i = 0; i < cols; i++) {

        for (int j = i; j < list.size(); j += cols) {
            System.out.print(list.get(j));

        }
        System.out.println();
    }
}
</code>```

It gives output as (which is wrong):

```<code>a d g
b e
c f
</code>```

I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.

FYI: This is not a HOMEWORK problem.

答:
Finally able to design the algorithm for this problem
Please refer below java code same</p>

```<code> public class puzzle{
        public static void main(String[] args){

            String list[] = { "a", "b", "c","d","e","f","g","h","i","j" };
            int column = 3;

            int rows = list.length/column; //Calculate total full rows
            int lastRowElement = list.length%column;//identify number of elements in last row
            if(lastRowElement >0){
                rows++;//add inclomplete row to total number of full filled rows
            }
            //Iterate over rows
             for (int i = 0; i < rows; i++) {
                int j=i;
                int columnIndex = 1;
                while(j < list.length && columnIndex <=column ){
                    System.out.print("\t"+list[j]);
                    if(columnIndex<=lastRowElement){
                        if(i==rows-1 && columnIndex==lastRowElement){
                            j=list.length; //for last row display nothing after column index reaches to number of elements in last row
                        }else{
                            j += rows; //for other rows if columnIndex is less than or equal to number of elements in last row then add j value by number of rows
                        }

                    }else {
                       if(lastRowElement==0){
                          j += rows;
                       }else{
                        j += rows-1; //for column greater than number of element in last row add j = row-1 as last row will not having the column for this column index.
                       }
                    }

                    columnIndex++;//Increase column Index by 1;
                }

                System.out.println();
                }
        }
    }
</code>```

Title: Print characters as a Matrix

Body:
Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.

list: a b c d e f g
colums: 3

Wrong:
a b c
d e f
g

Wrong:
a d g
b e
c f

Correct:
a d f
b e g
c

I have tried below:

public static void printPatern(List<Character> list, int cols) {

    for (int i = 0; i < cols; i++) {

        for (int j = i; j < list.size(); j += cols) {
            System.out.print(list.get(j));

        }
        System.out.println();
    }
}

It gives output as (which is wrong):

a d g
b e
c f

I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.

FYI: This is not a HOMEWORK problem.

Body:
Finally able to design the algorithm for this problem
Please refer below java code same

 public class puzzle{
        public static void main(String[] args){

            String list[] = { "a", "b", "c","d","e","f","g","h","i","j" };
            int column = 3;

            int rows = list.length/column; //Calculate total full rows
            int lastRowElement = list.length%column;//identify number of elements in last row
            if(lastRowElement >0){
                rows++;//add inclomplete row to total number of full filled rows
            }
            //Iterate over rows
             for (int i = 0; i < rows; i++) {
                int j=i;
                int columnIndex = 1;
                while(j < list.length && columnIndex <=column ){
                    System.out.print("\t"+list[j]);
                    if(columnIndex<=lastRowElement){
                        if(i==rows-1 && columnIndex==lastRowElement){
                            j=list.length; //for last row display nothing after column index reaches to number of elements in last row
                        }else{
                            j += rows; //for other rows if columnIndex is less than or equal to number of elements in last row then add j value by number of rows
                        }

                    }else {
                       if(lastRowElement==0){
                          j += rows;
                       }else{
                        j += rows-1; //for column greater than number of element in last row add j = row-1 as last row will not having the column for this column index.
                       }
                    }

                    columnIndex++;//Increase column Index by 1;
                }

                System.out.println();
                }
        }
    }


答:
You could use a custom deleter on std::unique_ptr.

Cf this question.

Title: Is there a class/template in std library to perform a task when out of scope?


问:
React / Redux conditionally applying style
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

```<code><div
    className="notify-success"
    style={{  ({this.props.terms}) ? "" : "display: 'none'" }}
>
    Saved successfully!
</div>
</code>```

But its not working for me, instead throwing an error!

答:
Just do not render the
 if it is not needed:

```<code>render() {
    return { this.props.terms ?
             <div className="notify-success">
               Saved successfully!
             </div> : null
           }
}
</code>```

Body:
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

    Saved successfully!

But its not working for me, instead throwing an error!

Body:
Just do not render the <div> if it is not needed:

render() {
    return { this.props.terms ?
             <div className="notify-success">
               Saved successfully!
             </div> : null
           }
}


问:
"Array keys must be CURLOPT constants or equivalent integer values" using curl_setopt_array() in PHP 7
I'm building a scrape script to extract some information from a website, and while testing it out I keep getting the following error:

PHP Warning:  curl_setopt_array(): Array keys must be CURLOPT
  constants or equivalent integer values

It points to the following line in my code:

```<code>curl_setopt_array($ch, $curlOptions);
</code>```

Now $ch is derived from:

```<code>$ch = curl_init($url);
</code>```

and $url is set like this (the URL is deliberate as I'm working on handling errors generated by trying to open the website if it doesn't exist):

```<code>$url = "https://www.kjsdsajlksajksajdklsadajklda.com";
</code>```

$curlOptions  is set here:

```<code>    $curlOptions = array(
        'CURLOPT_RETURNTRANSFER' => true,
        'CURLOPT_HEADER'         => true,
        'CURLOPT_FOLLOWLOCATION' => true,
        'CURLOPT_ENCODING'       => "",
        'CURLOPT_AUTOREFERER'    => true,
        'CURLOPT_CONNECTTIMEOUT' => 120,
        'CURLOPT_TIMEOUT'        => 120,
        'CURLOPT_MAXREDIRS'      => 10,
        'CURLINFO_HEADER_OUT'    => true,
        'CURLOPT_SSL_VERIFYPEER' => false,
        'CURLOPT_HTTP_VERSION'   => 'CURL_HTTP_VERSION_1_1',
        'CURLOPT_COOKIE'         => $cookiesJar,
        'CURLOPT_USERAGENT'      => $userAgent,
    );
</code>```

I've removed the $curlOptions block while testing, and when it's removed I don't get the error. However, commenting out the different elements of the array doesn't resolve the issue and the error persists. I've changed the URL I use as well and it doesn't make a difference. I have also changed any instance of true or false to 1 and 0 respectively and this hasn't made a difference either.

So I'm a bit stuck really. I'm developing this on a Debian 8 system that uses PHP 7, the version output is here:

```<code>PHP 7.0.16-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.16-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend Technologies
</code>```

What exactly is going on? Is there a compatibility issue with the code I've written (which should work with PHP 5) with PHP 7 or is there something more obvious or simple?

答:
You use strings('CURLOPT_RETURNTRANSFER') instead of constants (CURLOPT_RETURNTRANSFER)

```<code>var_dump(CURLOPT_RETURNTRANSFER, 'CURLOPT_RETURNTRANSFER');
// output
int 19913
string 'CURLOPT_RETURNTRANSFER'
</code>```

Body:
I'm building a scrape script to extract some information from a website, and while testing it out I keep getting the following error:

PHP Warning:  curl_setopt_array(): Array keys must be CURLOPT
  constants or equivalent integer values

It points to the following line in my code:

curl_setopt_array($ch, $curlOptions);

Now $ch is derived from:

$ch = curl_init($url);

and $url is set like this (the URL is deliberate as I'm working on handling errors generated by trying to open the website if it doesn't exist):

$url = "https://www.kjsdsajlksajksajdklsadajklda.com";

$curlOptions  is set here:

    $curlOptions = array(
        'CURLOPT_RETURNTRANSFER' => true,
        'CURLOPT_HEADER'         => true,
        'CURLOPT_FOLLOWLOCATION' => true,
        'CURLOPT_ENCODING'       => "",
        'CURLOPT_AUTOREFERER'    => true,
        'CURLOPT_CONNECTTIMEOUT' => 120,
        'CURLOPT_TIMEOUT'        => 120,
        'CURLOPT_MAXREDIRS'      => 10,
        'CURLINFO_HEADER_OUT'    => true,
        'CURLOPT_SSL_VERIFYPEER' => false,
        'CURLOPT_HTTP_VERSION'   => 'CURL_HTTP_VERSION_1_1',
        'CURLOPT_COOKIE'         => $cookiesJar,
        'CURLOPT_USERAGENT'      => $userAgent,
    );

I've removed the $curlOptions block while testing, and when it's removed I don't get the error. However, commenting out the different elements of the array doesn't resolve the issue and the error persists. I've changed the URL I use as well and it doesn't make a difference. I have also changed any instance of true or false to 1 and 0 respectively and this hasn't made a difference either.

So I'm a bit stuck really. I'm developing this on a Debian 8 system that uses PHP 7, the version output is here:

PHP 7.0.16-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.16-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend Technologies

What exactly is going on? Is there a compatibility issue with the code I've written (which should work with PHP 5) with PHP 7 or is there something more obvious or simple?

Body:
You use strings('CURLOPT_RETURNTRANSFER') instead of constants (CURLOPT_RETURNTRANSFER)

var_dump(CURLOPT_RETURNTRANSFER, 'CURLOPT_RETURNTRANSFER');
// output
int 19913
string 'CURLOPT_RETURNTRANSFER'


问:
Ruby-on-Rails: How to get rid of "you are being redirected" page
I am overriding Devise's failure response so that I can set a 401 status code. However, when the user fails to sign in, they are redirected to a page with a "you are being redirected" link. If I remove this :status => 401 from the redirect it works fine.

```<code>class CustomFailure < Devise::FailureApp
    def redirect_url
      new_user_session_url(:subdomain => 'secure')
    end

    def respond
        if http_auth?
           http_auth
        else
           store_location!
           flash[:alert] = i18n_message unless flash[:notice]
           redirect_to redirect_url, :status => 401
        end
    end
end
</code>```

edit

Alternatively I would like to display the flash message and remain on the same page but adding this line of code:

```<code>render :text => "unauthorized", :status => 401
</code>```

causes ruby to complain:

```<code>undefined method `render' for #<CustomFailure:0x00000103367f28>
</code>```

What's happening here?

答: Proper HTTP statuses for a redirection are in the 30x form (301 and 302 being the most frequently used).  By default, the redirect_to helper sets a 302 status header on the HTTP response.  If you override that and set that to a 401, your web browser will assume that the response is a regular web page and will render the response body --which, in a redirection, is the boilerplate text "You are being redirected".</p>

Body:
I am overriding Devise's failure response so that I can set a 401 status code. However, when the user fails to sign in, they are redirected to a page with a "you are being redirected" link. If I remove this :status => 401 from the redirect it works fine.

class CustomFailure < Devise::FailureApp
    def redirect_url
      new_user_session_url(:subdomain => 'secure')
    end

    def respond
        if http_auth?
           http_auth
        else
           store_location!
           flash[:alert] = i18n_message unless flash[:notice]
           redirect_to redirect_url, :status => 401
        end
    end
end

edit

Alternatively I would like to display the flash message and remain on the same page but adding this line of code:

render :text => "unauthorized", :status => 401

causes ruby to complain:

undefined method `render' for #<CustomFailure:0x00000103367f28>

What's happening here?


问:
should I use fragment or viewpager for my app
Demo1
Demo2

when users click the button to answer the questions for the TextView on the top, the TextView will change the questions depends on the user's answer.
(I think this part won't be hard for me)

But what should I do after user click the button, the buttons will change as well, please see the demo picture.

are there any skills I should study first? like framelayout?

Thank you for your answers.

答:
It really depends on specific needs, but generally speaking, google guidelines are toward the use of fragments.

I'm developing Android apps since just few months and I'm using the single activity/multiple fragments approach. You have to learn how to use fragments, e.g. their lifecycle compared to the attached activity or how to handle events among fragments (EventBus can help you for such task).

You can find more discussions about this approach here

Cheers.


问:
Submit form with selected concert seats with JavaScript and HTML
I have a form with input field

```<code><select name="tickets" multiple>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  ...
</select>
</code>```

With this select, I can choose which ticket ids I want to submit with the form.

But now I want to create a seat selector, so I need all the tickets as div elements. The seats will look something like

```<code><div class="seats">
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
  <div class="seat">Seat Number</div>
</div>
</code>```

How can I make these div elements selectable? I know that I with simple javascript can listen for clicks and then change the class of the div element.

So a solution could be

```<code>$('.seat').click(function () {
  $(this).toggleClass('.selected-seat');
});
</code>```

and then something like

```<code>$('form').submit(function () {
  event.preventDefault();

  // submit array of ids of all those div elements with class 'selected-seat'
});
</code>```

However, this approach seems a bit wrong to me. Could another solution be to make the elements into something like

```<code><div class="seats">
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
  <div class="seat">Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__"></div>
</div>
</code>```

and then submit my form exactly as I normally submit a form without any javascript?

How are these seat selectors normally done?

答:
u can submit the form  as usually. the form will auto detect checked checkbox has been select. hope this help.

$('.seat').click(function () {
 if($(this).attr("class") == "seat"){
    $(this).addClass('selected-seat');
    $(this).children().attr('checked', "checked");
   }
   else{
    $(this).removeClass('selected-seat');
    $(this).children().prop('checked', true);;
   }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .selected-seat{
  background : #f00;
 }
 input[type="checkbox"]{
  display: none;
 }</code>```

<form method="post" action="http://localhost/yourProject/SubmitProsesHere.php">

Seat Number 1
   <input type="checkbox" name="seats[]" value="__ticket_id__5">

Seat Number 2
   <input type="checkbox" name="seats[]" value="__ticket_id__4">

Seat Number 3
   <input type="checkbox" name="seats[]" value="__ticket_id__3">

Seat Number 4
   <input type="checkbox" name="seats[]" value="__ticket_id__2">

<input type="submit" value='send' name="test">
</form>```

sleect seat 1,2 and 3

result print_r $_POST

Body:
I have a form with input field

<select name="tickets" multiple>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  <option value="__ticket_id__">Ticket #</option>
  ...
</select>

With this select, I can choose which ticket ids I want to submit with the form.

But now I want to create a seat selector, so I need all the tickets as div elements. The seats will look something like

Seat Number

Seat Number

Seat Number

Seat Number

Seat Number

How can I make these div elements selectable? I know that I with simple javascript can listen for clicks and then change the class of the div element.

So a solution could be

$('.seat').click(function () {
  $(this).toggleClass('.selected-seat');
});

and then something like

$('form').submit(function () {
  event.preventDefault();

  // submit array of ids of all those div elements with class 'selected-seat'
});

However, this approach seems a bit wrong to me. Could another solution be to make the elements into something like

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

Seat Number <input type="checkbox" name="seats[]" value="__ticket_id__">

and then submit my form exactly as I normally submit a form without any javascript?

How are these seat selectors normally done?

Body:
u can submit the form  as usually. the form will auto detect checked checkbox has been select. hope this help.

$('.seat').click(function () {
 if($(this).attr("class") == "seat"){
    $(this).addClass('selected-seat');
    $(this).children().attr('checked', "checked");
   }
   else{
    $(this).removeClass('selected-seat');
    $(this).children().prop('checked', true);;
   }
});

 .selected-seat{
  background : #f00;
 }
 input[type="checkbox"]{
  display: none;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form method="post" action="http://localhost/yourProject/SubmitProsesHere.php">
<div class="seats">
  <div class="seat">Seat Number 1
   <input type="checkbox" name="seats[]" value="__ticket_id__5">
  </div>
  <div class="seat">Seat Number 2
   <input type="checkbox" name="seats[]" value="__ticket_id__4">
  </div>
  <div class="seat">Seat Number 3
   <input type="checkbox" name="seats[]" value="__ticket_id__3">
  </div>
  <div class="seat">Seat Number 4
   <input type="checkbox" name="seats[]" value="__ticket_id__2">
  </div>
</div>
<input type="submit" value='send' name="test">
</form>

sleect seat 1,2 and 3

result print_r $_POST


问:
Does Static Methods give bad results if two threads having own objects accessing same?
Does Static non synchronized Methods give bad results if two threads accessing same?

```<code>public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}
</code>```

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?

答:
Since MySubjectUtils.createMyResponseClass(record) method creates a new instance of MyResponseClass(), each call to this method will create a new object. So each thread will receive its own object.

If your both threads are passing the same record object, actual contents of their MyResponseClass instances will be the same.

If threads are passing different instances of record object, their MyResponseClass instances will have different contents.

Body:
Does Static non synchronized Methods give bad results if two threads accessing same?

public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?


问:
Filename ending with period and using FileInfo C#
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

```<code>echo "test" > "\\?\C:\Test\BadFileName."
</code>```

and this is the code I was using to test the file:

```<code>DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}
</code>```

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

答:
Here's a way to do file ops via the commandline. Not the most elegant solution, but hopefully a useful reference.</p>

```<code>using System;
using System.IO;
using System.Diagnostics;

namespace StackOverflow_FileNameShenanigans
{
    class Program
    {
        static void Main(string[] args)
        {
            string contents;

            DateTime origAccessDate;
            DateTime origCreateDate;
            long sizeBytes;

            string path = @"\\?\C:\Test\BadFileName.";

            try
            {
                contents = CommandLineFileOps.ReadAllText(path);
                origAccessDate = CommandLineFileOps.LastAccessTime(path);
                origCreateDate = CommandLineFileOps.CreationTime(path);
                sizeBytes = CommandLineFileOps.Length(path);

                Console.WriteLine($"Contents: {contents}");
                Console.WriteLine($"OrigAccessDate: {origAccessDate}");
                Console.WriteLine($"OrigCreateDate: {origCreateDate}");
                Console.WriteLine($"SizeBytes: {sizeBytes}");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

    }

    public static class CommandLineFileOps
    {
        public static string ReadAllText(string path)
        {
            string contents;
            RunOnCommandLine($"type {path}", out contents);

            contents = contents.Substring(0, contents.Length - 3);
            return contents;
        }

        public static DateTime CreationTime(string path)
        {
            string output;
            RunOnCommandLine($"dir /T:C {path}", out output);

            string dateLine = output.Split('\n')[5];
            string dateStr = dateLine.Replace("                 ", "\n").Split('\n')[0];
            return DateTime.Parse(dateStr);
        }

        public static DateTime LastAccessTime(string path)
        {
            string output;
            RunOnCommandLine($"dir /T:A {path}", out output);

            string dateLine = output.Split('\n')[5];
            string dateStr = dateLine.Replace("                 ", "\n").Split('\n')[0];
            return DateTime.Parse(dateStr);
        }

        public static long Length(string path)
        {
            string output;
            RunOnCommandLine($"dir {path}", out output);

            string lengthLine = output.Split('\n')[6];
            string lengthStr = lengthLine.Replace("              ", "\n").Split('\n')[2].Split(' ')[0];
            return long.Parse(lengthStr);
        }

        private static int RunOnCommandLine(string line)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();

            cmd.StandardInput.WriteLine(line);
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();

            int exitCode = cmd.ExitCode;
            return exitCode;
        }

        private static int RunOnCommandLine(string line, out string output)
        {
            string tempPath = Path.GetTempFileName();
            int exitCode = RunOnCommandLine($"{line} > {tempPath}");
            output = File.ReadAllText(tempPath);
            File.Delete(tempPath);

            return exitCode;
        }
    }
}
</code>```

Body:
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

echo "test" > "\\?\C:\Test\BadFileName."

and this is the code I was using to test the file:

DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

Body:
Here's a way to do file ops via the commandline. Not the most elegant solution, but hopefully a useful reference.

using System;
using System.IO;
using System.Diagnostics;

namespace StackOverflow_FileNameShenanigans
{
    class Program
    {
        static void Main(string[] args)
        {
            string contents;

            DateTime origAccessDate;
            DateTime origCreateDate;
            long sizeBytes;

            string path = @"\\?\C:\Test\BadFileName.";

            try
            {
                contents = CommandLineFileOps.ReadAllText(path);
                origAccessDate = CommandLineFileOps.LastAccessTime(path);
                origCreateDate = CommandLineFileOps.CreationTime(path);
                sizeBytes = CommandLineFileOps.Length(path);

                Console.WriteLine($"Contents: {contents}");
                Console.WriteLine($"OrigAccessDate: {origAccessDate}");
                Console.WriteLine($"OrigCreateDate: {origCreateDate}");
                Console.WriteLine($"SizeBytes: {sizeBytes}");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

    }

    public static class CommandLineFileOps
    {
        public static string ReadAllText(string path)
        {
            string contents;
            RunOnCommandLine($"type {path}", out contents);

            contents = contents.Substring(0, contents.Length - 3);
            return contents;
        }

        public static DateTime CreationTime(string path)
        {
            string output;
            RunOnCommandLine($"dir /T:C {path}", out output);

            string dateLine = output.Split('\n')[5];
            string dateStr = dateLine.Replace("                 ", "\n").Split('\n')[0];
            return DateTime.Parse(dateStr);
        }

        public static DateTime LastAccessTime(string path)
        {
            string output;
            RunOnCommandLine($"dir /T:A {path}", out output);

            string dateLine = output.Split('\n')[5];
            string dateStr = dateLine.Replace("                 ", "\n").Split('\n')[0];
            return DateTime.Parse(dateStr);
        }

        public static long Length(string path)
        {
            string output;
            RunOnCommandLine($"dir {path}", out output);

            string lengthLine = output.Split('\n')[6];
            string lengthStr = lengthLine.Replace("              ", "\n").Split('\n')[2].Split(' ')[0];
            return long.Parse(lengthStr);
        }

        private static int RunOnCommandLine(string line)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();

            cmd.StandardInput.WriteLine(line);
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();

            int exitCode = cmd.ExitCode;
            return exitCode;
        }

        private static int RunOnCommandLine(string line, out string output)
        {
            string tempPath = Path.GetTempFileName();
            int exitCode = RunOnCommandLine($"{line} > {tempPath}");
            output = File.ReadAllText(tempPath);
            File.Delete(tempPath);

            return exitCode;
        }
    }
}


问:
kubectl error: "You must be logged in to the server (the server has asked for the client to provide credentials)"
I'm running the following command and getting an error:

```<code>$ kubectl get nodes
error: You must be logged in to the server (the server has asked for the client to provide credentials)
</code>```

What's going on?

答:
You have to run:

```<code>$ gcloud container clusters get-credentials [cluster-name]
</code>```

Docs here.

Body:
I'm running the following command and getting an error:

$ kubectl get nodes
error: You must be logged in to the server (the server has asked for the client to provide credentials)

What's going on?

Body:
You have to run:

$ gcloud container clusters get-credentials [cluster-name]

Docs here.


问:
How to use message driven beans between two clients
I am new to EJB and JavaEE in general and I am currently working on a little project that basically implements a game where two players PlayerA and PlayerB can play via web browser.

I currently have a set up for several JSP pages like this:
login -> playerprofile -> acceptGame -> playGame -> outcome

There are two login pages for player A and B they link to same playerprofile page that shows the username and score for the chosen player, info is stored in the database. In that profile page players can click on link that sends them to acceptGame page where player has to click on accept button and if both players have accepted they can proceed to playGame. It makes sense in this scenario to use message beans since one player may have accepted whilst another has not, so the player who has accepted should wait for the other player to accept.

Unfortunately, every tutorial for message beans I have come across online just passes some TextMessage object and it gets printed on the server, but there is no example to scenarios similar to this.

答:
Message-driven beans are used to process asynchronous calls, when you as a caller don't want to wait for the result of the processing. In your case, I think using a message-driven bean is not optimal.

You can implement your logic with it too: playerA accept the game offer, the server sends a message to a MDB, playerA proceeds to a waiting state, the MDB stores that playerA accepted the game offer, playerB also accepts the game offer, etc., and when they're both in the waiting state and they both determine that the other has the acceptance stored, they proceed to playGame.

This seems overly complicated to me, the message-driven bean doesn't improve this process in any way. I think the same results could be accomplished with a stateful bean more comfortably, because the MDB can only eliminate wait-times from the technical point of view (eg. I want send out an e-mail, but I don't care when it is actually sent as long as it is sent), but not from the business point of view. If your business logic requires you to wait, then you'll have to wait.


问:
Transfer data from U-SQL managed table to Azure SQL Database table
I have a U-SQL managed table that contains schematized structured data.

```<code>CREATE TABLE [AdlaDb].[dbo].[User]
(
    UserGuid Guid,
    Postcode string,
    Age int?
    DateOfBirth DateTime?,
)
</code>```

And a Azure SQL Database table.

```<code>CREATE TABLE [SqlDb].[dbo].[User]
(
    UserGuid    uniqueidentifier NOT NULL,
    Postcode    varchar(15) NULL,
    Age         int NULL,
    DateOfBirth Date NULL,
)
</code>```

I would like to transfer data from U-SQL managed table to Azure SQLDB table without losing the data types.

I'm using azure data factory, seems like I cannot

directly query the U-SQL managed table as an input dataset for data factory

do a federated write query to Azure SQLDB

Hence I'm having an intermediate step where I copy from U-SQL managed table to Azure Blob and then move to Azure SQLDB table. Doing this, I'm losing the data type and having to have type conversion/transformations later again before inserting.

Is there any better way to transfer data from U-SQL managed table to Azure SQL Database table without losing data type? Or am I missing something?

答:
There is now another option to transfer data from USQL managed table to Azure SQL Database table.

Write out the data from USQL Managed table or from a USQL script to Azure Blob Storage as a text file (.csv, .txt etc..)

And then make use of the public preview feature in Azure SQL Database - BULK INSERT - wrap this into a stored procedure

Add an Stored procedure activity in Azure Data Factory to schedule

Note: There is one thing to be aware of when creating DATABASE SCOPED CREDENTIAL, refer this Stack Overflow question

Body:
I have a U-SQL managed table that contains schematized structured data.

CREATE TABLE [AdlaDb].[dbo].[User]
(
    UserGuid Guid,
    Postcode string,
    Age int?
    DateOfBirth DateTime?,
)

And a Azure SQL Database table.

CREATE TABLE [SqlDb].[dbo].[User]
(
    UserGuid    uniqueidentifier NOT NULL,
    Postcode    varchar(15) NULL,
    Age         int NULL,
    DateOfBirth Date NULL,
)

I would like to transfer data from U-SQL managed table to Azure SQLDB table without losing the data types.

I'm using azure data factory, seems like I cannot

directly query the U-SQL managed table as an input dataset for data factory

do a federated write query to Azure SQLDB

Hence I'm having an intermediate step where I copy from U-SQL managed table to Azure Blob and then move to Azure SQLDB table. Doing this, I'm losing the data type and having to have type conversion/transformations later again before inserting.

Is there any better way to transfer data from U-SQL managed table to Azure SQL Database table without losing data type? Or am I missing something?


问:
Firebase handleIntent AbstractMethodError
When I receive a push notification on Android, I get the below error. I can't really seem to find any information about it. Can anyone help? I am really at a loss.

FATAL EXCEPTION: pool-1-thread-1 Process: com.mycompany.myerror, PID:
  22712 java.lang.AbstractMethodError: abstract method "void
  com.google.firebase.iid.zzb.handleIntent(android.content.Intent)" at
  com.google.firebase.iid.zzb$1.run(Unknown Source) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:support-v4:25.3.0'
    compile 'com.android.support:design:25.3.0'
    //https://developers.google.com/android/guides/setup
    compile 'com.google.android.gms:play-services-places:10.2.1'
    compile 'com.google.android.gms:play-services-maps:10.2.1'
    compile 'com.google.android.gms:play-services-location:10.2.1'
    compile 'com.google.android.gms:play-services-vision:10.2.1'
    compile 'com.google.android.gms:play-services-gcm:10.2.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.zxing:core:3.2.0'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    testCompile 'junit:junit:4.12'
}
</code>```

FirebaseMessagingService.java

```<code>public class FirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        try {
            sendNotification(remoteMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNotification(final RemoteMessage remoteMessage) throws Exception {

        Calendar calendar = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
        String strDate = sdf.format(c.getTime());

        String contentTitle = "New Push Message";
        String contentText = "Received at " + strDate;

        Utilities.sendNotification(getApplicationContext(),
                getNotificationIcon(),
                contentTitle,
                contentText,
                0,
                HomeActivity.class,
                Utilities.getNotificationId(getApplicationContext()));

    }
</code>```

Utilities

```<code> public static void sendNotification(Context appContext,
                                            int icon,
                                            String title,
                                            String msg,
                                            long when,
                                            Class<? extends Context> classToLaunch,
                                            long processId) {

            //Define notification msg
            Intent launchIntent = null;

            if (classToLaunch != null) {
                launchIntent = new Intent(appContext, classToLaunch);
            } else {
                launchIntent = new Intent();
            }

            // This is dummy data for just differentiate Pending intent
            // only set value that is check IntentFilter
            launchIntent.addCategory("CATEGORY" + new Date(System.currentTimeMillis()));
            launchIntent.addFlags((int) System.currentTimeMillis());
            launchIntent.setAction("ACTION" + new Date(System.currentTimeMillis()));

            // also make launch mode to singleTop in manifest for that activity
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |
                            Intent.FLAG_ACTIVITY_NEW_TASK);

            // intent to be launched when click on notification
            PendingIntent pendingIntent = PendingIntent.getActivity(appContext,
                    0,
                    launchIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            //Instantiate the notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext); //(icon, msg, when);
            builder.setContentTitle(title);
            builder.setSmallIcon(icon);
            builder.setWhen(when);
            builder.setTicker(msg);
            builder.setContentText(msg);
            builder.setContentIntent(pendingIntent);
            builder.setAutoCancel(true);
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
            builder.setDefaults(Notification.DEFAULT_SOUND);

            NotificationManager notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify((int) processId, builder.build());
        }
</code>```

HomeActivity

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                if (BuildConfig.DEBUG_APPLICATION) {
                    Log.d(TAG, "Key: " + key + " Value: " + value);
                }
            }
        }
}
</code>```

答:
You should keep the Firebase libraties version and Google play services libraries similar. So update the version numbers of the Firebase libararies to 10.2.1:

Change:

```<code>compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'
</code>```

To:

```<code>compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'
</code>```

Body:
When I receive a push notification on Android, I get the below error. I can't really seem to find any information about it. Can anyone help? I am really at a loss.

FATAL EXCEPTION: pool-1-thread-1 Process: com.mycompany.myerror, PID:
  22712 java.lang.AbstractMethodError: abstract method "void
  com.google.firebase.iid.zzb.handleIntent(android.content.Intent)" at
  com.google.firebase.iid.zzb$1.run(Unknown Source) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:support-v4:25.3.0'
    compile 'com.android.support:design:25.3.0'
    //https://developers.google.com/android/guides/setup
    compile 'com.google.android.gms:play-services-places:10.2.1'
    compile 'com.google.android.gms:play-services-maps:10.2.1'
    compile 'com.google.android.gms:play-services-location:10.2.1'
    compile 'com.google.android.gms:play-services-vision:10.2.1'
    compile 'com.google.android.gms:play-services-gcm:10.2.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.zxing:core:3.2.0'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    testCompile 'junit:junit:4.12'
}

FirebaseMessagingService.java

public class FirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        try {
            sendNotification(remoteMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNotification(final RemoteMessage remoteMessage) throws Exception {

        Calendar calendar = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
        String strDate = sdf.format(c.getTime());

        String contentTitle = "New Push Message";
        String contentText = "Received at " + strDate;

        Utilities.sendNotification(getApplicationContext(),
                getNotificationIcon(),
                contentTitle,
                contentText,
                0,
                HomeActivity.class,
                Utilities.getNotificationId(getApplicationContext()));

    }

Utilities

 public static void sendNotification(Context appContext,
                                            int icon,
                                            String title,
                                            String msg,
                                            long when,
                                            Class<? extends Context> classToLaunch,
                                            long processId) {

            //Define notification msg
            Intent launchIntent = null;

            if (classToLaunch != null) {
                launchIntent = new Intent(appContext, classToLaunch);
            } else {
                launchIntent = new Intent();
            }

            // This is dummy data for just differentiate Pending intent
            // only set value that is check IntentFilter
            launchIntent.addCategory("CATEGORY" + new Date(System.currentTimeMillis()));
            launchIntent.addFlags((int) System.currentTimeMillis());
            launchIntent.setAction("ACTION" + new Date(System.currentTimeMillis()));

            // also make launch mode to singleTop in manifest for that activity
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |
                            Intent.FLAG_ACTIVITY_NEW_TASK);

            // intent to be launched when click on notification
            PendingIntent pendingIntent = PendingIntent.getActivity(appContext,
                    0,
                    launchIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            //Instantiate the notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext); //(icon, msg, when);
            builder.setContentTitle(title);
            builder.setSmallIcon(icon);
            builder.setWhen(when);
            builder.setTicker(msg);
            builder.setContentText(msg);
            builder.setContentIntent(pendingIntent);
            builder.setAutoCancel(true);
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
            builder.setDefaults(Notification.DEFAULT_SOUND);

            NotificationManager notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify((int) processId, builder.build());
        }

HomeActivity

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                if (BuildConfig.DEBUG_APPLICATION) {
                    Log.d(TAG, "Key: " + key + " Value: " + value);
                }
            }
        }
}

Body:
You should keep the Firebase libraties version and Google play services libraries similar. So update the version numbers of the Firebase libararies to 10.2.1:

Change:

compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'

To:

compile 'com.google.firebase:firebase-core:10.2.1'
compile 'com.google.firebase:firebase-messaging:10.2.1'