问:
Is stat's st_blksize measured in bits or bytes?
I'm trying to find the block size on my machine using these lines:

```<code>struct stat fi;
stat("/tmp", &fi);
BLOCK_SIZE = fi.st_blksize;
</code>```

Does BLOCK_SIZE represent the amount of bytes or the amount of bits in a single block?

The documentation says:

"    blksize_t st_blksize; /* blocksize for file system I/O */ "

答:
It is in Bytes. Refer the Linux man page example code here:-

printf("Preferred I/O block size: %ld bytes\n", (long) sb.st_blksize);

```<code>  The following program calls stat() and displays selected fields in
   the returned stat structure.

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <time.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <sys/sysmacros.h>

   int
   main(int argc, char *argv[])
   {
       struct stat sb;

       if (argc != 2) {
           fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
           exit(EXIT_FAILURE);
       }

       if (stat(argv[1], &sb) == -1) {
           perror("stat");
           exit(EXIT_FAILURE);
       }

       printf("ID of containing device:  [%lx,%lx]\n",
            (long) major(sb.st_dev), (long) minor(sb.st_dev));

       printf("File type: ");

       switch (sb.st_mode & S_IFMT) {
       case S_IFBLK:  printf("block device\n");            break;
       case S_IFCHR:  printf("character device\n");        break;
       case S_IFDIR:  printf("directory\n");               break;
       case S_IFIFO:  printf("FIFO/pipe\n");               break;
       case S_IFLNK:  printf("symlink\n");                 break;
       case S_IFREG:  printf("regular file\n");            break;
       case S_IFSOCK: printf("socket\n");                  break;
       default:       printf("unknown?\n");                break;
       }

       printf("I-node number:            %ld\n", (long) sb.st_ino);

       printf("Mode:                     %lo (octal)\n",
               (unsigned long) sb.st_mode);

       printf("Link count:               %ld\n", (long) sb.st_nlink);
       printf("Ownership:                UID=%ld   GID=%ld\n",
               (long) sb.st_uid, (long) sb.st_gid);

       printf("Preferred I/O block size: %ld bytes\n",
               (long) sb.st_blksize);
       printf("File size:                %lld bytes\n",
               (long long) sb.st_size);
       printf("Blocks allocated:         %lld\n",
               (long long) sb.st_blocks);

       printf("Last status change:       %s", ctime(&sb.st_ctime));
       printf("Last file access:         %s", ctime(&sb.st_atime));
       printf("Last file modification:   %s", ctime(&sb.st_mtime));

       exit(EXIT_SUCCESS);
   }
</code>```

Body:
I'm trying to find the block size on my machine using these lines:

struct stat fi;
stat("/tmp", &fi);
BLOCK_SIZE = fi.st_blksize;

Does BLOCK_SIZE represent the amount of bytes or the amount of bits in a single block?

The documentation says:

"    blksize_t st_blksize; /* blocksize for file system I/O */ "

Body:
It is in Bytes. Refer the Linux man page example code here:-

printf("Preferred I/O block size: %ld bytes\n", (long) sb.st_blksize);

  The following program calls stat() and displays selected fields in
   the returned stat structure.

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <time.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <sys/sysmacros.h>

   int
   main(int argc, char *argv[])
   {
       struct stat sb;

       if (argc != 2) {
           fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
           exit(EXIT_FAILURE);
       }

       if (stat(argv[1], &sb) == -1) {
           perror("stat");
           exit(EXIT_FAILURE);
       }

       printf("ID of containing device:  [%lx,%lx]\n",
            (long) major(sb.st_dev), (long) minor(sb.st_dev));

       printf("File type: ");

       switch (sb.st_mode & S_IFMT) {
       case S_IFBLK:  printf("block device\n");            break;
       case S_IFCHR:  printf("character device\n");        break;
       case S_IFDIR:  printf("directory\n");               break;
       case S_IFIFO:  printf("FIFO/pipe\n");               break;
       case S_IFLNK:  printf("symlink\n");                 break;
       case S_IFREG:  printf("regular file\n");            break;
       case S_IFSOCK: printf("socket\n");                  break;
       default:       printf("unknown?\n");                break;
       }

       printf("I-node number:            %ld\n", (long) sb.st_ino);

       printf("Mode:                     %lo (octal)\n",
               (unsigned long) sb.st_mode);

       printf("Link count:               %ld\n", (long) sb.st_nlink);
       printf("Ownership:                UID=%ld   GID=%ld\n",
               (long) sb.st_uid, (long) sb.st_gid);

       printf("Preferred I/O block size: %ld bytes\n",
               (long) sb.st_blksize);
       printf("File size:                %lld bytes\n",
               (long long) sb.st_size);
       printf("Blocks allocated:         %lld\n",
               (long long) sb.st_blocks);

       printf("Last status change:       %s", ctime(&sb.st_ctime));
       printf("Last file access:         %s", ctime(&sb.st_atime));
       printf("Last file modification:   %s", ctime(&sb.st_mtime));

       exit(EXIT_SUCCESS);
   }


来源: stackexchange

问:
NSStatusItem left click
First : I'm new with Swift developpement.

I'm using this tutorial to make a popup that will appears when I click on my top bar icon.

So my AppDelehgate code is :

```<code>func applicationDidFinishLaunching(_ aNotification: Notification){
    print("START !");
    if let button = statusItem.button {
        button.image = NSImage(named: "logo");
        button.action = Selector(("togglePopover:"));
        //button.target = self;
    }

    popover.contentViewController = QuotesViewController(nibName: "QuotesViewController", bundle: nil);
}

func togglePopover(envoyeur: AnyObject?){
    print("TOGGLE !");
    if popover.isShown{
        closePopover(sender: envoyeur)
    } else {
        showPopover(sender: envoyeur)
    }
}
</code>```

But never the "TOGGLE !" text appears, the event doesn't works.

I put the "button.target = self;" into comment because it's crashing if I don't do it. The event seem's to be trigged, but i've got an error :

```<code>START !
2017-06-08 15:55:29.116275+0200 MyWallpaper[7590:407660] -[MyWallpaper.AppDelegate togglePopover:]: unrecognized selector sent to instance 0x61000002a520
2017-06-08 15:55:29.122570+0200 MyWallpaper[7590:407660] [General] -[MyWallpaper.AppDelegate togglePopover:]: unrecognized selector sent to instance 0x61000002a520
2017-06-08 15:55:29.125822+0200 MyWallpaper[7590:407660] [General] (
    0   CoreFoundation                      0x00007fffb36f32cb __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffc84fe48d objc_exception_throw + 48
    2   CoreFoundation                      0x00007fffb3774f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00007fffb3665755 ___forwarding___ + 1061
    4   CoreFoundation                      0x00007fffb36652a8 _CF_forwarding_prep_0 + 120
    5   libsystem_trace.dylib               0x00007fffc90153a7 _os_activity_initiate_impl + 53
    6   AppKit                              0x00007fffb18e1721 -[NSApplication(NSResponder) sendAction:to:from:] + 456
    7   AppKit                              0x00007fffb13c5cc4 -[NSControl sendAction:to:] + 86
    8   AppKit                              0x00007fffb18ceff7 -[NSStatusBarButtonCell _sendActionFrom:] + 155
    9   libsystem_trace.dylib               0x00007fffc90153a7 _os_activity_initiate_impl + 53
    10  AppKit                              0x00007fffb13c4426 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2481
    11  AppKit                              0x00007fffb1408272 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 798
    12  AppKit                              0x00007fffb18cea1f -[NSStatusBarButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 327
    13  AppKit                              0x00007fffb13c2ddb -[NSControl mouseDown:] + 832
    14  AppKit                              0x00007fffb1a5d24f -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 6341
    15  AppKit                              0x00007fffb1a59a6c -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 1942
    16  AppKit                              0x00007fffb1a58f0a -[NSWindow(NSEventRouting) sendEvent:] + 541
    17  AppKit                              0x00007fffb18d26d1 -[NSStatusBarWindow sendEvent:] + 581
    18  AppKit                              0x00007fffb18dd681 -[NSApplication(NSEvent) sendEvent:] + 1145
    19  AppKit                              0x00007fffb1158427 -[NSApplication run] + 1002
    20  AppKit                              0x00007fffb1122e0e NSApplicationMain + 1237
    21  MyWallpaper                         0x00000001000039ad main + 13
    22  libdyld.dylib                       0x00007fffc8de3235 start + 1
    23  ???                                 0x0000000000000003 0x0 + 3
)
</code>```

答:
Use the Swift #selector syntax

```<code>button.action = #selector(togglePopover(_:)) // or just #selector(togglePopover)
</code>```

ContentLicense: CC BY-SA 3.0

Title: NSStatusItem left click

Body:
First : I'm new with Swift developpement.

I'm using this tutorial to make a popup that will appears when I click on my top bar icon.

So my AppDelehgate code is :

func applicationDidFinishLaunching(_ aNotification: Notification){
    print("START !");
    if let button = statusItem.button {
        button.image = NSImage(named: "logo");
        button.action = Selector(("togglePopover:"));
        //button.target = self;
    }

    popover.contentViewController = QuotesViewController(nibName: "QuotesViewController", bundle: nil);
}

func togglePopover(envoyeur: AnyObject?){
    print("TOGGLE !");
    if popover.isShown{
        closePopover(sender: envoyeur)
    } else {
        showPopover(sender: envoyeur)
    }
}

But never the "TOGGLE !" text appears, the event doesn't works.

I put the "button.target = self;" into comment because it's crashing if I don't do it. The event seem's to be trigged, but i've got an error :

