问:
Swift 4 : Set Different Date and Time
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

```<code>let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)
</code>```

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

答:
There are several different concepts involved here, and we need to understand (almost) all of them to get this right...

1) a Date (NSDate as was, in Swift) is an absolute point in time - it's slightly mis-named, because it has nothing to do with an actual date like 13th November 2017, because to get to that we need to define ...

2) a Calendar, because 13th November 2017 in the western Gregorian calendar could also be 23rd Safar 1439 in the Islamic calendar, or the 24th of Heshvan 5778 in the Hebrew calendar, or some other things in the many other calendars that iOS & MacOS support;

3) in turn Calendar changes not only what values are returned in the DateComponents that we have to use to unpack a Date + Calendar into days, months, years & eras (e.g. BC/AD), or even week number, etc..., but also some calendars might not have the same components as others;

4) time-of-day (as you know) depends on TimeZone, so the same absolute time can be one of many different times "o'clock" depending on where you are. It may also (as you can see in the example below) change the date as well as the "o'clock". This of course could be automatic (where you are) or set by the programmer;

5) further, we have DateFormatter (which is a convenience that wraps up DateComponents), because 13th November 2017 could be represented as 13/11/17 or 11/13/17 depending on whether you are British or American. We may also wish to choose whether we use text or numeric months, and, if displaying times, whether we want 12 hour or 24 hour format - all of these are covered by DateFormatter, but text representation may be "13e Novembre 2017" if you are French, which introduces the notion of

6) Locale, which can be set, like TimeZone, as being default (as chosen when you set up the device) or specified by the programmer.

The code you posted won't work, because all it does is takes a Date, transforms it through a Calendar to DateComponents (all good so far), but then recreates a Date from the components - all you will get is the original Date - the same absolute point in time.

What I believe from the question and your answers to questions in the comments is that you want a function that takes an absolute time (eg "now") aka a Date and displays it in a specific TimeZone. This works:

```<code>func timeComponents(date: Date, timeZone: TimeZone) -> DateComponents {
    var calendar = Calendar.current
    calendar.timeZone = timeZone
    return calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date)
}

let absTime: Date = Date() // Now
let edinburgh = TimeZone(abbreviation: "GMT")!
let newYork = TimeZone(abbreviation: "EST")!
let ec = timeComponents(date: absTime, timeZone: edinburgh)
let nycc = timeComponents(date: absTime, timeZone: newYork)
print(ec)// year: 2017 month: 11 day: 14 hour: 0 minute: 44 second: 10 weekOfMonth: 3 isLeapMonth: false
print(nycc) // year: 2017 month: 11 day: 13 hour: 19 minute: 44 second: 10 weekOfMonth: 3 isLeapMonth: false
</code>```

... which I think answers the minimum of your question, but to finesse it, we need to move from DateComponents to DateFormatter

```<code>func timeString(date: Date, timeZone: TimeZone, timeStyle: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = timeZone
    dateFormatter.dateStyle = .none
    dateFormatter.timeStyle = timeStyle
    return dateFormatter.string(from: date)
}

let es = timeString(date: absTime, timeZone: edinburgh, timeStyle: .full)
let nycs = timeString(date: absTime, timeZone: newYork, timeStyle: .full)
print(es) // 12:44:10 AM Greenwich Mean Time
print(nycs) // 7:44:10 PM Eastern Standard Time
</code>```

You can go on, and start to use Locale, if you want to internationalise your app, but I'l leave that as an exercise!

p.s. These are not all of the concepts - see here

p.p.s. See also this answer and this answer (neither duplicates)

Title: Swift 4 : Set Different Date and Time

Body:
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

Body:
There are several different concepts involved here, and we need to understand (almost) all of them to get this right...

1) a Date (NSDate as was, in Swift) is an absolute point in time - it's slightly mis-named, because it has nothing to do with an actual date like 13th November 2017, because to get to that we need to define ...

2) a Calendar, because 13th November 2017 in the western Gregorian calendar could also be 23rd Safar 1439 in the Islamic calendar, or the 24th of Heshvan 5778 in the Hebrew calendar, or some other things in the many other calendars that iOS & MacOS support;

3) in turn Calendar changes not only what values are returned in the DateComponents that we have to use to unpack a Date + Calendar into days, months, years & eras (e.g. BC/AD), or even week number, etc..., but also some calendars might not have the same components as others;

4) time-of-day (as you know) depends on TimeZone, so the same absolute time can be one of many different times "o'clock" depending on where you are. It may also (as you can see in the example below) change the date as well as the "o'clock". This of course could be automatic (where you are) or set by the programmer;

5) further, we have DateFormatter (which is a convenience that wraps up DateComponents), because 13th November 2017 could be represented as 13/11/17 or 11/13/17 depending on whether you are British or American. We may also wish to choose whether we use text or numeric months, and, if displaying times, whether we want 12 hour or 24 hour format - all of these are covered by DateFormatter, but text representation may be "13e Novembre 2017" if you are French, which introduces the notion of

6) Locale, which can be set, like TimeZone, as being default (as chosen when you set up the device) or specified by the programmer.

The code you posted won't work, because all it does is takes a Date, transforms it through a Calendar to DateComponents (all good so far), but then recreates a Date from the components - all you will get is the original Date - the same absolute point in time.

What I believe from the question and your answers to questions in the comments is that you want a function that takes an absolute time (eg "now") aka a Date and displays it in a specific TimeZone. This works:

func timeComponents(date: Date, timeZone: TimeZone) -> DateComponents {
    var calendar = Calendar.current
    calendar.timeZone = timeZone
    return calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date)
}

let absTime: Date = Date() // Now
let edinburgh = TimeZone(abbreviation: "GMT")!
let newYork = TimeZone(abbreviation: "EST")!
let ec = timeComponents(date: absTime, timeZone: edinburgh)
let nycc = timeComponents(date: absTime, timeZone: newYork)
print(ec)// year: 2017 month: 11 day: 14 hour: 0 minute: 44 second: 10 weekOfMonth: 3 isLeapMonth: false
print(nycc) // year: 2017 month: 11 day: 13 hour: 19 minute: 44 second: 10 weekOfMonth: 3 isLeapMonth: false

... which I think answers the minimum of your question, but to finesse it, we need to move from DateComponents to DateFormatter

func timeString(date: Date, timeZone: TimeZone, timeStyle: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = timeZone
    dateFormatter.dateStyle = .none
    dateFormatter.timeStyle = timeStyle
    return dateFormatter.string(from: date)
}

let es = timeString(date: absTime, timeZone: edinburgh, timeStyle: .full)
let nycs = timeString(date: absTime, timeZone: newYork, timeStyle: .full)
print(es) // 12:44:10 AM Greenwich Mean Time
print(nycs) // 7:44:10 PM Eastern Standard Time

You can go on, and start to use Locale, if you want to internationalise your app, but I'l leave that as an exercise!

p.s. These are not all of the concepts - see here

p.p.s. See also this answer and this answer (neither duplicates)


来源: stackexchange

问:
Image slideshow
I am using javascript to slideshow images.Images are loaded only when the user clicks the next button i.e there is no preloading before the slideshow begins. With every image there is a supporting description which is loaded by the same javascript from an array which is stored in the javascript file. The effect of this is such that the description on next image is shown even before the image is displayed. Please suggest me some method so that i can delay displaying the desprition until the image is loaded. Also a loading symbol could be of great help. Please let me know how to do that. Thanks.</p>

答: You need to add an event listener for the image onload event and display your text in that event handler.  Unfortunately, as with everything else, not every browser works the same way in this respect.  If you google image onload you will find some good suggestions.</p>

ContentLicense: CC BY-SA 2.5

Title: Image slideshow


问:
How do you use right outer join to join three separate columns together in mysql?
Write a SQL RIGHT OUTER JOIN statement that joins the user_id column from the blog.posts table, the name column of the blog.users table and the body column of the blog.posts table together.

Here is what I have so far:

```<code>USE blog;
SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON
    posts.user_id, posts.body = users.name;
</code>```

Here are the tables with their columns

```<code>posts: id,body,user_id
users: id, name
</code>```

How do I adjust this code to work?

答:
You can try like the following:</p>

