问:
Add Result of CustomObject to title
I have a small script which reads out a registry path, creates an output as a PSCUstomObject and displays it in the console and also logs it into a file.

This is the script:

```<code>$LastLicense = 0

while ($true)
{
    [int]$lizenzen = gp "HKCU:\SOFTWARE\Logik GmbH\Logik\Execution" -name Licenses -ea Stop |
    select -Expand Licenses

    if ($lizenzen -ne $LastLicense)
    {
        [PSCustomObject] @{
            "DateTime" = (get-date).DateTime
            "Lizenzen in Gebrauch" = $lizenzen
        } | tee -FilePath C:\install\LizenzLog.txt -Append | ft -AutoSize
        $LastLicense = $lizenzen
    }
    sleep -s 10
}
</code>```

Now the output is like this:

```<code>DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      6

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5
</code>```

but i'd like to have it like this:

```<code>DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5
2017.07.04 11:01:28                      6
2017.07.04 11:01:28                      5
</code>```

is this possible?

答:
I think in this case you can skip [pscustomobject] creation and just create a strings which will be saved in CSV file:

```<code>#Create CSV file with Separator char for Excel and headers, if file exists will be replaced with empty one
"SEP=," | out-file -FilePath C:\install\LizenzLog.csv -Force
"DateTime" + "," + "Lizenzen in Gebrauch" | out-file -FilePath C:\install\LizenzLog.csv -Append

while ($true)
{
    [int]$lizenzen = gp "HKCU:\SOFTWARE\Logik GmbH\Logik\Execution" -name Licenses -ea Stop | % Licenses
    if ($lizenzen -ne $LastLicense)
    {    #export values as string elements delimited by comma,  easy way to import to Excel (just open csv file it should open it corectly)
        "$((get-date).DateTime)"+ "," + $lizenzen | tee -FilePath C:\install\LizenzLog.csv -Append
        $LastLicense = $lizenzen
    }
    sleep -s 10
}
</code>```

by this you will get a CSV file ready to import to Excel - and if you just double click the columns should be imported at once.

after script execution if you want to see its presentation on console window
just import CSV: Import-Csv C:\install\LizenzLog.csv

Title: Add Result of CustomObject to title

Body:
I have a small script which reads out a registry path, creates an output as a PSCUstomObject and displays it in the console and also logs it into a file.

This is the script:

$LastLicense = 0

while ($true)
{
    [int]$lizenzen = gp "HKCU:\SOFTWARE\Logik GmbH\Logik\Execution" -name Licenses -ea Stop |
    select -Expand Licenses

    if ($lizenzen -ne $LastLicense)
    {
        [PSCustomObject] @{
            "DateTime" = (get-date).DateTime
            "Lizenzen in Gebrauch" = $lizenzen
        } | tee -FilePath C:\install\LizenzLog.txt -Append | ft -AutoSize
        $LastLicense = $lizenzen
    }
    sleep -s 10
}

Now the output is like this:

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      6

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5

but i'd like to have it like this:

DateTime              Lizenzen in Gebrauch
--------              --------------------
2017.07.04 11:01:28                      5
2017.07.04 11:01:28                      6
2017.07.04 11:01:28                      5

is this possible?

Body:
I think in this case you can skip [pscustomobject] creation and just create a strings which will be saved in CSV file:

#Create CSV file with Separator char for Excel and headers, if file exists will be replaced with empty one
"SEP=," | out-file -FilePath C:\install\LizenzLog.csv -Force
"DateTime" + "," + "Lizenzen in Gebrauch" | out-file -FilePath C:\install\LizenzLog.csv -Append

while ($true)
{
    [int]$lizenzen = gp "HKCU:\SOFTWARE\Logik GmbH\Logik\Execution" -name Licenses -ea Stop | % Licenses
    if ($lizenzen -ne $LastLicense)
    {    #export values as string elements delimited by comma,  easy way to import to Excel (just open csv file it should open it corectly)
        "$((get-date).DateTime)"+ "," + $lizenzen | tee -FilePath C:\install\LizenzLog.csv -Append
        $LastLicense = $lizenzen
    }
    sleep -s 10
}

by this you will get a CSV file ready to import to Excel - and if you just double click the columns should be imported at once.

after script execution if you want to see its presentation on console window
just import CSV: Import-Csv C:\install\LizenzLog.csv


来源: stackexchange

问:
expand wildcards in string variable
I'm reading strings from a blacklist file which contains files and folders which should get deleted. It works for simple file names, but not with wildcards.

E.g. if I type on the shell rm -rf !(abc|def) it deletes all but these two files. When putting this string !(abc|def) into blacklist it does not work, because the string does not get evaluated.

So I tried to use eval, but it does not work as expected.

```<code>#!/bin/bash
# test pattern (normally read from blacklist file)
LINE="!(abc|def)"

# output string
echo "$LINE"

# try to expand this wildcards
eval "ls $LINE"

# try with subshell
( ls $LINE )
</code>```

How can I make this working?

答:
Most likely, the extglob shell option is turned off for non-interactive shells (like the one your script runs in).

You have to change a few things:

```<code>#!/bin/bash

# Turn on extglob shell option
shopt -s extglob

line='!(abc|def)'

echo "$line"

# Quoting suppresses glob expansion; this will not work
ls "$line"

# Unquoted: works!
ls $line
</code>```

You have to

turn on the extglob shell option

use $line unquoted: quoting suppresses glob expansion, which is almost always desired, but not here

Notice that I use lowercase variable names. Uppercase is reserved for shell and environment variables; using lowercase reduces the probability of name clashes (see the POSIX spec, fourth paragraph).

Also, eval is not needed here.

ContentLicense: CC BY-SA 3.0

Title: expand wildcards in string variable

Body:
I'm reading strings from a blacklist file which contains files and folders which should get deleted. It works for simple file names, but not with wildcards.

E.g. if I type on the shell rm -rf !(abc|def) it deletes all but these two files. When putting this string !(abc|def) into blacklist it does not work, because the string does not get evaluated.

So I tried to use eval, but it does not work as expected.

#!/bin/bash
# test pattern (normally read from blacklist file)
LINE="!(abc|def)"

# output string
echo "$LINE"

# try to expand this wildcards
eval "ls $LINE"

# try with subshell
( ls $LINE )

How can I make this working?

Body:
Most likely, the extglob shell option is turned off for non-interactive shells (like the one your script runs in).

You have to change a few things:

#!/bin/bash

# Turn on extglob shell option
shopt -s extglob

line='!(abc|def)'

echo "$line"

# Quoting suppresses glob expansion; this will not work
ls "$line"

# Unquoted: works!
ls $line

You have to

turn on the extglob shell option

use $line unquoted: quoting suppresses glob expansion, which is almost always desired, but not here

Notice that I use lowercase variable names. Uppercase is reserved for shell and environment variables; using lowercase reduces the probability of name clashes (see the POSIX spec, fourth paragraph).

Also, eval is not needed here.


问:
How to associate an event with only one object? jqplot
Im using jqplot to draw some charts. It is a great tool, but it lacks a simple clickhandler option for each chart.

Its plugins like highlighter, draggable and cursor register their interest in capturing click/mouse-events from the jqplot canvas by adding themselves to jqplot.eventListenerHooks (eventListenerHooks.push(['jqplotClick', callback]); for example. or 'jqplotMouseDown' or such are also available.

After making my plot with the usual $.jqplot(target, data, options);
then I do this

$.jqplot.eventListenerHooks.push(['jqplotClick', myFunc]);

and sure enough myFunc gets called wherever I click on the plot, with event, neighbour, datapos and gridpos. Neighbour is the most interesting, it contains my data point if there was a click on it. This is the data I need to make a popup close to the gridpos with aditional information on the datapoint.

But the problem is if I have two charts on the same page and want to register different callbacks for each jqplot. As it is now, when I register the second myFunc2, all the clicks on the second plot go through the myFunc aswell!

Do I need to make changes to jqplot? Any directions, whatsoever?

Thanks

答:
This isn't well-documented, but you can find a discussion about it here.

Basically, you need to create event handlers for your chart before calling jqplot to create the actual chart.  To do that, you need to do something like this:

```<code>var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
};

$.jqplot.eventListenerHooks.push(['jqplotClick', handler]);
</code>```

That's just a simple event handler that checks to see if there's a neighboring data point near where you clicked.  See a working example here: http://jsfiddle.net/andrewwhitaker/PtyFG/

Update: If you want to only listen to events on a certain plot, you could do something like this:

```<code>var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (plot.targetId === "#chartdiv") {
        if (neighbor) {
            alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
        }
    }
    else if (plot.targetId === "#chart2div") {
        ....
    }
    // etc...
};
</code>```

Where you would replace #chartdiv with whatever the Id of the chart you want to listen to events for is.  The example has been updated.

Update 2:  Looks like you can use a regular bind event with the plot events:

```<code>$("#chartdiv").bind("jqplotClick", function(ev, gridpos, datapos, neighbor) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
});
</code>```

Example using this method, with 2 charts:

http://jsfiddle.net/andrewwhitaker/PtyFG/5/

Hope that helps!

ContentLicense: CC BY-SA 2.5

Body:
This isn't well-documented, but you can find a discussion about it here.

Basically, you need to create event handlers for your chart before calling jqplot to create the actual chart.  To do that, you need to do something like this:

var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
};