START !
2017-06-08 15:55:29.116275+0200 MyWallpaper[7590:407660] -[MyWallpaper.AppDelegate togglePopover:]: unrecognized selector sent to instance 0x61000002a520
2017-06-08 15:55:29.122570+0200 MyWallpaper[7590:407660] [General] -[MyWallpaper.AppDelegate togglePopover:]: unrecognized selector sent to instance 0x61000002a520
2017-06-08 15:55:29.125822+0200 MyWallpaper[7590:407660] [General] (
    0   CoreFoundation                      0x00007fffb36f32cb __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffc84fe48d objc_exception_throw + 48
    2   CoreFoundation                      0x00007fffb3774f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00007fffb3665755 ___forwarding___ + 1061
    4   CoreFoundation                      0x00007fffb36652a8 _CF_forwarding_prep_0 + 120
    5   libsystem_trace.dylib               0x00007fffc90153a7 _os_activity_initiate_impl + 53
    6   AppKit                              0x00007fffb18e1721 -[NSApplication(NSResponder) sendAction:to:from:] + 456
    7   AppKit                              0x00007fffb13c5cc4 -[NSControl sendAction:to:] + 86
    8   AppKit                              0x00007fffb18ceff7 -[NSStatusBarButtonCell _sendActionFrom:] + 155
    9   libsystem_trace.dylib               0x00007fffc90153a7 _os_activity_initiate_impl + 53
    10  AppKit                              0x00007fffb13c4426 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2481
    11  AppKit                              0x00007fffb1408272 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 798
    12  AppKit                              0x00007fffb18cea1f -[NSStatusBarButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 327
    13  AppKit                              0x00007fffb13c2ddb -[NSControl mouseDown:] + 832
    14  AppKit                              0x00007fffb1a5d24f -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 6341
    15  AppKit                              0x00007fffb1a59a6c -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 1942
    16  AppKit                              0x00007fffb1a58f0a -[NSWindow(NSEventRouting) sendEvent:] + 541
    17  AppKit                              0x00007fffb18d26d1 -[NSStatusBarWindow sendEvent:] + 581
    18  AppKit                              0x00007fffb18dd681 -[NSApplication(NSEvent) sendEvent:] + 1145
    19  AppKit                              0x00007fffb1158427 -[NSApplication run] + 1002
    20  AppKit                              0x00007fffb1122e0e NSApplicationMain + 1237
    21  MyWallpaper                         0x00000001000039ad main + 13
    22  libdyld.dylib                       0x00007fffc8de3235 start + 1
    23  ???                                 0x0000000000000003 0x0 + 3
)

Body:
Use the Swift #selector syntax

button.action = #selector(togglePopover(_:)) // or just #selector(togglePopover)


问:
rounded corners border around website
I have border around whole website and it works great,now how can I make it have rounded corners,I've tried :

```<code>border-radius: 25px
</code>```

but it doesnt work,and heres the normal border code that works but I need it rounded :

```<code>.ct, .cb, .cr, .cl {
border-radius: 25px
background-color: #ffffff;
    position: fixed;
    z-index: 99999;
}
.ct {
border-radius: 25px
  top: 0;
  right: 0;
  left: 0;
  height: 20px;
}
.cr {
border-radius: 25px
  top: 0;
  right: 0;
  bottom: 0;
  width: 20px;
}
.cb {
border-radius: 25px
  bottom: 0;
  right: 0;
  left: 0;
  height: 20px;
}
.cl {
border-radius: 25px
  top: 0;
  left: 0;
  bottom: 0;
  width: 20px;
}
</code>```

Thanks in advance

答:
Instead of using div's as borders just use border: size type color;

https://jsfiddle.net/dcLbza26/

html {
  height: 100vh;
  border: 20px solid red;
  border-radius: 25px;
}```

Title: rounded corners border around website

Body:
I have border around whole website and it works great,now how can I make it have rounded corners,I've tried :

border-radius: 25px

but it doesnt work,and heres the normal border code that works but I need it rounded :

.ct, .cb, .cr, .cl {
border-radius: 25px
background-color: #ffffff;
    position: fixed;
    z-index: 99999;
}
.ct {
border-radius: 25px
  top: 0;
  right: 0;
  left: 0;
  height: 20px;
}
.cr {
border-radius: 25px
  top: 0;
  right: 0;
  bottom: 0;
  width: 20px;
}
.cb {
border-radius: 25px
  bottom: 0;
  right: 0;
  left: 0;
  height: 20px;
}
.cl {
border-radius: 25px
  top: 0;
  left: 0;
  bottom: 0;
  width: 20px;
}

Thanks in advance


问:
Why this SFINAE snippet is not working in g++, but working in MSVC?
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

```<code>template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

```<code>In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'
</code>```

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

答:
@vsoftco answered "gcc is right to reject your code".  I agree.

To fix, I say do this:

```<code>namespace details {
  template<template<class...>class Z, class, class...Ts>
  struct can_apply:std::false_type{};
  template<class...>struct voider{using type=void;};
  template<class...Ts>using void_t = typename voider<Ts...>::type;

  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply=details::can_apply<Z,void,Ts...>;
</code>```

This is a can_apply library that makes this kind of SFINAE simple.

Now writing one of these traits is as simple as:

```<code>template<class T>
using dot_size_r = decltype( std::declval<T>().size() );

template<class T>
using has_dot_size = can_apply< dot_size_r, T >;
</code>```

test code:

```<code>int main() {
  static_assert( has_dot_size<std::vector<int>>{}, "TRUE" );
  static_assert( !has_dot_size<int>{}, "FALSE" );
}
</code>```

Live example.

In C++17 you can move over to less declval filled expressions.

```<code>#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }

template<class F>
constexpr auto can_invoke(F&&) {
  return [](auto&&...args) {
    return std::is_invocable< F(decltype(args)...) >{};
  };
}
</code>```

can_invoke takes a function f and returns a "invokation tester".  The invokation tester takes arguments, then returns true_type if those arguments would be valid to pass to f, and false_type otherwise.

RETURNS makes it easy to make a single-statement lambda SFINAE friendly.  And in C++17, the lambda's operations are constexpr if possible (which is why we need C++17 here).

Then, this gives us:

```<code>template<class T>
constexpr auto can_dot_size(T&& t) {
  return can_invoke([](auto&& x) RETURNS(x.size()))(t);
}
</code>```

Now, often we are doing this because we want to call .size() if possible, and otherwise return 0.

```<code>template<class T, class A, class...Bs>
decltype(auto) call_first_valid(T&& t, A&& a, Bs&&...bs) {
  if constexpr( can_invoke(std::forward<A>(a))(std::forward<T>(t)) ) {
    return std::forward<A>(a)(std::forward<T>(t));
  else
    return call_first_valid(std::forward<T>(t), std::forward<Bs>(bs)...);
}
</code>```

now we can

```<code>template<class T>
std::size_t size_at_least( T&& t ) {
  return call_first_valid( std::forward<T>(t),
    [](auto&& t) RETURNS(t.size()),
    [](auto&&)->std::size_t { return 0; }
  );
}
</code>```

As it happens, @Barry has proposed a feature in C++20 that replaces [](auto&& f) RETURNS(f.size()) with [](auto&& f)=>f.size() (and more).

Body:
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same
::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

Body:
@vsoftco answered "gcc is right to reject your code".  I agree.

To fix, I say do this:

namespace details {
  template<template<class...>class Z, class, class...Ts>
  struct can_apply:std::false_type{};
  template<class...>struct voider{using type=void;};
  template<class...Ts>using void_t = typename voider<Ts...>::type;

  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply=details::can_apply<Z,void,Ts...>;

This is a can_apply library that makes this kind of SFINAE simple.

Now writing one of these traits is as simple as:

template<class T>
using dot_size_r = decltype( std::declval<T>().size() );

template<class T>
using has_dot_size = can_apply< dot_size_r, T >;

test code:

int main() {
  static_assert( has_dot_size<std::vector<int>>{}, "TRUE" );
  static_assert( !has_dot_size<int>{}, "FALSE" );
}

Live example.

In C++17 you can move over to less declval filled expressions.

#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }

template<class F>
constexpr auto can_invoke(F&&) {
  return [](auto&&...args) {
    return std::is_invocable< F(decltype(args)...) >{};
  };
}

can_invoke takes a function f and returns a "invokation tester".  The invokation tester takes arguments, then returns true_type if those arguments would be valid to pass to f, and false_type otherwise.

RETURNS makes it easy to make a single-statement lambda SFINAE friendly.  And in C++17, the lambda's operations are constexpr if possible (which is why we need C++17 here).

Then, this gives us:

template<class T>
constexpr auto can_dot_size(T&& t) {
  return can_invoke([](auto&& x) RETURNS(x.size()))(t);
}

Now, often we are doing this because we want to call .size() if possible, and otherwise return 0.

template<class T, class A, class...Bs>
decltype(auto) call_first_valid(T&& t, A&& a, Bs&&...bs) {
  if constexpr( can_invoke(std::forward<A>(a))(std::forward<T>(t)) ) {
    return std::forward<A>(a)(std::forward<T>(t));
  else
    return call_first_valid(std::forward<T>(t), std::forward<Bs>(bs)...);
}

now we can

template<class T>
std::size_t size_at_least( T&& t ) {
  return call_first_valid( std::forward<T>(t),
    [](auto&& t) RETURNS(t.size()),
    [](auto&&)->std::size_t { return 0; }
  );
}

As it happens, @Barry has proposed a feature in C++20 that replaces [](auto&& f) RETURNS(f.size()) with [](auto&& f)=>f.size() (and more).


问:
NodeJS Passport-Steam, OpenID Invalid Return URL
I'm currently building a NodeJS back end with multiple OAuth and OpenID services. I have an issue with Passport-Steam that I just cannot figure out a solution.

Here is my Strategy:

```<code>var STEAM_KEY = process.env.STEAM_KEY;

// Use the SteamStrategy within Passport.
passport.use(new SteamStrategy({
    apiKey: STEAM_KEY,
    realm: 'https://player.abc/',
    returnURL: "https://player.abc/api/service/callback/steam"
}, function(identifier, profile, done) {
    done(null, profile);
}));
</code>```

When looking though the return URL and its parameters the server is receiving the correct URL within the "return_to" parameter and the correct endpoint is called. But I'm getting the following error:

```<code>GET /api/service/connect/steam 302 1500.518 ms - 0
{ [InternalOpenIDError: Failed to verify assertion]
  name: 'InternalOpenIDError',
  message: 'Failed to verify assertion',
  openidError: { message: 'Invalid return URL' }
}
</code>```

I've tried the following:

Changing to HTTP

Changing API Key (Current domain is set to "player.abc" within Steam Dev)

Changing the return URL completely

Reinstalling passport-steam

Any help would be much appreciated

答:
You forgot to add

profile.identifier = identifier;

passport.use(new SteamStrategy({
    apiKey: STEAM_KEY,
    realm: 'https://player.abc/',
    returnURL: "https://player.abc/api/service/callback/steam"
}, function(identifier, profile, done) {
    profile.identifier = identifier;
    done(null, profile);
}));```

Body:
I'm currently building a NodeJS back end with multiple OAuth and OpenID services. I have an issue with Passport-Steam that I just cannot figure out a solution.

Here is my Strategy:

var STEAM_KEY = process.env.STEAM_KEY;

// Use the SteamStrategy within Passport.
passport.use(new SteamStrategy({
    apiKey: STEAM_KEY,
    realm: 'https://player.abc/',
    returnURL: "https://player.abc/api/service/callback/steam"
}, function(identifier, profile, done) {
    done(null, profile);
}));

When looking though the return URL and its parameters the server is receiving the correct URL within the "return_to" parameter and the correct endpoint is called. But I'm getting the following error:

GET /api/service/connect/steam 302 1500.518 ms - 0
{ [InternalOpenIDError: Failed to verify assertion]
  name: 'InternalOpenIDError',
  message: 'Failed to verify assertion',
  openidError: { message: 'Invalid return URL' }
}

I've tried the following:

Changing to HTTP

Changing API Key (Current domain is set to "player.abc" within Steam Dev)

Changing the return URL completely

Reinstalling passport-steam

Any help would be much appreciated


问:
How to make a object instance of a existing instance of a usercontrol?
How to make a object instance of a existing instance of a usercontrol?

```<code>public partial class Rfid : UserControl
</code>```

This is how you would do it with an Window?

```<code>public partial class MainWindow : Window
MainWindow my = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
</code>```

答:
How to make a object instance of a existing instance of a usercontrol?

Like you would create an instance of any other class:

```<code>Rfid obj = new Rfid();
</code>```

Or in XAML:

```<code><local:Rfid />
</code>```

Both create an instance of the Rfid (UserControl) class at runtime.

This is how you would do it with an Window?

No. That gets a reference to an already existing instance of the MainWindow class that is referenced from the Application.Current.Windows collection property. It doesn't construct any new window object.

Body:
How to make a object instance of a existing instance of a usercontrol?

public partial class Rfid : UserControl

This is how you would do it with an Window?

public partial class MainWindow : Window
MainWindow my = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();

Body:
How to make a object instance of a existing instance of a usercontrol?

Like you would create an instance of any other class:

Rfid obj = new Rfid();

Or in XAML:

<local:Rfid />

Both create an instance of the Rfid (UserControl) class at runtime.

This is how you would do it with an Window?

No. That gets a reference to an already existing instance of the MainWindow class that is referenced from the Application.Current.Windows collection property. It doesn't construct any new window object.


问:
Swift & Parse - Empty PFFile
I'm using Parse and MongoDB for my app, and I have a problem concerning PFFile.
I would like to save an empty PFFile on the server.
Indeed, the user doesn't have to send a picture but in an other way, it's possible.

I would like to set a default PFFile which is null.

```<code>    let imageFile: PFFile?

if previewImg.image != nil {
             // Send pic to server after converting to FILE and compression
             let imageData = UIImageJPEGRepresentation(previewImg.image!, 0.5)
             imageFile = PFFile(name: "step.jpg", data: imageData!)
          } else {
             imageFile = ""
          }

          object["stepImg"] = imageFile
</code>```

This is my code. And my error is "cannot assign value of type string to type PFFile".

Do you have an idea about how I can do that ?

答:
You declare a PFFile? so your variable can a PFFile or nil

This is the corrected code

```<code>let imageFile: PFFile?

if let previewImage = previewImg.image {
    // Send pic to server after converting to FILE and compression
    let imageData = UIImageJPEGRepresentation(previewImage, 0.5)
    object["stepImg"] = PFFile(name: "step.jpg", data: imageData!)
}
</code>```

Title: Swift & Parse - Empty PFFile

Body:
I'm using Parse and MongoDB for my app, and I have a problem concerning PFFile.
I would like to save an empty PFFile on the server.
Indeed, the user doesn't have to send a picture but in an other way, it's possible.

I would like to set a default PFFile which is null.

    let imageFile: PFFile?

if previewImg.image != nil {
             // Send pic to server after converting to FILE and compression
             let imageData = UIImageJPEGRepresentation(previewImg.image!, 0.5)
             imageFile = PFFile(name: "step.jpg", data: imageData!)
          } else {
             imageFile = ""
          }

          object["stepImg"] = imageFile

This is my code. And my error is "cannot assign value of type string to type PFFile".

Do you have an idea about how I can do that ?

Body:
You declare a PFFile? so your variable can a PFFile or nil

This is the corrected code

let imageFile: PFFile?

if let previewImage = previewImg.image {
    // Send pic to server after converting to FILE and compression
    let imageData = UIImageJPEGRepresentation(previewImage, 0.5)
    object["stepImg"] = PFFile(name: "step.jpg", data: imageData!)
}


问:
Chrome Blank PDF Print Preview
Looks like print preview for some embed pdf files "application/x-google-chrome-pdf" is not working anymore.
Open this pdf file in Chrome version 59.x and try printing it.
I have Adobe Reader XI version 11.0.20 installed on my system.
Is there anyway to fix this issue?</p>

答:
For me the incompatibility issue with chrome 59 seems to be because of the javascript we are injecting to the PDF using QuickPDF library (PageJavaScriptAction).
The JS code is:

```<code>try{
   print( {bUI: true, bShrinkToFit: true});
} catch(e){
    try{
       print({bUI: true, bShrinkToFit: true});
    } catch(e1){app.alert(e + ',' + e1);}
}
</code>```

After removing this code, the preview seems to be working fine again similar to the older versions of chrome.

Title: Chrome Blank PDF Print Preview

Body:
For me the incompatibility issue with chrome 59 seems to be because of the javascript we are injecting to the PDF using QuickPDF library (PageJavaScriptAction).
The JS code is:

try{
   print( {bUI: true, bShrinkToFit: true});
} catch(e){
    try{
       print({bUI: true, bShrinkToFit: true});
    } catch(e1){app.alert(e + ',' + e1);}
}

After removing this code, the preview seems to be working fine again similar to the older versions of chrome.


问:
Modifying state & the correct way to update my reducer? (React / Redux)
I believe that I have been modifying my state for quite some time now. I wanted to do the following and was wondering why it did not work:

```<code>case "SAVE_DATA_TO_PERSON" :
        let newState = {...state, data: {start: action.payload.start, end: action.payload.end}};
        return newState;
</code>```

I am here creating a new object, take the old state, and add my new data.
While it does seem to make a difference, it does not keep the data for long. After firing other actions this is just gone. I wonder why?

This is how I used to do it, and it seems to work:

```<code>case "SAVE_DATA_TO_PERSON" :
        let newState = state;
        newState.audio = {start: action.payload.start, end: action.payload.end};

        return newState;
</code>```

But here, it seems, I am modifying state.

I would just like to know whether my first solution is the correct one, and my second solution here is indeed modifying state.

答:
In the second options you are modifying the state directly.

The reducer should changing state in a React-Redux application without mutate existing state.

Immutability is a requirement of Redux because Redux represents your
  application state as "frozen object snapshots". With these discrete
  snapshots, you can save your state, or reverse state, and generally
  have more "accounting" for all state changes. Ref.

You cloud consider using and immutable utility/library as dot-prop-immutable or Immutable.js

Related article from redux docs:

http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html

Body:
I believe that I have been modifying my state for quite some time now. I wanted to do the following and was wondering why it did not work:

case "SAVE_DATA_TO_PERSON" :
        let newState = {...state, data: {start: action.payload.start, end: action.payload.end}};
        return newState;

I am here creating a new object, take the old state, and add my new data.
While it does seem to make a difference, it does not keep the data for long. After firing other actions this is just gone. I wonder why?

This is how I used to do it, and it seems to work:

case "SAVE_DATA_TO_PERSON" :
        let newState = state;
        newState.audio = {start: action.payload.start, end: action.payload.end};

        return newState;

But here, it seems, I am modifying state.

I would just like to know whether my first solution is the correct one, and my second solution here is indeed modifying state.


问:
In JavaScript, 'onbeforeunload' not working until we clicked on opened window
In JavaScript, 'onbeforeunload' not working until we clicked on opened window.

Please suggest me any solution.

Thanks in advance

答:
Based on your comment, I don't think you're using it correctly. You need to return a string, not use an alert.

Parent page:

```<code><script>
var w;
function x(){
  w = window.open('test2.html');
}
</script>
<button onclick="x();">open</button>
<button onclick="w.close();">close</button>
</code>```

Popup:

```<code><html>
<head>
<script>
window.onbeforeunload=function (e) {
  e.returnValue = "Are you sure you want to leave this page?";
   return e.returnValue;
 }
</script>
</head>
<body>
popup
</body>
</html>
</code>```

Body:
Based on your comment, I don't think you're using it correctly. You need to return a string, not use an alert.

Parent page:

<script>
var w;
function x(){
  w = window.open('test2.html');
}
</script>
<button onclick="x();">open</button>
<button onclick="w.close();">close</button>

Popup:

<html>
<head>
<script>
window.onbeforeunload=function (e) {
  e.returnValue = "Are you sure you want to leave this page?";
   return e.returnValue;
 }
</script>
</head>
<body>
popup
</body>
</html>


问:
Enabling JPEG support for QImage in py2exe-compiled Python scripts?
I'm trying to use a JPEG image in a QImage object from a Python script, with PyQt4.

The script itself works perfectly, the image loads and can be manipulated and rendered and all. However, when I try to "compile" this script with py2exe, everything works but the JPEG image. Replacing it with a PNG equivalent works, but since my program downloads images from the web, they won't always be in PNG format and I can't afford converting them all with another library.

I've discovered that JPEG image support for QImage, along with other image formats, is provided by some DLLs in the \qt\plugins\imageformats directory (they're called qjpeg4.dll and qjpeg4d.dll). I think I need to use them somehow in my executable, but I don't know how. I've tried simply copying them to my exe directory, no luck. I've tried, as indicated here, to include those files as data_files in the setup.py script, but no luck (it looks like all it does is copying these files to the exe's directory, so it changes nothing from copying them manually anyway).

I'm sure there's a handful of applications out there using PyQt with JPEG images, how do they do it? It seemed like a trivial task but I'm stuck on it now.

Also, I want my app to be cross-platform (why else would I be coding in Python?), I hope I won't run into such packaging trouble (it's not the only one) when packaging for OS X or Linux. Will I?

答:
Everything above failed for me until I realized that I was bundling the .exe  (that is, I had the option "bundle_files" : 2  in my setup.py.  I changed it to bundle_files = 2, and now it works great.

The above solutions are fine. Specifically, I just added the following line in my setup.py:
data = [ ("imageformats", glob.glob("C:\Python26\Lib\site-packages\PyQt4\plugins\imageformats*.dll")) ]

(in addition to other files, of course).

Then, the image loading dlls are in MY_EXE_DIR/imageformats

I didn't need a qt.conf to make this work, though I'm sure you could use it if you want to keep your directory tree less cluttered.

ContentLicense: CC BY-SA 2.5


问:
MimeMessage.saveChanges is really slow
The following test is taking around 5 seconds to execute due to the inclusion of m.saveChanges().

```<code>import org.junit.Before;
import org.junit.Test;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@Test
public void test1() throws MessagingException, IOException {
    Session s = Session.getDefaultInstance(new Properties());
    MimeMessage m = new MimeMessage(s);
    m.setContent("<b>Hello</b>", "text/html; charset=utf-8");
    m.saveChanges();
    assertEquals(m.getContent(), "<b>Hello</b>");
    assertEquals(m.getContentType(), "text/html; charset=utf-8");
}
</code>```

I have also mocked the Session with mockito but it doesn't help:

```<code>Session s = mock(Session.class);
when(s.getProperties()).thenReturn(new Properties());
</code>```

What is the problem here? What can I mock to speed things up?

答:
Fix the most common mistakes people make when using JavaMail in your code first.

DNS lookup can hurt performance on some machines. For the JDK you can change the security properties for caching DNS lookup networkaddress.cache.ttl and networkaddress.cache.negative.ttl or set the system properties sun.net.inetaddr.ttl and sun.net.inetaddr.negative.ttl.  The default behavior in JDK 7 and later does a good job of caching so you shouldn't have to change these settings.

Preferably, you can use the session properties to avoid some these lookups.

Add session property for mail.from or mail.host (these exact key names) as either property will prevent the name lookup inside of InternetAddress.getLocalAddress(Session).  These properties can be set in addition to or without their counterpart properties which contain the protocol in the key names (more on that later).  These properties will improve the performance of MimeMessage.saveChanges(), MimeMessage.updateHeaders(), MimeMessage.updateMessageID(), and MimeMessage.setFrom() which all call InternetAddress::getLocalAddress.  If the above properties are not set then this method will attempt to query for the host name.  By setting the properties, this method will pull the host name string from the session instead of attempting the expensive DNS lookup.

Set the session property for mail.smtp.localhost or mail.smtps.localhost to prevent name lookup on the HELO command on transport.

Set session property for mail.smtp.from or mail.smtps.from to prevent lookup on EHLO command on transport.

Alternatively, you can set the system property mail.mime.address.usecanonicalhostname to false if your code is relying on the setFrom() but this will be handled if you applied point #1.

For IMAP, you can try to set mail.imap.sasl.usecanonicalhostname or mail.imaps.sasl.usecanonicalhostname to false which is the default value.

Since your are not transporting a message, apply rule #1 by changing your code to:

```<code>@Test
public void test1() throws MessagingException, IOException {
    Properties props = new Properties();
    props.put("mail.host", "localhost"); //Or use IP.
    Session s = Session.getInstance(props);
    MimeMessage m = new MimeMessage(s);
    m.setContent("<b>Hello</b>", "text/html; charset=utf-8");
    m.saveChanges();
    assertEquals(m.getContent(), "<b>Hello</b>");
    assertEquals(m.getContentType(), "text/html; charset=utf-8");
}
</code>```

If you are transporting a message then combine the rules #1, #2, and #3 which will prevent accessing the host system for a name lookup.  If you want to prevent all DNS lookups during a transport then you have to use IP addresses.

Title: MimeMessage.saveChanges is really slow

Body:
The following test is taking around 5 seconds to execute due to the inclusion of m.saveChanges().

import org.junit.Before;
import org.junit.Test;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@Test
public void test1() throws MessagingException, IOException {
    Session s = Session.getDefaultInstance(new Properties());
    MimeMessage m = new MimeMessage(s);
    m.setContent("Hello", "text/html; charset=utf-8");
    m.saveChanges();
    assertEquals(m.getContent(), "Hello");
    assertEquals(m.getContentType(), "text/html; charset=utf-8");
}

I have also mocked the Session with mockito but it doesn't help:

Session s = mock(Session.class);
when(s.getProperties()).thenReturn(new Properties());

What is the problem here? What can I mock to speed things up?

Body:
Fix the most common mistakes people make when using JavaMail in your code first.

DNS lookup can hurt performance on some machines. For the JDK you can change the security properties for caching DNS lookup networkaddress.cache.ttl and networkaddress.cache.negative.ttl or set the system properties sun.net.inetaddr.ttl and sun.net.inetaddr.negative.ttl.  The default behavior in JDK 7 and later does a good job of caching so you shouldn't have to change these settings.

Preferably, you can use the session properties to avoid some these lookups.

Add session property for mail.from or mail.host (these exact key names) as either property will prevent the name lookup inside of InternetAddress.getLocalAddress(Session).  These properties can be set in addition to or without their counterpart properties which contain the protocol in the key names (more on that later).  These properties will improve the performance of MimeMessage.saveChanges(), MimeMessage.updateHeaders(), MimeMessage.updateMessageID(), and MimeMessage.setFrom() which all call InternetAddress::getLocalAddress.  If the above properties are not set then this method will attempt to query for the host name.  By setting the properties, this method will pull the host name string from the session instead of attempting the expensive DNS lookup.

Set the session property for mail.smtp.localhost or mail.smtps.localhost to prevent name lookup on the HELO command on transport.

Set session property for mail.smtp.from or mail.smtps.from to prevent lookup on EHLO command on transport.

Alternatively, you can set the system property mail.mime.address.usecanonicalhostname to false if your code is relying on the setFrom() but this will be handled if you applied point #1.

For IMAP, you can try to set mail.imap.sasl.usecanonicalhostname or mail.imaps.sasl.usecanonicalhostname to false which is the default value.

Since your are not transporting a message, apply rule #1 by changing your code to:

@Test
public void test1() throws MessagingException, IOException {
    Properties props = new Properties();
    props.put("mail.host", "localhost"); //Or use IP.
    Session s = Session.getInstance(props);
    MimeMessage m = new MimeMessage(s);
    m.setContent("<b>Hello</b>", "text/html; charset=utf-8");
    m.saveChanges();
    assertEquals(m.getContent(), "<b>Hello</b>");
    assertEquals(m.getContentType(), "text/html; charset=utf-8");
}

If you are transporting a message then combine the rules #1, #2, and #3 which will prevent accessing the host system for a name lookup.  If you want to prevent all DNS lookups during a transport then you have to use IP addresses.

ContentLicense: CC BY-SA 4.0


问:
wkhtmltopdf not accepting values in url?
So I'm creating a tool which uses wkhtmltopdf to convert my html to PDF.
for example this does work:

```<code>wkhtmltopdf google.com test1.pdf
</code>```

However my tool requires to have some values changed whenever this is necessary, and that's why I send my values through my url.

I send these values like this:

```<code>.[url]final.php?myTextField1=name&myTextField2=man&myTextField3=Blablablabla&myTextField4=kleur&myTextField5=zekerwel&myTextField6=hoihallo
</code>```

However if I try to convert this url like this:

```<code>wkhtmltopdf [url]/final.php?myTextField1=name&myTextField2=man&myTextField3=Blablablabla&myTextField4=kleur&myTextField5=zekerwel&myTextField6=hoihallo test1.pdf
</code>```

wkhtmltopdf does not seem to accept it, is there any workaround for this?

答: It has been a while since I have used the tool, but there were a few issues I recall to using it this way -- one was you had to make sure to wrap the urls in quotes.</p>

Body:
So I'm creating a tool which uses wkhtmltopdf to convert my html to PDF.
for example this does work:

wkhtmltopdf google.com test1.pdf

However my tool requires to have some values changed whenever this is necessary, and that's why I send my values through my url.

I send these values like this:

.[url]final.php?myTextField1=name&myTextField2=man&myTextField3=Blablablabla&myTextField4=kleur&myTextField5=zekerwel&myTextField6=hoihallo

However if I try to convert this url like this:

wkhtmltopdf [url]/final.php?myTextField1=name&myTextField2=man&myTextField3=Blablablabla&myTextField4=kleur&myTextField5=zekerwel&myTextField6=hoihallo test1.pdf

wkhtmltopdf does not seem to accept it, is there any workaround for this?


问:
Loop through a string and wrap each word in a div - PHP
Im getting a websites "keywords" for my web ranker. Its returning the result I need, but I want to wrap each keyword its returning into a span tag.

This is how im  getting the keywords:

```<code>$websiteTags = get_meta_tags('http://www.'.$website.'/');

dd($websiteTags);
</code>```

Which gives me this:

Them I just call the $websiteTags['keywords']; to get this result:

I need to wrap each word in that string in a span tag so it will look nicer in the frontend, because right now its just putting out that long string.

My question is, how would I  loop through that string and wrap each keyword in a span tag.

I have tried doing foreach loops, str_replace() and looked online, but could not find the solution I need.

答: Not sure if it would work, but you could try placing your data in a database and query the data and use a while loop to echo the spans</p>

Body:
Im getting a websites "keywords" for my web ranker. Its returning the result I need, but I want to wrap each keyword its returning into a span tag.

This is how im  getting the keywords:

$websiteTags = get_meta_tags('http://www.'.$website.'/');

dd($websiteTags);

Which gives me this:

Them I just call the $websiteTags['keywords']; to get this result:

I need to wrap each word in that string in a span tag so it will look nicer in the frontend, because right now its just putting out that long string.

My question is, how would I  loop through that string and wrap each keyword in a span tag.

I have tried doing foreach loops, str_replace() and looked online, but could not find the solution I need.


问:
jQuery: prevent click queue
```<code>$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});
</code>```

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:

```<code><img src="/images/right.png" id="right" alt="" />
<div id="container">
    <div id="image_scroll">
        <img src="1.jpg" />
        <img src="3.jpg" />
        <img src="4.jpg" />
    </div><!-- /#image_scroll -->
</div> <!-- /#container
</code>```

答:
You need to provide a callback to animate...</p>

```<code>$("#right").live("click", function(event) {
    event.preventDefault();
    var src = $(this).attr('href');
    $(".image_scroll").animate({"left": "+=300px"}, "slow", function() { window.location.href = src; });
});
</code>```

Title: jQuery: prevent click queue

Body:
$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:

Body:
You need to provide a callback to animate...

$("#right").live("click", function(event) {
    event.preventDefault();
    var src = $(this).attr('href');
    $(".image_scroll").animate({"left": "+=300px"}, "slow", function() { window.location.href = src; });
});


问:
How do I parse the fields in a comma separated list and convert them to Integer
I have the following:

```<code>char *strings = "1998,9,20,"
</code>```

Here I want to store each number into an integer varaible and print as :

1998

9

20

I tried using strtok and then atoi but this did not help me as my variable is a character pointer and not an array.

答:
Maybe this does what you want to do in a simple way?</p>

```<code>const char *strings = "1998,9,20,";
const char *ptr = strings;
while (true) {
    int val;
    val = atoi(ptr);
    ptr = strchr(ptr,',');

    if (ptr == 0)
        break;

    std::cout << val << std::endl;
    ptr++;
}
</code>```

Body:
I have the following:

char *strings = "1998,9,20,"

Here I want to store each number into an integer varaible and print as :

1998

9

20

I tried using strtok and then atoi but this did not help me as my variable is a character pointer and not an array.

Body:
Maybe this does what you want to do in a simple way?

const char *strings = "1998,9,20,";
const char *ptr = strings;
while (true) {
    int val;
    val = atoi(ptr);
    ptr = strchr(ptr,',');

    if (ptr == 0)
        break;

    std::cout << val << std::endl;
    ptr++;
}


问:
Combining Rows by Code
Data set:

```<code>  CREATE TABLE Returned(
  Code varchar(20) not null,
  RUnits int not null,
  RCost int not null,
  RPrice int not null,
  RDate date not null);

  Insert into Returned(Code, Runits, rcost, rprice, rdate)
  values
  ('ORANGES123', 10, 200, 500, '2017-04-01'),
  ('BANANAS123', 15, 350, 900, '2017-04-01'),
  ('APPLES123', 7, 234, 756, '2017-04-01'),
    ('ORANGES123', 10, 200, 500, '2017-04-02'),
  ('BANANAS123', 15, 350, 900, '2017-04-02'),
  ('APPLES123', 7, 234, 756, '2017-04-02');

  CREATE TABLE Cancelled(
  Code varchar(20) not null,
  CUnits int not null,
  CCost int not null,
  CPrice int not null,
  CDate date not null
  );

    Insert into Cancelled(Code, Cunits, Ccost, Cprice, Cdate)
  values
  ('ORANGES123', 3, 100, 200, '2017-04-01'),
  ('BANANAS123', 5, 243, 500, '2017-04-01'),
  ('APPLES123', 10, 235, 537, '2017-04-01'),
  ('ORANGES123', 3, 100, 200, '2017-04-02'),
  ('BANANAS123', 5, 243, 500, '2017-04-02'),
  ('APPLES123', 10, 235, 537, '2017-04-02');
</code>```

Sqlfiddle here:

http://sqlfiddle.com/#!9/f10634

Background:

I have 2 tables. A table for returns, and a table for cancels. I want to get a summation over the past week of the total number of units/cost/price for a given item code. For example, from the sqlfiddle, ORANGES123, I want my query to return:

```<code>ItemCode  , TotalReturnedUnits, TotalReturnedCost, TotalReturnedPrice,TotalCancelledUnits, TotalCancelledCost, TotalCancelledPrice
ORANGES123,                 20,               400,               1000,                  6,                200,                 400
</code>```

This seems simple but for some reason when I'm doing an inner join by ItemCode between my two tables in SQL Server, Units between the Cancelled and Returned tables are being combined and the counts are being cross-polluted between Returned/Cancelled.

I feel like I'm missing something very simple.

Any help would be appreciated.

The actual query I'm working with is here. I tried to model the sqlfiddle as close as possible:

```<code>SELECT sales.Code AS Code,
       sales.Quantity AS QtyReturned,
       price.WghtAvgCost * sales.Quantity AS ReturnedCost,
       price.CurrentPrice * sales.Quantity AS ReturnedPrice,
       orders.CancelledUnits,
       orders.CancelledCost,
       orders.CancelledPrice,
       price.CurrentPriceType AS PriceType
FROM salesTable sales
     INNER JOIN costPriceTable price ON sales.Code= price.Code
                                                  AND (sales.BusinessDate BETWEEN price.StartDate AND price.EndDate)
                                                  AND sales.LocationId = price.LocationId
    INNER JOIN  ordersTable orders
       ON sales.Code= orders.Code
</code>```

答:
You can use a joined query to achieve this, follow the same structure for your cancellations as well.</p>

```<code>JOIN
(SELECT
Code, sum(RUnits) as TotalReturnedUnits, sum(RCost) as TotalReturnedCost,
sum(RPrice) as TotalReturnedPrice
from Returned
where

--parameterised dates can be used
--RDate between @Start and @End

group by Code
)returns
ON salesTable.Code = returns.Code
</code>```

Title: Combining Rows by Code

Body:
Data set:

  CREATE TABLE Returned(
  Code varchar(20) not null,
  RUnits int not null,
  RCost int not null,
  RPrice int not null,
  RDate date not null);

  Insert into Returned(Code, Runits, rcost, rprice, rdate)
  values
  ('ORANGES123', 10, 200, 500, '2017-04-01'),
  ('BANANAS123', 15, 350, 900, '2017-04-01'),
  ('APPLES123', 7, 234, 756, '2017-04-01'),
    ('ORANGES123', 10, 200, 500, '2017-04-02'),
  ('BANANAS123', 15, 350, 900, '2017-04-02'),
  ('APPLES123', 7, 234, 756, '2017-04-02');

  CREATE TABLE Cancelled(
  Code varchar(20) not null,
  CUnits int not null,
  CCost int not null,
  CPrice int not null,
  CDate date not null
  );

    Insert into Cancelled(Code, Cunits, Ccost, Cprice, Cdate)
  values
  ('ORANGES123', 3, 100, 200, '2017-04-01'),
  ('BANANAS123', 5, 243, 500, '2017-04-01'),
  ('APPLES123', 10, 235, 537, '2017-04-01'),
  ('ORANGES123', 3, 100, 200, '2017-04-02'),
  ('BANANAS123', 5, 243, 500, '2017-04-02'),
  ('APPLES123', 10, 235, 537, '2017-04-02');

Sqlfiddle here:

http://sqlfiddle.com/#!9/f10634

Background:

I have 2 tables. A table for returns, and a table for cancels. I want to get a summation over the past week of the total number of units/cost/price for a given item code. For example, from the sqlfiddle, ORANGES123, I want my query to return:

ItemCode  , TotalReturnedUnits, TotalReturnedCost, TotalReturnedPrice,TotalCancelledUnits, TotalCancelledCost, TotalCancelledPrice
ORANGES123,                 20,               400,               1000,                  6,                200,                 400

This seems simple but for some reason when I'm doing an inner join by ItemCode between my two tables in SQL Server, Units between the Cancelled and Returned tables are being combined and the counts are being cross-polluted between Returned/Cancelled.

I feel like I'm missing something very simple.

Any help would be appreciated.

The actual query I'm working with is here. I tried to model the sqlfiddle as close as possible:

SELECT sales.Code AS Code,
       sales.Quantity AS QtyReturned,
       price.WghtAvgCost * sales.Quantity AS ReturnedCost,
       price.CurrentPrice * sales.Quantity AS ReturnedPrice,
       orders.CancelledUnits,
       orders.CancelledCost,
       orders.CancelledPrice,
       price.CurrentPriceType AS PriceType
FROM salesTable sales
     INNER JOIN costPriceTable price ON sales.Code= price.Code
                                                  AND (sales.BusinessDate BETWEEN price.StartDate AND price.EndDate)
                                                  AND sales.LocationId = price.LocationId
    INNER JOIN  ordersTable orders
       ON sales.Code= orders.Code

Body:
You can use a joined query to achieve this, follow the same structure for your cancellations as well.

JOIN
(SELECT
Code, sum(RUnits) as TotalReturnedUnits, sum(RCost) as TotalReturnedCost,
sum(RPrice) as TotalReturnedPrice
from Returned
where

--parameterised dates can be used
--RDate between @Start and @End

group by Code
)returns
ON salesTable.Code = returns.Code


问:
Java BMI Calculator Issue - Imperial or Metric User Input, Error Handling, Correct Values Input, Conversion
I am currently working on my first Java program for my final assignment as a beginner programmer, however, I am quite confused with some parts of it. I saw that there are a lot of BMI calculator source codes but most of them are very simple.
  My assignment, however, requires input of Imperial or Metric values, conversion of the input from Metric to Imperial or vice versa, error handling, and validation of user input. I won't even try to use a GUI, so if someone can give me some directions for the simple form of the program, I would be very grateful.
Here is my code so far (I hope it's not a total mess):</p>

```<code>import java.util.Scanner;

public class BodyMassIndex {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

       double weightKg, weightPounds, weightStones, heightCm, heightMeters,
               heightFeet, heightInches, bMIMetric, bMIImperial;

       System.out.println("Please, enter your weight in kilograms: ");
       weightKg = input.nextDouble();
       System.out.println("Please enter your height in centimeters: ");
       heightCm = input.nextDouble();

       String correctValues1;
       if (weightKg < 20 && weightKg > 400) {
           System.out.println("Please enter valid weight.");
           correctValues1 = "Please enter valid weight.";
       }
       if (heightCm < 20 && heightCm > 250) {
           System.out.println("Please enter valid height.");
           correctValues1 = "Plase enter valid height.";
       }

       System.out.println("Please, enter your weight in pounds: ");
       weightPounds = input.nextDouble();
       System.out.println("Please enter your height in inches: ");
       heightInches = input.nextDouble();

       String correctValues2;
       if (weightPounds < 44 && weightPounds > 882) {
       System.out.println("Please enter valid weight.");
       correctValues2 = "Please enter valid weight.";
       }
       if (heightInches < 7 && heightInches > 98) {
       System.out.println("Please enter valid height.");
       correctValues2 = "Please enter valid height.";
       }

       heightMeters = heightCm/100;
       weightPounds = weightKg*0.453592;
       weightStones = weightKg*6.35029318;
       heightFeet = heightCm*0.0328084;
       heightInches = heightCm*0.393701;

       bMIMetric = (weightKg/(heightMeters*heightMeters));

       bMIImperial = (weightPounds/(heightInches*heightInches))*703;

    System.out.printf("Height in meters is %.2f\n", heightMeters);
    System.out.printf("Weight in pounds is %.2f\n", weightPounds);
    System.out.printf("Weight in stones is %.2f\n", weightStones);
    System.out.printf("Height in feet is %.2f\n", heightFeet);
    System.out.printf("Height in inches is %.2f\n", heightInches);

    String Result1;
            if (bMIMetric < 18.5) {
            System.out.println("less than 18.5");
            Result1 = "Underweight";
            } else if ((bMIMetric) >= 18.5 && (bMIMetric) <= 24.9) {
            System.out.println("between 18.5 and 24.9");
            Result1 = "Normal";
            } else if (bMIMetric >= 25 && bMIMetric <= 29.9) {
            System.out.println("between 25 and 29.9");
            Result1 = "Overweight";
            } else {
            System.out.println("greater than 30");
            Result1 = "Obese";
            }

    String Result2;
            if (bMIImperial < 18.5) {
            System.out.println("less than 18.5");
            Result2 = "Underweight";
            } else if ((bMIImperial) >= 18.5 && (bMIImperial) <= 24.9) {
            System.out.println("between 18.5 and 24.9");
            Result2 = "Normal";
            } else if (bMIImperial >= 25 && bMIImperial <= 29.9) {
            System.out.println("between 25 and 29.9");
            Result2 = "Overweight";
            } else {
            System.out.println("greater than 30");
            Result2 = "Obese";
            }

    System.out.println("Your Body Mass Index is:" + bMIMetric + "(" + Result1 +")");
    System.out.println("Your Body Mass Index is:" + bMIImperial +"(" + Result2 +")");

        }
    }