```<code>SELECT posts.user_id, posts.body, COALESCE(users.name, 'Unknown') AS user_name
  FROM Posts
       LEFT JOIN Users
          ON Posts.user_id = Users.id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Write a SQL RIGHT OUTER JOIN statement that joins the user_id column from the blog.posts table, the name column of the blog.users table and the body column of the blog.posts table together.

Here is what I have so far:

USE blog;
SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON
    posts.user_id, posts.body = users.name;

Here are the tables with their columns

posts: id,body,user_id
users: id, name

How do I adjust this code to work?

Body:
You can try like the following:

SELECT posts.user_id, posts.body, COALESCE(users.name, 'Unknown') AS user_name
  FROM Posts
       LEFT JOIN Users
          ON Posts.user_id = Users.id


问:
Firebase ecommerce
I have some doubts about firebase ecommerce.

I Firebase Documentation Ecommerce purchase I don't have the parameters item ID or item value, how can I know which product the user bought

I put this, but I don't see transactions in the firebase

```<code>Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.TRANSACTION_ID, "T04");
bundle.putDouble(FirebaseAnalytics.Param.VALUE, 2);
analytics.logEvent(FirebaseAnalytics.Event.ECOMMERCE_PURCHASE, bundle);
</code>```

Any help?

答:
To log enhanced ecommerce purchases event in Firebase so that you would be able to log various other parameters like item ID item value etc, you can use either of the two techniques.

1) Create ArrayList of Bundle and add Bundle products. Do the same for data. Put both bundles from Products and data into a new Bundle using putParcelableArrayList log that event using logEvent method call.

2) Make use of the Google Tag manager. Detailed description on Enhanced ecommerce. This method would also let you send Analytics custom parameters beyond the limit of 100 characters.

ContentLicense: CC BY-SA 4.0

Title: Firebase ecommerce

Body:
I have some doubts about firebase ecommerce.

I Firebase Documentation Ecommerce purchase I don't have the parameters item ID or item value, how can I know which product the user bought

I put this, but I don't see transactions in the firebase

Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.TRANSACTION_ID, "T04");
bundle.putDouble(FirebaseAnalytics.Param.VALUE, 2);
analytics.logEvent(FirebaseAnalytics.Event.ECOMMERCE_PURCHASE, bundle);

Any help?


问:
Can't figure out how to store command line arguments correctly
I need to store two command line arguments, but I can't figure out how to do so correctly. My code currently stores an int that isn't correct (if I set the second variable to nothing) and gives an error saying invalid initialization. I tried initializing name with strcpy and strcat but that didn't help either because I got different errors mostly relating to casting.</p>

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

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];

   printf("number is %d and name is %s\n", number, name);

   return 0;
}
</code>```

答:
Here is what your main function should look like:

```<code>int main(int argcount, char **args)
{
   int number = atoi(args[1]); // atoi() converts your string to an int
   char *name = args[2]; // Do not dereference twice, otherwise you get a char

   printf("number is %d and name is %s\n", number, name);

   return 0;
}
</code>```

int number = *args[1]; is wrong because args[1] is your first argument, and *argv[1] (or argv[1][0]) is the first letter of your argument. Putting this in your number variable will actually result in the ASCII value of the first letter of your first parameter been stocked in number. This is absolutely not what you want.

char name[] = *args[2]; isn't correct either because here, you are trying to get the first letter of your second parameter (*args[2], or args[2][0]), which is a type char and put it inside an array of char.

You might also want to check how many arguments your program gets and if these arguments are well formatted, otherwise your program could crash!

Body:
I need to store two command line arguments, but I can't figure out how to do so correctly. My code currently stores an int that isn't correct (if I set the second variable to nothing) and gives an error saying invalid initialization. I tried initializing name with strcpy and strcat but that didn't help either because I got different errors mostly relating to casting.

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

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];

   printf("number is %d and name is %s\n", number, name);

   return 0;
}

Body:
Here is what your main function should look like:

int main(int argcount, char **args)
{
   int number = atoi(args[1]); // atoi() converts your string to an int
   char *name = args[2]; // Do not dereference twice, otherwise you get a char

   printf("number is %d and name is %s\n", number, name);

   return 0;
}

int number = *args[1]; is wrong because args[1] is your first argument, and *argv[1] (or argv[1][0]) is the first letter of your argument. Putting this in your number variable will actually result in the ASCII value of the first letter of your first parameter been stocked in number. This is absolutely not what you want.

char name[] = *args[2]; isn't correct either because here, you are trying to get the first letter of your second parameter (*args[2], or args[2][0]), which is a type char and put it inside an array of char.

You might also want to check how many arguments your program gets and if these arguments are well formatted, otherwise your program could crash!


问:
What are pipe and tap methods in Angular tutorial?
I'm following the tutorial at https://angular.io, and I'm having trouble finding documentation; specifically for the methods pipe and tap.  I can't find anything on https://angular.io or http://reactivex.io/rxjs/.

My understanding is that pipe and tap are both methods of Observable, which is being imported from RxJS, correct? What are they supposed to do?

Are these methods part of Angular? What do these two methods do?

答:
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

```<code>  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */
</code>```

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Body:
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().


问:
Cannot install nativescript
I'm trying to install NativeScript and I am getting this error when I do

npm i -g nativescript

npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\Program
  Files\nodejs\node.exe"
  "C:\Users\John\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js"
  "i" "-g" "nativescript" npm ERR! node v8.9.1 npm ERR! npm  v4.0.3

npm ERR! Cannot read property 'assert-plus' of undefined

. . .

npm ERR! Cannot read property 'minimist' of undefined

when I run this command on a Mac, I get:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: abbrev@1.1.0
  (node_modules/nativescript/node_modules/fsevents/node_modules/abbrev):
  npm WARN enoent SKIPPING OPTIONAL DEPENDENCY: ENOENT: no such file or
  directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/abbrev'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.abbrev.DELETE'

npm ERR! path
  /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex
  npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall rename npm
  ERR! enoent ENOENT: no such file or directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.ansi-regex.DELETE'
  npm ERR! enoent This is related to npm not being able to find a file.
  npm ERR! enoent

Does anyone know how to work around this? I have the latest version of Node and npm. Maybe that is my problem? Does anyone know what version would work? Thanks!

答:
Since you are using windows you need to run this for installation

```<code>@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://www.nativescript.org/setup/win'))"
</code>```

See https://docs.nativescript.org/start/quick-setup section Windows

Title: Cannot install nativescript

Body:
Since you are using windows you need to run this for installation

@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://www.nativescript.org/setup/win'))"

See https://docs.nativescript.org/start/quick-setup section Windows


问:
Specifying argument attributes using JavaDoc notation (CFscript)
I was recently trying to use the cfscript version of cfcomponent along with JavaDoc notation and getting error:

The system has attempted to use an undefined value, which usually
  indicates a programming error, either in your code or some system code.

Null Pointers are another name for undefined values.

From CF docs:

```<code>/**
 * custom metadata for a cfc defined using annotation as well as key-value pairs
 * @cfcMetadata1 "cfc metadata1"
 */
component cfcMetadata2 = "cfc metadata2"
{
    /**
     * custom metadata for a property defined using annotation as well as key-value pairs
     * @propMetadata1 "property metadata1"
     */
    property type="numeric" name="age" default="10" propMetadata2="property metadata2";

    /**
     * custom metadata for a function/argument using both annotation and key-value pairs
     * @arg1.argmdata1 "arg metadata1"
     * output true
     * @fnMetadata1 "function metadata1"
     */
    public string function foo(required numeric arg1=20 argmdata2="arg metadata2") fnMetadata2="function metadata2"
    {
        writedump(getmetadata(this));
        return arg1;
    }
}
</code>```

My Code:

```<code>/**
 * @displayName Test
 * @output false
 *
 * @since 2016-10-25
 * @version 1.0
 */
component {

    /**
     * I am a test function.
     *
     * @limitFrom.required false
     * @limitFrom.default 0
     *
     * @limitBy.required false
     * @limitBy.default 0
     *
     * @returnFormat "json"
     *
     * @since 2016-10-25
     * @version 1.0
     */
    remote query function test(
        numeric limitFrom,
        numeric limitBy
    ) {
        return queryNew("");
    }
}
</code>```

This is only happening when I am trying to assign default value to the arguments using the JavaDoc notation i.e.,

@limitFrom.default 0

@limitBy.default 0

Removing these and everything is fine. Not sure why this is happening?

答:
I know you specifically asked about JavaDoc notation, but I'm not a fan, and it's possible that you haven't seen any alternative. I prefer this syntax.</p>

```<code>component
  displayName="test"
  output="false"
  hint="blah blah description..."
{

    // beware of `default`--it doesn't do what you might think.
    //  it's ignored unless you use ORM
    property type="numeric" name="age" default="10"
        hint="blah blah description..."
        propMetadata2="property metadata2";

    remote query function test(
        numeric limitFrom=0 hint="blah blah description...",
        numeric limitBy=0 hint="blah blah description..."
    )
    hint="I am a test function"
    {
        return queryNew("");
    }

}
</code>```

Body:
I was recently trying to use the cfscript version of cfcomponent along with JavaDoc notation and getting error:

The system has attempted to use an undefined value, which usually
  indicates a programming error, either in your code or some system code.

Null Pointers are another name for undefined values.

From CF docs:

/**
 * custom metadata for a cfc defined using annotation as well as key-value pairs
 * @cfcMetadata1 "cfc metadata1"
 */
