问:
rhtml (eruby) apache trouble
I am trying to run embedded ruby inside rhtml.

```<code>$cat test.rhtml

<html>
<body>
Testing <% foo = "Ruby"; print "#{foo}!" %>
</body>
</html>
</code>```

It works fine from the command line:

```<code>$eruby test.rhtml

<html>
<body>
Testing Ruby!
</body>
</html>
</code>```

But inside my apache setup it doesn't work.

Accessing "http://localhost/cgi-bin/test.rhtml" gives following error:

"Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, you@example.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log."

Error log says:

[Sat Jan 22 17:56:07 2011] [error] [client ::1] (8)Exec format error: exec of 'Dir/cgi-bin/test.rhtml' failed
[Sat Jan 22 17:56:07 2011] [error] [client ::1] Premature end of script headers: test.rhtml

I have copied "eruby" executable to "Dir/cgi-bin/" directory and configured apache (2.2) as follows:

```<code>AddType application/x-httpd-eruby .rhtml
Action application/x-httpd-eruby Dir/cgi-bin/eruby
</code>```

Any ideas? Thanks!

答:
You probably need to add, at a minimum,

```<code>Content-type: text/html

<html>
....
</code>```

at the top of your eruby file -- CGI scripts are responsible for sending back headers to the client before the content. There may be more headers that make sense to send back, but this might be sufficient to get started.

Title: rhtml (eruby) apache trouble

Body:
I am trying to run embedded ruby inside rhtml.

$cat test.rhtml

Testing <% foo = "Ruby"; print "#{foo}!" %>

It works fine from the command line:

$eruby test.rhtml

Testing Ruby!

But inside my apache setup it doesn't work.

Accessing "http://localhost/cgi-bin/test.rhtml" gives following error:

"Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, you@example.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log."

Error log says:

[Sat Jan 22 17:56:07 2011] [error] [client ::1] (8)Exec format error: exec of 'Dir/cgi-bin/test.rhtml' failed
[Sat Jan 22 17:56:07 2011] [error] [client ::1] Premature end of script headers: test.rhtml

I have copied "eruby" executable to "Dir/cgi-bin/" directory and configured apache (2.2) as follows:

AddType application/x-httpd-eruby .rhtml
Action application/x-httpd-eruby Dir/cgi-bin/eruby

Any ideas? Thanks!

Body:
You probably need to add, at a minimum,

Content-type: text/html

<html>
....

at the top of your eruby file -- CGI scripts are responsible for sending back headers to the client before the content. There may be more headers that make sense to send back, but this might be sufficient to get started.


来源: stackexchange

问:
Adding minutes to the publish time in wordpresss
I'm trying to make the time to be set 10 minutes after the publish time. here is the code i use but it just gives me the publish time in results.

```<code>$convertedTime = get_the_time('H:i',$post->ID,strtotime('+10 minutes'));
echo get_the_date('m/d/Y ', $post->ID);
echo $convertedTime;
</code>```

I also tried something like this but no results

```<code>$minutesTimer = get_the_time('H:i', $post->ID);
$cenvertedTime = time('H:i',strtotime('+10 minutes',strtotime($minutesTimer))
</code>```

Any Idea guys?

答:
First off, get_the_time() only accepts two arguments so passing more won't affect the output.

Get the post time in unix timestamp first and it's much easier;

```<code>// The offset in seconds
$offset = 60 * 10;

// 'U' gets the time as unix timestamp
$timestamp = get_the_time('U', $post->ID);

// Format the time and add the offset
$date = date('H:i', $timestamp + $offset);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make the time to be set 10 minutes after the publish time. here is the code i use but it just gives me the publish time in results.

$convertedTime = get_the_time('H:i',$post->ID,strtotime('+10 minutes'));
echo get_the_date('m/d/Y ', $post->ID);
echo $convertedTime;

I also tried something like this but no results

$minutesTimer = get_the_time('H:i', $post->ID);
$cenvertedTime = time('H:i',strtotime('+10 minutes',strtotime($minutesTimer))

Any Idea guys?

Body:
First off, get_the_time() only accepts two arguments so passing more won't affect the output.

Get the post time in unix timestamp first and it's much easier;

// The offset in seconds
$offset = 60 * 10;

// 'U' gets the time as unix timestamp
$timestamp = get_the_time('U', $post->ID);

// Format the time and add the offset
$date = date('H:i', $timestamp + $offset);


问:
How to get the country code from Google Places API
I am trying to use HTML 5 GeoLocation to get longitude and latitude and then use Google Maps API to get the country code of that longitude/latitude. Is there any simpler way to get country code from google places api?

I found the solution from this link ==> Getting country code from Google Maps and HTML 5 GeoLocation
to get the country code.

Is there way to get country code directly from google places api without getting latitude and longitude first and then passing to google maps api.

This is the following script that I am using to get the country code from google places api

```<code><script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
 // location types.
  autocomplete = new google.maps.places.Autocomplete(
  /** @type {!HTMLInputElement}     */(document.getElementById('autocomplete')),
  {types: ['(cities)']});

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  //autocomplete.addListener('place_changed', fillInAddress);

// Get Latitude and longitude

  google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        //document.getElementById('city2').value = place.name;
        document.getElementById('lat').value = place.geometry.location.lat();
        document.getElementById('lng').value = place.geometry.location.lng();

    });
}

// [START region_fillform]
function fillInAddress() {
 // Get the place details from the autocomplete object.
 var place = autocomplete.getPlace();

  for (var component in componentForm) {
   document.getElementById(component).value = '';
   document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
 // and fill the corresponding field on the form.
 for (var i = 0; i < place.address_components.length; i++) {
   var addressType = place.address_components[i].types[0];
   if (componentForm[addressType]) {
    var val = place.address_components[i][componentForm[addressType]];
    document.getElementById(addressType).value = val;
  }
  }
  }
  // [END region_fillform]

</script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&callback=initAutocomplete"
    async defer></script>
</code>```

答:
```<code><?php
$address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address)
$prepAddr = str_replace(' ','+',$address);

$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=AIzaSyDUpz-WEZ7r24PPkGKEuyqBd9VsPPVPcQk&sensor=false');
$output= json_decode($geocode);

if ( isset($output->results) ) {
    if ( isset($output->results[0]) ) {
        if ( isset($output->results[0]->address_components) ) {
            foreach ($output->results[0]->address_components as $key => $value) {
                if ( isset($value->types) ) {
                    if ( isset($value->types[0]) ) {
                        if($value->types[0] == 'country'){
                            print_r($value->short_name); //GB
                        }
                    }
                }
            }
        }
    }
} ?>
</code>```


问:
how to keep a delay line by line in web browser
hi i want to keep a delay to line by line for 5 seconds .
I used following code but it is not working.

```<code> private void button3_Click(object sender, System.EventArgs e)
 {
        textBox4.Text = textBox3.Text;
        string[] groups = textBox4.Text.Split('\n');

        webBrowser1.Navigate("https://mbasic.facebook.com/groups/516524655403741");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/548734261950831");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/202669939887242");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/259531940895144");
        Thread.Sleep(5000);
}
</code>```

After executing this code. it got 20 seconds to redirect to last website...

But i want to run all website within 5 seconds to 5 seconds..
Please fix my issue.

答:
The problem is not the webbrowser client you are using. The problem is that you are blocking the "GUI thread" by a total of 20 seconds. During these 20 seconds now GUI updates will take place until your button3_Click() method finishes.

Rewrite your code that a different thread is executing the Sleep() and Navigate() methods. You might need to use the Dispatcher.Invoke() method to get access to the "GUI thread" again, when you want to update the GUI from a non-"GUI thread".

Body:
hi i want to keep a delay to line by line for 5 seconds .
I used following code but it is not working.

 private void button3_Click(object sender, System.EventArgs e)
 {
        textBox4.Text = textBox3.Text;
        string[] groups = textBox4.Text.Split('\n');

        webBrowser1.Navigate("https://mbasic.facebook.com/groups/516524655403741");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/548734261950831");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/202669939887242");
        Thread.Sleep(5000);
        webBrowser1.Navigate("https://mbasic.facebook.com/groups/259531940895144");
        Thread.Sleep(5000);
}

After executing this code. it got 20 seconds to redirect to last website...

But i want to run all website within 5 seconds to 5 seconds..
Please fix my issue.


问:
Regex for find accent letters that aren't inside html/jsp comments

Hello I need to find all the accent words that aren't inside comments in jsp files.
By example.

```<code><%--This jsp comment have accents áóéí--%>
<html>
<!--This html comment have accents áóéí-->