$.jqplot.eventListenerHooks.push(['jqplotClick', handler]);

That's just a simple event handler that checks to see if there's a neighboring data point near where you clicked.  See a working example here: http://jsfiddle.net/andrewwhitaker/PtyFG/

Update: If you want to only listen to events on a certain plot, you could do something like this:

var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (plot.targetId === "#chartdiv") {
        if (neighbor) {
            alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
        }
    }
    else if (plot.targetId === "#chart2div") {
        ....
    }
    // etc...
};

Where you would replace #chartdiv with whatever the Id of the chart you want to listen to events for is.  The example has been updated.

Update 2:  Looks like you can use a regular bind event with the plot events:

$("#chartdiv").bind("jqplotClick", function(ev, gridpos, datapos, neighbor) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
});

Example using this method, with 2 charts:

http://jsfiddle.net/andrewwhitaker/PtyFG/5/

Hope that helps!


问:
Why is the beginning of a line not recognized by a regex?
given the following expression:

```<code>Pattern.compile("^Test.*\n").matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")
</code>```

This yields:

```<code>"foo\nNothing\nTest 2\n"
</code>```

for me. I expected that the last line is also replaced to foo\n since there is a linebreak immediately before Test 2 in the input string.

Why is doesn't the regex match there?

答:
You have to add the multiline flag to the pattern: Pattern.MULTILINE.

```<code>Pattern.compile("^Test.*\n", Pattern.MULTILINE).matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")
</code>```

By Default the match is only single line. For more Informations see the javadoc

Body:
given the following expression:

Pattern.compile("^Test.*\n").matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")

This yields:

"foo\nNothing\nTest 2\n"

for me. I expected that the last line is also replaced to foo\n since there is a linebreak immediately before Test 2 in the input string.

Why is doesn't the regex match there?

Body:
You have to add the multiline flag to the pattern: Pattern.MULTILINE.

Pattern.compile("^Test.*\n", Pattern.MULTILINE).matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")

By Default the match is only single line. For more Informations see the javadoc


答:
At the beginning of your regex you have a ^ sign which normally anchors the regex to the beginning of a tested string. You need to specify multiline regex option (Oracle Documentation link) to make it apply to start of each line instead.

Try this (I have split the lines for legibility, feel free to oneline it back):

```<code>Pattern.compile("^Test.*\n", Pattern.MULTILINE)
       .matcher("Test 123\nNothing\nTest 2\n")
       .replaceAll("foo\n")
</code>```

Unfortunately I do not have Java environment set up at the moment, so I'm unable to check this by myself.

Title: Why is the beginning of a line not recognized by a regex?

Body:
At the beginning of your regex you have a ^ sign which normally anchors the regex to the beginning of a tested string. You need to specify multiline regex option (Oracle Documentation link) to make it apply to start of each line instead.

Try this (I have split the lines for legibility, feel free to oneline it back):

Pattern.compile("^Test.*\n", Pattern.MULTILINE)
       .matcher("Test 123\nNothing\nTest 2\n")
       .replaceAll("foo\n")

Unfortunately I do not have Java environment set up at the moment, so I'm unable to check this by myself.


问:
Apache redirects sitemap.xml to error component
Here is my Angular router config:

```<code>const appRoutes: Routes = [
{ path: 'home', component: HomeComponent,
data: {
  animation: {
    value: 'home',
  }
}
},
{ path: 'about',  component: AboutComponent,
data: {
  animation: {
    value: 'about',
  }
}
},
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: ErrorComponent }
];
</code>```

Each time I try to navigate to www.myapp.com/sitemap.xml it matches the ErrorComponent and redirects to my 404 page.

How can I configure the apache server to stop sitemap.xml going to index.html?

Below is my rewrite rule in my .htaccess file:

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

答:
I figured it out. I just needed to add the below rewrite rule to redirect to the sitemap.xml file.</p>

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

Body:
Here is my Angular router config:

const appRoutes: Routes = [
{ path: 'home', component: HomeComponent,
data: {
  animation: {
    value: 'home',
  }
}
},
{ path: 'about',  component: AboutComponent,
data: {
  animation: {
    value: 'about',
  }
}
},
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: ErrorComponent }
];

Each time I try to navigate to www.myapp.com/sitemap.xml it matches the ErrorComponent and redirects to my 404 page.

How can I configure the apache server to stop sitemap.xml going to index.html?

Below is my rewrite rule in my .htaccess file:

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

Body:
I figured it out. I just needed to add the below rewrite rule to redirect to the sitemap.xml file.

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


问:
No route matches [GET] "/place/new"
I can't catch where a problem is.

I run on server

```<code>rails generate scaffold Place name:string lat:numeric lng:numeric
</code>```

Next, I run

```<code>rake db:migrate
</code>```

So, I try to create new Place on web browser and go to

```<code>/places/new
</code>```

But receive:

```<code>ActionController::RoutingError (No route matches [GET] "/place/new"):
</code>```

I confused because everything works fine on my local machine. What's wrong with me?

btw, routes.rb looks like:

```<code>Rails.application.routes.draw do
    resources :places
end
</code>```

答: You're saying you're navigating to places/new, but the log entry you've included shows that you're actually trying to navigate to place/new, which is not a valid route in this case. Use the plural for the resource.

Title: No route matches [GET] "/place/new"

Body:
I can't catch where a problem is.

I run on server

rails generate scaffold Place name:string lat:numeric lng:numeric

Next, I run

rake db:migrate

So, I try to create new Place on web browser and go to

/places/new

But receive:

ActionController::RoutingError (No route matches [GET] "/place/new"):

I confused because everything works fine on my local machine. What's wrong with me?

btw, routes.rb looks like:

Rails.application.routes.draw do
    resources :places
end


问:
Increment Version number when checking in to TFS
I have a folder in TFS which has SQL Scripts.  At the moment I am manually adding a comment and updating a version number inside the comment every time i make a change and check it back it.  This works however was hoping there might be a better way. Is there a way to automate this in TFS?

I have read the following article
Version control project files

do i have to go through such a process for simple .sql files? Are there any other simple ways.

答:
The first way mentioned by Jacob above can achieve that if you just want to incremental the version number of the script/folder, just create a CI build definition.

Actually you can just enable Label sources and set the Label format with predefined environment variables such as $(build.buildNumber), and set without publish any artifacts during build process.
Thus, it will automatically trigger the CI build when you check in files, and the source (SQL Script /folder) will be labeled with the incremental number.

Then you can find the specific versions with the label.


问:
defaultWriteObject method in serialization of java is used to read transient variable also if we use it with readObject method
```<code> private void writeObject(ObjectOutputStream o)
        throws IOException {
        o.writeObject(propertyTwo);

        o.defaultWriteObject();
  }

        private void readObject(ObjectInputStream o)
        throws IOException, ClassNotFoundException {

        propertyTwo = (String) o.readObject();
        o.defaultReadObject();
  }
</code>```

Please explain how it serialize transient variable if we use defaultWriteObject and writeObject together?

答: It serializes it because you serialized it. Nothing  to do with defaultWriteObject() or defaultReadObject() whatsoever. They won't serialize transient members. But you did.

Body:
 private void writeObject(ObjectOutputStream o)
        throws IOException {
        o.writeObject(propertyTwo);

        o.defaultWriteObject();
  }

        private void readObject(ObjectInputStream o)
        throws IOException, ClassNotFoundException {

        propertyTwo = (String) o.readObject();
        o.defaultReadObject();
  }