</code>```

答:
You are trying to make it complex, which is actually not easy task.
As a consequence youre making redundand and nonlogical steps.

input
Youre asking for double input in different metric. For example weight in kilograms and in pounds. You need to ask user which metric is he using and start from there.

error checking
I'd suggest to use try/catch block and look for non numerical values

```<code>try {
    // get your input
} catch(InputMismatchException ex) {
    // try again
}
</code>```

hope this helps a bit

Body:
I am currently working on my first Java program for my final assignment as a beginner programmer, however, I am quite confused with some parts of it. I saw that there are a lot of BMI calculator source codes but most of them are very simple.
  My assignment, however, requires input of Imperial or Metric values, conversion of the input from Metric to Imperial or vice versa, error handling, and validation of user input. I won't even try to use a GUI, so if someone can give me some directions for the simple form of the program, I would be very grateful.
Here is my code so far (I hope it's not a total mess):

import java.util.Scanner;

public class BodyMassIndex {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

       double weightKg, weightPounds, weightStones, heightCm, heightMeters,
               heightFeet, heightInches, bMIMetric, bMIImperial;

       System.out.println("Please, enter your weight in kilograms: ");
       weightKg = input.nextDouble();
       System.out.println("Please enter your height in centimeters: ");
       heightCm = input.nextDouble();

       String correctValues1;
       if (weightKg < 20 && weightKg > 400) {
           System.out.println("Please enter valid weight.");
           correctValues1 = "Please enter valid weight.";
       }
       if (heightCm < 20 && heightCm > 250) {
           System.out.println("Please enter valid height.");
           correctValues1 = "Plase enter valid height.";
       }

       System.out.println("Please, enter your weight in pounds: ");
       weightPounds = input.nextDouble();
       System.out.println("Please enter your height in inches: ");
       heightInches = input.nextDouble();

       String correctValues2;
       if (weightPounds < 44 && weightPounds > 882) {
       System.out.println("Please enter valid weight.");
       correctValues2 = "Please enter valid weight.";
       }
       if (heightInches < 7 && heightInches > 98) {
       System.out.println("Please enter valid height.");
       correctValues2 = "Please enter valid height.";
       }

       heightMeters = heightCm/100;
       weightPounds = weightKg*0.453592;
       weightStones = weightKg*6.35029318;
       heightFeet = heightCm*0.0328084;
       heightInches = heightCm*0.393701;

       bMIMetric = (weightKg/(heightMeters*heightMeters));

       bMIImperial = (weightPounds/(heightInches*heightInches))*703;

    System.out.printf("Height in meters is %.2f\n", heightMeters);
    System.out.printf("Weight in pounds is %.2f\n", weightPounds);
    System.out.printf("Weight in stones is %.2f\n", weightStones);
    System.out.printf("Height in feet is %.2f\n", heightFeet);
    System.out.printf("Height in inches is %.2f\n", heightInches);

    String Result1;
            if (bMIMetric < 18.5) {
            System.out.println("less than 18.5");
            Result1 = "Underweight";
            } else if ((bMIMetric) >= 18.5 && (bMIMetric) <= 24.9) {
            System.out.println("between 18.5 and 24.9");
            Result1 = "Normal";
            } else if (bMIMetric >= 25 && bMIMetric <= 29.9) {
            System.out.println("between 25 and 29.9");
            Result1 = "Overweight";
            } else {
            System.out.println("greater than 30");
            Result1 = "Obese";
            }

    String Result2;
            if (bMIImperial < 18.5) {
            System.out.println("less than 18.5");
            Result2 = "Underweight";
            } else if ((bMIImperial) >= 18.5 && (bMIImperial) <= 24.9) {
            System.out.println("between 18.5 and 24.9");
            Result2 = "Normal";
            } else if (bMIImperial >= 25 && bMIImperial <= 29.9) {
            System.out.println("between 25 and 29.9");
            Result2 = "Overweight";
            } else {
            System.out.println("greater than 30");
            Result2 = "Obese";
            }

    System.out.println("Your Body Mass Index is:" + bMIMetric + "(" + Result1 +")");
    System.out.println("Your Body Mass Index is:" + bMIImperial +"(" + Result2 +")");

        }
    }

Body:
You are trying to make it complex, which is actually not easy task.
As a consequence youre making redundand and nonlogical steps.

input
Youre asking for double input in different metric. For example weight in kilograms and in pounds. You need to ask user which metric is he using and start from there.

error checking
I'd suggest to use try/catch block and look for non numerical values

try {
    // get your input
} catch(InputMismatchException ex) {
    // try again
}

hope this helps a bit


问:
Why do CROSS JOIN conditions not work in the 'ON' clause, only the WHERE clause?
I'm wondering why a conditional cross join must have the condition(s) specified in the WHERE clause, and why it doesn't work in the 'ON' clause. See link for compiled example: http://rextester.com/IKY8693

Business context: I need to generate a list of dates between a start and end date in order to fill in gaps in order to left join against a third table, such that zeroes/nulls are returned for a particular month.

How I did this: Let's take for example a table of users, with YYYYMM start and end dates.

```<code>| user_id | start_yearmonth | end_yearmonth |
|---------|-----------------|---------------|
| u9876   | 201504          | 201610        |
| u5564   | 201602          | 201612        |
| u4435   | 201606          | NULL          |
</code>```

The table to be cross joined is a table of desired YYYYMM dates.

```<code>| yearmonth |
|-----------|
| 201601    |
| 201602    |
| 201603    |
| 201604    |
| 201605    |
| 201606    |
| 201607    |
| 201608    |
| 201609    |
| 201610    |
| 201611    |
| 201612    |
| 201701    |
| 201702    |
</code>```

A CROSS JOIN with conditions in the where clause works, but this doesn't work when the conditions are in the 'ON' clause. Why is that?

```<code>SELECT
    *