<h1>This text have accents áóí</h1>
<html>
</code>```

I need to find the accent letter inside the h1 tag but no the ones inside the comments.

Until now I had the regex to find the comments but I don't know how to negate that part.
This is the Regex I had:

```<code>\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>
</code>```

I try

```<code>[ó](?!(\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>))
</code>```

But it didn't works.

How I could negate that expresion?

答:
If you need to simply delete them, use Notepad++ regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

```<code>(--%?>(?:(?!<%--|<!--).)*?)[^-!~@#$%^&*()+=.,<>|?/{}\[\]\\""';:\w\s]+
</code>```

Replace with:

```<code>$1
</code>```

Repeat that Find-and-Replace until it can't find any more matches.

Otherwise, you can just use that regex to find them and deal with them individually.

Body:
Hello I need to find all the accent words that aren't inside comments in jsp files.
By example.

<%--This jsp comment have accents áóéí--%>

This text have accents áóí

I need to find the accent letter inside the h1 tag but no the ones inside the comments.

Until now I had the regex to find the comments but I don't know how to negate that part.
This is the Regex I had:

\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>

I try

[ó](?!(\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>))

But it didn't works.

How I could negate that expresion?

Body:
If you need to simply delete them, use Notepad++ regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

(--%?>(?:(?!<%--|<!--).)*?)[^-!~@#$%^&*()+=.,<>|?/{}\[\]\\""';:\w\s]+

Replace with:

$1

Repeat that Find-and-Replace until it can't find any more matches.

Otherwise, you can just use that regex to find them and deal with them individually.


问:
NuGet doesn't copy config file
I've tried many different things now, none of which seem to work out as expected.

I would like to share an example config(or image or whatever) file with my library that someone would be able to use and derive from. I tried to default to just To do so I tried to include it in the nuget package via *.nuspec and via *.csproj. None of which worked.

For the *.nuspec part, I've tried this:

```<code><file src="bin\$configuration$\example.mylib.config" target="lib\net45" />
<file src="bin\$configuration$\example.mylib.config" target="build" />
<file src="bin\$configuration$\example.mylib.config" target="bin" />
</code>```

I've also tried this, but that only copies the file to the other projects sources, which is not what I want. I would like it to only show up in the output of the build.

```<code><file src="bin\$configuration$\example.mylib.config" target="content" />
</code>```

For the *.csproj part, I've tried to set the build action of the file to content, resource, embedded resource and None.

Is there a way at all?
Is there a way to tell nuget, take this file, and behave like the dll I'm providing needs this by it's side, wherever you build?

答: One thought might be to perform a config file transformation. Rather than just deploying a config file directly, you could modify the app.config or web.config on the project with a sample for the user to apply. Alternatively, as you mentioned in your comment, you could add in a Powershell script to perform the manipulations you were considering.

Title: NuGet doesn't copy config file

Body:
I've tried many different things now, none of which seem to work out as expected.

I would like to share an example config(or image or whatever) file with my library that someone would be able to use and derive from. I tried to default to just To do so I tried to include it in the nuget package via *.nuspec and via *.csproj. None of which worked.

For the *.nuspec part, I've tried this:

<file src="bin\$configuration$\example.mylib.config" target="lib\net45" />
<file src="bin\$configuration$\example.mylib.config" target="build" />
<file src="bin\$configuration$\example.mylib.config" target="bin" />

I've also tried this, but that only copies the file to the other projects sources, which is not what I want. I would like it to only show up in the output of the build.

<file src="bin\$configuration$\example.mylib.config" target="content" />

For the *.csproj part, I've tried to set the build action of the file to content, resource, embedded resource and None.

Is there a way at all?
Is there a way to tell nuget, take this file, and behave like the dll I'm providing needs this by it's side, wherever you build?


问:
How to parse ant like path
How do I parse paths such as /aaa/bbb/**/*.java as used in ant. I guess I could have looked into the source code. Is there is simple solution.

答: You could use String.split() to split on the path separator character.  You could then iterate through the resulting array to descend through the directory tree.

ContentLicense: CC BY-SA 2.5

Title: How to parse ant like path


问:
In Java, how do I get the difference in seconds between 2 dates?
The Java class library has a class named DateTime. DateTime has this method:

```<code>int daysBetween(DateTime other)
</code>```

which returns the number of days between this and the parameter.
It doesn't have a method

```<code>int secondsBetween(DateTime other)
</code>```

which I happen to need.
Is there a class which is similar to DateTime but has such a method?

答:
I should like to provide the modern answer. The other answers were fine when this question was asked, but time moves on. Today I recommend you use java.time, the modern Java date and time API.

```<code>    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");
</code>```

This prints:

```<code>Difference: 2689 seconds
</code>```

ChronoUnit.SECONDS.between() works with two ZonedDateTime objects or two OffsetDateTimes, two LocalDateTimes, etc.

If you need anything else than just the seconds, you should consider using the Duration class:

```<code>    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");
</code>```

This prints:

```<code>Duration: PT44M49.247S
Difference: 2689 seconds
</code>```

The former of the two lines prints the duration in ISO 8601 format, the output means a duration of 44 minutes and 49.247 seconds.

Why java.time?

The Date class used in several of the other answers is now long outdated. Joda-Time also used in a couple (and possibly in the question) is now in maintenance mode, no major enhancements are planned, and the developers officially recommend migrating to java.time, also known as JSR-310.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.

Body:
The Java class library has a class named DateTime. DateTime has this method:

int daysBetween(DateTime other)

which returns the number of days between this and the parameter.
It doesn't have a method

int secondsBetween(DateTime other)

which I happen to need.
Is there a class which is similar to DateTime but has such a method?

Body:
I should like to provide the modern answer. The other answers were fine when this question was asked, but time moves on. Today I recommend you use java.time, the modern Java date and time API.

    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");

This prints:

Difference: 2689 seconds

ChronoUnit.SECONDS.between() works with two ZonedDateTime objects or two OffsetDateTimes, two LocalDateTimes, etc.

If you need anything else than just the seconds, you should consider using the Duration class:

    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");

This prints:

Duration: PT44M49.247S
Difference: 2689 seconds

The former of the two lines prints the duration in ISO 8601 format, the output means a duration of 44 minutes and 49.247 seconds.

Why java.time?

The Date class used in several of the other answers is now long outdated. Joda-Time also used in a couple (and possibly in the question) is now in maintenance mode, no major enhancements are planned, and the developers officially recommend migrating to java.time, also known as JSR-310.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.


问:
How to set up a colormap from white to green with n shades
I want to set up a Matlab colormap from white (min values) to green (max values) with any number of shades.
I think about a colormap similiar to the summer preset but reversed and with a white edge instead of the yellow one.</p>

答:
```<code>c = [zeros(64,1)        linspace(0,1,64)'  zeros(64,1);         % black to green
     linspace(0,1,64)'  ones(64,1)         linspace(0,1,64)'];  % green to white

surf(peaks);
colormap(c);
</code>```


问:
bigquery: Expression 'f0_' is not present in the GROUP BY list
I'd like to count the instances of some field values appearing in some lat/lon point. Lat/Lon are strings, so I cast them to float, and then round them to 1m (5 decimal places).

```<code>SELECT
  concat(ROUND(FLOAT(lat), 5),
    ROUND(FLOAT(lon), 5)),
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY
  lat,
  lon,
  fcount;
</code>```

I would like to have, as results, the for each lat/lon concatenation, the number of times some value appears in the values of "field".

My output should look like the following tuples:

```<code>  lat    lon  field fcount
12.34  12.38      A     23
12.34  12.38      B     11
12.34  12.38      C     23
11.34  12.38      A     15
...
</code>```

The query above gives me a Expression 'f0_' is not present in the GROUP BY list error in BigQuery. But if I put it in, it says: cannot group by an aggregate. I'd like some help in building this query.

答:
For your query to work you should try as below  (looks like you use BigQuery Legacy SQL - so below is in Legacy SQL)

```<code>#legacySQL
SELECT
  CONCAT(STRING(ROUND(FLOAT(lat), 5)),
    STRING(ROUND(FLOAT(lon), 5))) as latlong,
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY 1
</code>```

of course, in no way it returns what then you said you expect your query to return

for this you should try below

```<code>#legacySQL
SELECT
  ROUND(FLOAT(lat), 5) lat,
  ROUND(FLOAT(lon), 5) lon,
  field,
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY 1, 2, 3
</code>```

Body:
I'd like to count the instances of some field values appearing in some lat/lon point. Lat/Lon are strings, so I cast them to float, and then round them to 1m (5 decimal places).

SELECT
  concat(ROUND(FLOAT(lat), 5),
    ROUND(FLOAT(lon), 5)),
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY
  lat,
  lon,
  fcount;

I would like to have, as results, the for each lat/lon concatenation, the number of times some value appears in the values of "field".

My output should look like the following tuples:

  lat    lon  field fcount
12.34  12.38      A     23
12.34  12.38      B     11
12.34  12.38      C     23
11.34  12.38      A     15
...

The query above gives me a Expression 'f0_' is not present in the GROUP BY list error in BigQuery. But if I put it in, it says: cannot group by an aggregate. I'd like some help in building this query.

Body:
For your query to work you should try as below  (looks like you use BigQuery Legacy SQL - so below is in Legacy SQL)

#legacySQL
SELECT
  CONCAT(STRING(ROUND(FLOAT(lat), 5)),
    STRING(ROUND(FLOAT(lon), 5))) as latlong,
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY 1

of course, in no way it returns what then you said you expect your query to return

for this you should try below

#legacySQL
SELECT
  ROUND(FLOAT(lat), 5) lat,
  ROUND(FLOAT(lon), 5) lon,
  field,
  COUNT(field) AS fcount
FROM
  MyTable
GROUP BY 1, 2, 3


问:
In perl, when assigning a subroutine's return value to a variable, is the data duplicated in memory?
```<code>sub foo {
    my @return_value = (1, 2);
}
my @receiver = foo();
</code>```

Is this assigning like any other assigning in perl? the array is duplicated in memory? I doubt this cause of that since the array held by the subroutine is disposable, a duplication is totally redundant. it makes sense to just 'link' the array to @receiver for optimization reason.

by the way, I noticed a similar question Perl: function returns reference or copy? but didn't get what I want.

and I'm talking about Perl5

ps. any books or materials on such sort of topics about perl?

答:
The scalars returned by :lvalue subs aren't copied.

The scalars returned by XS subs aren't copied.

The scalars returned by function (named operators) aren't copied.

The scalars returned by other subs are copied.

But that's before any assignment comes into play. If you assign the returned values to a variable, you will be copying them (again, in the case of a normal Perl sub).

This means my $y = sub { $x }->(); copies $x twice!

But that doesn't really matter because of optimizations.

Let's start with an example of when they aren't copied.

```<code>$ perl -le'
    sub f :lvalue { my $x = 123; print \$x; $x }
    my $r = \f();
    print $r;
'
SCALAR(0x465eb48)  # $x
SCALAR(0x465eb48)  # The scalar on the stack
</code>```

But if you remove :lvalue...

```<code>$ perl -le'
    sub f { my $x = 123; print \$x; $x }
    my $r = \f();
    print $r;
'
SCALAR(0x17d0918)  # $x
SCALAR(0x17b1ec0)  # The scalar on the stack
</code>```

Worse, one usually follows up by assigning the scalar to a variable, so a second copy occurs.

```<code>$ perl -le'
    sub f { my $x = 123; print \$x; $x }
    my $r = \f();   # \
    print $r;       #  > my $y = f();
    my $y = $$r;    # /
    print \$y;
'
SCALAR(0x1802958)  # $x
SCALAR(0x17e3eb0)  # The scalar on the stack
SCALAR(0x18028f8)  # $y
</code>```

On the plus side, assignment in optimized to minimize the cost of copying strings.

XS subs and functions (named operators) typically return mortal ("TEMP") scalars. These are scalars "on death row". They will be automatically destroyed if nothing steps in to claim a reference to them.

In older versions of Perl (<5.20), assigning a mortal string to another scalar will cause ownership of the string buffer to be transferred to avoid having to copy the string buffer. For example, my $y = lc($x); doesn't copy the string created by lc; simply the string pointer is copied.

```<code>$ perl -MDevel::Peek -e'my $s = "abc"; Dump($s); $s = lc($s); Dump($s);'
SV = PV(0x1705840) at 0x1723768
  REFCNT = 1
  FLAGS = (PADMY,POK,IsCOW,pPOK)
  PV = 0x172d4c0 "abc"\0
  CUR = 3
  LEN = 10
  COW_REFCNT = 1
SV = PV(0x1705840) at 0x1723768
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x1730070 "abc"\0     <-- Note the change of address from stealing
  CUR = 3                        the buffer from the scalar returned by lc.
  LEN = 10
</code>```

In newer versions of Perl (≥5.20), the assignment operator never[1] copies the string buffer. Instead, newer versions of Perl uses a copy-on-write ("COW") mechanism.

```<code>$ perl -MDevel::Peek -e'my $x = "abc"; my $y = $x; Dump($x); Dump($y);'
SV = PV(0x26b0530) at 0x26ce230
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0x26d68a0 "abc"\0            <----+
  CUR = 3                                |
  LEN = 10                               |
  COW_REFCNT = 2                         +-- Same buffer (0x26d68a0)
SV = PV(0x26b05c0) at 0x26ce248          |
  REFCNT = 1                             |
  FLAGS = (POK,IsCOW,pPOK)               |
  PV = 0x26d68a0 "abc"\0            <----+
  CUR = 3
  LEN = 10
  COW_REFCNT = 2
</code>```

Ok, so far, I've only talked about scalars. Well, that's because subs and functions can only return scalars[2].

In your example, the scalar assigned to @return_value would be returned[3], copied, then copied a second time into @receiver by the assignment.

You could avoid all of this by returning a reference to the array.

```<code>sub f { my @fizbobs = ...; \@fizbobs }
my $fizbobs = f();
</code>```

The only thing copied there is a reference, the simplest non-undefined scalar.

Ok, maybe not never. I think there needs to be a free byte in the string buffer to hold the COW count.

In list context, they can return 0, 1 or many of them, but they can only return scalars.

The last operator of your sub is a list assignment operator. In list context, the list assignment operator returns the scalars to which its left-hand side (LHS) evaluates. See Scalar vs List Assignment Operator for more info.

ContentLicense: CC BY-SA 4.0

Body:
sub foo {
    my @return_value = (1, 2);
}
my @receiver = foo();

Is this assigning like any other assigning in perl? the array is duplicated in memory? I doubt this cause of that since the array held by the subroutine is disposable, a duplication is totally redundant. it makes sense to just 'link' the array to @receiver for optimization reason.

by the way, I noticed a similar question Perl: function returns reference or copy? but didn't get what I want.

and I'm talking about Perl5

ps. any books or materials on such sort of topics about perl?

Body:
The scalars returned by :lvalue subs aren't copied.

The scalars returned by XS subs aren't copied.

The scalars returned by function (named operators) aren't copied.

The scalars returned by other subs are copied.

But that's before any assignment comes into play. If you assign the returned values to a variable, you will be copying them (again, in the case of a normal Perl sub).

This means my $y = sub { $x }->(); copies $x twice!

But that doesn't really matter because of optimizations.

Let's start with an example of when they aren't copied.

$ perl -le'
    sub f :lvalue { my $x = 123; print \$x; $x }
    my $r = \f();
    print $r;
'
SCALAR(0x465eb48)  # $x
SCALAR(0x465eb48)  # The scalar on the stack

But if you remove :lvalue...

$ perl -le'
    sub f { my $x = 123; print \$x; $x }
    my $r = \f();
    print $r;
'
SCALAR(0x17d0918)  # $x
SCALAR(0x17b1ec0)  # The scalar on the stack

Worse, one usually follows up by assigning the scalar to a variable, so a second copy occurs.

$ perl -le'
    sub f { my $x = 123; print \$x; $x }
    my $r = \f();   # \
    print $r;       #  > my $y = f();
    my $y = $$r;    # /
    print \$y;
'
SCALAR(0x1802958)  # $x
SCALAR(0x17e3eb0)  # The scalar on the stack
SCALAR(0x18028f8)  # $y

On the plus side, assignment in optimized to minimize the cost of copying strings.

XS subs and functions (named operators) typically return mortal ("TEMP") scalars. These are scalars "on death row". They will be automatically destroyed if nothing steps in to claim a reference to them.

In older versions of Perl (<5.20), assigning a mortal string to another scalar will cause ownership of the string buffer to be transferred to avoid having to copy the string buffer. For example, my $y = lc($x); doesn't copy the string created by lc; simply the string pointer is copied.

$ perl -MDevel::Peek -e'my $s = "abc"; Dump($s); $s = lc($s); Dump($s);'
SV = PV(0x1705840) at 0x1723768
  REFCNT = 1
  FLAGS = (PADMY,POK,IsCOW,pPOK)
  PV = 0x172d4c0 "abc"\0
  CUR = 3
  LEN = 10
  COW_REFCNT = 1
SV = PV(0x1705840) at 0x1723768
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x1730070 "abc"\0     <-- Note the change of address from stealing
  CUR = 3                        the buffer from the scalar returned by lc.
  LEN = 10

In newer versions of Perl (≥5.20), the assignment operator never[1] copies the string buffer. Instead, newer versions of Perl uses a copy-on-write ("COW") mechanism.

$ perl -MDevel::Peek -e'my $x = "abc"; my $y = $x; Dump($x); Dump($y);'
SV = PV(0x26b0530) at 0x26ce230
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK)
  PV = 0x26d68a0 "abc"\0            <----+
  CUR = 3                                |
  LEN = 10                               |
  COW_REFCNT = 2                         +-- Same buffer (0x26d68a0)
SV = PV(0x26b05c0) at 0x26ce248          |
  REFCNT = 1                             |
  FLAGS = (POK,IsCOW,pPOK)               |
  PV = 0x26d68a0 "abc"\0            <----+
  CUR = 3
  LEN = 10
  COW_REFCNT = 2

Ok, so far, I've only talked about scalars. Well, that's because subs and functions can only return scalars[2].

In your example, the scalar assigned to @return_value would be returned[3], copied, then copied a second time into @receiver by the assignment.

You could avoid all of this by returning a reference to the array.

sub f { my @fizbobs = ...; \@fizbobs }
my $fizbobs = f();

The only thing copied there is a reference, the simplest non-undefined scalar.

Ok, maybe not never. I think there needs to be a free byte in the string buffer to hold the COW count.

In list context, they can return 0, 1 or many of them, but they can only return scalars.

The last operator of your sub is a list assignment operator. In list context, the list assignment operator returns the scalars to which its left-hand side (LHS) evaluates. See Scalar vs List Assignment Operator for more info.


问:
MVC project, Error because model not passed to view?
The Scenario is this...I goto the login screen on my web app.  I login with wrong username/password.  I get an error on the line in my HTML for tab-6 @HTML.Partial("../../Account/Register") because the RegisterModel is not passed in(Exact error below).  Well I'm not doing anything with the Register screen, just logging in.

However, I think the problem is because the Register section is always loaded.  So I'm thinking, I don't need to pass in both LogOnModel and RegisterModel, to fix the problem, but maybe should not load the Register page until it is specifically called, I think?  Is that the correct thing to do and how would I load the Register page only when it is called/clicked. I'm using JQuery UI tabs and asp.net mvc.

ERROR:
The model item passed into the dictionary is of type 'Portal.Web.Models.LogOnModel', but this dictionary requires a model item of type 'Portal.Web.Models.RegisterModel'.

Thanks a lot!

```<code><div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all" style=" position:relative; border:0px;"   >
                <ul class="ui-tabs-nav">
                    <li><a href="#tabs-1" >Home</a></li>
                    <li><a href="#tabs-2" >Statistics</a></li>
                    <li><a href="#tabs-3" >Topo Maps</a></li>
                    <li><a href="#tabs-4" >FAQs</a></li>
                    <li style="display:none;"><a href="#tabs-5">Login</a></li>
                    <li style="display:none;"><a href="#tabs-6">SignUp</a></li>
                </ul>
                <div id="tabs-1" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Home/Home") </div>
                <div id="tabs-2" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Statistics/Statistics")</div>
                <div id="tabs-3" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Maps/Maps")</div>
                <div id="tabs-4" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Home/FAQs")</div>
               <div id="tabs-5" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Account/LogOn")</div>
               <div id="tabs-6" class="ui-tabs-hide ui-tabs-panel">@Html.Partial("../Account/Register")</div>

            </div>
</code>```

Here is my AccountController with action method

```<code> [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        return View(model);
    }
</code>```

As Requested Here is the additional code:

```<code>public ActionResult LogOn()
    {
        return View();
    }
</code>```

答:
Double-check that you've set your partial view to inherit from the appropriate model. At the top of your partial view code, you should have a line like this.</p>

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Portal.Web.Models.LogOnModel>" %>
</code>```

Body:
The Scenario is this...I goto the login screen on my web app.  I login with wrong username/password.  I get an error on the line in my HTML for tab-6 @HTML.Partial("../../Account/Register") because the RegisterModel is not passed in(Exact error below).  Well I'm not doing anything with the Register screen, just logging in.

However, I think the problem is because the Register section is always loaded.  So I'm thinking, I don't need to pass in both LogOnModel and RegisterModel, to fix the problem, but maybe should not load the Register page until it is specifically called, I think?  Is that the correct thing to do and how would I load the Register page only when it is called/clicked. I'm using JQuery UI tabs and asp.net mvc.

ERROR:
The model item passed into the dictionary is of type 'Portal.Web.Models.LogOnModel', but this dictionary requires a model item of type 'Portal.Web.Models.RegisterModel'.

Thanks a lot!

Home

Statistics

Topo Maps

FAQs

Login

SignUp

@Html.Partial("../Home/Home")

@Html.Partial("../Statistics/Statistics")

@Html.Partial("../Maps/Maps")

@Html.Partial("../Home/FAQs")

@Html.Partial("../Account/LogOn")

@Html.Partial("../Account/Register")

Here is my AccountController with action method

 [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        return View(model);
    }

As Requested Here is the additional code:

public ActionResult LogOn()
    {
        return View();
    }

Body:
Double-check that you've set your partial view to inherit from the appropriate model. At the top of your partial view code, you should have a line like this.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Portal.Web.Models.LogOnModel>" %>


问:
Java Swing Line Graph
I'm attempting to draw a line graph based on data held in array. I have managed to get the X and Y axis drawn. However when I draw the line with the data onto the graph it does not line up with the X and Y axis values. I am unsure of how this can be fixed. I have shown the code below:

```<code>public void drawLineG(Graphics g, int yCoords[]) {
    String maxY = Integer.toString(getMax(yCoords));
    String minY = Integer.toString(getMin(yCoords));
    String maxX = Double.toString((xInterval * yCoords.length) - xInterval);
    String minX = Double.toString(xStart);

    g.setColor(Color.BLUE);
    int height = (getHeight() / 2);
    int x = 200; // start x point

    // previous coord positions.
    int prevX = x;
    int prevY = yCoords[0];

    g.setColor(Color.BLACK);
    g.drawLine(prevX, getHeight() / 2, 500, getHeight() / 2);
    g.drawLine(prevX, 200, 200, getHeight() / 2);

    g.setColor(Color.BLUE);
    g.drawString(minY, 190, (getHeight() / 2));
    g.drawString(maxY, 180, (getHeight() / 2) - 255);
    g.drawString(yLabel, 140, (getHeight() / 2) - 100);
    g.drawString(minX, 192, (getHeight() / 2) + 20);
    g.drawString(maxX, 500, (getHeight() / 2) + 20);
    g.drawString(xLabel, 350, (getHeight() / 2) + 50);
    for (int y : yCoords) {
        g.setColor(Color.RED);
        g.drawLine(prevX, height - prevY, x, height - y);
        prevX = x;
        prevY = y;

        // add an increment to the X pos.
        x = x + 50;
    }
}
</code>```

The array of data I have been testing contains the values: 0, 3, 4, 7, 5, 10, 3

However when this is plotted on the graph it doesn't line up with the values on the x and y axis.

Current: https://i.stack.imgur.com/Ju8BQ.jpg
What I am trying to achieve: https://i.stack.imgur.com/n9Aio.jpg

Any help?

Thanks

答:
Your problem is your scale, you're trying to draw your yCoords as they're given, (3, 10 and so on) but they should be like: 30, 100 to fit the window's scale (Window = your program window).

For example in my code below, each "square" or each "unit" are of 30 x 30 pixels each, so I must convert yCoord = 3 to it's equivalent which would be 3 * 30 = 90 but as the axis is below starting at 400 I must substract it so I get the coord from the axis or from the bottom of the window to the real yCoord which would be 400 - 90 = 310, now this is my real point that I must paint.

However the painting should be done in the paintComponent method.

For my example I didn't draw the Strings for 0, 10, 0.0, 90.0 but you can do it later if you wish

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphSample {
    private JFrame frame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GraphSample()::createAndShowGui);
    }

    private void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        GraphDrawer drawer = new GraphDrawer(new int[] {0, 3, 4, 7, 5, 10, 3});

        frame.add(drawer);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @SuppressWarnings("serial")
    class GraphDrawer extends JPanel {
        private int[] yCoords;
        private int startX = 100;
        private int startY = 100;
        private int endX = 400;
        private int endY = 400;
        private int unitX = (endX - startX) / 10;
        private int unitY = (endY - startY) / 10;
        private int prevX = startX;
        private int prevY = endY;

        public GraphDrawer(int[] yCoords) {
            this.yCoords = yCoords;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            //We draw in the following 2 loops the grid so it's visible what I explained before about each "unit"
            g2d.setColor(Color.BLUE);
            for (int i = startX; i <= endX; i += unitX) {
                g2d.drawLine(i, startY, i, endY);
            }

            for (int i = startY; i <= endY; i += unitY) {
                g2d.drawLine(startX, i, endX, i);
            }

            //We draw the axis here instead of before because otherwise they would become blue colored.
            g2d.setColor(Color.BLACK);
            g2d.drawLine(startX, startY, startX, endY);
            g2d.drawLine(startX, endY, endX, endY);

            //We draw each of our coords in red color
            g2d.setColor(Color.RED);
            for (int y : yCoords) {
                g2d.drawLine(prevX, prevY, prevX += unitX, prevY = endY - (y * unitY));
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(endX + 100, endY + 100);
        }
    }
}
</code>```

I hope it's clear what the error was.

This is a sample of what the output looks like with a 10 x 10 grid

Title: Java Swing Line Graph

Body:
I'm attempting to draw a line graph based on data held in array. I have managed to get the X and Y axis drawn. However when I draw the line with the data onto the graph it does not line up with the X and Y axis values. I am unsure of how this can be fixed. I have shown the code below:

public void drawLineG(Graphics g, int yCoords[]) {
    String maxY = Integer.toString(getMax(yCoords));
    String minY = Integer.toString(getMin(yCoords));
    String maxX = Double.toString((xInterval * yCoords.length) - xInterval);
    String minX = Double.toString(xStart);

    g.setColor(Color.BLUE);
    int height = (getHeight() / 2);
    int x = 200; // start x point

    // previous coord positions.
    int prevX = x;
    int prevY = yCoords[0];

    g.setColor(Color.BLACK);
    g.drawLine(prevX, getHeight() / 2, 500, getHeight() / 2);
    g.drawLine(prevX, 200, 200, getHeight() / 2);

    g.setColor(Color.BLUE);
    g.drawString(minY, 190, (getHeight() / 2));
    g.drawString(maxY, 180, (getHeight() / 2) - 255);
    g.drawString(yLabel, 140, (getHeight() / 2) - 100);
    g.drawString(minX, 192, (getHeight() / 2) + 20);
    g.drawString(maxX, 500, (getHeight() / 2) + 20);
    g.drawString(xLabel, 350, (getHeight() / 2) + 50);
    for (int y : yCoords) {
        g.setColor(Color.RED);
        g.drawLine(prevX, height - prevY, x, height - y);
        prevX = x;
        prevY = y;

        // add an increment to the X pos.
        x = x + 50;
    }
}

The array of data I have been testing contains the values: 0, 3, 4, 7, 5, 10, 3

However when this is plotted on the graph it doesn't line up with the values on the x and y axis.

Current: https://i.stack.imgur.com/Ju8BQ.jpg
What I am trying to achieve: https://i.stack.imgur.com/n9Aio.jpg

Any help?

Thanks

Body:
Your problem is your scale, you're trying to draw your yCoords as they're given, (3, 10 and so on) but they should be like: 30, 100 to fit the window's scale (Window = your program window).

For example in my code below, each "square" or each "unit" are of 30 x 30 pixels each, so I must convert yCoord = 3 to it's equivalent which would be 3 * 30 = 90 but as the axis is below starting at 400 I must substract it so I get the coord from the axis or from the bottom of the window to the real yCoord which would be 400 - 90 = 310, now this is my real point that I must paint.

However the painting should be done in the paintComponent method.

For my example I didn't draw the Strings for 0, 10, 0.0, 90.0 but you can do it later if you wish

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphSample {
    private JFrame frame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GraphSample()::createAndShowGui);
    }

    private void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        GraphDrawer drawer = new GraphDrawer(new int[] {0, 3, 4, 7, 5, 10, 3});

        frame.add(drawer);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @SuppressWarnings("serial")
    class GraphDrawer extends JPanel {
        private int[] yCoords;
        private int startX = 100;
        private int startY = 100;
        private int endX = 400;
        private int endY = 400;
        private int unitX = (endX - startX) / 10;
        private int unitY = (endY - startY) / 10;
        private int prevX = startX;
        private int prevY = endY;

        public GraphDrawer(int[] yCoords) {
            this.yCoords = yCoords;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            //We draw in the following 2 loops the grid so it's visible what I explained before about each "unit"
            g2d.setColor(Color.BLUE);
            for (int i = startX; i <= endX; i += unitX) {
                g2d.drawLine(i, startY, i, endY);
            }

            for (int i = startY; i <= endY; i += unitY) {
                g2d.drawLine(startX, i, endX, i);
            }

            //We draw the axis here instead of before because otherwise they would become blue colored.
            g2d.setColor(Color.BLACK);
            g2d.drawLine(startX, startY, startX, endY);
            g2d.drawLine(startX, endY, endX, endY);

            //We draw each of our coords in red color
            g2d.setColor(Color.RED);
            for (int y : yCoords) {
                g2d.drawLine(prevX, prevY, prevX += unitX, prevY = endY - (y * unitY));
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(endX + 100, endY + 100);
        }
    }
}

I hope it's clear what the error was.

This is a sample of what the output looks like with a 10 x 10 grid


问:
MySQL Query keep numbers which do not fall between a range
Could anyone point me in the correct direction on how to do this SQL query?  I have two tables coord_table and rm_table.  I would like to perform a query where any coord_table.loc which falls between any rm_table.start_loc or rm_table.end_loc is removed from the result of the query. </p>

```<code>    coord_table
    coord_id    loc
    ____________________
    1           9
    2           19
    3           30
    4           55

    rm_table
    rast_id start_loc   end_loc
    ___________________________
    1       10          20
    2       50          60

    query_result
    coord_id    loc
    _____________
    1           9
    3           30