component cfcMetadata2 = "cfc metadata2"
{
    /**
     * custom metadata for a property defined using annotation as well as key-value pairs
     * @propMetadata1 "property metadata1"
     */
    property type="numeric" name="age" default="10" propMetadata2="property metadata2";

    /**
     * custom metadata for a function/argument using both annotation and key-value pairs
     * @arg1.argmdata1 "arg metadata1"
     * output true
     * @fnMetadata1 "function metadata1"
     */
    public string function foo(required numeric arg1=20 argmdata2="arg metadata2") fnMetadata2="function metadata2"
    {
        writedump(getmetadata(this));
        return arg1;
    }
}

My Code:

/**
 * @displayName Test
 * @output false
 *
 * @since 2016-10-25
 * @version 1.0
 */
component {

    /**
     * I am a test function.
     *
     * @limitFrom.required false
     * @limitFrom.default 0
     *
     * @limitBy.required false
     * @limitBy.default 0
     *
     * @returnFormat "json"
     *
     * @since 2016-10-25
     * @version 1.0
     */
    remote query function test(
        numeric limitFrom,
        numeric limitBy
    ) {
        return queryNew("");
    }
}

This is only happening when I am trying to assign default value to the arguments using the JavaDoc notation i.e.,

@limitFrom.default 0

@limitBy.default 0

Removing these and everything is fine. Not sure why this is happening?

Body:
I know you specifically asked about JavaDoc notation, but I'm not a fan, and it's possible that you haven't seen any alternative. I prefer this syntax.

component
  displayName="test"
  output="false"
  hint="blah blah description..."
{

    // beware of `default`--it doesn't do what you might think.
    //  it's ignored unless you use ORM
    property type="numeric" name="age" default="10"
        hint="blah blah description..."
        propMetadata2="property metadata2";

    remote query function test(
        numeric limitFrom=0 hint="blah blah description...",
        numeric limitBy=0 hint="blah blah description..."
    )
    hint="I am a test function"
    {
        return queryNew("");
    }

}


问:
Laravel service provider class not found in forked vender
I was developing with a repo that worked fine in Laravel. When I forked the repo, I now get this error:

```<code>[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'DevIT\Hasoffers\Laravel\Providers\HasoffersServiceProvider' not found
</code>```

I tried commenting out the provider line in app.php, then ran these, and afterward uncommented the line but these didn't help:

```<code>composer dump-autoload
php artisan clear-compiled
php artisan optimize
</code>```

Here is the config for that in composer.json:

```<code>"require": {
    "devit/hasoffers-php-client": "dev-master",
    "devit/hasoffers-laravel-client": "dev-master"
},
"repositories": [
    {
        "type": "package",
        "package": {
            "name": "devit/hasoffers-php-client",
            "version": "dev-master",
            "source": {
                "url": "https://github.com/ecomevo/hasoffers-php.git",
                "type": "git",
                "reference": "master"
            }
        }
    },
    {
        "type": "package",
        "package": {
            "name": "devit/hasoffers-laravel-client",
            "version": "dev-master",
            "source": {
                "url": "https://github.com/ecomevo/hasoffers-laravel.git",
                "type": "git",
                "reference": "master"
            }
        }
    }
],
</code>```

If I navigate to the vendor dir, the package is there and composer claims it brought it in during latest update.

What have I gotten wrong here?

答:
Your composer file is using package repositories, which will not read the composer.json file of the packages being pulled in. Since the PSR-4 autoloading is defined in those composer.json files, it is not being setup, and your class is not being found.

You could add the autoload functionality to your packages definition, but your best bet would be to use the vcs repository type, so that their composer.json files will be respected.

Your composer file should look something like:

```<code>"require": {
    "devit/hasoffers-php-client": "dev-master",
    "devit/hasoffers-laravel-client": "dev-master"
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/ecomevo/hasoffers-php"
    },
    {
        "type": "vcs",
        "url": "https://github.com/ecomevo/hasoffers-laravel"
    }
],
</code>```

Since you have already pulled these packages in with a previous method, you may need to clear your composer cache before doing a composer update:

```<code>composer clearcache
composer update devit/hasoffers-php-client
composer update devit/hasoffers-laravel-client
</code>```

Body:
I was developing with a repo that worked fine in Laravel. When I forked the repo, I now get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'DevIT\Hasoffers\Laravel\Providers\HasoffersServiceProvider' not found

I tried commenting out the provider line in app.php, then ran these, and afterward uncommented the line but these didn't help:

composer dump-autoload
php artisan clear-compiled
php artisan optimize

Here is the config for that in composer.json:

"require": {
    "devit/hasoffers-php-client": "dev-master",
    "devit/hasoffers-laravel-client": "dev-master"
},
"repositories": [
    {
        "type": "package",
        "package": {
            "name": "devit/hasoffers-php-client",
            "version": "dev-master",
            "source": {
                "url": "https://github.com/ecomevo/hasoffers-php.git",
                "type": "git",
                "reference": "master"
            }
        }
    },
    {
        "type": "package",
        "package": {
            "name": "devit/hasoffers-laravel-client",
            "version": "dev-master",
            "source": {
                "url": "https://github.com/ecomevo/hasoffers-laravel.git",
                "type": "git",
                "reference": "master"
            }
        }
    }
],

If I navigate to the vendor dir, the package is there and composer claims it brought it in during latest update.

What have I gotten wrong here?

Body:
Your composer file is using package repositories, which will not read the composer.json file of the packages being pulled in. Since the PSR-4 autoloading is defined in those composer.json files, it is not being setup, and your class is not being found.

You could add the autoload functionality to your packages definition, but your best bet would be to use the vcs repository type, so that their composer.json files will be respected.

Your composer file should look something like:

"require": {
    "devit/hasoffers-php-client": "dev-master",
    "devit/hasoffers-laravel-client": "dev-master"
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/ecomevo/hasoffers-php"
    },
    {
        "type": "vcs",
        "url": "https://github.com/ecomevo/hasoffers-laravel"
    }
],

Since you have already pulled these packages in with a previous method, you may need to clear your composer cache before doing a composer update:

composer clearcache
composer update devit/hasoffers-php-client
composer update devit/hasoffers-laravel-client


问:
How to change a Python 3 module to a package without changing the imports?
Is it possible to change a Python module to a package without changing the import statements in other files?

Example: other files in the project use import x, and x is x.py, but I want to move it to something like ./x/x.py without changing the import statements in other files to from x import x.

Even if I use __all__ = ["x"] in __init__.py, it needs from x import x to work.

Is there a way or do I have to update the import statements in the other files?

答:
One way to do this is move x.py - but then create a new x.py (or in this case, __init__.py that resides in the x directory) that imports everything it used to expose.

For example, if x.py contained def example you could import this using from x import example. This would basically be a proxy to the real definition.

Let me know if I haven't explained this clearly enough.


问:
Presenting a ViewController
Does presenting a ViewController cause the presented controller to run its viewDidLoad method?

If a view1 is loaded and another is presented. Then something triggers to present view1. Will it run through its viewDidLoad method?

IF not how should this be done? ViewDidAppear?

答:
viewDidLoad is only called when the view is loaded into memory. Usually the first time it appears (could be more often if there are memory dumps and etc).

viewDidAppear: is called every time the viewController's view becomes the 'active' view in the window.

Title: Presenting a ViewController


问:
Matching root route in webpack-dev-server's historyApiFallback`
Sample repo demonstrating the issue is here.

I'm trying to set up webpack dev server so that:

Requests to / are served by public/landing.html (a static landing page)

Requests to anything else are served by my React app

Using create-react-app, and based on webpack-dev-server's options, I've set up my webpackDevServer.config.js as follows:

    historyApiFallback: {
      // Paths with dots should still use the history fallback.
      // See https://github.com/facebookincubator/create-react-app/issues/387.
      disableDotRule: true,
      rewrites: [
        // shows views/landing.html as the landing page
        { from: /^\/$/, to: 'landing.html' },
        // shows views/subpage.html for all routes starting with /subpage
        { from: /^\/subpage/, to: 'subpage.html' },
        // shows views/404.html on all other pages
        { from: /./, to: '404.html' },
      ],
    },

And when I start webpack here's what I see:

Requests to /subpage are routed correctly to subpage.html

Requests to /foo are routed correctly to 404.html. Eventually, these would be handled by my React app.

Requests to / are routed incorrectly to my React app.

How can I get landing.html to respond to requests at /?

答:
Two thoughts come to mind:

What you want to do is not possible with Webpack Dev Server (as far as I'm aware)

And, once npm run build is run and deployed the deployed app would not follow the same rules as configured in Webpack Dev Server

Even if I'm mistaken on #1, #2 seems like a bigger issue if you ever plan to deploy the app. This leads me to recommend an alternate setup which will work on dev and production (or wherever it's deployed).

A few options:

setup the app as a single-page app (SPA) and use React Router to serve the static routes (/ and /subpage) and wildcards (everything else)

setup node (or another server) to serve the static routes (/ and /subpage) and wildcards (everything else)

An Attempt