FROM
    user_tbl
    CROSS JOIN date_range
WHERE
    user_tbl.start_yearmonth <= date_range.yearmonth
    AND (user_tbl.end_yearmonth >= date_range.yearmonth
         OR user_tbl.end_yearmonth IS NULL)
ORDER BY
    user_tbl.user_id, date_range.yearmonth ;
</code>```

答:
CROSS JOIN is the SQL operator to perform a full cartesian product between two tables. Since it is a cartesian product, it does not allow any condition during the operation, you can only restrict its result with some filtering operation (the WHERE condition).

JOIN (INNER and OUTER JOIN, that is) operators, are simply cartesian product together with the filtering operator expressed in the ON part of the operator (and in fact in the original syntax of SQL there was no JOIN operator, simply the “comma” notation to denote the product with the join condition expressed always in the WHERE part).

Examples:

"old" notation:

```<code>SELECT ...
FROM table1 t1, table2 t2
WHERE t1.attribute = t2.attribute
</code>```

equivalent to the "modern" notation:

```<code>SELECT ...
FROM table1 t1 INNER JOIN table2 t2 ON t1.attribute = t2.attribute
</code>```

while, for the cartesian product:

"old" notation:

```<code>SELECT ...
FROM table1 t1, table2 t2
</code>```

equivalent to the "modern" notation:

```<code>SELECT ...
FROM table1 t1 CROSS JOIN table2 t2
</code>```

In other words, a CROSS JOIN that require a condition is actually some kind of INNER JOIN.

Body:
I'm wondering why a conditional cross join must have the condition(s) specified in the WHERE clause, and why it doesn't work in the 'ON' clause. See link for compiled example: http://rextester.com/IKY8693

Business context: I need to generate a list of dates between a start and end date in order to fill in gaps in order to left join against a third table, such that zeroes/nulls are returned for a particular month.

How I did this: Let's take for example a table of users, with YYYYMM start and end dates.

| user_id | start_yearmonth | end_yearmonth |
|---------|-----------------|---------------|
| u9876   | 201504          | 201610        |
| u5564   | 201602          | 201612        |
| u4435   | 201606          | NULL          |

The table to be cross joined is a table of desired YYYYMM dates.

| yearmonth |
|-----------|
| 201601    |
| 201602    |
| 201603    |
| 201604    |
| 201605    |
| 201606    |
| 201607    |
| 201608    |
| 201609    |
| 201610    |
| 201611    |
| 201612    |
| 201701    |
| 201702    |

A CROSS JOIN with conditions in the where clause works, but this doesn't work when the conditions are in the 'ON' clause. Why is that?

SELECT
    *
FROM
    user_tbl
    CROSS JOIN date_range
WHERE
    user_tbl.start_yearmonth <= date_range.yearmonth
    AND (user_tbl.end_yearmonth >= date_range.yearmonth
         OR user_tbl.end_yearmonth IS NULL)
ORDER BY
    user_tbl.user_id, date_range.yearmonth ;

Body:
CROSS JOIN is the SQL operator to perform a full cartesian product between two tables. Since it is a cartesian product, it does not allow any condition during the operation, you can only restrict its result with some filtering operation (the WHERE condition).

JOIN (INNER and OUTER JOIN, that is) operators, are simply cartesian product together with the filtering operator expressed in the ON part of the operator (and in fact in the original syntax of SQL there was no JOIN operator, simply the “comma” notation to denote the product with the join condition expressed always in the WHERE part).

Examples:

"old" notation:

SELECT ...
FROM table1 t1, table2 t2
WHERE t1.attribute = t2.attribute

equivalent to the "modern" notation:

SELECT ...
FROM table1 t1 INNER JOIN table2 t2 ON t1.attribute = t2.attribute

while, for the cartesian product:

"old" notation:

SELECT ...
FROM table1 t1, table2 t2

equivalent to the "modern" notation:

SELECT ...
FROM table1 t1 CROSS JOIN table2 t2

In other words, a CROSS JOIN that require a condition is actually some kind of INNER JOIN.


答:
You can do this is you just want to wrap each word into :

```<code>'<span>'.str_replace(', ', '</span><span>', $string).'</span>'
</code>```

http://php.net/manual/en/function.str-replace.php

Title: Loop through a string and wrap each word in a div - PHP

Body:
You can do this is you just want to wrap each word into <span></span>:

'<span>'.str_replace(', ', '</span><span>', $string).'</span>'

http://php.net/manual/en/function.str-replace.php


问:
Set max value of chart.js bar chart
I am creating a bar chart to show a percentage so I therefore only want the graph to go up to a max value of 100.

I got the following in the options:

```<code>    var options = {
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
        tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
        maintainAspectRatio: false,
        responsive: true,
        animation: false,
        scaleBeginAtZero: true,
        scales: {
            yAxis: [{
                ticks: {
                    beginAtZero:true,
                    min: 0,
                    max: 100
                }
            }]
        }
    };