</code>```

答:
EDIT: This should work. It uses the BETWEEN syntax:

```<code>SELECT a.* FROM coords_table a
LEFT JOIN
  (
  SELECT
    *
  FROM
      (
      SELECT
          coords_id, loc, start_loc, end_loc,
          (loc BETWEEN start_loc AND end_loc) as is_between
      FROM
          coords_table, rm_table
      ) a
  WHERE a.is_between = 1
  ) b
ON a.coords_id = b.coords_id
WHERE b.coords_id IS NULL
</code>```

Fiddle: http://sqlfiddle.com/#!9/3acdb/2

Body:
Could anyone point me in the correct direction on how to do this SQL query?  I have two tables coord_table and rm_table.  I would like to perform a query where any coord_table.loc which falls between any rm_table.start_loc or rm_table.end_loc is removed from the result of the query.

    coord_table
    coord_id    loc
    ____________________
    1           9
    2           19
    3           30
    4           55

    rm_table
    rast_id start_loc   end_loc
    ___________________________
    1       10          20
    2       50          60

    query_result
    coord_id    loc
    _____________
    1           9
    3           30

Body:
EDIT: This should work. It uses the BETWEEN syntax:

SELECT a.* FROM coords_table a
LEFT JOIN
  (
  SELECT
    *
  FROM
      (
      SELECT
          coords_id, loc, start_loc, end_loc,
          (loc BETWEEN start_loc AND end_loc) as is_between
      FROM
          coords_table, rm_table
      ) a
  WHERE a.is_between = 1
  ) b
ON a.coords_id = b.coords_id
WHERE b.coords_id IS NULL

Fiddle: http://sqlfiddle.com/#!9/3acdb/2


问:
Don't drop dimensions when subseting 3-dimensional array
Let A be a 1 x 2 x 2-array:

```<code>> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0
</code>```

Then A[,,1] is dimensionless:

```<code>> A[,,1]
[1] 0 0
</code>```

I would like to have:

```<code>     [,1] [,2]
[1,]    0    0
</code>```

The drop argument does not yield what I want:

```<code>> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0
</code>```

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

答:
Another package solution: the keep package.

```<code>> library(keep)
> A <- karray(0, dim=c(1,2,2))
> A[,,1]
     [,1] [,2]