Please explain how it serialize transient variable if we use defaultWriteObject and writeObject together?


问:
informatica Datetime conversion to SQL server Timstamp
I have a requirement where I have to load Informatica SESSSTARTTIME(datetime) to SQL server timestamp. When I am trying to connect datetime to timestamp I am getting error incompatible data type.

Any suggestions how this can be achieved?

Thanks

答:
in the mapping try to create output port in expression as sessionstarttime (which is a inbuilt variable) and pass it to target
hope this will help to get desire output

in session there is config tab where you can change the format for date and time


问:
Pass month name dynamically in AWK (GNU) with control statement
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

tried this also

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l
</code>```

but it is working if I hardcode Month

```<code>ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l
</code>```

Please suggest what I'm missing in the code?

答:
I tried to use your awk filter query, but I could not make it to work.

I solved your problem by rewriting the query and using grep with a constructed date string to filter instead of awk.

```<code>ls -ltr |egrep "$(date --date="6 days ago" +%b) +$(date --date="6 days ago" +%d | sed 's/^0*//')" |awk '{print $9}'|wc -l
</code>```

Body:
Hi I'm trying out below command to match month and day (of 6 days ago, which is Jun 29) to search a directory using AWK, but the result is always '0' instead it is supposed to be around 1800.

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

tried this also

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +%b)", -v day="$(date --date="6 days ago" +%d)"  '$6 ==month && $7==day {print $9}'|wc -l

but it is working if I hardcode Month

ls -ltr /test/output|awk  -v month="$(date --date="6 days ago" +"\"%b\"")", -v day="$(date --date="6 days ago" +%d)"  '$6 =="Jun" && $7==day {print $9}'|wc -l

Please suggest what I'm missing in the code?

Body:
I tried to use your awk filter query, but I could not make it to work.

I solved your problem by rewriting the query and using grep with a constructed date string to filter instead of awk.

ls -ltr |egrep "$(date --date="6 days ago" +%b) +$(date --date="6 days ago" +%d | sed 's/^0*//')" |awk '{print $9}'|wc -l


问:
How to remove an element found in an array and shift the array elements to the left?
```<code>int search(int a[]) {

   int i,V,index;
   printf("Enter the element (V),That you want to find:>");
   scanf("%d",&V);

   for (i=0;i<N;i++) {
       if(a[i]==V) {
           V=a[i];
           index=i;
       }
   }
   printf("%d is located in a[%d].",V,index
)
</code>```

答:
If you do not care about the ordering of the elements you can delete the found element in O(1) time.</p>

```<code>// Find the element you're looking for.
int index = find(A, V);

// Stuff the last element into the index found.
A[index] = A[N-1];

// Reduce the total number of elements.
N--;
</code>```

Body:
If you do not care about the ordering of the elements you can delete the found element in O(1) time.

// Find the element you're looking for.
int index = find(A, V);

// Stuff the last element into the index found.
A[index] = A[N-1];

// Reduce the total number of elements.
N--;


问:
sqlite error, reading value as column
hey experts I am trying to add value to specific column in table but python reading my value as column.

```<code>conn = sqlite3.connect('ddbinven')

c = conn.cursor()
def insert_data(name,value):
    c.execute('INSERT INTO testingddb(%s) VALUES(%s);' %(name,value))
    conn.commit()
    c.close()
    conn.close()

insert_data("tablename", "reverseeng02")
</code>```

error:

```<code>    c.execute('INSERT INTO testingddb(%s) VALUES(%s);' %(name,value))
sqlite3.OperationalError: no such column: reverseeng02
</code>```

答:
found issue missing "" around %s

```<code>conn = sqlite3.connect('ddbinven')

c = conn.cursor()
def insert_data(name,value):
    c.execute('INSERT INTO testingddb("%s") VALUES("%s");' %(name,value))
    conn.commit()
    c.close()
    conn.close()
</code>```

Title: sqlite error, reading value as column

Body:
hey experts I am trying to add value to specific column in table but python reading my value as column.

conn = sqlite3.connect('ddbinven')

c = conn.cursor()
def insert_data(name,value):
    c.execute('INSERT INTO testingddb(%s) VALUES(%s);' %(name,value))
    conn.commit()
    c.close()
    conn.close()

insert_data("tablename", "reverseeng02")

error:

    c.execute('INSERT INTO testingddb(%s) VALUES(%s);' %(name,value))
sqlite3.OperationalError: no such column: reverseeng02

Body:
found issue missing "" around %s

conn = sqlite3.connect('ddbinven')

c = conn.cursor()
def insert_data(name,value):
    c.execute('INSERT INTO testingddb("%s") VALUES("%s");' %(name,value))
    conn.commit()
    c.close()
    conn.close()


问:
Add files programmatically to Order in Woocommerce
I'm using the "woocommerce_order_status_completed" hook to create a file dynamically after the user has paid for the order.
I need to add this file to his downloadable area in that order in this hooks. </p>

<p>Any ideias how to attach a file to a order? </p>

答:
woocommerce_order_status_completed you can add below code...
First store the file you have created in uploads using media_handle_upload

```<code>if($_FILES){
//if u don't want to $post_id u gan give 0
$attachment_id = media_handle_upload( 'abe_update_epub', $post_id );
if ( is_wp_error( $attachment_id ) ) {
    $errors = $attachment_id->get_error_messages();
    foreach( $errors as $error ){
        echo $error;
    }
    echo 'There was an error uploading the image';
} else {
    // NEW FILE: Setting the name, getting the url and and Md5 hash number
    $file_name = 'Epub Files';
    $file_url  = wp_get_attachment_url($attachment_id);
    $md5_num = md5( $file_url );

    // Inserting new file in downloadable files
    $files[$md5_num] = array(
        'name' => $file_name,
        'file' => $file_url
    );

    // Updating database with the new array

    $order = new WC_Order($order_id);

    if(!empty($files)){
        update_post_meta($order->ID,_files,$files));
    }
    // Displaying a success notice
    echo 'The image was uploaded successfully!';
}
}
</code>```

Hopes this help u..

Body:
I'm using the "woocommerce_order_status_completed" hook to create a file dynamically after the user has paid for the order.
I need to add this file to his downloadable area in that order in this hooks.

Any ideias how to attach a file to a order?

Body:
woocommerce_order_status_completed you can add below code...
First store the file you have created in uploads using media_handle_upload

if($_FILES){
//if u don't want to $post_id u gan give 0
$attachment_id = media_handle_upload( 'abe_update_epub', $post_id );
if ( is_wp_error( $attachment_id ) ) {
    $errors = $attachment_id->get_error_messages();
    foreach( $errors as $error ){
        echo $error;
    }
    echo 'There was an error uploading the image';
} else {
    // NEW FILE: Setting the name, getting the url and and Md5 hash number
    $file_name = 'Epub Files';
    $file_url  = wp_get_attachment_url($attachment_id);
    $md5_num = md5( $file_url );

    // Inserting new file in downloadable files
    $files[$md5_num] = array(
        'name' => $file_name,
        'file' => $file_url
    );

    // Updating database with the new array

    $order = new WC_Order($order_id);

    if(!empty($files)){
        update_post_meta($order->ID,_files,$files));
    }
    // Displaying a success notice
    echo 'The image was uploaded successfully!';
}
}

Hopes this help u..


问:
Where is the code that causes setState (React) to be asynchronous?
I recently read through a large portion of the React and ReactDOM codebase in order to get an understanding of what happens when a call to setState occurs. At this point, I would say that I understand the sequence of events at a high level. A call to setState results in a message being added to a queue of updates that need to be processed. The updates are processed and changes to the DOM are only made if necessary.

Here's where I am lost. There are hundreds of blog posts discussing the asynchronous behavior of setState. While I don't doubt that setState is asynchronous, I cannot find a line of code in the ReactDOM codebase that would introduce asynchronous behavior. Does anyone know exactly where this happens?

答:
First of all setState may be execute in async way, but it is not allwys executed as such. Ben Nadel list some of his findings in setState() State Mutation Operation May Be Synchronous In ReactJS

To summarize setStates seems to gets batched in situations where react can intercept originating event, like onClick handlers. Since react creates actual DOM from virtual react DOM (and since it is aware of semantics of attributes) it can wrap any of onClick handlers that you provide into something like this

```<code>wrappedHandler = () => {
  turnBatchingOn()
  originalHanlder()
  executeBatched()
}
</code>```

In this case you get async behavior, all setState calls get enqueued, and they get executed only after your original onClick handler has finished executing.

Note this is not actual react code it is just my speculation how it is async effect achieved. I understand it is not actual line of code that does it, but I think it could help you find it.

Best article explaining setState implementation that I found is on React Kung Fu

Body:
First of all setState may be execute in async way, but it is not allwys executed as such. Ben Nadel list some of his findings in setState() State Mutation Operation May Be Synchronous In ReactJS

To summarize setStates seems to gets batched in situations where react can intercept originating event, like onClick handlers. Since react creates actual DOM from virtual react DOM (and since it is aware of semantics of attributes) it can wrap any of onClick handlers that you provide into something like this

wrappedHandler = () => {
  turnBatchingOn()
  originalHanlder()
  executeBatched()
}

In this case you get async behavior, all setState calls get enqueued, and they get executed only after your original onClick handler has finished executing.

Note this is not actual react code it is just my speculation how it is async effect achieved. I understand it is not actual line of code that does it, but I think it could help you find it.

Best article explaining setState implementation that I found is on React Kung Fu


问:
Statement ignored 14/13 PLS-00222: no function with name 'P' exists in this scope
Package Specification:

```<code>CREATE OR REPLACE PACKAGE dt_pkg AS
    PROCEDURE Simpleint(
        p number, n number, r number := 10);

    PROCEDURE Compoundint(
        p number, n number, r number);