In an attempt to setup the routes I was able to achieve this setup:

Display landing.html when / is requested

Display subpage.html when /subpage is requested

Display the React App at a specific path, like app.html

To do this make the following changes:

Move /public/index.html to /public/app.html

```<code>mv ./public/index.html ./public/app.html
</code>```

In /config/webpackDevServer.config.js, update historyApiFallback to:

```<code>historyApiFallback: {
  // Paths with dots should still use the history fallback.
  // See https://github.com/facebookincubator/create-react-app/issues/387.
  disableDotRule: true,
  rewrites: [
    // shows views/landing.html as the landing page
    { from: /^\/$/, to: "landing.html" },
    // shows views/subpage.html for all routes starting with /subpage
    { from: /^\/subpage/, to: "subpage.html" },
    // shows views/app.html on all other pages
    // but doesn't work for routes other than app.html
    { from: /./, to: "app.html" }
  ]
}
</code>```

In /config/paths.js update appHTML to:

```<code>appHtml: resolveApp("public/app.html")
</code>```

In /config/webpack.config.dev.js, updateplugins` to include:

```<code>new HtmlWebpackPlugin({
  filename: "app.html",
  inject: true,
  template: paths.appHtml
})
</code>```

Requesting a random URL, like localhost:3000/foo will return a blank page but contains the HTML from the app.html page without the bundled

Body:
Two thoughts come to mind:

What you want to do is not possible with Webpack Dev Server (as far as I'm aware)

And, once npm run build is run and deployed the deployed app would not follow the same rules as configured in Webpack Dev Server

Even if I'm mistaken on #1, #2 seems like a bigger issue if you ever plan to deploy the app. This leads me to recommend an alternate setup which will work on dev and production (or wherever it's deployed).

A few options:

setup the app as a single-page app (SPA) and use React Router to serve the static routes (/ and /subpage) and wildcards (everything else)

setup node (or another server) to serve the static routes (/ and /subpage) and wildcards (everything else)

An Attempt

In an attempt to setup the routes I was able to achieve this setup:

Display landing.html when / is requested

Display subpage.html when /subpage is requested

Display the React App at a specific path, like app.html

To do this make the following changes:

Move /public/index.html to /public/app.html

mv ./public/index.html ./public/app.html

In /config/webpackDevServer.config.js, update historyApiFallback to:

historyApiFallback: {
  // Paths with dots should still use the history fallback.
  // See https://github.com/facebookincubator/create-react-app/issues/387.
  disableDotRule: true,
  rewrites: [
    // shows views/landing.html as the landing page
    { from: /^\/$/, to: "landing.html" },
    // shows views/subpage.html for all routes starting with /subpage
    { from: /^\/subpage/, to: "subpage.html" },
    // shows views/app.html on all other pages
    // but doesn't work for routes other than app.html
    { from: /./, to: "app.html" }
  ]
}

In /config/paths.js update appHTML to:

appHtml: resolveApp("public/app.html")

In /config/webpack.config.dev.js, updateplugins` to include:

new HtmlWebpackPlugin({
  filename: "app.html",
  inject: true,
  template: paths.appHtml
})

Requesting a random URL, like localhost:3000/foo will return a blank page but contains the HTML from the app.html page without the bundled <script> tags injected. So maybe you can find a solution to this final hurdle.


问:
Dependency was not found using vuex
I am following an online tutorial in which he uses vuex. I installed vuex as can be seen in my package.json dependencies.

```<code>{
  "name": "blabla",
  "version": "1.0.0",
  "description": "blablaa",
  "author": "blabla",
  "private": true,
  "scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js",
    "lint": "eslint --ext .js,.vue src"
  },
  "dependencies": {
    "vue": "^2.4.2",
    "vue-router": "^2.7.0",
    "vuetify": "^0.16.9",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^7.1.2",
    "babel-plugin-add-filehash": "^6.9.4",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "chalk": "^2.0.1",
    "connect-history-api-fallback": "^1.3.0",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "cssnano": "^3.10.0",
    "eslint": "^3.19.0",
    "eslint-config-standard": "^6.2.1",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-html": "^3.0.0",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-standard": "^2.0.1",
    "eventsource-polyfill": "^0.9.6",
    "express": "^4.14.1",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.11.1",
    "friendly-errors-webpack-plugin": "^1.1.3",
    "html-webpack-plugin": "^2.28.0",
    "http-proxy-middleware": "^0.17.3",
    "opn": "^5.1.0",
    "optimize-css-assets-webpack-plugin": "^2.0.0",
    "ora": "^1.2.0",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.6",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.1",
    "url-loader": "^0.5.8",
    "vue-loader": "^13.5.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.4.2",
    "webpack": "^2.6.1",
    "webpack-bundle-analyzer": "^2.2.1",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-hot-middleware": "^2.18.0",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 4.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}
</code>```

In my store folder, I have an index.js file where I am creating my vuex in this manner

```<code>import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export const store = new Vuex.store({
   //my code here
})
</code>```

Then in my main.js under src I am importing it like this

```<code>import Vue from 'vue'

import Vuetify from 'vuetify'
import './stylus/main.styl'

import App from './App'
import router from './router'
import { store } from '/.store/index.js'

Vue.use(Vuetify)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
</code>```

However I am getting the following error:

```<code>This dependency was not found:

* /.store/index.js in ./src/main.js

To install it, you can run: npm install --save /.store/index.js
</code>```

I have no idea why I am getting this. What would cause this error? I am new to webdev and not using a compiler so not sure how I can use a debugger here either. Would appreciate if someone could guide me on how to find the error if not the error itself.

答:
I think:

import { store } from '/.store/index.js'

Should be:

import { store } from './store/index.js'

Title: Dependency was not found using vuex

Body:
I am following an online tutorial in which he uses vuex. I installed vuex as can be seen in my package.json dependencies.