[1,]    0    0
attr(,"class")
[1] "keep"    "numeric"
</code>```

Body:
Let A be a 1 x 2 x 2-array:

> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0

Then A[,,1] is dimensionless:

> A[,,1]
[1] 0 0

I would like to have:

     [,1] [,2]
[1,]    0    0

The drop argument does not yield what I want:

> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

Body:
Another package solution: the keep package.

> library(keep)
> A <- karray(0, dim=c(1,2,2))
> A[,,1]
     [,1] [,2]
[1,]    0    0
attr(,"class")
[1] "keep"    "numeric"


问:
How to send signal from a children to another children in C?
How can I send a signal form passenger-children to the taxi - children?

I have the following C code:

```<code> passengerPid = fork()
 if(passengerPid) { //passenger-parents

                taxiPid = fork();
                if(taxiPid) { //taxi - parents
                } else { //taxi - children
                }
        }
        else { //passenger - children
        }
</code>```

答:
How can I send a signal form passenger-children to the taxi - children? yes it's possible but question here is how will you get taxi-children pid in passenger-children process ? once you got pid of that taxi-children, for sending signal to one process from another process you can use kill() function. Use any IPC mechanism to sending pid(any int data) of one process to other process.

Here is my Solution, before this go through man page of wait() & waitpid() :

```<code>/**How can I send a signal form passenger-children to the taxi - children? **/
#include<stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
    int passengerPid, taxiPid;
    passengerPid = fork();
    if(passengerPid) { //passenger-parents

        taxiPid = fork();
        if(taxiPid) {
            //taxi - parents

            printf("taxi parents or main parent process : pid = %d ppid = %d\n",getpid(),getppid());
            /** parents should wait until all children's got finish
               use wait() or waitpid() to collect the children's status **/
            int s,ret;
            while((ret = wait(&s))!=-1)//if there is no further child, wait returns
            {
                if(ret == passengerPid) {
                    if(WIFEXITED(s)) {
                    printf("passenger children removed after sleep, status is : %d\n",WEXITSTATUS(s));
                    } else if(WIFSIGNALED(s)) {
                        printf("passenger children removed forcefully because of signal no : %d \n",WTERMSIG(s));
                    }
                } else if(ret == taxiPid) {
                    if(WIFEXITED(s)) {
                    printf("taxi children removed after sleep, status is : %d\n",WEXITSTATUS(s));
                    } else if(WIFSIGNALED(s)) {
                        printf("taxi children removed forcefully because of signal no : %d \n",WTERMSIG(s));
                    }

                }
            }
            printf("all done !! parents is also going to complete \n");
        }
        else {
            //for sending pid of this process

        #if 0
            int fd = open("data",O_WRONLY | 0664);
            if(fd == -1) {
                perror("open");
                return 0;
            }
            int w_pid = getpid();
            write(fd,&w_pid,4);
            close(fd);
        #endif
            //taxi - children
            printf("taxi children : pid = %d ppid = %d\n",getpid(),getppid());
            sleep(10);//random delay to observe whether this process got any signal or not ?
            exit(1);//sends it's exit status to it's parent process whether it's terminated normally or by any external signal
        }
    }
    else {
        //passenger - children
        printf("passenger children : pid = %d ppid = %d\n",getpid(),getppid());
        printf("sending signal from passenger children to taxi children :\n");
        sleep(5);
        int pid;
    #if 0
        int fd = open("data",O_RDONLY | 0664);
        if(fd == -1) {
            perror("open");
            return 0;
        }
        read(fd,&pid,4);
        close(fd);
    #endif
        printf("pid of child received : %d \n",pid);
        kill(pid,SIGKILL);//sending signal no 2 to taxi child, bydefault action of SIGINT will be performed
        perror("kill");
        printf("passenger children dies after sending signal & completion of delay\n");
        exit(0);
    }
}
</code>```

how above code works is explained in comments itself. usage of macro(#if 0) part in both process is for sending pid of that taxi-child process to passenger-child process. Enable the macro for observing the output.

I hope it help's.

Body:
How can I send a signal form passenger-children to the taxi - children?

I have the following C code:

 passengerPid = fork()
 if(passengerPid) { //passenger-parents

                taxiPid = fork();
                if(taxiPid) { //taxi - parents
                } else { //taxi - children
                }
        }
        else { //passenger - children
        }

Body:
How can I send a signal form passenger-children to the taxi - children? yes it's possible but question here is how will you get taxi-children pid in passenger-children process ? once you got pid of that taxi-children, for sending signal to one process from another process you can use kill() function. Use any IPC mechanism to sending pid(any int data) of one process to other process.

Here is my Solution, before this go through man page of wait() & waitpid() :

/**How can I send a signal form passenger-children to the taxi - children? **/
#include<stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
    int passengerPid, taxiPid;
    passengerPid = fork();
    if(passengerPid) { //passenger-parents

        taxiPid = fork();
        if(taxiPid) {
            //taxi - parents

            printf("taxi parents or main parent process : pid = %d ppid = %d\n",getpid(),getppid());
            /** parents should wait until all children's got finish
               use wait() or waitpid() to collect the children's status **/
            int s,ret;
            while((ret = wait(&s))!=-1)//if there is no further child, wait returns
            {
                if(ret == passengerPid) {
                    if(WIFEXITED(s)) {
                    printf("passenger children removed after sleep, status is : %d\n",WEXITSTATUS(s));
                    } else if(WIFSIGNALED(s)) {
                        printf("passenger children removed forcefully because of signal no : %d \n",WTERMSIG(s));
                    }
                } else if(ret == taxiPid) {
                    if(WIFEXITED(s)) {
                    printf("taxi children removed after sleep, status is : %d\n",WEXITSTATUS(s));
                    } else if(WIFSIGNALED(s)) {
                        printf("taxi children removed forcefully because of signal no : %d \n",WTERMSIG(s));
                    }

                }
            }
            printf("all done !! parents is also going to complete \n");
        }
        else {
            //for sending pid of this process

        #if 0
            int fd = open("data",O_WRONLY | 0664);
            if(fd == -1) {
                perror("open");
                return 0;
            }
            int w_pid = getpid();
            write(fd,&w_pid,4);
            close(fd);
        #endif
            //taxi - children
            printf("taxi children : pid = %d ppid = %d\n",getpid(),getppid());
            sleep(10);//random delay to observe whether this process got any signal or not ?
            exit(1);//sends it's exit status to it's parent process whether it's terminated normally or by any external signal
        }
    }
    else {
        //passenger - children
        printf("passenger children : pid = %d ppid = %d\n",getpid(),getppid());
        printf("sending signal from passenger children to taxi children :\n");
        sleep(5);
        int pid;
    #if 0
        int fd = open("data",O_RDONLY | 0664);
        if(fd == -1) {
            perror("open");
            return 0;
        }
        read(fd,&pid,4);
        close(fd);
    #endif
        printf("pid of child received : %d \n",pid);
        kill(pid,SIGKILL);//sending signal no 2 to taxi child, bydefault action of SIGINT will be performed
        perror("kill");
        printf("passenger children dies after sending signal & completion of delay\n");
        exit(0);
    }
}

how above code works is explained in comments itself. usage of macro(#if 0) part in both process is for sending pid of that taxi-child process to passenger-child process. Enable the macro for observing the output.

I hope it help's.


问:
Connection issue with API when using JSON data only in Postman

I'm trying to setup a simple login API using node.js/restify. The code below shows a simple route, with nothing but a console.log() statement within it, as I'm just trying to prove I can gain a connection.

```<code>var restify = require('restify');