END dt_pkg;
/
</code>```

Package BODY:

```<code>CREATE OR REPLACE PACKAGE BODY dt_pkg  IS
    PROCEDURE Simpleint (p NUMBER, n number, r NUMBER) IS
        si number :=0;
    BEGIN
        si:=p*n*r;
        DBMS_OUTPUT.PUT_LINE('sIMPLE INT: '||si);
    END Simpleint;

   PROCEDURE Compoundint (p number,n number,r number) IS
       ci number:=0;
   BEGIN
       ci:=p(1+r/100)**n;
       DBMS_OUTPUT.PUT_LINE('COMPOUND INTEREST: '||ci);
    END Compoundint;
END dt_pkg;
/
</code>```

Error I get

LINE/COL ERROR

14/9     PL/SQL: Statement ignored

  14/13    PLS-00222: no function with name 'P' exists in this scope

please help
Thank you.

答:
your package have typo.

```<code>ci:=p(1+r/100)**n;
</code>```

Try this:

```<code>ci:=p*(1+r/100)*n;
</code>```

Hope this will help you

Body:
Package Specification:

CREATE OR REPLACE PACKAGE dt_pkg AS
    PROCEDURE Simpleint(
        p number, n number, r number := 10);

    PROCEDURE Compoundint(
        p number, n number, r number);
END dt_pkg;
/

Package BODY:

CREATE OR REPLACE PACKAGE BODY dt_pkg  IS
    PROCEDURE Simpleint (p NUMBER, n number, r NUMBER) IS
        si number :=0;
    BEGIN
        si:=p*n*r;
        DBMS_OUTPUT.PUT_LINE('sIMPLE INT: '||si);
    END Simpleint;

   PROCEDURE Compoundint (p number,n number,r number) IS
       ci number:=0;
   BEGIN
       ci:=p(1+r/100)**n;
       DBMS_OUTPUT.PUT_LINE('COMPOUND INTEREST: '||ci);
    END Compoundint;
END dt_pkg;
/

Error I get

LINE/COL ERROR

14/9     PL/SQL: Statement ignored

  14/13    PLS-00222: no function with name 'P' exists in this scope

please help
Thank you.

Body:
your package have typo.

ci:=p(1+r/100)**n;

Try this:

ci:=p*(1+r/100)*n;

Hope this will help you


问:
Use asp include to include asp.net page
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.</p>

```<code>  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.
</code>```

答: I'm pretty sure the include functionality in ASP is strictly for including other ASP files which contain code to be parsed by the ASP engine.  It wouldn't know what to do with ASP .NET code.</p>

Title: Use asp include to include asp.net page

Body:
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.

  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.


问:
ERROR [org.jboss.msc.service.fail] MSC00001: Failed to start service jboss.deployment-mount-provider
I can run my Jboss server without problems from the command line but via  eclipse i get the following error. In the server Details i can see the server is "Not connected" and after the timeout is expired (450 sec) stops trying to be connected.

I need to be able to start the jboss via eclise so as to facilitate the deploy process and be able to debug the code.

This is the error log...

```<code>12:26:21,740 INFO  [org.jboss.modules] JBoss Modules version 1.1.1.GA
12:26:21,942 INFO  [org.jboss.msc] JBoss MSC version 1.0.2.GA
12:26:22,002 INFO  [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final "Brontes" starting
12:26:22,116 ERROR [org.jboss.msc.service.fail] MSC00001: Failed to start service jboss.deployment-mount-provider: org.jboss.msc.service.StartException in service jboss.deployment-mount-provider: JBAS015843: Failed to create temp file provider
    at org.jboss.as.server.deployment.DeploymentMountProvider$Factory$ServerDeploymentRepositoryImpl.start(DeploymentMountProvider.java:111) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_23]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_23]
    at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_23]
</code>```

Could someone please help with this problem.

答: This error is getting displayed, because maybe you do not have appropriate permissions for that folder. Switch user to root user and try to run the 'standalone.sh' command. I guess that will solve you problem. Else change permissions in your user.</p>

Body:
I can run my Jboss server without problems from the command line but via  eclipse i get the following error. In the server Details i can see the server is "Not connected" and after the timeout is expired (450 sec) stops trying to be connected.

I need to be able to start the jboss via eclise so as to facilitate the deploy process and be able to debug the code.

This is the error log...

12:26:21,740 INFO  [org.jboss.modules] JBoss Modules version 1.1.1.GA
12:26:21,942 INFO  [org.jboss.msc] JBoss MSC version 1.0.2.GA
12:26:22,002 INFO  [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final "Brontes" starting
12:26:22,116 ERROR [org.jboss.msc.service.fail] MSC00001: Failed to start service jboss.deployment-mount-provider: org.jboss.msc.service.StartException in service jboss.deployment-mount-provider: JBAS015843: Failed to create temp file provider
    at org.jboss.as.server.deployment.DeploymentMountProvider$Factory$ServerDeploymentRepositoryImpl.start(DeploymentMountProvider.java:111) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_23]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_23]
    at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_23]

Could someone please help with this problem.


问:
How to stop the Visibility of the ProgressBar inside LinearLayout
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

```<code>public class MainActivity extends AppCompatActivity {

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

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

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}
</code>```

Here is my activity.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

This is my fragment.java

```<code>    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}
</code>```

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

答:
In the your HomeFragment, when you call

```<code>     loadJSON()
</code>```

on response or failure you call your activity's stopBar() method from where you hide progress bar

make you stopBar() method public, so that it can be accessed from Activity

```<code>public void stopBar() {
linearLayout.setVisibility(View.GONE);
}
</code>```

In your HomeFragment's onCreate you can get reference to your activity like below, then you can call the stopBar() method

```<code>MainActivity activity = ((MainActivity)getActivity());
activity.stopBar();
</code>```

it will look like this,

```<code>private void loadJSON() {

    Retrofit retrofit = new Retrofit.Builder()
          //
          // here goes your retrofit code
          //
    Call<HomeResponse> call = request.getHomeJSON();

    call.enqueue(new Callback<HomeResponse>() {
        @Override
        public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {
            //
            // here goes your code
            //
             activity.stopBar();

        }

        @Override
        public void onFailure(Call<HomeResponse> call, Throwable t) {
               //
               // here goes your code
               //

              activity.stopBar();

            Error_Dialog alert = new Error_Dialog();
            alert.showDialog(getActivity()," Please Check Your Internet Connection");

        }
    });

}
</code>```

Body:
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

public class MainActivity extends AppCompatActivity {

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

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

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}

Here is my activity.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

This is my fragment.java

    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

Body:
In the your HomeFragment, when you call

     loadJSON()

on response or failure you call your activity's stopBar() method from where you hide progress bar

make you stopBar() method public, so that it can be accessed from Activity

public void stopBar() {
linearLayout.setVisibility(View.GONE);
}

In your HomeFragment's onCreate you can get reference to your activity like below, then you can call the stopBar() method

MainActivity activity = ((MainActivity)getActivity());
activity.stopBar();

it will look like this,

private void loadJSON() {

    Retrofit retrofit = new Retrofit.Builder()
          //
          // here goes your retrofit code
          //
    Call<HomeResponse> call = request.getHomeJSON();

    call.enqueue(new Callback<HomeResponse>() {
        @Override
        public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {
            //
            // here goes your code
            //
             activity.stopBar();

        }

        @Override
        public void onFailure(Call<HomeResponse> call, Throwable t) {
               //
               // here goes your code
               //

              activity.stopBar();

            Error_Dialog alert = new Error_Dialog();
            alert.showDialog(getActivity()," Please Check Your Internet Connection");

        }
    });

}


问:
Loop between worksheets - Write Over Error
I'm writing a macro to get information from a worksheet to write that information to another sheet with specified conditions in vba.

But unfortunately I have an interesting problem with my codes.

I have given a range to the worksheets with Array, and wrote down the conditions.
So it should go with the specific order for "hcr1" and also "hcr2" in the codes.

If the values for WS_Name3, WS_Name4 and WS_Name5 are different, everything works perfectly and writes the data to their sheets.
But, if 2 of those values or all 3 are same, macro gets confused and writes the last values to every row.

Let's say if WS_Name3 and WS_Name4 are same, WS_Name5 is empty, the hcr1 value is always 20, which is WS_Name4 value.

Here is the all codes;

```<code>Sub Atama()