</code>```

When the graph loads, my data contains a value of 100%, but instead of the bar graph yAxis value being 100 its going up to 120.

答:
The reason of this not working is merely related to the ChartJS version you are using. Since you are using ChartJS version 1.x, the current scales option will not be applicable for the chart.

You should rather use the following scale options ...

```<code>scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var ctx = document.getElementById("canvas").getContext("2d");
var data = {
   labels: ['Jan', 'Feb', 'Mar'],
   datasets: [{
      label: "# of votes",
      fillColor: "#07C",
      data: [50, 80, 200]
   }]
};

var myBarChart = new Chart(ctx).Bar(data, {
   scaleOverride: true,
   scaleSteps: 10, // number of ticks
   scaleStepWidth: 10, // tick interval
   scaleBeginAtZero: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="canvas" width="350" height="200"></canvas></code>```

Title: Set max value of chart.js bar chart

Body:
I am creating a bar chart to show a percentage so I therefore only want the graph to go up to a max value of 100.

I got the following in the options:

    var options = {
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>
",
        tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
        maintainAspectRatio: false,
        responsive: true,
        animation: false,
        scaleBeginAtZero: true,
        scales: {
            yAxis: [{
                ticks: {
                    beginAtZero:true,
                    min: 0,
                    max: 100
                }
            }]
        }
    };

When the graph loads, my data contains a value of 100%, but instead of the bar graph yAxis value being 100 its going up to 120.

Body:
The reason of this not working is merely related to the ChartJS version you are using. Since you are using ChartJS version 1.x, the current scales option will not be applicable for the chart.

You should rather use the following scale options ...

scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var ctx = document.getElementById("canvas").getContext("2d");
var data = {
   labels: ['Jan', 'Feb', 'Mar'],
   datasets: [{
      label: "# of votes",
      fillColor: "#07C",
      data: [50, 80, 200]
   }]
};

var myBarChart = new Chart(ctx).Bar(data, {
   scaleOverride: true,
   scaleSteps: 10, // number of ticks
   scaleStepWidth: 10, // tick interval
   scaleBeginAtZero: true
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="canvas" width="350" height="200"></canvas>


问:
Liferay IDE Alternatives
I am using Liferay Developer Studio for theme development and as a frontend developer, I am not impress with the tool's performance.

Below are few reasons I am looking for alternative IDE, compatible for Liferay development.

It occupies more than 75% of the memory

It slower down the whole system

I cannot use chat application while running IDE as to switch from one app to another takes irrelevant time

I use to build theme through CLI. Sometime I need to close the IDE or else it gives runtime error and doesn't build the theme.

I am sure there are many others too faced same issues, which actually makes the development slower. This question is not against the Liferay of course, it's a great enterprise level CMS tool. But yes looking for alternate IDE with best compatibility for the purpose.

Thanks in advance.

答:
You can use any IDE you want. The only one difference between LiferayIDE and others IDEs is you can avoid using BladeCLI by hands.
And nothing can stop you to use another IDE, build you project with maven or gradle and then continue to develop.

If you are a front-end developer you really should use Gulp and Yo. First time you'll feel yourself confused a bit, but after short period of time you'll understand all benefits.

Title: Liferay IDE Alternatives


问:
Python - Tkinter GUI update multiple modules
thanks in advance for any help.

I have 2 .py files, one which runs a GUI and another which does a basic calculation and creates a graph with the input of the GUI, these are then outputted to the console. The values are printed twice, once from the calculation file and again from the GUI file.

The problem is that if I update the input the output doesn't update and neither does the graph. Thank you in advance for any help with this.

GUI (test1GUI.py):

```<code>import tkinter as tk
from tkinter import ttk

import csv

def To_Print(self):

    if len(self.e_xf.get()) != 0:

        Write_Inputs_To_CSV(self)

        import test1Eqm

        test1Eqm.Pre_Output()

        Rmin = test1Eqm.Outputs('Rmin')
        xf = float(self.e_xf.get())/100

        print('xf (fromGUI) = ', xf)
        print('Rmin (fromGUI) = ', Rmin)

        del test1Eqm

    else:
        print('Enter All Inputs')

def Write_Inputs_To_CSV(self):

    xf = float(self.e_xf.get())/100

    with open('TestInputs.csv', 'w', newline='') as csvfile:

        filewriter = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)

        filewriter.writerow(['Variable', 'Value'])

        filewriter.writerow(['xf', xf])

class ChemEngApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.wm_title(self, "ChemEng")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, PageOne):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        ##### Making Labels #####

        self.l_Title = ttk.Label(self, text="Start Page")
        self.l_Title.grid(row=0, columnspan = 2)

        self.l_xf = ttk.Label(self, text="xA of Feed (%)")
        self.l_xf.grid(row=1, sticky="e", padx=5)

        ##### Making Entry Boxes #####

        self.e_xf = ttk.Entry(self)
        self.e_xf.grid(row=1, column=1)

        self.b_Run = ttk.Button(self, text="Click to Run", command=lambda: RUN(self))
        self.b_Run.grid(row=2, column=0, columnspan = 2)

        def RUN(self):

            To_Print(self)

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