var user = require('./user');
var reference = require('./reference');

var fs = require('fs');
var bodyParser = require('body-parser');
var _= require('lodash');

const server = restify.createServer();

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended:false}));

server.use(restify.plugins.fullResponse())
server.use(restify.plugins.bodyParser());
server.use(restify.plugins.queryParser())           server.use(restify.plugins.authorizationParser())

var port = 8080;

server.post('/user/login', (req, res) => {

    console.log("---LOGIN ATTEMPT---");

  res.status(200);
  res.end();

});
</code>```

Using Postman for testing, I expect to get a statement back in the console, stating "LOGIN ATTEMPT".

Postman freezes with the 'Loading' text and stays like that until it crashes saying  'There was an error connecting to localhost:8080/user/login'. This only occurs when sending JSON data and not when sending form-data, which is where my confusion is occurring. It is acting as if an infinite loop is occurring with JSON data but can not trace where it is happening.

答:
because you are not sending any data back to requesting browser(in this case postman) try returning some response as body

for example use res.send('success')

Body:
I'm trying to setup a simple login API using node.js/restify. The code below shows a simple route, with nothing but a console.log() statement within it, as I'm just trying to prove I can gain a connection.

var restify = require('restify');

var user = require('./user');
var reference = require('./reference');

var fs = require('fs');
var bodyParser = require('body-parser');
var _= require('lodash');

const server = restify.createServer();

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended:false}));

server.use(restify.plugins.fullResponse())
server.use(restify.plugins.bodyParser());
server.use(restify.plugins.queryParser())           server.use(restify.plugins.authorizationParser())

var port = 8080;

server.post('/user/login', (req, res) => {

    console.log("---LOGIN ATTEMPT---");

  res.status(200);
  res.end();

});

Using Postman for testing, I expect to get a statement back in the console, stating "LOGIN ATTEMPT".

Postman freezes with the 'Loading' text and stays like that until it crashes saying  'There was an error connecting to localhost:8080/user/login'. This only occurs when sending JSON data and not when sending form-data, which is where my confusion is occurring. It is acting as if an infinite loop is occurring with JSON data but can not trace where it is happening.


问:
WebJob access to Azure VM mapped file share
I have a webjob which has a queue triggered function. But I also need another "signal". A third party OCR agent pulls files from an Azure File Share storage, performs its task, and drops it to another known location on the same file share. The file share is mapped to a virtual drive on an Azure VM. The agent runs in the same VM, so it has access to the virtual drive.

My issue is that I need to sync between the moment that the message in the queue arrives and the moment that the file has been dropped in the output location.
I have no control over the agent, and there is no option to run a script upon completion.

The incoming message simply signals the fact that the file has been picked up by the agent.

My question is this: in the webjob, can i use something like FileSystemWatcher to monitor the network path mapped on the VM, so that I can wait until the file has been dropped, and then continue with whatever processing I need to perform?

答:
Doesn't seems AppService
supports SMB protocol which utimately make \network share work. Hence no WebJob</p>


问:
MongoDB to store different (schema) log files
Do you think that using a MongoDB Json Database to store log files from application is a good idea and why ?

The only advantage for me is the schema abstraction, but i think it's also a weakness we cannot ensure the integrity of a log file.

答:
I'm using MongoDB to store logs from many applications and it's working out very well so far.

You might want to take a look at the slides from a presentation on Logging Application Behavior to MongoDB that I gave at Mongo SV and at the last MongoDB SF Meetup for more background on why I think it is good for logging, as well as for info on libraries for Java, Python, Ruby, PHP and C# that support logging to MongoDB.

I'm now the main committer on log4mongo-java, Log4J appenders for MongoDB. So, it's probably not too surprising that that's what I'm using.

With respect to log integrity, I assume you mean confidence that it hasn't been modified after it was written. One option you have, at least with log4mongo-java, it to store logging events in a database that requires authentication. That would limit to some degree the number of users who could add, delete or update events.

In addition, you could set up a replication slave that is tightly locked down. Frequent backups of the slave would at least limit the time during which the set of logged events could be modified.


问:
What does an exclamation mark means in if condition?
```<code><!DOCTYPE html>
<html>