Application.ScreenUpdating = False

Dim WS_Name As String
Dim i As Integer
For i = 23 To 34
    WS_Name = Worksheets("Sheet1").Cells(i, 6).Value
    Worksheets(WS_Name).Activate

    Dim Acik_is As Long
    For Acik_is = Cells(Rows.Count, 10).End(xlUp).Row To 2 Step -1
        With Cells(Acik_is, 10)
            If .Value = "Devam Ediyor" Or .Value = "Revize Devam Ediyor" Then Rows(Acik_is).EntireRow.Delete
        End With
    Next Acik_is
Next i

Dim lRow As Long
Dim lLastRow As Long
Dim WS_Name2 As String
On Error Resume Next
lRow = Application.WorksheetFunction.Match("Acik", Worksheets("Egitim Bilgileri").Range("BR2:BR20"), 0) + 1
On Error Goto 0

If lRow > 0 Then

    WS_Name2 = Worksheets("Egitim Bilgileri").Cells(lRow, 1).Value
    Worksheets(WS_Name2).Activate

    lLastRow = WorksheetFunction.Max(Worksheets(WS_Name2).Range("AA22:AA1100"))
    lLastrow2 = lLastRow + 21

    For Satir = 22 To lLastrow2
        With Cells(Satir, 26)
            If .Value = "" Then
                WS_Name3 = Worksheets(WS_Name2).Cells(Satir, 16).Value
                WS_Name4 = Worksheets(WS_Name2).Cells(Satir, 19).Value
                WS_Name5 = Worksheets(WS_Name2).Cells(Satir, 22).Value
            End If

            Dim WS_X_Code As Variant
            For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)

                If WS_X_Code = WS_Name3 Then hcr1 = 17
                If WS_X_Code = WS_Name4 Then hcr1 = 20
                If WS_X_Code = WS_Name5 Then hcr1 = 23
                hcr2 = hcr1 + 1

                RowCount = Worksheets(WS_X_Code).Cells(Rows.Count, 1).End(xlUp).Row
                On Error Resume Next

                With Worksheets(WS_X_Code)
                    NextRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

                    Worksheets(WS_Name2).Cells(2, 3).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, hcr1).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 3).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, hcr2).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 4).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, 34).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 2).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_X_Code).Cells(NextRow, 6).FormulaR1C1 = _
                    "=IFERROR(IF(AND(R[-1]C="""",R[-1]C[2]=""""),"""",WORKDAY(IF(R[-1]C="""",R[-1]C[2],R[-1]C),(SUM(R4C4:RC[-2])/7))),"""")"
                    Worksheets(WS_X_Code).Cells(NextRow, 10).FormulaR1C1 = _
                    "=IF(RC[-2]="""",IF(RC[-4]="""","""",IF(RC[-3]<>"""",""Üretim Tamamlandi"",""Devam Ediyor"")),IF(RC[-1]<>"""",""Revize Tamamlandi"",""Revize Devam Ediyor""))"

                End With
            Next WS_X_Code

        End With
    Next Satir

End If
</code>```

End Sub

New version of the codes starting from the "Satir" loop are below;

```<code>    For Satir = 22 To lLastrow2
    With Cells(Satir, 26)
         If .Value = "" Then
             WS_Name3 = Worksheets(WS_Name2).Cells(Satir, 16).Value
             WS_Name4 = Worksheets(WS_Name2).Cells(Satir, 19).Value
             WS_Name5 = Worksheets(WS_Name2).Cells(Satir, 22).Value
         End If

            Dim WS_X_Code As Variant
            Dim X As Integer
            For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)

                Select Case X
                    Case 0: hcr1 = 17
                    Case 1: hcr1 = 20
                    Case 2: hcr1 = 23
                End Select
            hcr2 = hcr1 + 1

            RowCount = Worksheets(WS_X_Code).Cells(Rows.Count, 1).End(xlUp).Row
            On Error Resume Next

            With Worksheets(WS_X_Code)
            NextRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

                Worksheets(WS_Name2).Cells(2, 3).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, hcr1).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 3).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, hcr2).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 4).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, 34).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 2).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_X_Code).Cells(NextRow, 6).FormulaR1C1 = _
        "=IFERROR(IF(AND(R[-1]C="""",R[-1]C[2]=""""),"""",WORKDAY(IF(R[-1]C="""",R[-1]C[2],R[-1]C),(SUM(R4C4:RC[-2])/7))),"""")"
                 Worksheets(WS_X_Code).Cells(NextRow, 10).FormulaR1C1 = _
        "=IF(RC[-2]="""",IF(RC[-4]="""","""",IF(RC[-3]<>"""",""Üretim Tamamlandi"",""Devam Ediyor"")),IF(RC[-1]<>"""",""Revize Tamamlandi"",""Revize Devam Ediyor""))"

        X = X + 1
        End With
        Next WS_X_Code

End With
Next Satir

End If

End Sub
</code>```

答:
So your error is in the IF statements.

```<code>If WS_X_Code = WS_Name3 Then hcr1 = 17
If WS_X_Code = WS_Name4 Then hcr1 = 20
If WS_X_Code = WS_Name5 Then hcr1 = 23
</code>```

You want to compare to the name, but it actually compares to the values, so if there are the same values it will go with the previous one, as you mentioned.

One way to fix this, is to use a counter like this:

```<code>Dim WS_X_Code As Variant
Dim i As Integer: i = 0

For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)
    Select Case i
        Case 0: hcr1 = 17
        Case 1: hcr1 = 20
        Case 2: hcr1 = 23
    End Select

'i.e
Worksheets(WS_Name2).Cells(2, 3).Copy
Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
'....