{
  "name": "blabla",
  "version": "1.0.0",
  "description": "blablaa",
  "author": "blabla",
  "private": true,
  "scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js",
    "lint": "eslint --ext .js,.vue src"
  },
  "dependencies": {
    "vue": "^2.4.2",
    "vue-router": "^2.7.0",
    "vuetify": "^0.16.9",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^7.1.2",
    "babel-plugin-add-filehash": "^6.9.4",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "chalk": "^2.0.1",
    "connect-history-api-fallback": "^1.3.0",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "cssnano": "^3.10.0",
    "eslint": "^3.19.0",
    "eslint-config-standard": "^6.2.1",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-html": "^3.0.0",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-standard": "^2.0.1",
    "eventsource-polyfill": "^0.9.6",
    "express": "^4.14.1",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.11.1",
    "friendly-errors-webpack-plugin": "^1.1.3",
    "html-webpack-plugin": "^2.28.0",
    "http-proxy-middleware": "^0.17.3",
    "opn": "^5.1.0",
    "optimize-css-assets-webpack-plugin": "^2.0.0",
    "ora": "^1.2.0",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.6",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.1",
    "url-loader": "^0.5.8",
    "vue-loader": "^13.5.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.4.2",
    "webpack": "^2.6.1",
    "webpack-bundle-analyzer": "^2.2.1",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-hot-middleware": "^2.18.0",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 4.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

In my store folder, I have an index.js file where I am creating my vuex in this manner

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export const store = new Vuex.store({
   //my code here
})

Then in my main.js under src I am importing it like this

import Vue from 'vue'

import Vuetify from 'vuetify'
import './stylus/main.styl'

import App from './App'
import router from './router'
import { store } from '/.store/index.js'

Vue.use(Vuetify)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

However I am getting the following error:

This dependency was not found:

* /.store/index.js in ./src/main.js

To install it, you can run: npm install --save /.store/index.js

I have no idea why I am getting this. What would cause this error? I am new to webdev and not using a compiler so not sure how I can use a debugger here either. Would appreciate if someone could guide me on how to find the error if not the error itself.


问:
Wait for user to accept or decline download before redirect in IE
I have created a script which generates a PDF using PDFMake based on user input and attempts to download that PDF before redirecting the user to a new page. This works fine in Chrome and Firefox, which have separate popups that allow the user to accept the download. However, in IE 11, the popup disappears as soon as the page redirects so the user cannot click 'Save' or 'Open' or whatever they want. Is there a way I can wait for this event to stall the redirect?

I am downloading the PDF instead of opening it as IE cannot open Blob URLs.
This is the JavaScript I have

```<code>let theForm = document.getElementById('pdf-form');
let documentDefinition = {
  content: [
    { text: 'Text and contents of PDF here' }
  ]
};
pdfMake.createPdf(documentDefinition).download();
theForm.submit();
</code>```

Basically, I take the form data and generate a PDF with the data, then I want to actually submit the form to add to the database. The PDF is just for the user to have a record.

答: As a solution, I added target="_blank" to the form so that it submits it in a new page, thus I don't have to wait for the user to make a decision.

Body:
I have created a script which generates a PDF using PDFMake based on user input and attempts to download that PDF before redirecting the user to a new page. This works fine in Chrome and Firefox, which have separate popups that allow the user to accept the download. However, in IE 11, the popup disappears as soon as the page redirects so the user cannot click 'Save' or 'Open' or whatever they want. Is there a way I can wait for this event to stall the redirect?

I am downloading the PDF instead of opening it as IE cannot open Blob URLs.
This is the JavaScript I have

let theForm = document.getElementById('pdf-form');
let documentDefinition = {
  content: [
    { text: 'Text and contents of PDF here' }
  ]
};
pdfMake.createPdf(documentDefinition).download();
theForm.submit();

Basically, I take the form data and generate a PDF with the data, then I want to actually submit the form to add to the database. The PDF is just for the user to have a record.


问:
Javascript play button for animation
I have a Javascript animation using Raphael which is in an external file linked to HTML. I would like to have the user click on the animation to start it rather than the animation starting as soon as the page is loaded.</p>

```<code>window.addEventListener("load",function(){
    var paper = new Raphael(document.getElementById("animation"), 800, 600);
    var img = paper.image("backimg.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    img.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});
</code>```

答:
Thank you OP for providing the code. The Raphael JS library uses SVG so the only applicable solution is to set a click event listener to the parent node which, in this case, it the element with an id of animation.

Examine the code snippet:

//https://www.w3schools.com/css/img_fjords.jpg

window.addEventListener("load",function(){
  var animation = document.getElementById('animation');
    var paper = new Raphael(animation, 800, 600);
    var img = paper.image("https://www.w3schools.com/css/img_fjords.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    animation.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<div id="animation"></div></code>```

Hopefully this is helpful.

Title: Javascript play button for animation

Body:
I have a Javascript animation using Raphael which is in an external file linked to HTML. I would like to have the user click on the animation to start it rather than the animation starting as soon as the page is loaded.

window.addEventListener("load",function(){
    var paper = new Raphael(document.getElementById("animation"), 800, 600);
    var img = paper.image("backimg.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    img.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});

Body:
Thank you OP for providing the code. The Raphael JS library uses SVG so the only applicable solution is to set a click event listener to the parent node which, in this case, it the element with an id of animation.

Examine the code snippet:

//https://www.w3schools.com/css/img_fjords.jpg

window.addEventListener("load",function(){
  var animation = document.getElementById('animation');
    var paper = new Raphael(animation, 800, 600);
    var img = paper.image("https://www.w3schools.com/css/img_fjords.jpg",0,0,950,600);
    img.attr({"clip-rect":"0,0,800,600"});
    animation.addEventListener("click",function() {
      var squ = paper.rect(-100,50,100,100);
      squ.attr("fill", "#ffffff");

      squ.animate({transform: "T450,0"}, 2000, "ease-out", explode);
      var cir2 = paper.rect(400,100,1,1);

      function explode(){
        cir2.attr("fill","#f00");
        cir2.animate({ transform:'s100' }, 2000);
      }
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<div id="animation"></div>

Hopefully this is helpful.


答:
Might be one of the rare reasons to use wildcard import in your x/__init__.py:

```<code>from .x import *
</code>```

Title: How to change a Python 3 module to a package without changing the imports?

Body:
Is it possible to change a Python module to a package without changing the import statements in other files?

Example: other files in the project use import x, and x is x.py, but I want to move it to something like ./x/x.py without changing the import statements in other files to from x import x.

Even if I use __all__ = ["x"] in __init__.py, it needs from x import x to work.

Is there a way or do I have to update the import statements in the other files?

Body:
Might be one of the rare reasons to use wildcard import in your x/__init__.py:

from .x import *


问:
Read Guitar Pro files with php
I want to parse guitar pro files using php. I came across this question which directed me to a description of the gp4 format.

As I understand, the file is highly readable :), I just need to know the structure of it. What is the way to do this using php (or maybe javascript)?

Is this php function a way to "blindly" parse through the file?

答: Check phptabs library.It handles midi and guitar pro files. Has a comprehensive sets of API's</p>

Title: Read Guitar Pro files with php


问:
not finding android sdk (Unity)
Error:

```<code>Invalid command android
UnityEditor.HostView:OnGUI()
</code>```

CommandInvokationFailure:

```<code>Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/great/AppData/Local/Android/Sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()
</code>```

Error building Player:

```<code>CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/great/AppData/Local/Android/Sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
</code>```

Screenshot:

答:
These are the steps that eventually worked for me...

Install JDK jdk1.8.0_131 (yes, this specific version, not a later version) and set it as the JDK Path in Unity.

Delete android sdk tools folder : [android_sdk_root]/tools

Download SDK Tools v25.2.5 (this specific version) from http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

Extract the tools folder in that archive to Android SDK root

Build your project

Title: not finding android sdk (Unity)

Body:
Error:

Invalid command android
UnityEditor.HostView:OnGUI()

CommandInvokationFailure:

Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/great/AppData/Local/Android/Sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

Error building Player:

CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/great/AppData/Local/Android/Sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error:Invalid command android
]
stdout[

]
exit code: 64

Screenshot:


答:
Here is the syntax for RIGHT JOIN.

```<code>SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
</code>```

For more details, go to this link.

https://www.w3schools.com/sql/sql_join_right.asp

Hope this helps.

Title: How do you use right outer join to join three separate columns together in mysql?

Body:
Write a SQL RIGHT OUTER JOIN statement that joins the user_id column from the blog.posts table, the name column of the blog.users table and the body column of the blog.posts table together.

Here is what I have so far:

USE blog;
SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON
    posts.user_id, posts.body = users.name;

Here are the tables with their columns

posts: id,body,user_id
users: id, name

How do I adjust this code to work?

Body:
Here is the syntax for RIGHT JOIN.

SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

For more details, go to this link.

https://www.w3schools.com/sql/sql_join_right.asp

Hope this helps.


问:
Creating a CGEvent tap the right way
I am trying to learn how to create a CGEvent tap using examples on SO and and elsewhere.

I know how to create an event tap using:

```<code>let eventTap = CGEvent.tapCreate(*/arguments to create the tap*/)
</code>```

After that I run

```<code>let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
</code>```

Some, but not all examples I've found online also add the following two lines

```<code>CGEvent.tapEnable(tap: eventTap, enable: true)
CFRunLoopRun()
</code>```

Can someone briefly explain if or when is adding the last two lines are useful/recommended?

答:
The first is easy: the docs say:

Event taps are normally enabled when created. If an event tap becomes unresponsive, or if a user requests that event taps be disabled, then a kCGEventTapDisabled event is passed to the event tap callback function. Event taps may be re-enabled by calling this function.

The second one is probably for cases where the program doesn't have a run loop (on the current thread).  For example, a command-line program which doesn't use NSApplication would need to create and run its own run loop.

Title: Creating a CGEvent tap the right way

Body:
I am trying to learn how to create a CGEvent tap using examples on SO and and elsewhere.

I know how to create an event tap using:

let eventTap = CGEvent.tapCreate(*/arguments to create the tap*/)

After that I run

let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)

Some, but not all examples I've found online also add the following two lines

CGEvent.tapEnable(tap: eventTap, enable: true)
CFRunLoopRun()

Can someone briefly explain if or when is adding the last two lines are useful/recommended?


问:
Go HTTP Client adds chunked encoding which is not support by service
The go HTTP client is adding a "chunked" transfer encoding field to my client request.  Unfortunately, this is not supported by the service I'm connecting to and it comes back with an error.

Is there a way to disable this?

This is my Request code:

```<code>// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
    }

    client := &http.Client{
        Timeout: timeout,
    }

    return client.Do(req)
}
</code>```

Basically I would like this header dropped.  This client is talking to S3 which is rather sensitive as to what headers it is sent.

I get this error:

```<code>A header you provided implies functionality that is not implemented
</code>```

答:
Setting Transfer Encoding header like this makes it not use chunked:

```<code>req.TransferEncoding = []string{"identity"}
</code>```

However the http client sources give the reason for it choosing chunked in my case.  Specifically, I was using "PUT" as the method and had no content-length specified.  So all I needed was to set the req.ContentLength.

However, you can see my DoHTTPRequest wrapper function doesn't know how big to set it.  And I had assumed that setting the header will make it work originally.  Well, it doesn't work by setting the header. And you can see why in the sources that determine whether to make it use chunked encoding.

```<code>// shouldSendChunkedRequestBody reports whether we should try to send a
// chunked request body to the server. In particular, the case we really
// want to prevent is sending a GET or other typically-bodyless request to a
// server with a chunked body when the body has zero bytes, since GETs with
// bodies (while acceptable according to specs), even zero-byte chunked
// bodies, are approximately never seen in the wild and confuse most
// servers. See Issue 18257, as one example.
//
// The only reason we'd send such a request is if the user set the Body to a
// non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
// set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
// there's bytes to send.
//
// This code tries to read a byte from the Request.Body in such cases to see
// whether the body actually has content (super rare) or is actually just
// a non-nil content-less ReadCloser (the more common case). In that more
// common case, we act as if their Body were nil instead, and don't send
// a body.
func (t *transferWriter) shouldSendChunkedRequestBody() bool {
    // Note that t.ContentLength is the corrected content length
    // from rr.outgoingLength, so 0 actually means zero, not unknown.
    if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
        return false
    }
    if requestMethodUsuallyLacksBody(t.Method) {
        // Only probe the Request.Body for GET/HEAD/DELETE/etc
        // requests, because it's only those types of requests
        // that confuse servers.
        t.probeRequestBody() // adjusts t.Body, t.ContentLength
        return t.Body != nil
    }
    // For all other request types (PUT, POST, PATCH, or anything
    // made-up we've never heard of), assume it's normal and the server
    // can deal with a chunked request body. Maybe we'll adjust this
    // later.
    return true
}
</code>```

So my solution is simply:

```<code>// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
        // Set the Content Length correctly if specified.
        if strings.EqualFold(k, "Content-Length") {
            length, err := strconv.Atoi(v)
            if err != nil {
               return nil, fmt.Errorf("Bad Content-Length header")
            }
            req.ContentLength = int64(length)
        }
    }

    client := &http.Client{
        Timeout:   timeout,
        Transport: &loghttp.Transport{},
    }

    return client.Do(req)
}
</code>```

Which satisfies S3 as far as having a correct content length.  I didn't need to set the TransferEncoding to identity.

Body:
The go HTTP client is adding a "chunked" transfer encoding field to my client request.  Unfortunately, this is not supported by the service I'm connecting to and it comes back with an error.

Is there a way to disable this?

This is my Request code:

// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
    }

    client := &http.Client{
        Timeout: timeout,
    }

    return client.Do(req)
}

Basically I would like this header dropped.  This client is talking to S3 which is rather sensitive as to what headers it is sent.

I get this error:

A header you provided implies functionality that is not implemented

Body:
Setting Transfer Encoding header like this makes it not use chunked:

req.TransferEncoding = []string{"identity"}

However the http client sources give the reason for it choosing chunked in my case.  Specifically, I was using "PUT" as the method and had no content-length specified.  So all I needed was to set the req.ContentLength.

However, you can see my DoHTTPRequest wrapper function doesn't know how big to set it.  And I had assumed that setting the header will make it work originally.  Well, it doesn't work by setting the header. And you can see why in the sources that determine whether to make it use chunked encoding.

// shouldSendChunkedRequestBody reports whether we should try to send a
// chunked request body to the server. In particular, the case we really
// want to prevent is sending a GET or other typically-bodyless request to a
// server with a chunked body when the body has zero bytes, since GETs with
// bodies (while acceptable according to specs), even zero-byte chunked
// bodies, are approximately never seen in the wild and confuse most
// servers. See Issue 18257, as one example.
//
// The only reason we'd send such a request is if the user set the Body to a
// non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
// set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
// there's bytes to send.
//
// This code tries to read a byte from the Request.Body in such cases to see
// whether the body actually has content (super rare) or is actually just
// a non-nil content-less ReadCloser (the more common case). In that more
// common case, we act as if their Body were nil instead, and don't send
// a body.
func (t *transferWriter) shouldSendChunkedRequestBody() bool {
    // Note that t.ContentLength is the corrected content length
    // from rr.outgoingLength, so 0 actually means zero, not unknown.
    if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
        return false
    }
    if requestMethodUsuallyLacksBody(t.Method) {
        // Only probe the Request.Body for GET/HEAD/DELETE/etc
        // requests, because it's only those types of requests
        // that confuse servers.
        t.probeRequestBody() // adjusts t.Body, t.ContentLength
        return t.Body != nil
    }
    // For all other request types (PUT, POST, PATCH, or anything
    // made-up we've never heard of), assume it's normal and the server
    // can deal with a chunked request body. Maybe we'll adjust this
    // later.
    return true
}

So my solution is simply:

// DoHTTPRequest Do a full HTTP Client Request, with timeout
func DoHTTPRequest(method, url string, body io.Reader, headers map[string]string, timeout time.Duration) (*http.Response, error) {

    // Create the request
    req, err := http.NewRequest(method, url, body)
    if err != nil {
        return nil, err
    }

    // Add headers
    for k, v := range headers {
        req.Header.Set(k, v)
        // Set the Content Length correctly if specified.
        if strings.EqualFold(k, "Content-Length") {
            length, err := strconv.Atoi(v)
            if err != nil {
               return nil, fmt.Errorf("Bad Content-Length header")
            }
            req.ContentLength = int64(length)
        }
    }

    client := &http.Client{
        Timeout:   timeout,
        Transport: &loghttp.Transport{},
    }

    return client.Do(req)
}

Which satisfies S3 as far as having a correct content length.  I didn't need to set the TransferEncoding to identity.


问:
Check if tab exists in TabControl c#
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

```<code>private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}
</code>```

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

答:
```<code>VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
</code>```

You just created a brand new TabPage.  Obviously, that isn't in TabPages.

You need to check the existing instance, by only creating it once.

Title: Check if tab exists in TabControl c#

Body:
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

Body:
VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)

You just created a brand new TabPage.  Obviously, that isn't in TabPages.

You need to check the existing instance, by only creating it once.


问:
Image slideshow
I am using javascript to slideshow images.Images are loaded only when the user clicks the next button i.e there is no preloading before the slideshow begins. With every image there is a supporting description which is loaded by the same javascript from an array which is stored in the javascript file. The effect of this is such that the description on next image is shown even before the image is displayed. Please suggest me some method so that i can delay displaying the desprition until the image is loaded. Also a loading symbol could be of great help. Please let me know how to do that. Thanks.</p>

答:
You will have to show some code and be more specific if you want more specific answers but in the meanwhile, I think this tutorial could help you out:

JavaScript Timers with setTimeout and setInterval

Title: Image slideshow


问:
Why AesManaged.FeedbackSizeValue = 8 when AesManaged.FeedbackSize = 128
I wish to explicitly set the encryption parameters (as read from .NET 4.7 defaults) so as to avoid decryption difficulties later down the line when future framework versions implement different defaults.

Why is it that after manually setting the feedback FeedbackSize, the FeedbackSizeValue doesn't change ?

```<code>AesManaged aes = new AesManaged();
aes.Mode = CipherMode.CBC;
aes.KeySize = 256;
aes.Padding = PaddingMode.PKCS7;
aes.BlockSize = 128;
aes.FeedbackSize = aes.BlockSize;
</code>```

Here is the aes object, see the FeedbackSizeValue   8

```<code>-       aes {System.Security.Cryptography.AesManaged}   System.Security.Cryptography.AesManaged

-       aes {System.Security.Cryptography.AesManaged}   System.Security.Cryptography.AesManaged
        BlockSize   128 int
        BlockSizeValue  128 int
        FeedbackSize    128 int
        FeedbackSizeValue   8   int
+       IV  {byte[16]}  byte[]
        IVValue null    byte[]
+       Key {byte[32]}  byte[]
        KeySize 256 int
        KeySizeValue    256 int
        KeyValue    null    byte[]
+       LegalBlockSizes {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalBlockSizesValue    {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalKeySizes   {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalKeySizesValue  {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
        Mode    CBC System.Security.Cryptography.CipherMode
        ModeValue   CBC System.Security.Cryptography.CipherMode
        Padding PKCS7   System.Security.Cryptography.PaddingMode
        PaddingValue    PKCS7   System.Security.Cryptography.PaddingMode
+       m_rijndael  {System.Security.Cryptography.RijndaelManaged}  System.Security.Cryptography.RijndaelManaged
+       Static members
</code>```

答:
CBC mode does not have a feedback size. See CBC mode:

Graphic from Wikipedia

Also there is no need to specify the block size (aes.BlockSize = 128;), AES only has one block size. Rijndael does support several block sizes and it is necessary to specify a block size of 128-bits to essentially be AES. While many Rijndael implementation default to a block size of 128-bits it is always better to fully specify parameters.

Body:
I wish to explicitly set the encryption parameters (as read from .NET 4.7 defaults) so as to avoid decryption difficulties later down the line when future framework versions implement different defaults.

Why is it that after manually setting the feedback FeedbackSize, the FeedbackSizeValue doesn't change ?

AesManaged aes = new AesManaged();
aes.Mode = CipherMode.CBC;
aes.KeySize = 256;
aes.Padding = PaddingMode.PKCS7;
aes.BlockSize = 128;
aes.FeedbackSize = aes.BlockSize;

Here is the aes object, see the FeedbackSizeValue   8

-       aes {System.Security.Cryptography.AesManaged}   System.Security.Cryptography.AesManaged

-       aes {System.Security.Cryptography.AesManaged}   System.Security.Cryptography.AesManaged
        BlockSize   128 int
        BlockSizeValue  128 int
        FeedbackSize    128 int
        FeedbackSizeValue   8   int
+       IV  {byte[16]}  byte[]
        IVValue null    byte[]
+       Key {byte[32]}  byte[]
        KeySize 256 int
        KeySizeValue    256 int
        KeyValue    null    byte[]
+       LegalBlockSizes {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalBlockSizesValue    {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalKeySizes   {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
+       LegalKeySizesValue  {System.Security.Cryptography.KeySizes[1]}  System.Security.Cryptography.KeySizes[]
        Mode    CBC System.Security.Cryptography.CipherMode
        ModeValue   CBC System.Security.Cryptography.CipherMode
        Padding PKCS7   System.Security.Cryptography.PaddingMode
        PaddingValue    PKCS7   System.Security.Cryptography.PaddingMode
+       m_rijndael  {System.Security.Cryptography.RijndaelManaged}  System.Security.Cryptography.RijndaelManaged
+       Static members


问:
How to use Firebase's ServerValue.TIMESTAMP as a child and set a value to it
I want to create a structure like

```<code>"child1/1510612788766/": key: "quantity", value: 10
"child1/1510612788767/": key: "quantity", value: 4
"child1/1510612788768/": key: "quantity", value: 1
"child2/1510612788710/": key: "quantity", value: 6
"child2/1510612788756/": key: "quantity", value: 8
</code>```

but when I try:

```<code>ref.child("child1").child(ServerValue.TIMESTAMP);
</code>```

there is a compilation error on the second child call:

```<code>Error:(59, 52) error: incompatible types: Map<String,String> cannot be converted to String
</code>```

I know that this error is because the method expects a Map<String, Object> map instead of Map of timestamp.

But how could I store the ServerValue this way and set a value to it?

答:
This isn't how ServerValue.TIMESTAMP is meant to be used.

child() takes a String with the name of the child you want to access.  This is the name of a node in the database.  It can only be referenced as a string, even if it's formatted as a number.

ServerValue.TIMESTAMP is a special (Map) value that you can use where you want to insert the server's sense of current time when adding or updating child data inside a node.  It can't be used for the name of the node itself.

If you want to create a location of the database that's based on some time, you need to know what that time is before you start accessing it.  ServerValue.TIMESTAMP won't help you with that, since it's a only generated on the server.

If you want to add data ordered by time, you should instead push() data into the database.  The push id is based on time, but it is the client's sense of time, not the server.

If you REALLY need to use the server's sense of time in the name of a node, you should instead be using Cloud Functions for Firebase to measure time on Google servers and generate the path that you want to write.

Body:
I want to create a structure like

"child1/1510612788766/": key: "quantity", value: 10
"child1/1510612788767/": key: "quantity", value: 4
"child1/1510612788768/": key: "quantity", value: 1
"child2/1510612788710/": key: "quantity", value: 6
"child2/1510612788756/": key: "quantity", value: 8

but when I try:

ref.child("child1").child(ServerValue.TIMESTAMP);

there is a compilation error on the second child call:

Error:(59, 52) error: incompatible types: Map<String,String> cannot be converted to String

I know that this error is because the method expects a Map<String, Object> map instead of Map of timestamp.

But how could I store the ServerValue this way and set a value to it?


问:
Keep android app awake at all times
I have a tracking app that needs to send location updates to a web server every 5 seconds.  This works fine as long as the app is awake/visible.

If the device is locked the app is put to sleep after 15 minutes (give or take a second or two).

Adding the app to the "Unmonitored apps" under Battery app power monitor doesn't stop it getting put to sleep either.

I have tried creating a wakelock, ie

```<code>pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TrackerTag");
wakeLock.acquire();
</code>```

but even that does not help.  The app still goes to sleep and stops sending updates.  I do not need to keep the screen on (hence the PARTIAL_WAKE_LOCK) but I do need the app to stay awake so it can feed GPS coordinates to a server database.

I have added the app to the ignore list for battery optimization list so it isn't that killing it and the above wakelock seems to do nothing.

I also tried creating the service as a foreground service ie Android - implementing startForeground for a service? and that also does not save the app being put to sleep after 15 minutes.

What do I need to do to tell android "leave this app alone no matter what and do not stop it unless I specifically close all and kill it"?

答:
After trying every possible way I could find to stop android killing my app the end "fix" is to restart the main activity every 3 minutes.  Because the app is never running for 15 minutes this seems to stop Android killing it.

This is the runnable I use.  Put this in the main activity onCreate

```<code>h.postDelayed(new Runnable() {
    public void run() {
        runnable = this;
        recreate();
        h.postDelayed(runnable, 3*60*1000);
    }
}, 3*60*1000);
</code>```

This also restarts the activity when it is paused/hidden.  If the app is visible there is a quick flicker as the activity is relaunched, but this is not a problem in my case.

Unless someone can give me a real official solution the above will do for now.  My app has been running and updating the web server for over an hour when locked.  Perviosuly it would never get past 15 minutes.

Title: Keep android app awake at all times

Body:
I have a tracking app that needs to send location updates to a web server every 5 seconds.  This works fine as long as the app is awake/visible.

If the device is locked the app is put to sleep after 15 minutes (give or take a second or two).

Adding the app to the "Unmonitored apps" under Battery app power monitor doesn't stop it getting put to sleep either.

I have tried creating a wakelock, ie

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TrackerTag");
wakeLock.acquire();

but even that does not help.  The app still goes to sleep and stops sending updates.  I do not need to keep the screen on (hence the PARTIAL_WAKE_LOCK) but I do need the app to stay awake so it can feed GPS coordinates to a server database.

I have added the app to the ignore list for battery optimization list so it isn't that killing it and the above wakelock seems to do nothing.

I also tried creating the service as a foreground service ie Android - implementing startForeground for a service? and that also does not save the app being put to sleep after 15 minutes.

What do I need to do to tell android "leave this app alone no matter what and do not stop it unless I specifically close all and kill it"?

Body:
After trying every possible way I could find to stop android killing my app the end "fix" is to restart the main activity every 3 minutes.  Because the app is never running for 15 minutes this seems to stop Android killing it.

This is the runnable I use.  Put this in the main activity onCreate

h.postDelayed(new Runnable() {
    public void run() {
        runnable = this;
        recreate();
        h.postDelayed(runnable, 3*60*1000);
    }
}, 3*60*1000);

This also restarts the activity when it is paused/hidden.  If the app is visible there is a quick flicker as the activity is relaunched, but this is not a problem in my case.

Unless someone can give me a real official solution the above will do for now.  My app has been running and updating the web server for over an hour when locked.  Perviosuly it would never get past 15 minutes.


问:
Accessing Python instance variables with __dict__- Is it wrong?
If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys().  I want to use this attribute to print out all instance variables of an object.  I am hesitant to do this because __dict__ is a "secret" attribute, and I do not understand what this footnote means.

So is it wrong to use myObject.__dict__?

答:
Using it for things like printing out members for debugging should be fine.  But if that's all you're doing, check out pretty print.

http://docs.python.org/library/pprint.html

The main problem with __dict__, is it violates the implied visibility rules of objects that python has.


问:
Can't figure out how to store command line arguments correctly
I need to store two command line arguments, but I can't figure out how to do so correctly. My code currently stores an int that isn't correct (if I set the second variable to nothing) and gives an error saying invalid initialization. I tried initializing name with strcpy and strcat but that didn't help either because I got different errors mostly relating to casting.</p>

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

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];

   printf("number is %d and name is %s\n", number, name);

   return 0;
}
</code>```

答:
Please note that all cmdline args are given in string (a series of characters, so if you want to use them as their literal meaning, you have to convert them:

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

int number = atoi(args[1]);
char *name = args[2];
</code>```

If you want to copy args[2], you should use strcpy:

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

char name[1+strlen(args[2])];
strcpy(name, args[2]);

// Now this works:
printf("number is %d and name is %s\n", number, name);
</code>```

Finally, it is recommended that you check if there's enough arguments given, so that you won't access args out of bound.

Body:
I need to store two command line arguments, but I can't figure out how to do so correctly. My code currently stores an int that isn't correct (if I set the second variable to nothing) and gives an error saying invalid initialization. I tried initializing name with strcpy and strcat but that didn't help either because I got different errors mostly relating to casting.

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

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];

   printf("number is %d and name is %s\n", number, name);

   return 0;
}

Body:
Please note that all cmdline args are given in string (a series of characters, so if you want to use them as their literal meaning, you have to convert them:

#include <stdlib.h>

int number = atoi(args[1]);
char *name = args[2];

If you want to copy args[2], you should use strcpy:

#include <string.h>

char name[1+strlen(args[2])];
strcpy(name, args[2]);

// Now this works:
printf("number is %d and name is %s\n", number, name);

Finally, it is recommended that you check if there's enough arguments given, so that you won't access args out of bound.


问:
How do you use right outer join to join three separate columns together in mysql?
Write a SQL RIGHT OUTER JOIN statement that joins the user_id column from the blog.posts table, the name column of the blog.users table and the body column of the blog.posts table together.

Here is what I have so far:

```<code>USE blog;
SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON
    posts.user_id, posts.body = users.name;
</code>```

Here are the tables with their columns

```<code>posts: id,body,user_id
users: id, name
</code>```

How do I adjust this code to work?

答:
to stick with a right join then:

```<code>SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON posts.user_id = users.id;
</code>```

but, more conventionally that is the same at this:

```<code>SELECT posts.user_id, posts.body, users.name
  FROM users
    LEFT OUTER JOIN posts ON users.id = posts.user_id;
</code>```

However, I am going to hope you cannot have a blog without a user, so my guess is it really should be an inner join:

```<code>SELECT posts.user_id, posts.body, users.name
  FROM posts
    INNER JOIN users ON posts.user_id = users.id;
</code>```

Body:
to stick with a right join then:

SELECT posts.user_id, posts.body, users.name
  FROM posts
    RIGHT OUTER JOIN users ON posts.user_id = users.id;

but, more conventionally that is the same at this:

SELECT posts.user_id, posts.body, users.name
  FROM users
    LEFT OUTER JOIN posts ON users.id = posts.user_id;

However, I am going to hope you cannot have a blog without a user, so my guess is it really should be an inner join:

SELECT posts.user_id, posts.body, users.name
  FROM posts
    INNER JOIN users ON posts.user_id = users.id;


问:
Unrecognized element '<runtime>' when upgrading Google App Engine to Java 8
I have a Google App Engine Standard server running Java 7, and would like to upgrade to Java 8. I have added <runtime>java8</runtime> to my pom.xml as follows:

```<code><appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>my-app</application>
    <version>1.0</version>
    <threadsafe>true</threadsafe>
    <runtime>java8</runtime>
    ...
</code>```

This was described in https://cloud.google.com/appengine/docs/standard/java/runtime-java8#specifying_the_java_8_runtime_for_your_app.

However when building the application, it fails with the error Unrecognized element <runtime>. Can anyone advise?

答:
You should probably be using an old version of appengine sdk currently. Check whether you have the latest version of appengine-api dependency.

I use following appengine-api and it works fine for me.

```<code><dependency>
    <groupId>com.google.appengine</groupId>
    <artifactId>appengine-api-1.0-sdk</artifactId>
    <version>1.9.58</version>
</dependency>
</code>```

Body:
I have a Google App Engine Standard server running Java 7, and would like to upgrade to Java 8. I have added <runtime>java8</runtime> to my pom.xml as follows:

<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>my-app</application>
    <version>1.0</version>
    <threadsafe>true</threadsafe>
    <runtime>java8</runtime>
    ...

This was described in https://cloud.google.com/appengine/docs/standard/java/runtime-java8#specifying_the_java_8_runtime_for_your_app.

However when building the application, it fails with the error Unrecognized element <runtime>. Can anyone advise?

Body:
You should probably be using an old version of appengine sdk currently. Check whether you have the latest version of appengine-api dependency.

I use following appengine-api and it works fine for me.

<dependency>
    <groupId>com.google.appengine</groupId>
    <artifactId>appengine-api-1.0-sdk</artifactId>
    <version>1.9.58</version>
</dependency>


问:
Alignment restrictions for malloc()/free()
Older K&R (2nd ed.) and other C-language texts I have read that discuss the implementation of a dynamic memory allocator in the style of malloc() and free() usually also mention, in passing, something about data type alignment restrictions. Apparently certain computer hardware architectures (CPU, registers, and memory access) restrict how you can store and address certain value types. For example, there may be a requirement that a 4 byte (long) integer must be stored beginning at addresses that are multiples of four.

What restrictions, if any, do major platforms (Intel & AMD, SPARC, Alpha) impose for memory allocation and memory access, or can I safely ignore aligning memory allocations on specific address boundaries?

答:
Sparc, MIPS, Alpha, and most other "classical RISC" architectures only allow aligned accesses to memory, even today. An unaligned access will cause an exception, but some operating systems will handle the exception by copying from the desired address in software using smaller loads and stores. The application code won't know there was a problem, except that the performance will be very bad.

MIPS has special instructions (lwl and lwr) which can be used to access 32 bit quantities from unaligned addresses. Whenever the compiler can tell that the address is likely unaligned it will use this two instruction sequence instead of a normal lw instruction.

x86 can handle unaligned memory accesses in hardware without an exception, but there is still a performance hit of up to 3X compared to aligned accesses.

Ulrich Drepper wrote a comprehensive paper on this and other memory-related topics, What Every Programmer Should Know About Memory. It is a very long writeup, but filled with chewy goodness.

OwnerDisplayName: anon c hacker

OwnerDisplayName: Denton Gentry


问:
Testing for a deadlock with nUnit
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

答:
To test for a deadlock, you must implement a state graph and a check for cycles in your current state graph in the unit test. The state graph consists of the ressources as nodes and the dependencies as edges.
I have no idea of the implementation of such a thing, but thats the theory.

A unit test tests for the correctness of the in and output of data (mainly for the later point) and not for the correctness of the execution flow of your application.

Mark Heath's idea seems reasonable, but is academically wrong.

OwnerDisplayName: frou

Title: Testing for a deadlock with nUnit

OwnerDisplayName: bitschnau

LastEditorDisplayName: bitschnau


问:
Cannot insert duplicate key when directly assigning Foreign Key with EF
Model:

```<code>class TableA
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID {get;set;}
}

class TableB
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID {get;set;}
    public int TableAID {get;set;}
    [ForeignKey("TableAID")]
    public virtual TableA TableA {get;set;}
}
</code>```

Code:

```<code>var copyB = sourceDb.TableB.Single(B => B.ID == TableBID_Param); //EG. B.ID == 17
copyB.TableAID = TableAID_Param; //EG. B.TableAID = 5;
destDb.TableB.Add(copyB);
destDb.SaveChanges(); //Error occurs here
</code>```

I have changed the Foreign Key ID, and the Primary Key should be regenerated

答:
The problem here, is the the copyB object is:

still associated with sourceDb

likely lazy loading TableA (if TableAID has a value)

The TableA navigation property will take precedence over the TableAID foreign key property. DestDb will try to insert the TableA object, and this likely already exists (possibly from a previous successful execution of this flawed code).

You should quarantine your objects between contexts, in a similar way that you should use a separate ViewModel when sending data to a web client - you have control how it gets serialised. This also makes it clear to a future developer that a new Primary Key is expected (not implied)

Extend TableB:

```<code>class TableB
{
    public string SomeData {get;set;} //Let's pretend there's something interesting to clone

    public TableA ContextClone()
    {
        var clone = new TableA();
        clone.SomeData = SomeData;
        //Nothing else get's assigned - it's up to the caller to map ForeignKeys
    }
}
</code>```

New Code:

```<code>var sourceB= sourceDb.TableB.Single(B => B.ID == TableBID_Param); //EG. B.ID == 17
var clone = sourceB.ContextClone();
clone.TableAID = TableAID_Param; //EG. B.TableAID = 5;
destDb.TableB.Add(clone);
destDb.SaveChanges();
</code>```

Body:
Model:

class TableA
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID {get;set;}
}

class TableB
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID {get;set;}
    public int TableAID {get;set;}
    [ForeignKey("TableAID")]
    public virtual TableA TableA {get;set;}
}

Code:

var copyB = sourceDb.TableB.Single(B => B.ID == TableBID_Param); //EG. B.ID == 17
copyB.TableAID = TableAID_Param; //EG. B.TableAID = 5;
destDb.TableB.Add(copyB);
destDb.SaveChanges(); //Error occurs here

I have changed the Foreign Key ID, and the Primary Key should be regenerated

Body:
The problem here, is the the copyB object is:

still associated with sourceDb

likely lazy loading TableA (if TableAID has a value)

The TableA navigation property will take precedence over the TableAID foreign key property. DestDb will try to insert the TableA object, and this likely already exists (possibly from a previous successful execution of this flawed code).

You should quarantine your objects between contexts, in a similar way that you should use a separate ViewModel when sending data to a web client - you have control how it gets serialised. This also makes it clear to a future developer that a new Primary Key is expected (not implied)

Extend TableB:

class TableB
{
    public string SomeData {get;set;} //Let's pretend there's something interesting to clone

    public TableA ContextClone()
    {
        var clone = new TableA();
        clone.SomeData = SomeData;
        //Nothing else get's assigned - it's up to the caller to map ForeignKeys
    }
}

New Code:

var sourceB= sourceDb.TableB.Single(B => B.ID == TableBID_Param); //EG. B.ID == 17
var clone = sourceB.ContextClone();
clone.TableAID = TableAID_Param; //EG. B.TableAID = 5;
destDb.TableB.Add(clone);
destDb.SaveChanges();