if __name__ == '__main__':
    app = ChemEngApp()
    app.mainloop()
</code>```

Calculations (test1Eqm.py):

```<code>import matplotlib.pyplot as plt
import numpy as np

#--------------------------------------------------------------------------------------------------------------------------------
# Getting variables from .csv

import csv

Variables = []
Values = []

def getval(x):

    with open('TestInputs.csv', 'rt') as g:
        reader = csv.reader(g)

        # read file row by row
        rowNr = 0
        for row in reader:
            # Skip the header row.
            if rowNr >= 1:
                #g.seek(0) <-- makes it freeze on start up
                Variables.append(row[0])
                Values.append(row[1])

            # Increase the row number
            rowNr = rowNr + 1

    if x == 'xf':
        x = float(Values[0])

    return x

xf = getval('xf')
Rmin = xf*2.5           # Multiplies xf by 2.5

xl = np.linspace(0,1,2)
yl = [xf, Rmin]

def GUI_MT():
    plt.plot(xl, yl, label='Test')
    plt.xlabel('xA')
    plt.ylabel('yA')
    plt.xlim([0, 1])
    plt.ylim([0, Rmin*1.5])
    plt.legend()
    plt.savefig('TestMT.png')
    plt.show()

def Pre_Output():
    print(' ')
    print('New Run')
    GUI_MT()
    print('xf (fromEqm) = ', xf)
    print('Rmin (fromEqm) = ', Rmin)