i = i + 1
Next WS_X_Code
</code>```

Next time i suggest going through your code with F8 then you hover over the variables and see the values.

Body:
I'm writing a macro to get information from a worksheet to write that information to another sheet with specified conditions in vba.

But unfortunately I have an interesting problem with my codes.

I have given a range to the worksheets with Array, and wrote down the conditions.
So it should go with the specific order for "hcr1" and also "hcr2" in the codes.

If the values for WS_Name3, WS_Name4 and WS_Name5 are different, everything works perfectly and writes the data to their sheets.
But, if 2 of those values or all 3 are same, macro gets confused and writes the last values to every row.

Let's say if WS_Name3 and WS_Name4 are same, WS_Name5 is empty, the hcr1 value is always 20, which is WS_Name4 value.

Here is the all codes;

Sub Atama()

Application.ScreenUpdating = False

Dim WS_Name As String
Dim i As Integer
For i = 23 To 34
    WS_Name = Worksheets("Sheet1").Cells(i, 6).Value
    Worksheets(WS_Name).Activate

    Dim Acik_is As Long
    For Acik_is = Cells(Rows.Count, 10).End(xlUp).Row To 2 Step -1
        With Cells(Acik_is, 10)
            If .Value = "Devam Ediyor" Or .Value = "Revize Devam Ediyor" Then Rows(Acik_is).EntireRow.Delete
        End With
    Next Acik_is
Next i

Dim lRow As Long
Dim lLastRow As Long
Dim WS_Name2 As String
On Error Resume Next
lRow = Application.WorksheetFunction.Match("Acik", Worksheets("Egitim Bilgileri").Range("BR2:BR20"), 0) + 1
On Error Goto 0

If lRow > 0 Then

    WS_Name2 = Worksheets("Egitim Bilgileri").Cells(lRow, 1).Value
    Worksheets(WS_Name2).Activate

    lLastRow = WorksheetFunction.Max(Worksheets(WS_Name2).Range("AA22:AA1100"))
    lLastrow2 = lLastRow + 21

    For Satir = 22 To lLastrow2
        With Cells(Satir, 26)
            If .Value = "" Then
                WS_Name3 = Worksheets(WS_Name2).Cells(Satir, 16).Value
                WS_Name4 = Worksheets(WS_Name2).Cells(Satir, 19).Value
                WS_Name5 = Worksheets(WS_Name2).Cells(Satir, 22).Value
            End If

            Dim WS_X_Code As Variant
            For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)

                If WS_X_Code = WS_Name3 Then hcr1 = 17
                If WS_X_Code = WS_Name4 Then hcr1 = 20
                If WS_X_Code = WS_Name5 Then hcr1 = 23
                hcr2 = hcr1 + 1

                RowCount = Worksheets(WS_X_Code).Cells(Rows.Count, 1).End(xlUp).Row
                On Error Resume Next

                With Worksheets(WS_X_Code)
                    NextRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

                    Worksheets(WS_Name2).Cells(2, 3).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, hcr1).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 3).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, hcr2).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 4).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_Name2).Cells(Satir, 34).Copy
                    Worksheets(WS_X_Code).Cells(NextRow, 2).PasteSpecial Paste:=xlPasteValues
                    Worksheets(WS_X_Code).Cells(NextRow, 6).FormulaR1C1 = _
                    "=IFERROR(IF(AND(R[-1]C="""",R[-1]C[2]=""""),"""",WORKDAY(IF(R[-1]C="""",R[-1]C[2],R[-1]C),(SUM(R4C4:RC[-2])/7))),"""")"
                    Worksheets(WS_X_Code).Cells(NextRow, 10).FormulaR1C1 = _
                    "=IF(RC[-2]="""",IF(RC[-4]="""","""",IF(RC[-3]<>"""",""Üretim Tamamlandi"",""Devam Ediyor"")),IF(RC[-1]<>"""",""Revize Tamamlandi"",""Revize Devam Ediyor""))"

                End With
            Next WS_X_Code

        End With
    Next Satir

End If

End Sub

New version of the codes starting from the "Satir" loop are below;

    For Satir = 22 To lLastrow2
    With Cells(Satir, 26)
         If .Value = "" Then
             WS_Name3 = Worksheets(WS_Name2).Cells(Satir, 16).Value
             WS_Name4 = Worksheets(WS_Name2).Cells(Satir, 19).Value
             WS_Name5 = Worksheets(WS_Name2).Cells(Satir, 22).Value
         End If

            Dim WS_X_Code As Variant
            Dim X As Integer
            For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)

                Select Case X
                    Case 0: hcr1 = 17
                    Case 1: hcr1 = 20
                    Case 2: hcr1 = 23
                End Select
            hcr2 = hcr1 + 1

            RowCount = Worksheets(WS_X_Code).Cells(Rows.Count, 1).End(xlUp).Row
            On Error Resume Next

            With Worksheets(WS_X_Code)
            NextRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

                Worksheets(WS_Name2).Cells(2, 3).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, hcr1).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 3).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, hcr2).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 4).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_Name2).Cells(Satir, 34).Copy
                Worksheets(WS_X_Code).Cells(NextRow, 2).PasteSpecial Paste:=xlPasteValues
                Worksheets(WS_X_Code).Cells(NextRow, 6).FormulaR1C1 = _
        "=IFERROR(IF(AND(R[-1]C="""",R[-1]C[2]=""""),"""",WORKDAY(IF(R[-1]C="""",R[-1]C[2],R[-1]C),(SUM(R4C4:RC[-2])/7))),"""")"
                 Worksheets(WS_X_Code).Cells(NextRow, 10).FormulaR1C1 = _
        "=IF(RC[-2]="""",IF(RC[-4]="""","""",IF(RC[-3]<>"""",""Üretim Tamamlandi"",""Devam Ediyor"")),IF(RC[-1]<>"""",""Revize Tamamlandi"",""Revize Devam Ediyor""))"

        X = X + 1
        End With
        Next WS_X_Code

End With
Next Satir

End If

End Sub

Body:
So your error is in the IF statements.

If WS_X_Code = WS_Name3 Then hcr1 = 17
If WS_X_Code = WS_Name4 Then hcr1 = 20
If WS_X_Code = WS_Name5 Then hcr1 = 23

You want to compare to the name, but it actually compares to the values, so if there are the same values it will go with the previous one, as you mentioned.

One way to fix this, is to use a counter like this:

Dim WS_X_Code As Variant
Dim i As Integer: i = 0

For Each WS_X_Code In Array(WS_Name3, WS_Name4, WS_Name5)
    Select Case i
        Case 0: hcr1 = 17
        Case 1: hcr1 = 20
        Case 2: hcr1 = 23
    End Select

'i.e
Worksheets(WS_Name2).Cells(2, 3).Copy
Worksheets(WS_X_Code).Cells(NextRow, 1).PasteSpecial Paste:=xlPasteValues
'....

i = i + 1
Next WS_X_Code

Next time i suggest going through your code with F8 then you hover over the variables and see the values.


问:
neo4j APOC does not work locally on Win10
edit: Using Neo4j Community Edition 3.2.1.

I successfully installed APOC on my remote machine (debian) and it's working just fine.
However locally (Win10) I can't seem to get it to work.

What I did:

pasted the jar into the plugins folder

tried to run some APOC stuff via neo4j browser and REST/Postman as well and I got: Unknown function 'apoc.convert.fromJsonList'

What I tried to fix it so far:

Restarted Neo4j

Restarted the machine

Reinstalled Java

答:
Solution: create a plugins folder in the default.graphdb folder and put APOC there.
Also see https://stackoverflow.com/a/42357481/974731.

In my opinion this should be at least hinted at in the readme of the APOC git repo.


问:
Why runtime.caller(0) is giving different path with '--cover' argument in unit testing
When trying to execute a unit test function without any argument it  give following output path

```<code>C:/Program Files (x86)/Go1.8\bin\go.exe" test -v gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== C:/GerritNew/goclassec/src/gclassec/skyline/loggers/logs.go
</code>```

But when I try to run it with any argument such as --cover the file path value changes as below:

```<code>"C:/Program Files (x86)/Go1.8\bin\go.exe" test -v --cover gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== gclassec/skyline/loggers/_test/_obj_test/logs.go
</code>```

I am using runtime.caller(0) to get file path.

答: It worked by using os.Getwd() and runtime.caller  with a variable to diffrentiate between testing and normal running.  </p>

Body:
When trying to execute a unit test function without any argument it  give following output path

C:/Program Files (x86)/Go1.8\bin\go.exe" test -v gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== C:/GerritNew/goclassec/src/gclassec/skyline/loggers/logs.go

But when I try to run it with any argument such as --cover the file path value changes as below:

"C:/Program Files (x86)/Go1.8\bin\go.exe" test -v --cover gclassec/skyline/loggers -run ^TestCreateLogFilesPath$

filePath:=== gclassec/skyline/loggers/_test/_obj_test/logs.go

I am using runtime.caller(0) to get file path.


问:
Two HTML headings - swap places in circles?
I have two headings/divs and I need to change places after 5 seconds in the way like on the picture. I tried some transitions and similar, but I have not find anywhere how to move elements in a circular way.

Moving of elements must be like "half circular". The example code is in the comments.

答: Try the setInterval() function. And just like other said. If you still can't get it work. Please put your example code then we can help you.


问:
scroll to bottom doesn't work in componentDidMount react
What's wrong with my code? I don't see the scroll happening, no error. Perhaps props came after the scroll happens? </p>

```<code>class MsgPanel extends Component {

    componentDidMount() {
        window.scrollTo(0, 0) // won't work
    }

    render() {
        return(
            <div>
                {this.props.something}
            </div>
        )
    }
}
</code>```

答:
window.scrollTo(0, 0) is the top of the page, if you want it to scroll to the bottom of the page then you need to increase the value of the second argument.

```<code>window.scrollTo(0, 500);
</code>```

Ok, so that was not the problem. If you are using react-router you could do it on the Route.

```<code><Route exact onUpdate={() => window.scrollTo(0, 0)} path="/mycomponent" component={MyComponent} />
</code>```

Check out the discussion here: https://github.com/ReactTraining/react-router/issues/2144

Also, make sure your css it ok: JavaScript scrollTo method does nothing?

Body:
What's wrong with my code? I don't see the scroll happening, no error. Perhaps props came after the scroll happens?

class MsgPanel extends Component {

    componentDidMount() {
        window.scrollTo(0, 0) // won't work
    }

    render() {
        return(

                {this.props.something}

        )
    }
}

Body:
window.scrollTo(0, 0) is the top of the page, if you want it to scroll to the bottom of the page then you need to increase the value of the second argument.

window.scrollTo(0, 500);

Ok, so that was not the problem. If you are using react-router you could do it on the Route.

<Route exact onUpdate={() => window.scrollTo(0, 0)} path="/mycomponent" component={MyComponent} />

Check out the discussion here: https://github.com/ReactTraining/react-router/issues/2144

Also, make sure your css it ok: JavaScript scrollTo method does nothing?


问:
Spring Integration SFTP code getting called twice
I am trying basic spring integration to download file from SFTP.
Below is a code. The issue is that service-activator gets called twice.

In short, if you see the log, the log's in FileListener bean get called twice and also the com.jcraft.jsch logs
get logged twice, if feel there are two sessions and hence my program is getting executed twice.

Please suggest.

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jms="http://www.springframework.org/schema/jms" xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms.xsd
        http://www.springframework.org/schema/integration/sftp
        http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd">

    <bean id="sftpSessionFactory"
        class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="11.222.333.44" />
        <property name="user" value="*****" />
        <property name="password" value="******"></property>
        <property name="allowUnknownKeys" value="true" />
    </bean>

    <int-sftp:inbound-channel-adapter id="sftpadapter"
        auto-startup="true" session-factory="sftpSessionFactory"
        channel="requestChannel" filename-pattern="*.csv" remote-directory="/someDirectory/"
        local-directory="D:\\somelocalDirectory\\"
        auto-create-local-directory="true" delete-remote-files="false">
    </int-sftp:inbound-channel-adapter>

    <int:channel id="requestChannel">
        <int:queue />
    </int:channel>

    <int:service-activator input-channel="requestChannel"
        ref="FileListener" method="handle" />

    <int:poller id="defaultpoller" default="true" fixed-rate="10000"
        max-messages-per-poll="1"></int:poller>

    <bean id="FileListener" class="com.somePackage.FileListener">
    </bean>
</code>```