<body>
  <script>
    'use strict';
    if (!String.prototype.repeat) {
      String.prototype.repeat = function(n) {
        return new Array(n + 1).join(this);
      };
    }

    alert( "La".repeat(3) ); // LaLaLa
  </script>
</body>

</html>
</code>```

I didn't understand the following line of code:

if (!String.prototype.repeat)

答: This is a relational operator meaning NOT.  In your example, it will return true if String.prototype.repeat does NOT exist.

Body:
<!DOCTYPE html>

I didn't understand the following line of code:

if (!String.prototype.repeat)


问:
Rails Render Index with URL Parameters
At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.

```<code>class ReactPagesController < ApplicationController
  def index
    render :index #this will open up the react app
  end
end
</code>```

Is it possible to render a view and pass along parameters in the url?

I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi

I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?

答:
I don't think so, render is for rending the view and has nothing to do with the setting the url.
ruby docs</p>

Title: Rails Render Index with URL Parameters

Body:
At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.

class ReactPagesController < ApplicationController
  def index
    render :index #this will open up the react app
  end
end

Is it possible to render a view and pass along parameters in the url?

I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi

I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?


问:
Calculate Date / Time difference in Bash on macOS
I realize there are tons of questions and answers involving date calculation, but I haven't found a solution to the issue on OS X/macOS. I would like to calculate the time difference between two dates and times, but I must have the syntax incorrect.

```<code>now=$(date +"%b %d %Y %H:%M:%S")
end=$(date +"Dec 25 2017 08:00:00")
dif=$(date -j -f "%b %d %Y %H:%M:%S" "$end" - "$now")
echo $dif
# Mon Dec 25 08:00:00 MST 2017
</code>```

It returns only the $end value, so I'm not sure how to actually calculate the difference in time.

答:
The ideal way is convert the current time into EPOCH and also the date you need also in EPOCH and get the diff (This works on bash on macOS Sierra)

```<code>dudeOnMac:~ $ date +%s
1512757414
dudeOnMac:~ $ date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s
1514169000
</code>```

So now storing in the variables as you wanted

```<code>end=$(date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s)
now=$(date +%s)
printf '%d seconds left till target date\n' "$(( (end-now) ))"
printf '%d days left till target date\n' "$(( (end-now)/86400 ))"
</code>```

Body:
I realize there are tons of questions and answers involving date calculation, but I haven't found a solution to the issue on OS X/macOS. I would like to calculate the time difference between two dates and times, but I must have the syntax incorrect.

now=$(date +"%b %d %Y %H:%M:%S")
end=$(date +"Dec 25 2017 08:00:00")
dif=$(date -j -f "%b %d %Y %H:%M:%S" "$end" - "$now")
echo $dif
# Mon Dec 25 08:00:00 MST 2017

It returns only the $end value, so I'm not sure how to actually calculate the difference in time.

Body:
The ideal way is convert the current time into EPOCH and also the date you need also in EPOCH and get the diff (This works on bash on macOS Sierra)

dudeOnMac:~ $ date +%s
1512757414
dudeOnMac:~ $ date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s
1514169000

So now storing in the variables as you wanted

end=$(date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s)
now=$(date +%s)
printf '%d seconds left till target date\n' "$(( (end-now) ))"
printf '%d days left till target date\n' "$(( (end-now)/86400 ))"


问:
making a client server application of sales inventory system including sql database in c#
i am a beginer and i am making a client server application in c# using sql database.
i am using just two computers, at one computer i want to store my database as well as the application will also run on the same computer it one computer is the server and the client both and the another computer will be a simple client that will access the database.
can any one help me how shoud i write the code for both systems to connect the database.
thank you.</p>

答:
To connect to SQL Server from C#.NET, you need to create a connection string such as below:

private SqlConnection connection;
private string connectionString =
@"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );

Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = @Cid", connection);

The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.

Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.

This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.


问:
How to put JSON data into a HTML div?
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

答:
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.

Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:

```<code>{
    "Columns": [
        "DateDeNaissance",
        "Nom",
        "Sexe"
    ],
    "Especes": [{
        "DateDeNaissance": "05-MAY-15",
        "Nom": "Chachi",
        "Sexe": "F"
    }, {
        "DateDeNaissance": "07-JAN-15",
        "Nom": "Rafiki",
        "Sexe": "M"
    }, {
        "DateDeNaissance": "17-SEP-17",
        "Nom": "Chakra",
        "Sexe": "F"
    }]
}
</code>```

Once you have this output from your PHP, change your JS to this:

```<code>$.getJSON("getespece.php", {
    espece: espece,
    categorie: categorie
})
.done(function(json) {
    // Build the html Table
    var html = "<table>\n";
        html += "<thead>\n";
        html += "<tr>\n";
    // Columns
    $.each(json.Columns, function(k, value) {
        html += "<th>" + column + "</th>\n";
    });
    html += "</tr>\n";
    html += "<tbody>\n";
    // Rows
    $.each(json.Especes, function(column, values) {
        html += "<tr>\n";
        // Cells
        $.each(values, function(k, val) {
            html += "<td>" + val + "</td>\n";
        });
        html += "</tr>\n";
    });
    html += "</tbody>\n";
    html += "</table>\n";
    $("#output").html(html);
});
</code>```

Title: How to put JSON data into a HTML div?

Body:
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

Body:
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.

Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:

{
    "Columns": [
        "DateDeNaissance",
        "Nom",
        "Sexe"
    ],
    "Especes": [{
        "DateDeNaissance": "05-MAY-15",
        "Nom": "Chachi",
        "Sexe": "F"
    }, {
        "DateDeNaissance": "07-JAN-15",
        "Nom": "Rafiki",
        "Sexe": "M"
    }, {
        "DateDeNaissance": "17-SEP-17",
        "Nom": "Chakra",
        "Sexe": "F"
    }]
}

Once you have this output from your PHP, change your JS to this:

$.getJSON("getespece.php", {
    espece: espece,
    categorie: categorie
})
.done(function(json) {
    // Build the html Table
    var html = "<table>\n";
        html += "<thead>\n";
        html += "<tr>\n";
    // Columns
    $.each(json.Columns, function(k, value) {
        html += "<th>" + column + "</th>\n";
    });
    html += "</tr>\n";
    html += "<tbody>\n";
    // Rows
    $.each(json.Especes, function(column, values) {
        html += "<tr>\n";
        // Cells
        $.each(values, function(k, val) {
            html += "<td>" + val + "</td>\n";
        });
        html += "</tr>\n";
    });
    html += "</tbody>\n";
    html += "</table>\n";
    $("#output").html(html);
});


问:
state.resolve returns an empty object in the controller
I have a state defined like so

```<code>.state('login', {
    url: '/login',
    controller: 'LoginController',
    templateUrl: 'templates/login.tpl.html',
    data: {
      loginState: true
    },
    resolve: {
      saml_auth: function ($cookies) {
        var saml_auth = $cookies.get('saml_auth');
        console.log(saml_auth) // returns the string value
        return {claim: saml_auth};
      }
    }
</code>```

In the controller, I get an empty object, no properties even within the object

```<code>angular.module('swSelfService')
  .controller('LoginController', LoginController);

LoginController.$inject = [
  '$scope',
  'SWSessionService',
  '$state',
  '$stateParams',
  'saml_auth',
];

function LoginController($scope, SWSessionService, $state, saml_auth) {
    console.log(saml_auth) // {}
}
</code>```

答:
You missed to add 4th parameter of $stateParams injectable on. You placed saml_auth at wrong place inside controller constructor, it should appear on 5th place.

```<code>LoginController.$inject = [
  '$scope',
  'SWSessionService',
  '$state',
  '$stateParams',
  'saml_auth',
];

function LoginController($scope, SWSessionService, $state, $stateParams, saml_auth) {
    console.log(saml_auth) // {}
}
</code>```

Body:
I have a state defined like so

.state('login', {
    url: '/login',
    controller: 'LoginController',
    templateUrl: 'templates/login.tpl.html',
    data: {
      loginState: true
    },
    resolve: {
      saml_auth: function ($cookies) {
        var saml_auth = $cookies.get('saml_auth');
        console.log(saml_auth) // returns the string value
        return {claim: saml_auth};
      }
    }

In the controller, I get an empty object, no properties even within the object

angular.module('swSelfService')
  .controller('LoginController', LoginController);

LoginController.$inject = [
  '$scope',
  'SWSessionService',
  '$state',
  '$stateParams',
  'saml_auth',
];

function LoginController($scope, SWSessionService, $state, saml_auth) {
    console.log(saml_auth) // {}
}

Body:
You missed to add 4th parameter of $stateParams injectable on. You placed saml_auth at wrong place inside controller constructor, it should appear on 5th place.

LoginController.$inject = [
  '$scope',
  'SWSessionService',
  '$state',
  '$stateParams',
  'saml_auth',
];

function LoginController($scope, SWSessionService, $state, $stateParams, saml_auth) {
    console.log(saml_auth) // {}
}


问:
How can I use isPressed()
How can I use isPressed();?
I need to do something like this:

```<code>if (btn1.isPressed){
    //Do something
}
</code>```

答:
Use OnTouch listener:

```<code>btn1.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                    // btn1 is pressed
                    return true;
                }

                return false;
            }
        });