def Outputs(x):

    a = Rmin

    if x == 'Rmin':
        x = a

    return x

if __name__ == '__main__':
    print('Run GUI instead')
    print('xf = ', xf)
    print('Rmin = ', Rmin)
</code>```

答:
test1Eqm.py only reads the CSV file when it's originally imported.  Importing it again does not cause any code to be executed, you just get another reference to the existing module.  Basically, all of its code needs to be inside functions that you actually call when you want the calculation to be performed.

Also, using a CSV file to transfer data from one module to another within a single program is completely insane.  Pass the data as parameters!

Body:
thanks in advance for any help.

I have 2 .py files, one which runs a GUI and another which does a basic calculation and creates a graph with the input of the GUI, these are then outputted to the console. The values are printed twice, once from the calculation file and again from the GUI file.

The problem is that if I update the input the output doesn't update and neither does the graph. Thank you in advance for any help with this.

GUI (test1GUI.py):

import tkinter as tk
from tkinter import ttk

import csv

def To_Print(self):

    if len(self.e_xf.get()) != 0:

        Write_Inputs_To_CSV(self)

        import test1Eqm

        test1Eqm.Pre_Output()

        Rmin = test1Eqm.Outputs('Rmin')
        xf = float(self.e_xf.get())/100

        print('xf (fromGUI) = ', xf)
        print('Rmin (fromGUI) = ', Rmin)

        del test1Eqm

    else:
        print('Enter All Inputs')

def Write_Inputs_To_CSV(self):

    xf = float(self.e_xf.get())/100

    with open('TestInputs.csv', 'w', newline='') as csvfile:

        filewriter = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)

        filewriter.writerow(['Variable', 'Value'])

        filewriter.writerow(['xf', xf])

class ChemEngApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.wm_title(self, "ChemEng")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, PageOne):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        ##### Making Labels #####

        self.l_Title = ttk.Label(self, text="Start Page")
        self.l_Title.grid(row=0, columnspan = 2)

        self.l_xf = ttk.Label(self, text="xA of Feed (%)")
        self.l_xf.grid(row=1, sticky="e", padx=5)

        ##### Making Entry Boxes #####

        self.e_xf = ttk.Entry(self)
        self.e_xf.grid(row=1, column=1)

        self.b_Run = ttk.Button(self, text="Click to Run", command=lambda: RUN(self))
        self.b_Run.grid(row=2, column=0, columnspan = 2)

        def RUN(self):

            To_Print(self)

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

if __name__ == '__main__':
    app = ChemEngApp()
    app.mainloop()

Calculations (test1Eqm.py):

import matplotlib.pyplot as plt
import numpy as np

#--------------------------------------------------------------------------------------------------------------------------------
# Getting variables from .csv

import csv

Variables = []
Values = []

def getval(x):

    with open('TestInputs.csv', 'rt') as g:
        reader = csv.reader(g)

        # read file row by row
        rowNr = 0
        for row in reader:
            # Skip the header row.
            if rowNr >= 1:
                #g.seek(0) <-- makes it freeze on start up
                Variables.append(row[0])
                Values.append(row[1])

            # Increase the row number
            rowNr = rowNr + 1

    if x == 'xf':
        x = float(Values[0])

    return x

xf = getval('xf')
Rmin = xf*2.5           # Multiplies xf by 2.5

xl = np.linspace(0,1,2)
yl = [xf, Rmin]

def GUI_MT():
    plt.plot(xl, yl, label='Test')
    plt.xlabel('xA')
    plt.ylabel('yA')
    plt.xlim([0, 1])
    plt.ylim([0, Rmin*1.5])
    plt.legend()
    plt.savefig('TestMT.png')
    plt.show()

def Pre_Output():
    print(' ')
    print('New Run')
    GUI_MT()
    print('xf (fromEqm) = ', xf)
    print('Rmin (fromEqm) = ', Rmin)

def Outputs(x):

    a = Rmin

    if x == 'Rmin':
        x = a

    return x

if __name__ == '__main__':
    print('Run GUI instead')
    print('xf = ', xf)
    print('Rmin = ', Rmin)


问:
Javascript slideshow array issue
I'm pretty new to Javascript and im trying to build slideshow myself now. Only im stuck right now after i build the array where i get my pictures from. It only shows a white screen.

My Javascript

```<code> $(function () {
var counter = 0;
var defaultSettings = {
    "sliderContainer": "#slider"
    , "pauseWithMouse": true
    , "sliderSpeed": 2000
    , "transitionSpeed": 1500
};

function cycleImages() {
    counter++;
if (counter >= images.Length) {
    counter = 0;
}
document.getElementById("#slider img").src = MyImages[counter];

var images = $('#slider img')
    , now = images.filter(':visible')
    , next = now.next().length ? now.next() : images.first()
    , speed = 1500; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed);
 }

var theInterval; // Slide speed

var = images = [];
// if myImages exists then
images = myImages;
if (images.length > 0) {
    $(defaultSettings.sliderContainer).append('<img id="sliderImage" src="' + images[0] + '" />');
    startSlide();
}
var startSlide = function () {
    setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};
var stopSlide = function () {
    if (defaultSettings.pauseWithMouse) {
        clearInterval(theInterval);
    }
};
startSlide();
$('#slider img').on('mouseover', function () {
    stopSlide();
});
$('#slider img').on('mouseout', function () {
    startSlide();
});
});
</code>```

And my HTML:

```<code>  <!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Javascript Slider</title>
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <link rel="stylesheet" href="css/style.css">
  <script src="js/slideshow.js"></script>