ANd the java code is as simple as this.

```<code>public class InboundFileListener2 {

    private static Log logger = LogFactory.getLog(InboundFileListener2.class);

    public void handle(Message<?> message) {
        String someId = null;
        String fileName = null;

        try {

            someId = UUID.randomUUID().toString();
            fileName = getFilename(message);

            logger.debug(" CorrelationId : "
                    + someId + " FileName is : " + fileName);
</code>```

Below is the log.

```<code> SomeId : a77b2bc4-b874-40e7-998d-6ca17aeec196 FileName is : somefile_05032017142503.csv
 SomeId : c50a95e9-83f5-4bb8-a3d9-15da0ff553ee FileName is : somefile_05032017142503.csv
Connecting to 11.222.333.44 port 22
Connecting to 11.222.333.44 port 22
Connection established
Connection established
aes256-ctr is not available.
aes192-ctr is not available.
aes256-cbc is not available.
aes192-cbc is not available.
</code>```

UPDATED:

web.xml

```<code><web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>some-name</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
</code>```

答:
Commenting below code from web.xml fixed the issue.

```<code><servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
</code>```

But I am not sure why it happened, if webcontext is just an extension to root context to load just resources for web other than root scope, either of them should load the sftp adapter and initialize it rather than both of then initializing it..... Can some please explain....

Body:
I am trying basic spring integration to download file from SFTP.
Below is a code. The issue is that service-activator gets called twice.

In short, if you see the log, the log's in FileListener bean get called twice and also the com.jcraft.jsch logs
get logged twice, if feel there are two sessions and hence my program is getting executed twice.

Please suggest.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jms="http://www.springframework.org/schema/jms" xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms.xsd
        http://www.springframework.org/schema/integration/sftp
        http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd">

    <bean id="sftpSessionFactory"
        class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="11.222.333.44" />
        <property name="user" value="*****" />
        <property name="password" value="******"></property>
        <property name="allowUnknownKeys" value="true" />
    </bean>

    <int-sftp:inbound-channel-adapter id="sftpadapter"
        auto-startup="true" session-factory="sftpSessionFactory"
        channel="requestChannel" filename-pattern="*.csv" remote-directory="/someDirectory/"
        local-directory="D:\\somelocalDirectory\\"
        auto-create-local-directory="true" delete-remote-files="false">
    </int-sftp:inbound-channel-adapter>

    <int:channel id="requestChannel">
        <int:queue />
    </int:channel>

    <int:service-activator input-channel="requestChannel"
        ref="FileListener" method="handle" />

    <int:poller id="defaultpoller" default="true" fixed-rate="10000"
        max-messages-per-poll="1"></int:poller>

    <bean id="FileListener" class="com.somePackage.FileListener">
    </bean>

ANd the java code is as simple as this.

public class InboundFileListener2 {

    private static Log logger = LogFactory.getLog(InboundFileListener2.class);