</code>```

Title: How can I use isPressed()

Body:
How can I use isPressed();?
I need to do something like this:

if (btn1.isPressed){
    //Do something
}

Body:
Use OnTouch listener:

btn1.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                    // btn1 is pressed
                    return true;
                }

                return false;
            }
        });


问:
My app crashes before running in the emulator
I am building my app and when I run it with  emulator/my phone its crash before opening even. Here is the code:

Mainactivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.marvelx.phonecall.MainActivity">

         <Button
        android:id="@+id/button"
        android:onClick="send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="105dp"
        android:text="Button" />

    <EditText
        android:id="@+id/et1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_marginTop="68dp"
        />

    <EditText
        android:id="@+id/et2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/et1"
        android:layout_below="@+id/et1"
        android:layout_marginTop="37dp"
         />

    <EditText
        android:id="@+id/et3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/et2"
        android:layout_below="@+id/et2"
        android:layout_marginTop="32dp"
         />

</RelativeLayout>
</code>```

androidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.marvelx.phonecall">

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

MainActivity.java

```<code>package com.example.marvelx.phonecall;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

     EditText[] number;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        number= new EditText[3];
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       number[0]= findViewById(R.id.et1);
        number[1]= findViewById(R.id.et2);
        number[2]= findViewById(R.id.et3);

    }

    public void send(View v) {
        Call();
    }
    int index = 0;

    public void Call(){

         String num = number[index].getText().toString();

         Intent intent = new Intent(Intent.ACTION_CALL);
         intent.setData(Uri.parse("tel:"+num));
         startActivity(intent);

    }
}
</code>```

I've tried rebuilding, cleaning the Project and research on Google, Stack, and Youtube without success.

Where i can also upload the Logcat?

答:
Simply remove the <uses-permission android:name="android.permission.CALL_PHONE"/> from your MainActivity.xml file.  I tested it on my side, and it fixed the problem.

Also, consider changing Intent.ACTION_CALL into Intent.ACTION_DIAL.  The dial action doesn't require the permission you would remove.

Body:
I am building my app and when I run it with  emulator/my phone its crash before opening even. Here is the code:

Mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.marvelx.phonecall.MainActivity">

         <Button
        android:id="@+id/button"
        android:onClick="send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="105dp"
        android:text="Button" />

    <EditText
        android:id="@+id/et1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_marginTop="68dp"
        />

    <EditText
        android:id="@+id/et2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/et1"
        android:layout_below="@+id/et1"
        android:layout_marginTop="37dp"
         />

    <EditText
        android:id="@+id/et3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/et2"
        android:layout_below="@+id/et2"
        android:layout_marginTop="32dp"
         />

</RelativeLayout>

androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.marvelx.phonecall">

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.marvelx.phonecall;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

     EditText[] number;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        number= new EditText[3];
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       number[0]= findViewById(R.id.et1);
        number[1]= findViewById(R.id.et2);
        number[2]= findViewById(R.id.et3);

    }

    public void send(View v) {
        Call();
    }
    int index = 0;

    public void Call(){

         String num = number[index].getText().toString();

         Intent intent = new Intent(Intent.ACTION_CALL);
         intent.setData(Uri.parse("tel:"+num));
         startActivity(intent);

    }
}

I've tried rebuilding, cleaning the Project and research on Google, Stack, and Youtube without success.

Where i can also upload the Logcat?


问:
PrimeNG dropdown selected option with dynamic value
How to set PrimeNG p-dropdown selected option with dynamic value ?

I am using Formgroup, Formcontrol and my dropdown are set with data querying from database. Now in one of my edit component page I want selected option with dynamic value.

答:
Get the dynamic list of values and push it to the drop down. Below is an example.

data.dtOrgList contains list of values from service layer.

```<code>    html
    ------------------
    <p-dropdown [options]="orgs" [(ngModel)]="selectedOrg"></p-dropdown>

    component.ts
    -------------------

     orgs:SelectItem[];
     selectedOrg : string;
     dtOrgList: Array<any>;

    this.itemDetailsService.getItemDetails(input).subscribe(
                data => {
                    this.dtOrgList = data.dtOrgList;
                    this.orgs = [];
                    this.orgs.push({label: 'Select', value: null});
                    for(var i = 0; i < this.dtOrgList.length; i++) {
                        this.orgs.push({label: this.dtOrgList[i], value: this.dtOrgList[i]});
                    }
                    })
</code>```

Body:
Get the dynamic list of values and push it to the drop down. Below is an example.

data.dtOrgList contains list of values from service layer.

    html
    ------------------
    <p-dropdown [options]="orgs" [(ngModel)]="selectedOrg"></p-dropdown>

    component.ts
    -------------------

     orgs:SelectItem[];
     selectedOrg : string;
     dtOrgList: Array<any>;

    this.itemDetailsService.getItemDetails(input).subscribe(
                data => {
                    this.dtOrgList = data.dtOrgList;
                    this.orgs = [];
                    this.orgs.push({label: 'Select', value: null});
                    for(var i = 0; i < this.dtOrgList.length; i++) {
                        this.orgs.push({label: this.dtOrgList[i], value: this.dtOrgList[i]});
                    }
                    })


问:
How to summarize column price from 2 tables with no relationship?
In a mysql databse, I have tblA.price and tblB.price. There is no relationship between them.

I want summarize all sales from tableA and tableB. It will be something like that sum(tblA.price)+sum(tblB.price) AS total.

how could I perform that query?

答:
In order to complement the other answers, I had some issues when there is no result from one of the tables. It was returning null. For that reason I had to filter that result and turn it into 0. Just just did IFNULL(SUM(field),0).

Here is my final query:

```<code>SELECT
   IFNULL(SUM(tblA.price),0) + (SELECT
           IFNULL(SUM(fieldB),0)
       FROM
           tblB
       WHERE
           creation_date BETWEEN '$startDT' AND DATE_SUB(NOW(), INTERVAL 1 HOUR) AS amount
FROM
   tableA tblA
WHERE
   tblA.transaction_date BETWEEN 'startDT' AND DATE_SUB(NOW(),
       INTERVAL 1 HOUR)
       AND tblA.service_type <> 'service1'
       AND tblA.service_type <> 'service2'
       AND tblA.service_type <> 'service3';
</code>```

Body:
In order to complement the other answers, I had some issues when there is no result from one of the tables. It was returning null. For that reason I had to filter that result and turn it into 0. Just just did IFNULL(SUM(field),0).

Here is my final query:

SELECT
   IFNULL(SUM(tblA.price),0) + (SELECT
           IFNULL(SUM(fieldB),0)
       FROM
           tblB
       WHERE
           creation_date BETWEEN '$startDT' AND DATE_SUB(NOW(), INTERVAL 1 HOUR) AS amount
FROM
   tableA tblA
WHERE
   tblA.transaction_date BETWEEN 'startDT' AND DATE_SUB(NOW(),
       INTERVAL 1 HOUR)
       AND tblA.service_type <> 'service1'
       AND tblA.service_type <> 'service2'
       AND tblA.service_type <> 'service3';


问:
How to create a fixed and detached menu in jquery
Good morning everyone,

I am working on a menu and would like it to behave a certain way.

When I scroll down, the "TOP" section moves up (this is already working)

I would like the "MY MENU" section to be hidden initially and only appear when   the "TOP" section disappears up when scroll.

and example of what I am trying to achieve can be seen at https://flipkart.com? (on mobile vue)

here is a working fiddle:
https://jsfiddle.net/gad123/j695to5b/1/ (solved)

```<code><div class="container">
<div class="row">

<div class="span">
<div class="wll">
<h3>TOP</h3>
</div>

</div>

</div>
</div>
<div id="nav-wrapper">

<div id="na">
<div id="nav" class="navbar">
<div class="navbar-inner">
<div class="container">
<div class="span12"  style="background:#888;
padding:1em 0 1em 0;">

<span class="navbar-text">
My menu
</span>
</div>
</div>
div>
</div>
</div>

</div>
<div class="container">
<div class="span3">
<h2>some lorem ipsum for scrolling:</h2>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.
<div id="detach"><b>test</b></div>

</div>
</div>
</code>```

jquery:

```<code>$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#detach').position()
});
</code>```

css:

```<code>#nav.affix {
position: fixed;
top: 0;
width: 100%

}

h3{color:red;}
.top{
background:#999;
width: 100%
}

#nav.detached {
position:static;
top:0;
}

#nav > .navbar-inner {
border-left: 0;
border-right: 0;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-o-border-radius: 0;
}

h3{
color:orange
}

.wll{
padding:1em 0 1em 0;
background:#444;
}
</code>```

答:
the simplest and easiest way to go about it. i tested it on your fiddle.
Alright so i made some changes to your code and it worked perfectly

change the id="na" to id="menu" as shown below

```<code><div id="menu">
<div id="nav" class="navbar">
    <div class="navbar-inner">
        <div class="container">
            <div  class="span12"  style="background:#888;
            padding:1em 0 1em 0;">

                <span class="navbar-text">
                My menu
                </span>
            </div>
        </div> <!-- container -->
    </div> <!-- navbar-inner -->
</div> <!-- navbar -->
</code>```

add the following to your css

```<code>#menu {
position:fixed;
top:0px;
width:100%;
background-color:#DDDDDD;
color: #FFFFFF;
z-index:9999;
display: none;
</code>```

}

and change your script to

```<code>$(document).ready(function(){
    $(window).scroll(function(){
        if ($(this).scrollTop() > 0) {
            $('#menu').fadeIn(500);
        } else {
            $('#menu').fadeOut(500);
        }
    });
});
</code>```

link to the fiddle : https://jsfiddle.net/7wfryfmL/3/

Body:
Good morning everyone,

I am working on a menu and would like it to behave a certain way.

When I scroll down, the "TOP" section moves up (this is already working)

I would like the "MY MENU" section to be hidden initially and only appear when   the "TOP" section disappears up when scroll.

and example of what I am trying to achieve can be seen at https://flipkart.com? (on mobile vue)

here is a working fiddle:
https://jsfiddle.net/gad123/j695to5b/1/ (solved)

TOP

My menu

div>

some lorem ipsum for scrolling:

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.

test

jquery:

$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#detach').position()
});

css:

#nav.affix {
position: fixed;
top: 0;
width: 100%

}

h3{color:red;}
.top{
background:#999;
width: 100%
}

#nav.detached {
position:static;
top:0;
}

#nav > .navbar-inner {
border-left: 0;
border-right: 0;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-o-border-radius: 0;
}

h3{
color:orange
}

.wll{
padding:1em 0 1em 0;
background:#444;
}

Body:
the simplest and easiest way to go about it. i tested it on your fiddle.
Alright so i made some changes to your code and it worked perfectly

change the id="na" to id="menu" as shown below

<div id="menu">
<div id="nav" class="navbar">
    <div class="navbar-inner">
        <div class="container">
            <div  class="span12"  style="background:#888;
            padding:1em 0 1em 0;">

                <span class="navbar-text">
                My menu
                </span>
            </div>
        </div> <!-- container -->
    </div> <!-- navbar-inner -->
</div> <!-- navbar -->

add the following to your css

#menu {
position:fixed;
top:0px;
width:100%;
background-color:#DDDDDD;
color: #FFFFFF;
z-index:9999;
display: none;

}

and change your script to

$(document).ready(function(){
    $(window).scroll(function(){
        if ($(this).scrollTop() > 0) {
            $('#menu').fadeIn(500);
        } else {
            $('#menu').fadeOut(500);
        }
    });
});

link to the fiddle : https://jsfiddle.net/7wfryfmL/3/