<script>
  var myImages = ["slide1.jpg", "slide2.jpg", "bg/slide3.jpg"];
 </script>
</head>

<body>
<main>
<div id="slider">
</div>
</main>
</body>
</html>
</code>```

答:
you have strange declaration of variable here

var = images = [];

also you need to move this part

```<code>var startSlide = function() {
  setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};
</code>```

before

```<code>if (images.length > 0) {
  $(defaultSettings.sliderContainer).append('<img id="sliderImage" src="' + images[0] + '" />');
  startSlide();
}
</code>```

you have wrong variable name (MyImages) here

```<code>document.getElementById("#slider img").src = MyImages[counter];
</code>```

first try to debug your code

Title: Javascript slideshow array issue

Body:
I'm pretty new to Javascript and im trying to build slideshow myself now. Only im stuck right now after i build the array where i get my pictures from. It only shows a white screen.

My Javascript

 $(function () {
var counter = 0;
var defaultSettings = {
    "sliderContainer": "#slider"
    , "pauseWithMouse": true
    , "sliderSpeed": 2000
    , "transitionSpeed": 1500
};

function cycleImages() {
    counter++;
if (counter >= images.Length) {
    counter = 0;
}
document.getElementById("#slider img").src = MyImages[counter];

var images = $('#slider img')
    , now = images.filter(':visible')
    , next = now.next().length ? now.next() : images.first()
    , speed = 1500; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed);
 }

var theInterval; // Slide speed

var = images = [];
// if myImages exists then
images = myImages;
if (images.length > 0) {
    $(defaultSettings.sliderContainer).append('');
    startSlide();
}
var startSlide = function () {
    setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};
var stopSlide = function () {
    if (defaultSettings.pauseWithMouse) {
        clearInterval(theInterval);
    }
};
startSlide();
$('#slider img').on('mouseover', function () {
    stopSlide();
});
$('#slider img').on('mouseout', function () {
    startSlide();
});
});

And my HTML:

  <!DOCTYPE html>

<meta charset="UTF-8">
<title>Javascript Slider</title>

  <link rel="stylesheet" href="css/style.css">

Body:
you have strange declaration of variable here

var = images = [];

also you need to move this part

var startSlide = function() {
  setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};

before

if (images.length > 0) {
  $(defaultSettings.sliderContainer).append('<img id="sliderImage" src="' + images[0] + '" />');
  startSlide();
}

you have wrong variable name (MyImages) here

document.getElementById("#slider img").src = MyImages[counter];

first try to debug your code


答:
The intention of what you have below is great--checking to make sure that the entered parameters are correct. However, it only error checks once and does not provide the user with what the correct values should be. (Also it should be an or, not and, as that condition right now can never be true.)

```<code>   String correctValues2;
       if (weightPounds < 44 && weightPounds > 882) {
       System.out.println("Please enter valid weight.");
       correctValues2 = "Please enter valid weight.";
       }
</code>```

I would suggest something more along the lines of:

```<code>     while (weightPounds < 44 || weightPounds > 882) {
           System.out.println("Please enter valid weight.(44 lb - 882 lb)");
           weightPounds = input.nextDouble();
           }
</code>```

This way you are able to avoid the need for a 'correct value' string and ensure that the value is correct when you exit the while loop.

Also, if the program is supposed to specify whether or not the user want's their BMI in metric or imperial, ask that FIRST.

By the way, this post probably belongs in Code Review for future reference

Title: Java BMI Calculator Issue - Imperial or Metric User Input, Error Handling, Correct Values Input, Conversion

Body:
The intention of what you have below is great--checking to make sure that the entered parameters are correct. However, it only error checks once and does not provide the user with what the correct values should be. (Also it should be an or, not and, as that condition right now can never be true.)

   String correctValues2;
       if (weightPounds < 44 && weightPounds > 882) {
       System.out.println("Please enter valid weight.");
       correctValues2 = "Please enter valid weight.";
       }

I would suggest something more along the lines of:

     while (weightPounds < 44 || weightPounds > 882) {
           System.out.println("Please enter valid weight.(44 lb - 882 lb)");
           weightPounds = input.nextDouble();
           }

This way you are able to avoid the need for a 'correct value' string and ensure that the value is correct when you exit the while loop.

Also, if the program is supposed to specify whether or not the user want's their BMI in metric or imperial, ask that FIRST.

By the way, this post probably belongs in Code Review for future reference


问:
Jquery popup for images
there are three or more images in a single html page and need to show same image in popup after clicking on particular image. Is there anything which I can use for this?</p>

```<code><img class="wp-image-4596 size-medium" src="img1.jpg" alt="img1" width="232" height="300">
<img class="wp-image-4596 size-medium" src="img2.jpg" alt="img2" width="232" height="300">
<img class="wp-image-4596 size-medium" src="img3.jpg" alt="img3" width="232" height="300">
</code>```

答:
Hey man use lightbox2 jQuery plugin, this have cool effects and functionality. </p>

<p>If you like to use more simpler plugin then you can use magnafic popup plugin. </p>

Title: Jquery popup for images

Body:
Hey man use lightbox2 jQuery plugin, this have cool effects and functionality.

If you like to use more simpler plugin then you can use magnafic popup plugin.


问:
SPAN tag ignored by JAWS screen Reader
So I was able to get my page working just fine with the NDVA screen reader, however, when testing in JAWS, it tabs to the span, but doesn't read the text.

whatever

UPDATE:

What I am trying to achieve is a I have a few elements which expand/collapse certain sections of the site I'm building.  These functional elements, however are not links.

Reponse to @discojoe (thanks for the response)

Adding a TABINDEX="0" attribute will insert the SPAN/DIV element into tabbing list in natural order (whereas by default, they're usually not added to the tabbing list).  This allows screen readers to tab to that element, and is working just fine.  Specifically, my problems is JAWS will just tab to that element, it just doesn't read it.

I agree, using TABINDEX="n" (where n > 0) is a bad thing which messes with the natural order of the tabbing list, and I am not doing that.

Also, you can use TABINDEX="-1" to remove an element from the tabbing list if it's placed in there by default (example an A or INPUT tag).

I have already tried using  tags, however, when user hits enter on this link (to trigger the onclick event), it does something (not quite reloading, but kinda re-initializing) to the page which delays the animation associated with that element.  I find that to be a bad experience to both normal and disabled users.

using the # tag in the A tag adds the hash tag to the page title in IE.

Additionally, using A tags makes the screen reader read out "LINK" before/after each element, and since they're not actually links, I feel this is negative impact on accessibility.

答:
Use  anchor tag for screen reading simple text related works. You can simply do :-

```<code><a href="javascript:void(0);" title="What you want to be read by jaws></a>
</code>```

That's it. I tested it with JAWS.

Title: SPAN tag ignored by JAWS screen Reader

Body:
Use  anchor tag for screen reading simple text related works. You can simply do :-

<a href="javascript:void(0);" title="What you want to be read by jaws></a>

That's it. I tested it with JAWS.


问:
cron.hourly "exited with return code 1"
I'm currently on Linux Ubuntu 14.04 (I think).

So I previously had a cron.daily script which was working fine. I decided to use the same script but move it to cron.hourly and now it wont work.

/etc/cron.hourly/dstealth-watch-tv

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

times=$(date)
echo "${times}:" >> /var/log/dstealth/watch-tv.log
/usr/bin/curl --silent http://watch.dstealth.com/tv/refreshToken.php?k=secretRefreshKey >> /var/log/dstealth/watch-tv.log
</code>```

I've given the file CHMOD: 755

The log file was created manually with CHMOD: 644 and is empty.

Then I used:

```<code>service cron reload
</code>```

and waited several hours hoping for an output into my log file but it remains empty.

I've tried

```<code>run-parts --verbose /etc/cron.hourly
</code>```

and this is the output I get:

```<code>/etc/cron.hourly/dstealth-watch-tv:
run-parts: failed to exec /etc/cron.hourly/dstealth-watch-tv: No such file or directory
run-parts: /etc/cron.hourly/dstealth-watch-tv exited with return code 1
</code>```

This also did not result in anything being input into the log file. I'm not sure where I've gone wrong. Please assist.

答:
Thanks to guidance from JWW, I posted on Unix & Linux Stack Exchange and someone was able to answer the question almost immediately.

The script was created essentially in Windows using NppFTP so the following command was required:

```<code>dos2unix /etc/cron.hourly/dstealth-watch-tv
</code>```

Credit goes to roaima

Title: cron.hourly "exited with return code 1"

Body:
I'm currently on Linux Ubuntu 14.04 (I think).

So I previously had a cron.daily script which was working fine. I decided to use the same script but move it to cron.hourly and now it wont work.

/etc/cron.hourly/dstealth-watch-tv

#!/bin/bash

times=$(date)
echo "${times}:" >> /var/log/dstealth/watch-tv.log
/usr/bin/curl --silent http://watch.dstealth.com/tv/refreshToken.php?k=secretRefreshKey >> /var/log/dstealth/watch-tv.log

I've given the file CHMOD: 755

The log file was created manually with CHMOD: 644 and is empty.

Then I used:

service cron reload

and waited several hours hoping for an output into my log file but it remains empty.

I've tried

run-parts --verbose /etc/cron.hourly

and this is the output I get:

/etc/cron.hourly/dstealth-watch-tv:
run-parts: failed to exec /etc/cron.hourly/dstealth-watch-tv: No such file or directory
run-parts: /etc/cron.hourly/dstealth-watch-tv exited with return code 1

This also did not result in anything being input into the log file. I'm not sure where I've gone wrong. Please assist.

Body:
Thanks to guidance from JWW, I posted on Unix & Linux Stack Exchange and someone was able to answer the question almost immediately.

The script was created essentially in Windows using NppFTP so the following command was required:

dos2unix /etc/cron.hourly/dstealth-watch-tv

Credit goes to roaima