    public void handle(Message<?> message) {
        String someId = null;
        String fileName = null;

        try {

            someId = UUID.randomUUID().toString();
            fileName = getFilename(message);

            logger.debug(" CorrelationId : "
                    + someId + " FileName is : " + fileName);

Below is the log.

 SomeId : a77b2bc4-b874-40e7-998d-6ca17aeec196 FileName is : somefile_05032017142503.csv
 SomeId : c50a95e9-83f5-4bb8-a3d9-15da0ff553ee FileName is : somefile_05032017142503.csv
Connecting to 11.222.333.44 port 22
Connecting to 11.222.333.44 port 22
Connection established
Connection established
aes256-ctr is not available.
aes192-ctr is not available.
aes256-cbc is not available.
aes192-cbc is not available.

UPDATED:

web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>some-name</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

Body:
Commenting below code from web.xml fixed the issue.

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

But I am not sure why it happened, if webcontext is just an extension to root context to load just resources for web other than root scope, either of them should load the sftp adapter and initialize it rather than both of then initializing it..... Can some please explain....


答:
I think error is here:
error: ci:=p(1+r/100)**n;
correct:  ci:=p*(1+r/100)**n;</p>

Title: Statement ignored 14/13 PLS-00222: no function with name 'P' exists in this scope


问:
Avoiding repetition in Django class-based view
I am writing a web application in Django, which is used in a particular way. Instead of using models stored in a database, it builds forms dynamically from JSON data gathered from another application and platform using REST API.

The web page renders a form, which displays a list of mathematical parameters and their values. The user can then change (or not) those values and press a "Run" button to display some calculation results.

The forms are built from data obtained by querying JSON data via a URL (which gives me the list of parameters and their initial values). By specification, I have to use Django and do not use the database to store any parameter value data (the only data which are stored are the URL addresses of the JSON data).

I ended up with some working solution, using CBV. I have a DetailedView, of that structure:

```<code>class SimulationView(DetailView):
    template_name='template.html'
    model=SimModel # provides URLs for REST API (URLs for querying parameter list and simulation function)

    # this is used to display the page with GET
    def get_context_data(self, **kwargs):
        # conn.request function that returns param_JSON in JSON/REST
        # for a SUBSET of parameters in param_JSON build a list of entries named init_entries. Note not all parameters from the JSON request are used for the user interface.
        # form = paramForm(initial=init_entries) and store in context['form']
        return context

    def post(self, request, *args, **kwargs):
        # because the user may have changed parameter values, need to rebuild the JSON dataset to return to the URL with a simulation request
        # conn.request function that returns param_list in JSON/REST
        # for each param in JSON param_list build a list of entries
        # form = paramForm(request.POST, request.FILES, initial=init_entries) and store in context['form']
        # use form data to build REST request for the simulation function
        # conn.request simulation function and get result in JSON
        # store result in context['result']
        return render(request, 'template.html', context)
</code>```

template.html is reponsible to display both the initial form when doing a GET, and the results as well when doing a POST.

As you can see, there is a performance issue. When you do GET to build the page, you have to do the REST connection to get the data and build the form and interface (this is normal). But when you POST to request simulation, you need to run the URL connection again to get the parameter list in JSON format, change the values, and then request simulation results. Please note that the REST request returns many more parameters than the one displayed to the user, hence it is not possible to use only the form data to build a proper JSON request. This works, but is inefficient. I tried to store param_JSON in a field of the class, but this does not work: the class is instanciated again when doing a POST, and param_JSON values are lost.

Do I need a get function? Or am I doing it totally wrong? In general, is there a better way? Thanks a lot in adavance for your suggestions.

答: I am going back to my original question. I was wondering if the best solution was to use AJAX? I render the form once when user accesses the page via GET, and then POST calls are processed with AJAX, which only updates the result part of the page (graphs, table) without rendering the form again. Does that sound a reasonable solution?</p>

Body:
I am writing a web application in Django, which is used in a particular way. Instead of using models stored in a database, it builds forms dynamically from JSON data gathered from another application and platform using REST API.

The web page renders a form, which displays a list of mathematical parameters and their values. The user can then change (or not) those values and press a "Run" button to display some calculation results.

The forms are built from data obtained by querying JSON data via a URL (which gives me the list of parameters and their initial values). By specification, I have to use Django and do not use the database to store any parameter value data (the only data which are stored are the URL addresses of the JSON data).

I ended up with some working solution, using CBV. I have a DetailedView, of that structure:

class SimulationView(DetailView):
    template_name='template.html'
    model=SimModel # provides URLs for REST API (URLs for querying parameter list and simulation function)

    # this is used to display the page with GET
    def get_context_data(self, **kwargs):
        # conn.request function that returns param_JSON in JSON/REST
        # for a SUBSET of parameters in param_JSON build a list of entries named init_entries. Note not all parameters from the JSON request are used for the user interface.
        # form = paramForm(initial=init_entries) and store in context['form']
        return context

    def post(self, request, *args, **kwargs):
        # because the user may have changed parameter values, need to rebuild the JSON dataset to return to the URL with a simulation request
        # conn.request function that returns param_list in JSON/REST
        # for each param in JSON param_list build a list of entries
        # form = paramForm(request.POST, request.FILES, initial=init_entries) and store in context['form']
        # use form data to build REST request for the simulation function
        # conn.request simulation function and get result in JSON
        # store result in context['result']
        return render(request, 'template.html', context)

template.html is reponsible to display both the initial form when doing a GET, and the results as well when doing a POST.

As you can see, there is a performance issue. When you do GET to build the page, you have to do the REST connection to get the data and build the form and interface (this is normal). But when you POST to request simulation, you need to run the URL connection again to get the parameter list in JSON format, change the values, and then request simulation results. Please note that the REST request returns many more parameters than the one displayed to the user, hence it is not possible to use only the form data to build a proper JSON request. This works, but is inefficient. I tried to store param_JSON in a field of the class, but this does not work: the class is instanciated again when doing a POST, and param_JSON values are lost.

Do I need a get function? Or am I doing it totally wrong? In general, is there a better way? Thanks a lot in adavance for your suggestions.


问:
Upload progress with RxJava, Retrofit
In my project, I'm using MVP design pattern, RxJava,RxAndroid and Retrofit for consuming the API calls. Currently I am looking for solutions for trying to display an upload progress while I'm sending a picture. I have seen a couple of possible implementations, but I am afraid they do not fit within my implementation. Here's how I consume the API call with the libraries I mentioned:

```<code>Subscription subscription = mApiService.modVideoFromVideoController(userHash, videoId, publicVideo, rate)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ModifyVideoResponse>() {
                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "modVideo onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, e.getMessage());
                        Crashlytics.logException(e);
                    }

                    @Override
                    public void onNext(ModifyVideoResponse modifyVideoResponse) {
                        mVideosPresenter.onVideoEdited(position, publicVideo);
                    }
                });
        mCompositeSubscription.add(subscription);
</code>```

Is there a way to achieve this?

答:
The best way to achieve this is use Side Effects methods.

For progress view hide/show:

Bind this two events with doOnSubscribe() and doFinally().
This are two operators, so we can logically bind them with RxCall.

doOnSubscribe() will be called, when you are attached to Subscriber.

and

doFinaly() will be called at the end. In any cases Success or Error.

Title: Upload progress with RxJava, Retrofit

Body:
In my project, I'm using MVP design pattern, RxJava,RxAndroid and Retrofit for consuming the API calls. Currently I am looking for solutions for trying to display an upload progress while I'm sending a picture. I have seen a couple of possible implementations, but I am afraid they do not fit within my implementation. Here's how I consume the API call with the libraries I mentioned:

Subscription subscription = mApiService.modVideoFromVideoController(userHash, videoId, publicVideo, rate)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ModifyVideoResponse>() {
                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "modVideo onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, e.getMessage());
                        Crashlytics.logException(e);
                    }

                    @Override
                    public void onNext(ModifyVideoResponse modifyVideoResponse) {
                        mVideosPresenter.onVideoEdited(position, publicVideo);
                    }
                });
        mCompositeSubscription.add(subscription);

Is there a way to achieve this?


问:
Connect multiple 360 images using Google Street View Publish API
Using batchUpadte method, I'm trying to connect multiple 360 images from the source image.

e.g. Below is my python request for batchUpdate method:

```<code>update_photo_url = 'https://streetviewpublish.googleapis.com/v1/photos:batchUpdate'

headers = {"Authorization": "Bearer {}".format("ya29.Glx6BO91jWbj...."), "Content-Length": "0", "Content-Type": "application/json"}

update_body = {
  "updatePhotoRequests": [
    {
      "updateMask": "connections",
      "photo": {
        "photoId": {
          "id": "image_1"
        },
        "connections": [
          {
            "target": {
              "id": "image_2"
            }
          },
          {
            "target": {
              "id": "image_3"
            }
          }
        ]
      }
    },
    {
      "updateMask": "connections",
      "photo": {
        "photoId": {
          "id": "image_3"
        },
        "connections": [
          {
            "target": {
              "id": "image_4"
            }
          }
        ]
      }
    }
  ]
}
update_response = requests.post(update_photo_url,headers=headers,json=update_body)
update_response.text
</code>```

After sending this request, I'm getting status 200 OK but there is one problem, I have four images. I'm making connection between images as in:

```<code>image_1 -> image_2, image_3
image_3 -> image_4
</code>```

Using above code, I'm able to go from image_2 -> image_1, image_1 -> image_3, image_3 -> image_1, image_3 -> image_4 and image_4 -> image_3 but   why I'm unable to go from image_1 -> image_2?

Please help me to resolve this issue. Can anybody tell, what is wrong in my request?

答: Have you checked the connections in the mobile Street View app or the browser? The browser sometimes adds or looses connections, but I have found the mobile App to be the best way to see the "ground truth" that is stored on Googles servers.</p>

Body:
Using batchUpadte method, I'm trying to connect multiple 360 images from the source image.

e.g. Below is my python request for batchUpdate method:

update_photo_url = 'https://streetviewpublish.googleapis.com/v1/photos:batchUpdate'

headers = {"Authorization": "Bearer {}".format("ya29.Glx6BO91jWbj...."), "Content-Length": "0", "Content-Type": "application/json"}

update_body = {
  "updatePhotoRequests": [
    {
      "updateMask": "connections",
      "photo": {
        "photoId": {
          "id": "image_1"
        },
        "connections": [
          {
            "target": {
              "id": "image_2"
            }
          },
          {
            "target": {
              "id": "image_3"
            }
          }
        ]
      }
    },
    {
      "updateMask": "connections",
      "photo": {
        "photoId": {
          "id": "image_3"
        },
        "connections": [
          {
            "target": {
              "id": "image_4"
            }
          }
        ]
      }
    }
  ]
}
update_response = requests.post(update_photo_url,headers=headers,json=update_body)
update_response.text

After sending this request, I'm getting status 200 OK but there is one problem, I have four images. I'm making connection between images as in:

image_1 -> image_2, image_3
image_3 -> image_4

Using above code, I'm able to go from image_2 -> image_1, image_1 -> image_3, image_3 -> image_1, image_3 -> image_4 and image_4 -> image_3 but   why I'm unable to go from image_1 -> image_2?

Please help me to resolve this issue. Can anybody tell, what is wrong in my request?