问:
Virtual Filesystem in Perl with Fuse
Anybody help me make a virtual file system in Perl.
Very simple, 2 depth level, as

```<code>/subdir
   subdir-l2
   file2.txt
/file1.txt
</code>```

I try use Fuse.pm, but not understand how create subdir level. I create %files hash, and if go to subdir, recreate it with new records. It's for test only.

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use Fuse;
use POSIX qw(ENOENT EISDIR EINVAL);

my (%files) = (
    '.' => {
        type => 0040,
        mode => 0755,
        ctime => 1490603721
    },
    subdir => {
        type => 0040,
        mode => 0755,
        ctime => 1490603721
    },
    "file1.txt" => {
            type => 0100,
            mode => 0755,
            ctime => 1490603721
        }
 );

sub filename_fixup {
    my ($file) = shift;
    $file =~ s,^/,,;
    $file = '.' unless length($file);
    return $file;
}

sub getdir {
    my $tmp = shift;
    if ($tmp eq '/') {
        return (keys %files),0;
    } else {
        (%files) = (
                '.' => {
                    type => 0040,
                    mode => 0755,
                    ctime => 1490603721
                },

                # /subdir/subdir-l2
                "subdir-l2" => {
                    type => 0040,
                    mode => 0755,
                    ctime => 1490603721
                } ,

                # /subdir/a-l2.file
                "file2.txt" => {
                    cont => "File 'al2'.\n",
                    type => 0100,
                    mode => 0755,
                    ctime => 1490603721
                }
        );
        return (keys %files),0;
    }
}

sub getattr {
    my ($file) = filename_fixup(shift);
    $file =~ s,^/,,;
    $file = '.' unless length($file);
    return -ENOENT() unless exists($files{$file});
    my ($size) = exists($files{$file}{cont}) ? length($files{$file}{cont}) : 0;
    $size = $files{$file}{size} if exists $files{$file}{size};
    my ($modes) = ($files{$file}{type}<<9) + $files{$file}{mode};
    my ($dev, $ino, $rdev, $blocks, $gid, $uid, $nlink, $blksize) = (0,0,0,1,0,0,1,1024);
    my ($atime, $ctime, $mtime);
    $atime = $ctime = $mtime = $files{$file}{ctime};
    return ($dev,$ino,$modes,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks);
}

Fuse::main(
    mountpoint  => "/tmp/123",
    getdir      => \&getdir,
    getattr     => \&getattr,
);
</code>```

one level mount fine, but if go to deeper i get

```<code>?????????? ? ? ? ?            ? file2.txt
?????????? ? ? ? ?            ? subdir-l2
</code>```

答:
I'm really not a regular user of the Fuse module, neither of FUSE system. Tinkered with this issue out of pure curiosity. Thus, although I can't explain in very much details how to use the plain Fuse module to achieve your goal, I have a working code that does create the wanted filesystem (at least on my system, and seems that it is capable of creating any arbitrary filesystem tree), and I can explain how I got this code working.

So first of all I discovered the Fuse::Simple module on CPAN.
Its SYNOPSIS shows that it provides a really simple API to the Fuse module for creating arbitrary filesystems from a hash structure. Its source code isn't that huge, so I just created 'listing.pl' script file and copied there most of the functions (except fserr that caused a Modification of a read-only value exception), put the main sub contents out, so they will be the main script's flow, hardcoded the filesystem structure ($fs var), and made some little adjustments here and there (like declare vars with my to prevent exceptions), and finally got the filesystem mounted, with all directories listed and files readable. So this is the code I got at last:

```<code>#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use Carp;
use Fuse;
use Errno qw(:POSIX);         # ENOENT EISDIR etc
use Fcntl qw(:DEFAULT :mode); # S_IFREG S_IFDIR, O_SYNC O_LARGEFILE etc.
use Switch;

my $debug = 0;
my %codecache = ();
my $ctime = time();
my $uid = $>;
my $gid = $) + 0;

my $fs = {
    "file1.txt" => "File 1 contents",
    "subdir" => {
        "subdir-l2" => {},
        "file2.txt" => "File 2 contents"
    }
};

# some default args
my %args = (
    "mountpoint"  => "listing",
    "debug"       => $debug,
    "fuse_debug"  => 0,
    "threaded"    => 0,
    "/"           => $fs
);
# the default subs
my %fs_subs = (
    "chmod"       => \&fs_not_imp,
    "chown"       => \&fs_not_imp,
    "flush"       => \&fs_flush,
    "fsync"       => \&fs_not_imp,
    "getattr"     => \&fs_getattr,
    "getdir"      => \&fs_getdir,
    "getxattr"    => \&fs_not_imp,
    "link"        => \&fs_not_imp,
    "listxattr"   => \&fs_not_imp,
    "mkdir"       => \&fs_not_imp,
    "mknod"       => \&fs_not_imp,
    "open"        => \&fs_open,
    "read"        => \&fs_read,
    "readlink"    => \&fs_readlink,
    "release"     => \&fs_release,
    "removexattr" => \&fs_not_imp,
    "rmdir"       => \&fs_not_imp,
    "rename"      => \&fs_not_imp,
    "setxattr"    => \&fs_not_imp,
    "statfs"      => \&fs_statfs,
    "symlink"     => \&fs_not_imp,
    "truncate"    => \&fs_truncate,
    "unlink"      => \&fs_not_imp,
    "utime"       => sub{return 0},
    "write"       => \&fs_write,
);
# except extract these ones back out.
$debug = delete $args{"debug"};
$args{"debug"} = delete( $args{"fuse_debug"} ) || 0;
delete $args{"/"};
# add the functions, if not already defined.
# wrap in debugger if debug is set.
for my $name (keys %fs_subs) {
    my $sub = $fs_subs{$name};
#   $sub = wrap($sub, $name) if $debug;
    $args{$name} ||= $sub;
}
Fuse::main(%args);

sub fetch {
    my ($path, @args) = @_;

    my $obj = $fs;
    for my $elem (split '/', $path) {
    next if $elem eq ""; # skip empty // and before first /
    $obj = runcode($obj); # if there's anything to run
    # the dir we're changing into must be a hash (dir)
    return ENOTDIR() unless ref($obj) eq "HASH";
    # note that ENOENT and undef are NOT the same thing!
    return ENOENT() unless exists $obj->{$elem};
    $obj = $obj->{$elem};
    }

    return runcode($obj, @args);
}

sub runcode {
    my ($obj, @args) = @_;

    while (ref($obj) eq "CODE") {
    my $old = $obj;
    if (@args) { # run with these args. don't cache
        delete $codecache{$old};
        print "running $obj(",quoted(@args),") NO CACHE\n" if $debug;
        $obj = saferun($obj, @args);
    } elsif (exists $codecache{$obj}) { # found in cache
        print "got cached $obj\n" if $debug;
        $obj = $codecache{$obj}; # could be undef, or an error, BTW
    } else {
        print "running $obj() to cache\n" if $debug;
        $obj = $codecache{$old} = saferun($obj);
    }

    if (ref($obj) eq "NOCACHE") {
        print "returned a nocache() value - flushing\n" if $debug;
        delete $codecache{$old};
        $obj = $$obj;
    }

    print "returning ",ref($obj)," ",
      defined($obj) ? $obj : "undef",
      "\n" if $debug;
    }
    return $obj;
}

sub saferun {
    my ($sub, @args) = @_;

    my $ret = eval { &$sub(@args) };
    my $died = $@;
    if (ref($died)) {
    print "+++ Error $$died\n" if ref($died) eq "ERROR";
    return $died;
    } elsif ($died) {
    print "+++ $died\n";
    # stale file handle? moreorless?
    return ESTALE();
    }
    return $ret;
}

sub nocache {
    return bless(\ shift, "NOCACHE"); # yup, utter abuse of bless   :-)
}

sub dump_open_flags {
    my $flags = shift;

    printf "  flags: 0%o = (", $flags;
    for my $bits (
    [ O_ACCMODE(),   O_RDONLY(),     "O_RDONLY"    ],
    [ O_ACCMODE(),   O_WRONLY(),     "O_WRONLY"    ],
    [ O_ACCMODE(),   O_RDWR(),       "O_RDWR"      ],
    [ O_APPEND(),    O_APPEND(),    "|O_APPEND"    ],
    [ O_NONBLOCK(),  O_NONBLOCK(),  "|O_NONBLOCK"  ],
    [ O_SYNC(),      O_SYNC(),      "|O_SYNC"      ],
    [ O_DIRECT(),    O_DIRECT(),    "|O_DIRECT"    ],
    [ O_LARGEFILE(), O_LARGEFILE(), "|O_LARGEFILE" ],
    [ O_NOFOLLOW(),  O_NOFOLLOW(),  "|O_NOFOLLOW"  ],
    ) {
    my ($mask, $flag, $name) = @$bits;
    if (($flags & $mask) == $flag) {
        $flags -= $flag;
        print $name;
    }
    }
    printf "| 0%o !!!", $flags if $flags;
    print ")\n";
}

sub accessor {
    my $var_ref = shift;

    croak "accessor() requires a reference to a scalar var\n"
      unless defined($var_ref) && ref($var_ref) eq "SCALAR";

    return sub {
    my $new = shift;
    $$var_ref = $new if defined($new);
    return $$var_ref;
    }
}

sub fs_not_imp { return -ENOSYS() }

sub fs_flush {
    # we're passed a path, but finding my coderef stuff from a path
    # is a bit of a 'mare. flush the lot, won't hurt TOO much.
    print "Flushing\n" if $debug;
    %codecache = ();
    return 0;
}

sub easy_getattr {
    my ($mode, $size) = @_;

    return (
    0, 0,       # $dev, $ino,
    $mode,
    1,          # $nlink, see fuse.sourceforge.net/wiki/index.php/FAQ
    $uid, $gid, # $uid, $gid,
    0,          # $rdev,
    $size,      # $size,
    $ctime, $ctime, $ctime, # actually $atime, $mtime, $ctime,
    1024, 1,    # $blksize, $blocks,
    );
}

sub fs_getattr {
    my $path = shift;
    my $obj = fetch($path);

    # undef doesn't actually mean "file not found", it could be a coderef
    # file-sub which has returned undef.
    return easy_getattr(S_IFREG | 0200, 0) unless defined($obj);

    switch (ref($obj)) {
    case "ERROR" {  # this is an error to be returned.
        return -$$obj;
    }
    case "" {       # this isn't a ref, it's a real string "file"
        return easy_getattr(S_IFREG | 0644, length($obj));
    }
    # case "CODE" should never happen - already been run by fetch()
    case "HASH" {   # this is a directory hash
        return easy_getattr(S_IFDIR | 0755, 1);
    }
    case "SCALAR" { # this is a scalar ref. we use these for symlinks.
        return easy_getattr(S_IFLNK | 0777, 1);
    }
    else {          # what the hell is this file?!?
        print "+++ What on earth is ",ref($obj)," $path ?\n";
        return easy_getattr(S_IFREG | 0000, 0);
    }
    }
}

sub fs_getdir {
    my $obj = fetch(shift);
    return -$$obj if ref($obj) eq "ERROR"; # THINK this is a good idea.
    return -ENOENT() unless ref($obj) eq "HASH";
    return (".", "..", sort(keys %$obj), 0);
}

sub fs_open {
    # doesn't really need to open, just needs to check.
    my $obj = fetch(shift);
    my $flags = shift;
    dump_open_flags($flags) if $debug;

    # if it's undefined, and we're not writing to it, return an error
    return -EBADF() unless defined($obj) or ($flags & O_ACCMODE());

    switch (ref($obj)) {
    case "ERROR"  { return -$$obj; }
    case ""       { return 0 }          # this is a real string "file"
    case "HASH"   { return -EISDIR(); } # this is a directory hash
    else          { return -ENOSYS(); } # what the hell is this file?!?
    }
}

sub fs_read {
    my $obj = fetch(shift);
    my $size = shift;
    my $off = shift;

    return -ENOENT() unless defined($obj);
    return -$$obj if ref($obj) eq "ERROR";
    # any other types of refs are probably bad
    return -ENOENT() if ref($obj);

    if ($off >  length($obj)) {
    return -EINVAL();
    } elsif ($off == length($obj)) {
    return 0; # EOF
    }
    return substr($obj, $off, $size);
}

sub fs_readlink {
    my $obj = fetch(shift);
    return -$$obj if ref($obj) eq "ERROR";
    return -EINVAL() unless ref($obj) eq "SCALAR";
    return $$obj;
}

sub fs_release {
    my ($path, $flags) = @_;
    dump_open_flags($flags) if $debug;
    return 0;
}

sub fs_statfs {
    return (
        255, # $namelen,
        1,1, # $files, $files_free,
        1,1, # $blocks, $blocks_avail, # 0,0 seems to hide it from df?
        2,   # $blocksize,
    );
}

sub fs_truncate {
    my $obj = fetch(shift, ""); # run anything to set it to ""
    return -$$obj if ref($obj) eq "ERROR";
    return 0;
}

sub fs_write {
    my ($path, $buf, $off) = @_;
    my $obj = fetch($path, $buf, $off); # this runs the coderefs!
    return -$$obj if ref($obj) eq "ERROR";
    return length($buf);
}
</code>```

Final word: I didn't try to use the module itself (it's not listed in my distro package repository, and I was too lazy (sorry) to install it by cpanm or other way). But I think that if I'll have to just use FUSE with Perl, I'll probably just use Fuse::Simple instead of Fuse, maybe forking it. I'd use plain Fuse only for my academic research, I think...

Hope this helps.

Title: Virtual Filesystem in Perl with Fuse

Body:
Anybody help me make a virtual file system in Perl.
Very simple, 2 depth level, as

/subdir
   subdir-l2
   file2.txt
/file1.txt

I try use Fuse.pm, but not understand how create subdir level. I create %files hash, and if go to subdir, recreate it with new records. It's for test only.

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use Fuse;
use POSIX qw(ENOENT EISDIR EINVAL);

my (%files) = (
    '.' => {
        type => 0040,
        mode => 0755,
        ctime => 1490603721
    },
    subdir => {
        type => 0040,
        mode => 0755,
        ctime => 1490603721
    },
    "file1.txt" => {
            type => 0100,
            mode => 0755,
            ctime => 1490603721
        }
 );

sub filename_fixup {
    my ($file) = shift;
    $file =~ s,^/,,;
    $file = '.' unless length($file);
    return $file;
}

sub getdir {
    my $tmp = shift;
    if ($tmp eq '/') {
        return (keys %files),0;
    } else {
        (%files) = (
                '.' => {
                    type => 0040,
                    mode => 0755,
                    ctime => 1490603721
                },

                # /subdir/subdir-l2
                "subdir-l2" => {
                    type => 0040,
                    mode => 0755,
                    ctime => 1490603721
                } ,

                # /subdir/a-l2.file
                "file2.txt" => {
                    cont => "File 'al2'.\n",
                    type => 0100,
                    mode => 0755,
                    ctime => 1490603721
                }
        );
        return (keys %files),0;
    }
}

sub getattr {
    my ($file) = filename_fixup(shift);
    $file =~ s,^/,,;
    $file = '.' unless length($file);
    return -ENOENT() unless exists($files{$file});
    my ($size) = exists($files{$file}{cont}) ? length($files{$file}{cont}) : 0;
    $size = $files{$file}{size} if exists $files{$file}{size};
    my ($modes) = ($files{$file}{type}<<9) + $files{$file}{mode};
    my ($dev, $ino, $rdev, $blocks, $gid, $uid, $nlink, $blksize) = (0,0,0,1,0,0,1,1024);
    my ($atime, $ctime, $mtime);
    $atime = $ctime = $mtime = $files{$file}{ctime};
    return ($dev,$ino,$modes,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks);
}

Fuse::main(
    mountpoint  => "/tmp/123",
    getdir      => \&getdir,
    getattr     => \&getattr,
);

one level mount fine, but if go to deeper i get

?????????? ? ? ? ?            ? file2.txt
?????????? ? ? ? ?            ? subdir-l2

Body:
I'm really not a regular user of the Fuse module, neither of FUSE system. Tinkered with this issue out of pure curiosity. Thus, although I can't explain in very much details how to use the plain Fuse module to achieve your goal, I have a working code that does create the wanted filesystem (at least on my system, and seems that it is capable of creating any arbitrary filesystem tree), and I can explain how I got this code working.

So first of all I discovered the Fuse::Simple module on CPAN.
Its SYNOPSIS shows that it provides a really simple API to the Fuse module for creating arbitrary filesystems from a hash structure. Its source code isn't that huge, so I just created 'listing.pl' script file and copied there most of the functions (except fserr that caused a Modification of a read-only value exception), put the main sub contents out, so they will be the main script's flow, hardcoded the filesystem structure ($fs var), and made some little adjustments here and there (like declare vars with my to prevent exceptions), and finally got the filesystem mounted, with all directories listed and files readable. So this is the code I got at last:

#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use Carp;
use Fuse;
use Errno qw(:POSIX);         # ENOENT EISDIR etc
use Fcntl qw(:DEFAULT :mode); # S_IFREG S_IFDIR, O_SYNC O_LARGEFILE etc.
use Switch;

my $debug = 0;
my %codecache = ();
my $ctime = time();
my $uid = $>;
my $gid = $) + 0;

my $fs = {
    "file1.txt" => "File 1 contents",
    "subdir" => {
        "subdir-l2" => {},
        "file2.txt" => "File 2 contents"
    }
};

# some default args
my %args = (
    "mountpoint"  => "listing",
    "debug"       => $debug,
    "fuse_debug"  => 0,
    "threaded"    => 0,
    "/"           => $fs
);
# the default subs
my %fs_subs = (
    "chmod"       => \&fs_not_imp,
    "chown"       => \&fs_not_imp,
    "flush"       => \&fs_flush,
    "fsync"       => \&fs_not_imp,
    "getattr"     => \&fs_getattr,
    "getdir"      => \&fs_getdir,
    "getxattr"    => \&fs_not_imp,
    "link"        => \&fs_not_imp,
    "listxattr"   => \&fs_not_imp,
    "mkdir"       => \&fs_not_imp,
    "mknod"       => \&fs_not_imp,
    "open"        => \&fs_open,
    "read"        => \&fs_read,
    "readlink"    => \&fs_readlink,
    "release"     => \&fs_release,
    "removexattr" => \&fs_not_imp,
    "rmdir"       => \&fs_not_imp,
    "rename"      => \&fs_not_imp,
    "setxattr"    => \&fs_not_imp,
    "statfs"      => \&fs_statfs,
    "symlink"     => \&fs_not_imp,
    "truncate"    => \&fs_truncate,
    "unlink"      => \&fs_not_imp,
    "utime"       => sub{return 0},
    "write"       => \&fs_write,
);
# except extract these ones back out.
$debug = delete $args{"debug"};
$args{"debug"} = delete( $args{"fuse_debug"} ) || 0;
delete $args{"/"};
# add the functions, if not already defined.
# wrap in debugger if debug is set.
for my $name (keys %fs_subs) {
    my $sub = $fs_subs{$name};
#   $sub = wrap($sub, $name) if $debug;
    $args{$name} ||= $sub;
}
Fuse::main(%args);

sub fetch {
    my ($path, @args) = @_;

    my $obj = $fs;
    for my $elem (split '/', $path) {
    next if $elem eq ""; # skip empty // and before first /
    $obj = runcode($obj); # if there's anything to run
    # the dir we're changing into must be a hash (dir)
    return ENOTDIR() unless ref($obj) eq "HASH";
    # note that ENOENT and undef are NOT the same thing!
    return ENOENT() unless exists $obj->{$elem};
    $obj = $obj->{$elem};
    }

    return runcode($obj, @args);
}

sub runcode {
    my ($obj, @args) = @_;

    while (ref($obj) eq "CODE") {
    my $old = $obj;
    if (@args) { # run with these args. don't cache
        delete $codecache{$old};
        print "running $obj(",quoted(@args),") NO CACHE\n" if $debug;
        $obj = saferun($obj, @args);
    } elsif (exists $codecache{$obj}) { # found in cache
        print "got cached $obj\n" if $debug;
        $obj = $codecache{$obj}; # could be undef, or an error, BTW
    } else {
        print "running $obj() to cache\n" if $debug;
        $obj = $codecache{$old} = saferun($obj);
    }

    if (ref($obj) eq "NOCACHE") {
        print "returned a nocache() value - flushing\n" if $debug;
        delete $codecache{$old};
        $obj = $$obj;
    }

    print "returning ",ref($obj)," ",
      defined($obj) ? $obj : "undef",
      "\n" if $debug;
    }
    return $obj;
}

sub saferun {
    my ($sub, @args) = @_;

    my $ret = eval { &$sub(@args) };
    my $died = $@;
    if (ref($died)) {
    print "+++ Error $$died\n" if ref($died) eq "ERROR";
    return $died;
    } elsif ($died) {
    print "+++ $died\n";
    # stale file handle? moreorless?
    return ESTALE();
    }
    return $ret;
}

sub nocache {
    return bless(\ shift, "NOCACHE"); # yup, utter abuse of bless   :-)
}

sub dump_open_flags {
    my $flags = shift;

    printf "  flags: 0%o = (", $flags;
    for my $bits (
    [ O_ACCMODE(),   O_RDONLY(),     "O_RDONLY"    ],
    [ O_ACCMODE(),   O_WRONLY(),     "O_WRONLY"    ],
    [ O_ACCMODE(),   O_RDWR(),       "O_RDWR"      ],
    [ O_APPEND(),    O_APPEND(),    "|O_APPEND"    ],
    [ O_NONBLOCK(),  O_NONBLOCK(),  "|O_NONBLOCK"  ],
    [ O_SYNC(),      O_SYNC(),      "|O_SYNC"      ],
    [ O_DIRECT(),    O_DIRECT(),    "|O_DIRECT"    ],
    [ O_LARGEFILE(), O_LARGEFILE(), "|O_LARGEFILE" ],
    [ O_NOFOLLOW(),  O_NOFOLLOW(),  "|O_NOFOLLOW"  ],
    ) {
    my ($mask, $flag, $name) = @$bits;
    if (($flags & $mask) == $flag) {
        $flags -= $flag;
        print $name;
    }
    }
    printf "| 0%o !!!", $flags if $flags;
    print ")\n";
}

sub accessor {
    my $var_ref = shift;

    croak "accessor() requires a reference to a scalar var\n"
      unless defined($var_ref) && ref($var_ref) eq "SCALAR";

    return sub {
    my $new = shift;
    $$var_ref = $new if defined($new);
    return $$var_ref;
    }
}

sub fs_not_imp { return -ENOSYS() }

sub fs_flush {
    # we're passed a path, but finding my coderef stuff from a path
    # is a bit of a 'mare. flush the lot, won't hurt TOO much.
    print "Flushing\n" if $debug;
    %codecache = ();
    return 0;
}

sub easy_getattr {
    my ($mode, $size) = @_;

    return (
    0, 0,       # $dev, $ino,
    $mode,
    1,          # $nlink, see fuse.sourceforge.net/wiki/index.php/FAQ
    $uid, $gid, # $uid, $gid,
    0,          # $rdev,
    $size,      # $size,
    $ctime, $ctime, $ctime, # actually $atime, $mtime, $ctime,
    1024, 1,    # $blksize, $blocks,
    );
}

sub fs_getattr {
    my $path = shift;
    my $obj = fetch($path);

    # undef doesn't actually mean "file not found", it could be a coderef
    # file-sub which has returned undef.
    return easy_getattr(S_IFREG | 0200, 0) unless defined($obj);

    switch (ref($obj)) {
    case "ERROR" {  # this is an error to be returned.
        return -$$obj;
    }
    case "" {       # this isn't a ref, it's a real string "file"
        return easy_getattr(S_IFREG | 0644, length($obj));
    }
    # case "CODE" should never happen - already been run by fetch()
    case "HASH" {   # this is a directory hash
        return easy_getattr(S_IFDIR | 0755, 1);
    }
    case "SCALAR" { # this is a scalar ref. we use these for symlinks.
        return easy_getattr(S_IFLNK | 0777, 1);
    }
    else {          # what the hell is this file?!?
        print "+++ What on earth is ",ref($obj)," $path ?\n";
        return easy_getattr(S_IFREG | 0000, 0);
    }
    }
}

sub fs_getdir {
    my $obj = fetch(shift);
    return -$$obj if ref($obj) eq "ERROR"; # THINK this is a good idea.
    return -ENOENT() unless ref($obj) eq "HASH";
    return (".", "..", sort(keys %$obj), 0);
}

sub fs_open {
    # doesn't really need to open, just needs to check.
    my $obj = fetch(shift);
    my $flags = shift;
    dump_open_flags($flags) if $debug;

    # if it's undefined, and we're not writing to it, return an error
    return -EBADF() unless defined($obj) or ($flags & O_ACCMODE());

    switch (ref($obj)) {
    case "ERROR"  { return -$$obj; }
    case ""       { return 0 }          # this is a real string "file"
    case "HASH"   { return -EISDIR(); } # this is a directory hash
    else          { return -ENOSYS(); } # what the hell is this file?!?
    }
}

sub fs_read {
    my $obj = fetch(shift);
    my $size = shift;
    my $off = shift;

    return -ENOENT() unless defined($obj);
    return -$$obj if ref($obj) eq "ERROR";
    # any other types of refs are probably bad
    return -ENOENT() if ref($obj);

    if ($off >  length($obj)) {
    return -EINVAL();
    } elsif ($off == length($obj)) {
    return 0; # EOF
    }
    return substr($obj, $off, $size);
}

sub fs_readlink {
    my $obj = fetch(shift);
    return -$$obj if ref($obj) eq "ERROR";
    return -EINVAL() unless ref($obj) eq "SCALAR";
    return $$obj;
}

sub fs_release {
    my ($path, $flags) = @_;
    dump_open_flags($flags) if $debug;
    return 0;
}

sub fs_statfs {
    return (
        255, # $namelen,
        1,1, # $files, $files_free,
        1,1, # $blocks, $blocks_avail, # 0,0 seems to hide it from df?
        2,   # $blocksize,
    );
}

sub fs_truncate {
    my $obj = fetch(shift, ""); # run anything to set it to ""
    return -$$obj if ref($obj) eq "ERROR";
    return 0;
}

sub fs_write {
    my ($path, $buf, $off) = @_;
    my $obj = fetch($path, $buf, $off); # this runs the coderefs!
    return -$$obj if ref($obj) eq "ERROR";
    return length($buf);
}

Final word: I didn't try to use the module itself (it's not listed in my distro package repository, and I was too lazy (sorry) to install it by cpanm or other way). But I think that if I'll have to just use FUSE with Perl, I'll probably just use Fuse::Simple instead of Fuse, maybe forking it. I'd use plain Fuse only for my academic research, I think...

Hope this helps.


来源: stackexchange

问:
Latitude and Longitude showing as 0 in Android
```<code>  ************* TrackGPS.java *****************************

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;

    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.widget.Toast;

    /**
     * Created by ANQ on 8/8/2016.
     */

    public class TrackGPS extends Service implements LocationListener {

        private final Context mContext;

        boolean checkGPS = false;

        boolean checkNetwork = false;

        boolean canGetLocation = false;

        Location loc;
        double latitude;
        double longitude;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
        protected LocationManager locationManager;

        public TrackGPS(Context mContext) {
            this.mContext = mContext;
            getLocation();
        }

        private Location getLocation() {

            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                checkGPS = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                checkNetwork = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!checkGPS && !checkNetwork) {
                    Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (checkNetwork) {
                        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Network", "Network");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                            }

                            if (loc != null) {
                                latitude = loc.getLatitude();
                                longitude = loc.getLongitude();
                            }
                        }
                        catch(SecurityException e){

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (checkGPS) {
                    Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
                    if (loc == null) {
                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (loc != null) {
                                    latitude = loc.getLatitude();
                                    longitude = loc.getLongitude();
                                }
                            }
                        } catch (SecurityException e) {

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return loc;
        }

        public double getLongitude() {
            if (loc != null) {
                longitude = loc.getLongitude();
            }
            return longitude;
        }

        public double getLatitude() {
            if (loc != null) {
                latitude = loc.getLatitude();
            }
            return latitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            alertDialog.setTitle("GPS Not Enabled");

            alertDialog.setMessage("Do you wants to turn On GPS");

            alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            alertDialog.show();
        }

        public void stopUsingGPS() {
            if (locationManager != null) {

                locationManager.removeUpdates(TrackGPS.this);
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

************* MainActivity.java ****************

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        private Button b_get;
        private TrackGPS gps;
        double longitude;
        double latitude;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b_get = (Button)findViewById(R.id.get);

            b_get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gps = new TrackGPS(MainActivity.this);

                    if(gps.canGetLocation()){

                        longitude = gps.getLongitude();
                        latitude = gps .getLatitude();

                        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                        gps.showSettingsAlert();
                    }

                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            gps.stopUsingGPS();
        }
    }
</code>```

When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.

答:
Please manage required permission for marshmallow.

First you add  this permission in manifest file

```<code> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

After in your activity First declare two variable like this,

```<code> private static final int REQUEST_CODE_PERMISSION = 1;
 String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
</code>```

After in onCreate method

```<code> if(Build.VERSION.SDK_INT>= 23) {

        if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{mPermission,
                    },
                    REQUEST_CODE_PERMISSION);
            return;
        }

        else
        {
            *here manage your code if permission already access
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
  ************* TrackGPS.java *****************************

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;

    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;
    import android.util.Log;
    import android.widget.Toast;

    /**
     * Created by ANQ on 8/8/2016.
     */

    public class TrackGPS extends Service implements LocationListener {

        private final Context mContext;

        boolean checkGPS = false;

        boolean checkNetwork = false;

        boolean canGetLocation = false;

        Location loc;
        double latitude;
        double longitude;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
        protected LocationManager locationManager;

        public TrackGPS(Context mContext) {
            this.mContext = mContext;
            getLocation();
        }

        private Location getLocation() {

            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                checkGPS = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                checkNetwork = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!checkGPS && !checkNetwork) {
                    Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (checkNetwork) {
                        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Network", "Network");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                            }

                            if (loc != null) {
                                latitude = loc.getLatitude();
                                longitude = loc.getLongitude();
                            }
                        }
                        catch(SecurityException e){

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (checkGPS) {
                    Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
                    if (loc == null) {
                        try {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                loc = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (loc != null) {
                                    latitude = loc.getLatitude();
                                    longitude = loc.getLongitude();
                                }
                            }
                        } catch (SecurityException e) {

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return loc;
        }

        public double getLongitude() {
            if (loc != null) {
                longitude = loc.getLongitude();
            }
            return longitude;
        }

        public double getLatitude() {
            if (loc != null) {
                latitude = loc.getLatitude();
            }
            return latitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            alertDialog.setTitle("GPS Not Enabled");

            alertDialog.setMessage("Do you wants to turn On GPS");

            alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            alertDialog.show();
        }

        public void stopUsingGPS() {
            if (locationManager != null) {

                locationManager.removeUpdates(TrackGPS.this);
            }
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

************* MainActivity.java ****************

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        private Button b_get;
        private TrackGPS gps;
        double longitude;
        double latitude;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b_get = (Button)findViewById(R.id.get);

            b_get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    gps = new TrackGPS(MainActivity.this);

                    if(gps.canGetLocation()){

                        longitude = gps.getLongitude();
                        latitude = gps .getLatitude();

                        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                        gps.showSettingsAlert();
                    }

                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            gps.stopUsingGPS();
        }
    }

When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.

Body:
Please manage required permission for marshmallow.

First you add  this permission in manifest file

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

After in your activity First declare two variable like this,

 private static final int REQUEST_CODE_PERMISSION = 1;
 String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

After in onCreate method

 if(Build.VERSION.SDK_INT>= 23) {

        if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{mPermission,
                    },
                    REQUEST_CODE_PERMISSION);
            return;
        }

        else
        {
            *here manage your code if permission already access
        }
    }


问:
Eclipse string literal line wrapping
When I run the Formatter it indents string literal lines all the way to the last line of the variable name, even if that exceeds the column guide, as shown in this screenshot:

Ideally, I want all of the lines to be wrapped similar to the way the first line is wrapped, with just a couple of tabs (or 1 tab if possible). I've changed all the Formatter settings for assignment and binary expression and it doesn't affect the Formatter's line wrapping behavior.

Is there a way to make Eclipse wrap lines like NetBeans or maybe with some plugin?

Here's what my Formatter settings are for Line Wrapping:

答:
Plugins

Eclipse Colorer

has an "Enhanced and fixed word wrapping mode".

Eclipse Word-Wrap

is dedicated to word wrapping and might do the job.

Customization

Here's how and where you do it in Eclipse: Preferences->Java->Code Style->Formatter, then click the Edit button and select the Comments tab. After that, the same place, you can select the Line Wrapping tab and the Indentation tab. You can also set margins and tab sizes in Preferences>General>Editors>Text Editors by editing the Displayed Tab Width

I'll note that the Eclipse version should be Eclipse Project Neon (4.6) M4 or higher because Eclipse 4.6 came with some updated word wrapping out of the box.

Title: Eclipse string literal line wrapping


问:
Is it possible to embed a login page with cookie and localstorage in iframe?
I have many websites: www.a.com & www.b.com & www.c.com & ... etc

And a user system, https://www.my-login.com/

I create many iframes like  on all pages.

The login logic in my-login.com/embed.html is:

check if user already login by a cookie (domain=my-login.com)

if not, show login page, user can login, everything will done with a ajax request, then set a cookie on my-login.com, remember user already login.

if user already login, notify the parent pages with

window.parent.postMessage({ msg: 'userlogin', user: xxxx }), 'www.a.com')

the parent page will get the user information asynchronously.

this works well before, but recently chrome blocked "3rd party cookies and data", so the 1st step failed, user must login everytime.

Is there any workaround without require users config their browser?

答:
finally I found that this is a update only on google chrome, it reject any "3-rd party data" by default on recent release.

no way to resolve.


问:
How to generate auto increment ID and do not set to default when a program is closed and opened again in java?
I am generating the auto increment number as the code below.

```<code>public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}
</code>```

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?

答:
You can store the value in an ini file. You will need to update the value each time it changes.

If you do not want the users to easily detect the value, then you can store it in a database.

Anyway, you will need to not initialize it to 10000, just in the case the value was not already saved somewhere.

Body:
I am generating the auto increment number as the code below.

public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?


问:
Search only children of a protractor webElementFinder using CSS
I have a protractor webElementFinder testElement. I want to match only its  div children (NOT grandchildren or any other further descendants) and thus testElement.find('div') will not work as it will find all descendant divs.

If protractor worked like jQuery (which would make sense since Angular is smart enough to use jQuery if its present and protractor is built with Angular in mind), I would just do testElement.find(' > div') which would work despite the find argument not being a valid CSS selector by itself; however because protractor just uses built in Element functions, that CSS selector is not valid by itself, and protractor throws an error.

I could go this route Angular JS, Protractor locator, get direct children of element since xpath natively lets you look at children, but I'd much rather use CSS than xpath.

答:
Just use:</p>

```<code>$('testElement > div')
</code>```

Body:
Just use:

$('testElement > div')


问:
Using AWS Kinesis for large file uploads
My client has a service which stores a lot of files, like video or sound files. The service works well, however looks like the long-time file storing is quite a challenge, and we would like to use AWS for storing these files.

The problem is the following, the client wants to use AWS kinesis for transferring every file from our servers to AWS. Is this possible? Can we transfer files using that service? There's a lot of video files, and we got more and more every day. And every files is relatively big.

We would also like to save some detail of the files, possibly into dynamoDB, we could use Lambda functions for that.

The most important thing, that we need a reliable data transfer option.

答:
KInesis would not be the right tool to upload files, unless they were all very small - and most videos would almost certainly be over the 1MB record size limit:

The maximum size of a data blob (the data payload before
  Base64-encoding) within one record is 1 megabyte (MB).

https://aws.amazon.com/kinesis/streams/faqs/


问:
Body with height 100% with background-image: cover to fill enire page not just a viewport - without js if possible

Is it possible to have background image cover the entire page even if the viewport is smaller than the page, only with css?

btw I have to setup html,body to 100% height.

答: Try using 100vh height and background-size: cover; it will cover full page this will work


问:
Can't Add Service Reference to self-hosted WCF Service
I've created a REST web service that I need to consume from within an asp.net app. The service is hosted from a console window. I can get it running fine, and I can get output from it as well when surfing to it in a web browser. The problem is, when I try to "Add Service Reference" from my asp.net app, it complains of various things depending on which service URL I point it at. End result is I cannot figure out how to add the service reference.

My Interface is defined like so:

```<code>[ServiceContract]
public interface IWave {
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/devices")]
    List<Device> getDevices();

    ...
}
</code>```

Here's how I'm hosting my service:

```<code>// Port is 1178
var endPoint = new EndpointAddress(string.Format("http://localhost:{0}/wave", port));
var waveServiceSingleton = new WaveSVC();

binding = new WebHttpBinding();

var behavior = new WebHttpBehavior();
behavior.FaultExceptionEnabled = true;

host = new WebServiceHost(waveServiceSingleton, endPoint.Uri);

// Get the service debug behavior and tell it to include details about errors
ServiceDebugBehavior sdb;
sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.IncludeExceptionDetailInFaults = true;

host.AddServiceEndpoint(typeof(IWave), binding, "");

// Add mex endpoint
ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
mexBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(mexBehavior);
host.AddServiceEndpoint(typeof(IWave), MetadataExchangeBindings.CreateMexHttpBinding(), endPoint.Uri.AbsoluteUri + "/mex");

host.Open();
</code>```

When I browse to http://localhost:1180/wave/devices, I see a json string in the body of my browser. This is expected and works as desired. I cannot point my "Add Service Reference" wizard to this URL, as it complains that:

```<code>The document at the url http://localhost:1178/wave/devices was not recognized as a known     document type.
The error message from each known type may help you fix the problem:
- Report from 'XML Schema' is 'Data at the root level is invalid. Line 1, position 1.'.
- Report from 'DISCO Document' is 'Data at the root level is invalid. Line 1, position  1.'.
- Report from 'WSDL Document' is 'There is an error in XML document (1, 1).'.
  - Data at the root level is invalid. Line 1, position 1.
Metadata contains a reference that cannot be resolved: 'http://localhost:1178/wave/devices'.
The remote server returned an unexpected response: (405) Method Not Allowed.
The remote server returned an error: (405) Method Not Allowed.
If the service is defined in the current solution, try building the solution and adding the service reference again.
</code>```

I have a nagging suspicion that I need to point my "Add Service Reference" to the mex, but that doesn't work either and indeed, when I browse to the mex address of http://localhost:1178/wave/mex, I get a blank page.

EDIT 1

Just to eliminate JSON being the culprit, I changed my contract to output Xml instead of Json. The result was the same: I can't add a service reference using this URL: http://localhost:1178/zwave/devices/xml (even though that URL produces XML).

```<code>[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate= "/devices/xml")]
</code>```

Thanks in advance for any help provided.

答:
Traditionally, the "add web reference" option you are using in Visual Studio is meant for referencing XML Web Services only. Your service is defined in terms of rest/json and not in terms of soap/xml/wsdl that visual studio expects.

I suspect that Visual Studio simply isn't able to generate proxies for a json/rest service as yours. This is confirmed in the documentation on the WCF rest starter kit for .NET 3.5 (see the section "Consuming RESTful Services with HttpClient", search for "not possible to generate strongly-typed proxies like you’re used to with SOAP").

I'm not sure whether it is still unsupported in VS2010 / .NET 4.0, but I think you have to look for another option than "add web reference".

ContentLicense: CC BY-SA 2.5

Body:
I've created a REST web service that I need to consume from within an asp.net app. The service is hosted from a console window. I can get it running fine, and I can get output from it as well when surfing to it in a web browser. The problem is, when I try to "Add Service Reference" from my asp.net app, it complains of various things depending on which service URL I point it at. End result is I cannot figure out how to add the service reference.

My Interface is defined like so:

[ServiceContract]
public interface IWave {
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/devices")]
    List<Device> getDevices();

    ...
}

Here's how I'm hosting my service:

// Port is 1178
var endPoint = new EndpointAddress(string.Format("http://localhost:{0}/wave", port));
var waveServiceSingleton = new WaveSVC();

binding = new WebHttpBinding();

var behavior = new WebHttpBehavior();
behavior.FaultExceptionEnabled = true;

host = new WebServiceHost(waveServiceSingleton, endPoint.Uri);

// Get the service debug behavior and tell it to include details about errors
ServiceDebugBehavior sdb;
sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.IncludeExceptionDetailInFaults = true;

host.AddServiceEndpoint(typeof(IWave), binding, "");

// Add mex endpoint
ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
mexBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(mexBehavior);
host.AddServiceEndpoint(typeof(IWave), MetadataExchangeBindings.CreateMexHttpBinding(), endPoint.Uri.AbsoluteUri + "/mex");

host.Open();

When I browse to http://localhost:1180/wave/devices, I see a json string in the body of my browser. This is expected and works as desired. I cannot point my "Add Service Reference" wizard to this URL, as it complains that:

The document at the url http://localhost:1178/wave/devices was not recognized as a known     document type.
The error message from each known type may help you fix the problem:
- Report from 'XML Schema' is 'Data at the root level is invalid. Line 1, position 1.'.
- Report from 'DISCO Document' is 'Data at the root level is invalid. Line 1, position  1.'.
- Report from 'WSDL Document' is 'There is an error in XML document (1, 1).'.
  - Data at the root level is invalid. Line 1, position 1.
Metadata contains a reference that cannot be resolved: 'http://localhost:1178/wave/devices'.
The remote server returned an unexpected response: (405) Method Not Allowed.
The remote server returned an error: (405) Method Not Allowed.
If the service is defined in the current solution, try building the solution and adding the service reference again.

I have a nagging suspicion that I need to point my "Add Service Reference" to the mex, but that doesn't work either and indeed, when I browse to the mex address of http://localhost:1178/wave/mex, I get a blank page.

EDIT 1

Just to eliminate JSON being the culprit, I changed my contract to output Xml instead of Json. The result was the same: I can't add a service reference using this URL: http://localhost:1178/zwave/devices/xml (even though that URL produces XML).

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate= "/devices/xml")]

Thanks in advance for any help provided.


问:
applescript does not run from terminal
why doesn't my applescript run from terminal  I can run it successfully from the editor

I run command

```<code>/usr/bin/osascript -e my_script.scpt
</code>```

I get error

0:12: syntax error: A unknown token can’t go after this identifier. (-2740)

my script

```<code>set volume 2
set x to 0
open location "spotify:user:wunspe:playlist:meininki"
tell application "Spotify"
    set the sound volume to 0
    play
    repeat 10 times
        if sound volume is less than 70 then
            set sound volume to (sound volume + 10)
            set x to (x + 9)
            set volume output volume x without output muted --100%

            delay 3
        end if
    end repeat

end tell
</code>```

答:
If you write

```<code>osascript -e "set Volume 10"
</code>```

after the -e is the full content of the script.

if you put into some file (lets call it volume.scpt)

```<code>set Volume 10
</code>```

you can call the script-file as

```<code>osascript /path/to/volume.scpt
</code>```

Title: applescript does not run from terminal

Body:
why doesn't my applescript run from terminal  I can run it successfully from the editor

I run command

/usr/bin/osascript -e my_script.scpt

I get error

0:12: syntax error: A unknown token can’t go after this identifier. (-2740)

my script

set volume 2
set x to 0
open location "spotify:user:wunspe:playlist:meininki"
tell application "Spotify"
    set the sound volume to 0
    play
    repeat 10 times
        if sound volume is less than 70 then
            set sound volume to (sound volume + 10)
            set x to (x + 9)
            set volume output volume x without output muted --100%

            delay 3
        end if
    end repeat

end tell

Body:
If you write

osascript -e "set Volume 10"

after the -e is the full content of the script.

if you put into some file (lets call it volume.scpt)

set Volume 10

you can call the script-file as

osascript /path/to/volume.scpt


问:
scanf is collecting the wrong input
```<code> #include<stdio.h>
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }
</code>```

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.

答:
the outputTry %lf instead of %f

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

int main()
{
double c;
scanf("%lf",&c);
printf("%lf",c);
return 0;
}
</code>```

What you've used is %f, which is used for a regular float datatype.
since you've specified double , you need to use %lf , which is long float. it reads a double.
hope this helps you.

Title: scanf is collecting the wrong input

Body:
 #include<stdio.h>
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.

Body:
the outputTry %lf instead of %f

#include<stdio.h>

int main()
{
double c;
scanf("%lf",&c);
printf("%lf",c);
return 0;
}

What you've used is %f, which is used for a regular float datatype.
since you've specified double , you need to use %lf , which is long float. it reads a double.
hope this helps you.


问:
Can't get ES6 promise value to display in AngularJS view
I'm trying to use the Pinterest JavaScript SDK to get some pin data for a project. I have a method in a Pinterest service I created that gets called in my HomeController. I tried throwing the response inside of a promise so I could put it on my HomeController's $scope and display it in my view.  However, $scope.pins is undefined in my view.  Why is it undefined?  Seems like the promise is working. Still learning promises.

Pinterest Service

```<code>function getBoardPins (id) {
  return new Promise(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}
</code>```

Home Controller

```<code>Pinterest.getBoardPins('490329546869188172').then(function (response) {
  $scope.pins = response.data;
});
</code>```

View

```<code><h1>Pinterest</h1>
<div ng-repeat="pin in pins">
  <div>{{pin}}</div>
</div>
</code>```

答:
Use $q.when to convert the ES6 promise to an AngularJS promise:

```<code>$q.when(Pinterest.getBoardPins('490329546869188172'))
  .then(function (response) {
    $scope.pins = response.data;
});
</code>```

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

To bring an ES6 promise into the AngularJS execution context, use $q.when.

$q.when

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

— AngularJS $q Service API Reference - $q.when

Alternately create the promise with the $q constructor.

```<code>function getBoardPins (id) {
  //return new Promise(function (resolve, reject) {
  return $q(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}
</code>```

This creates a promise that is integrated with the AngularJS framework and its digest cycle.

Body:
I'm trying to use the Pinterest JavaScript SDK to get some pin data for a project. I have a method in a Pinterest service I created that gets called in my HomeController. I tried throwing the response inside of a promise so I could put it on my HomeController's $scope and display it in my view.  However, $scope.pins is undefined in my view.  Why is it undefined?  Seems like the promise is working. Still learning promises.

Pinterest Service

function getBoardPins (id) {
  return new Promise(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}

Home Controller

Pinterest.getBoardPins('490329546869188172').then(function (response) {
  $scope.pins = response.data;
});

View

Pinterest

{{pin}}

Body:
Use $q.when to convert the ES6 promise to an AngularJS promise:

$q.when(Pinterest.getBoardPins('490329546869188172'))
  .then(function (response) {
    $scope.pins = response.data;
});

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

To bring an ES6 promise into the AngularJS execution context, use $q.when.

$q.when

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

— AngularJS $q Service API Reference - $q.when

Alternately create the promise with the $q constructor.

function getBoardPins (id) {
  //return new Promise(function (resolve, reject) {
  return $q(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}

This creates a promise that is integrated with the AngularJS framework and its digest cycle.


问:
PHP & MySQL UPDATE 10 columns
I want to update customer data which means 10 different columns would be updated in one UPDATE SET WHERE statement but I keep getting a warning in NetBeans that says method length 26 ( allowed 20)
Can anyone tell me what the method length refers to and what another way is to update all those columns in one statement ? </p>

答:
Netbeans is notorious for these informational messages which are really a matter of style preference rather than an actual limitation.

I like to create my SQL code directly using a tool like phpMyAdmin to verify the statement works then port it over to my code.

Title: PHP & MySQL UPDATE 10 columns


问:
Making the data from the csv file double when put in the Textbox
txtRate.setText(emp.getRate());

I cant display the data from the csv file in the textbox because it keeps on saying

double cannot be converted to java.lang.String.
My method is public Double getRate()
If i try to make is public String it would work but i cant use the value for calculation because it already has been set
to String

答:
The class you are working on contains method with signature setText(String value) but there's no method with signature setText(Double value).

When you call a method compiler checks the parameter type and tries to recognize what method should be in use for this case.

As you are using Double type for the parameter, the compiler is unable to find a method with signature setText(Double value) and you get the error you have reported in your question.

To overcome this issue, convert your parameter from Double to String type before passing it to setText method.

```<code>txtRate.setText(String.valueOf(emp.getRate()));
</code>```

or

```<code>txtRate.setText(emp.getRate().toString());
</code>```

But the second approach may throw NullPointerException if emp.getRate() returns null, so the first approach is safer.

In case you want to format your numbers in a fancy way, consider this tutorial: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Body:
The class you are working on contains method with signature setText(String value) but there's no method with signature setText(Double value).

When you call a method compiler checks the parameter type and tries to recognize what method should be in use for this case.

As you are using Double type for the parameter, the compiler is unable to find a method with signature setText(Double value) and you get the error you have reported in your question.

To overcome this issue, convert your parameter from Double to String type before passing it to setText method.

txtRate.setText(String.valueOf(emp.getRate()));

or

txtRate.setText(emp.getRate().toString());

But the second approach may throw NullPointerException if emp.getRate() returns null, so the first approach is safer.

In case you want to format your numbers in a fancy way, consider this tutorial: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html


问:
laravel mailables -> replace tokens after view rendered
following thing:

I read posts from a wordpress database. The idea is that the posts act as master.

E.g. we have a wordpress post with post content:

```<code>Hi XX_USERNAME_XX,

nice to meet you.

XX_LARAVEL_CONTENT_XX

thanks for your donation of XX_DONATION_AMOUNT_XX

bye
</code>```

I now want to send a normal laravel mailable that when sending out, does the replacements. Now the thing is the views in laravel typically act as master.

in this case though, I want the wordpress post content to be the master, and insert the laravel view into the wordpress content (XX_LARAVEL_CONTENT_XX). And while doing that, replace additional tokens (XX_DONATION_AMOUNT_XX).

How can I do stuff, just before the laravel mailable is rendered? e.g. before the output of the mailable is passed to the mail service, i want to hook in my own filter, take the output from the mailable and put that output into the wordpress post. Is there something supporting this?

答:
not quite clear to me why you choose to compose your views this way, but in order to achieve this your way, you could use the callbacks variable in the Mailable class. They will be called upon the message right after it has been composed from your view

Class MyMail extends Mailable
{
    use Queueable, SerializesModels;
    public $master;
    publiс $placeholder = 'XX_LARAVEL_CONTENT_XX';

    public function __construct($master)
    {
        $this->master = $master; // 'BEFORE + XX_LARAVEL_CONTENT_XX + AFTER';
    }

    public function build()
    {
        $this->callbacks[] = function ($message) {
            $oldBody = $message->getBody();
            $newBody = str_replace($this->placeholder, $oldBody, $this->master);
            $message->setBody($newBody);
        };

        return $this->view('my-laravel-mail-view') // your normal message setup
            ->to('test@example.com')
            ->subject('Hello');
    }
}
```

<p>And if you want to replace multiple variables, remember that str_replace supports arrays as search and replacement:</p>

```str_replace(['aa', 'bb'], ['AA', 'BB'], $subject);
```

Body:
following thing:

I read posts from a wordpress database. The idea is that the posts act as master.

E.g. we have a wordpress post with post content:

Hi XX_USERNAME_XX,

nice to meet you.

XX_LARAVEL_CONTENT_XX

thanks for your donation of XX_DONATION_AMOUNT_XX

bye

I now want to send a normal laravel mailable that when sending out, does the replacements. Now the thing is the views in laravel typically act as master.

in this case though, I want the wordpress post content to be the master, and insert the laravel view into the wordpress content (XX_LARAVEL_CONTENT_XX). And while doing that, replace additional tokens (XX_DONATION_AMOUNT_XX).

How can I do stuff, just before the laravel mailable is rendered? e.g. before the output of the mailable is passed to the mail service, i want to hook in my own filter, take the output from the mailable and put that output into the wordpress post. Is there something supporting this?

Body:
not quite clear to me why you choose to compose your views this way, but in order to achieve this your way, you could use the callbacks variable in the Mailable class. They will be called upon the message right after it has been composed from your view

Class MyMail extends Mailable
{
    use Queueable, SerializesModels;
    public $master;
    publiс $placeholder = 'XX_LARAVEL_CONTENT_XX';

    public function __construct($master)
    {
        $this->master = $master; // 'BEFORE + XX_LARAVEL_CONTENT_XX + AFTER';
    }

    public function build()
    {
        $this->callbacks[] = function ($message) {
            $oldBody = $message->getBody();
            $newBody = str_replace($this->placeholder, $oldBody, $this->master);
            $message->setBody($newBody);
        };

        return $this->view('my-laravel-mail-view') // your normal message setup
            ->to('test@example.com')
            ->subject('Hello');
    }
}

And if you want to replace multiple variables, remember that str_replace supports arrays as search and replacement:

str_replace(['aa', 'bb'], ['AA', 'BB'], $subject);


问:
How to define network interface
I'm developing Kaa. i don't understand this part:
$ sudo nano /etc/kaa-node/conf/kaa-node.properties
transport_public_interface=localhost=YOUR_PUBLIC_INTERFACE
the link is :http://kaaproject.github.io/kaa/docs/v0.10.0/Administration-guide/System-installation/Single-node-installation/

how to define YOUR_PUBLIC_INTERFACE ?

答:
YOUR_PUBLIC_INTERFACE means the public IP or DNS where the Kaa server runs.
For  example the entry in property file will be as follows
transport_public_interface=54.17.30.158

Title: How to define network interface


问:
Using ngSwitch on a numeric range in Angular 2
I have recently started learning Angular2.

I want to know if there is a possibility to use ngSwitch or ngIf angular2

directives for a specific numeric range?

Say I want to update the color of some text based on a range.

```<code><25 = Mark the text in red
>25 && <75 = Mark the text in orange
>75 = Mark the text in green
</code>```

How do I achieve the same using Angular2 ngIf/ngSwitch directives.

Is there a way something to write like this ?

```<code><div [ngIf]="item.status < 25">
<h2 class="text-red">{{item.status}}</h2>
</div>
<div [ngIf]="item.status > 25 && item.status < 75">
<h2 class="headline text-orange">{{item.status}}</h2>
</div>
<div [ngIf]="item.status > 75">
<h2 class="headline text-green">{{item.status}}</h2>
</div>
</code>```

Or anything that would have to do with using ngSwitch, ngSwitchWhen statements.

答:
In dealing with angular2 conditional styling it's best to use [class] when you are adding a single class or [ngClass] when you are returning an array of classes like so: headline text-green someOtherClass.

```<code>// display div
<div [ngClass]="getItemClass(item.status)">{{item.status}}</div>

// logic
getItemClass(status) {
  let itemClass: string;

  if (status < 25) {
    itemClass = 'text-red';
  } else if (status > 25 && status < 75) {
    itemClass = 'headline text-orange';
  } else {
    itemClass = 'headline text-green';
  }

  return itemClass;
}
</code>```

Similarly, instead of declaring itemClass as a string, we could declare it as an array, i.e let itemClass: Array<string>; in which case we reassign it in our if blocks as itemClass = ['headline', 'text-green']. This works just as fine.

Body:
I have recently started learning Angular2.

I want to know if there is a possibility to use ngSwitch or ngIf angular2

directives for a specific numeric range?

Say I want to update the color of some text based on a range.

<25 = Mark the text in red
>25 && <75 = Mark the text in orange
>75 = Mark the text in green

How do I achieve the same using Angular2 ngIf/ngSwitch directives.

Is there a way something to write like this ?

<div [ngIf]="item.status < 25">

{{item.status}}

 25 && item.status < 75">

{{item.status}}

 75">

{{item.status}}

Or anything that would have to do with using ngSwitch, ngSwitchWhen statements.

Body:
In dealing with angular2 conditional styling it's best to use [class] when you are adding a single class or [ngClass] when you are returning an array of classes like so: headline text-green someOtherClass.

// display div
<div [ngClass]="getItemClass(item.status)">{{item.status}}</div>

// logic
getItemClass(status) {
  let itemClass: string;

  if (status < 25) {
    itemClass = 'text-red';
  } else if (status > 25 && status < 75) {
    itemClass = 'headline text-orange';
  } else {
    itemClass = 'headline text-green';
  }

  return itemClass;
}

Similarly, instead of declaring itemClass as a string, we could declare it as an array, i.e let itemClass: Array<string>; in which case we reassign it in our if blocks as itemClass = ['headline', 'text-green']. This works just as fine.


问:
mod_authnz_ldap OR multiple LDAP groups
I am working with Apache 2.4 and the module mod_authnz_ldap to grant or authorize to users in a group to certain pages.
This is my current configuration. This is working fine:

```<code>    AuthLDAPUrl "ldap://myldapserver.com:389/dc=example, dc=com?uid"
    AuthLDAPBindAuthoritative on
    AuthLDAPGroupAttribute memberUid
    AuthLDAPGroupAttributeIsDN off

    <RequireAll>

       Require ldap-group cn=mygroup,ou=group,dc=example,dc=com

    </RequireAll>
</code>```

My question is:

It is possible to authorize to more than one group? This means to make an OR of the groups and authorize to any of them.

I was trying to do it inserting a SatisfyAny directive inside the RequireAll and I did not manage to make it work.

Thanks a lot in advance.

Cheers,

答:
The Require ldap-filter can be used with any valid LDAP filter. So something like:

```<code>Require ldap-filter (&(memberOf='cn=mygroup,ou=group,dc=example,dc=com')(cn=mygroup33,ou=group,dc=example,dc=com))
</code>```

Should work. Of course assuming that memberOf is present in your LDAP implementation.

Title: mod_authnz_ldap OR multiple LDAP groups

Body:
I am working with Apache 2.4 and the module mod_authnz_ldap to grant or authorize to users in a group to certain pages.
This is my current configuration. This is working fine:

    AuthLDAPUrl "ldap://myldapserver.com:389/dc=example, dc=com?uid"
    AuthLDAPBindAuthoritative on
    AuthLDAPGroupAttribute memberUid
    AuthLDAPGroupAttributeIsDN off

    <RequireAll>

       Require ldap-group cn=mygroup,ou=group,dc=example,dc=com

    </RequireAll>

My question is:

It is possible to authorize to more than one group? This means to make an OR of the groups and authorize to any of them.

I was trying to do it inserting a SatisfyAny directive inside the RequireAll and I did not manage to make it work.

Thanks a lot in advance.

Cheers,

Body:
The Require ldap-filter can be used with any valid LDAP filter. So something like:

Require ldap-filter (&(memberOf='cn=mygroup,ou=group,dc=example,dc=com')(cn=mygroup33,ou=group,dc=example,dc=com))

Should work. Of course assuming that memberOf is present in your LDAP implementation.


问:
Git: How to maintain two branches of a project and merge only shared data?
Suppose I have two branches of a project IMClient-MacOS and IMClient-Windows, and their code only differs by (let's say) one directory main/.  All the other directories contain system-independent code and are interchangeable.

Some workers work on the Windows version, and some work on the MacOS version.  How do they prevent overwriting changing into the main/ directory when they merge from their counterparts' branch?  Is there a way to merge in Git that will always ignore the OS-dependent directory?

答: An alternative to trying to filter merges would be to split the common and OS-specific parts into two repositories. You can then set up the one as a submodule for the other. Whether to have the common part set up as a submodule of the OS specific parts, or the other way around probably depends a bit on where do most of the commits go.</p>

OwnerDisplayName: Jake

OwnerDisplayName: Timo


问:
Reliabily unload dll in java
I am trying to unload a dll in java. I have read this and this but it seems that you can not guarantee that the dll will actually be unloaded at a certain time. This is because System.gc() simply "asks kindly" for the garbage collector to run.

So here is a break down of the situation. I have a dll that provides some functionality via JNI. Lets call this dll MainDll. MainDll is loaded from a call to System.load("MainDll"). I need to be able to unload and load this dll on the fly.

Is it possible to create another dll that's sole purpose is to load and unload MainDll. Lets call this dll LoaderDll. I could then simple call System.load("LoaderDll") and have some native functions to load and unload MainDll. The reason for doing this, is I have access to functions on the native system that can load and unload the dll on the fly. The tricky part with this is, will I have still be able to access the native functions I have written in MainDll if it loaded from inside LoaderDll.

Sorry if this is a confusing question. It seems its a little difficult to explain.

Thanks

答:
If you have a need to dynamically load and unload code, have you considered OSGi. This works in felix at least.

In Oracle/Sun's JDK, System.gc() will trigger a full gc (unless it has been turned off on the command line).  It could be just a hint on other JVMs.

Title: Reliabily unload dll in java


问:
Render Alert component in singleton class
I have singleton class that handles all server request of my app.
My issue is to show Alert from this singleton if there is connection issues during internet connection.
So far I try to show Alert in this way:

```<code>ReactDom.render(Alert.alert(
   'Alert title',
   'Alert message'
));
</code>```

This one shows an Alert on app screen but after one second shown red screen with message: ReactDom.render(): Invalid component element.

So, how can i show an Alert on screen without this error message?

答:
Oh..For newbies like me..
If you want to show Alert inside class that not expands Component just write:

```<code>Alert.alert('alert title', 'alert message');
</code>```

and it works!

Body:
I have singleton class that handles all server request of my app.
My issue is to show Alert from this singleton if there is connection issues during internet connection.
So far I try to show Alert in this way:

ReactDom.render(Alert.alert(
   'Alert title',
   'Alert message'
));

This one shows an Alert on app screen but after one second shown red screen with message: ReactDom.render(): Invalid component element.

So, how can i show an Alert on screen without this error message?

Body:
Oh..For newbies like me..
If you want to show Alert inside class that not expands Component just write:

Alert.alert('alert title', 'alert message');

and it works!


问:
Xamarin iOS designer : There was a error rendering this document
I am working on Xamarin iOS app. I just recently update the Xamarin Studio to the latest version 6.2 . but now I stuck at the below point.

My iOS designer can't work and it display the below error message.

System.AggregateException: One or more errors occurred. --->
  System.InvalidOperationException: The returned remote SDK entries are
  invalid   at
  MonoTouch.Design.Client.IosSdkTarget.InitializeLocalFileStore ()
  [0x00065] in
  /Users/builder/data/lanes/4010/3a28108f/source/md-addins/Xamarin.Designer.iOS/MonoTouch.Design.Client/DesignerItems/IosSdkTarget.cs:90
  at MonoTouch.Design.Client.IosSdkTarget..ctor (System.Version
  xcodeVersion, MonoTouch.Design.DataPackEntry[] datapack, System.String
  storeDirectory) [0x0004d] in
  /Users/builder/data/lanes/4010/3a28108f/source/md-addins/Xamarin.Designer.iOS/MonoTouch.Design.Client/DesignerItems/IosSdkTarget.cs:80
  at
  MonoTouch.Design.Client.IPhoneDesignerSession+c__async12.MoveNext
  () [0x00189] in
  /Users/builder/data/lanes/4010/3a28108f/source/md-addins/Xamarin.Designer.iOS/MonoTouch.Design.Client/IPhoneDesignerSession.cs:2015
  --- End of inner exception stack trace ---

Error in ScreenShot :

Xamarin Version :

XCode Version :

Is there any workaround to solve it.

答:
Prashant C is correct. Updating to the latest version fixes it.

In addition when using Visual Studio 2017 on Windows I had the same issue.
Upgrading Xamarin (stable channel on mac & windows) and updating Visual Studio 2017 to the latest version (15.0.26228.12) fixed it for me.

see: https://releases.xamarin.com/technical-bulletin-xcode-8-3-support-for-vs-2017/


问:
Keep CSS background properties when setting an inline background-image
I'm trying to figure out why when setting an inline background-image all other background properties are not working.

External CSS:

```<code>background: linear-gradient(rgba(0,0,0,.8), rgba(0,0,0,.8)), url("http://lorempixel.com/1400/900/");
</code>```

Result:

But when an inline background-image is added the gradient property seems to be ignored.

Inline CSS

```<code><div class="intro-img" style="background-image: url('http://lorempixel.com/1400/900/')">
</code>```

Result:

答:
you're actually overriding your background property with your

```<code>background-image: url('XXX')
</code>```

You could fix it by also adding your gradient to your inline style

Another solution would be using another element / pseudo element to handle your gradient

#test, #test2 {
  width: 600px;
  height: 400px;
}

.is-overlayed {
position: relative
}
.is-overlayed::after {
  content: '';
  background: linear-gradient(rgba(0,0,0,.6), rgba(0,0,0,.6));
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.text {
  color: #fff;

}
.above-overlay {
  z-index: 1;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test" class='is-overlayed' style='background-image:url("http://lorempixel.com/1400/900/")'>
<p class='text above-overlay'>ABOVE OVERLAY</p>
<p class='text under-overlay'>UNDER OVERLAY</p>
</div></code>```

Body:
I'm trying to figure out why when setting an inline background-image all other background properties are not working.

External CSS:

background: linear-gradient(rgba(0,0,0,.8), rgba(0,0,0,.8)), url("http://lorempixel.com/1400/900/");

Result:

But when an inline background-image is added the gradient property seems to be ignored.

Inline CSS

Result:

Body:
you're actually overriding your background property with your

background-image: url('XXX')

You could fix it by also adding your gradient to your inline style

Another solution would be using another element / pseudo element to handle your gradient

#test, #test2 {
  width: 600px;
  height: 400px;
}

.is-overlayed {
position: relative
}
.is-overlayed::after {
  content: '';
  background: linear-gradient(rgba(0,0,0,.6), rgba(0,0,0,.6));
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.text {
  color: #fff;

}
.above-overlay {
  z-index: 1;
  position: relative;
}

<div id="test" class='is-overlayed' style='background-image:url("http://lorempixel.com/1400/900/")'>
<p class='text above-overlay'>ABOVE OVERLAY</p>
<p class='text under-overlay'>UNDER OVERLAY</p>
</div>


问:
Get a HTML5 video to play once on page load and then fade out
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

```<code><!DOCTYPE html>
<html>
<head>
<script src="jquery-3.2.0.min.js"></script>
<script>
$(document).ready(function(){
$("#video").one("load", function(){
$('#video').get(0).play()
});

</script>

</head>
<body>

<h2>This is a website</h2>

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>
</body>
</html>
</code>```

答:
You can use html "autoplay" property to play video once page loaded as here.

```<code><div id="video">
<video width="100%" height="auto" autoplay="autoplay">
  <source src="monarch.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  <source src="monarch.ogv" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
</code>```

then use jquery to to fade out the vedio after play as below,

```<code>$('#video video').bind('ended', function(){
   $(this).parent().fadeOut()
});
</code>```

Created a fiddle for you here: https://jsfiddle.net/Safoora/ddukpcbd/1/
Hope it will help.

Body:
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

<!DOCTYPE html>

This is a website

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>

Body:
You can use html "autoplay" property to play video once page loaded as here.

<div id="video">
<video width="100%" height="auto" autoplay="autoplay">
  <source src="monarch.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  <source src="monarch.ogv" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>

then use jquery to to fade out the vedio after play as below,

$('#video video').bind('ended', function(){
   $(this).parent().fadeOut()
});

Created a fiddle for you here: https://jsfiddle.net/Safoora/ddukpcbd/1/
Hope it will help.


问:
Scala: map just first element in tuple
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

```<code>def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)
</code>```

Though, it doesn't feel native, what I want is to write it this way:

```<code>(1, 2).mapFirst(_ * 5)
</code>```

I wrote implicit conversion then:

```<code>class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)
</code>```

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

答:
We are able to use _1 as tuple's field. One more solution, just using standard library:</p>

```<code>val x = (1, 2, 3)
val y = x.copy(_1 = x._1 * 5)
</code>```

Title: Scala: map just first element in tuple

Body:
I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.

This is naive version for Tuple2:

def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
     |   case (x, y) => f(x) -> y
     | }

mapFirst((1, 2))(_ * 5) // returns (5, 2)

Though, it doesn't feel native, what I want is to write it this way:

(1, 2).mapFirst(_ * 5)

I wrote implicit conversion then:

class RichTuple[T, U](tuple: (T, U)) {
  def mapFirst[R](f: T => R): (R, U) = tuple match {
    case (x, y) => f(x) -> y
  }
}

implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)

(1, 2).mapFirst(_ * 5)

Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?

Body:
We are able to use _1 as tuple's field. One more solution, just using standard library:

val x = (1, 2, 3)
val y = x.copy(_1 = x._1 * 5)


问:
How do I subtract the max element of each row of a 2D tensor from all elements of that row
Originally, I asked this with the global max, but the solution of just subtracting tf.reduce_max() doesn't work when you put in dimensions. I'd want something like

mytensor - tf.reduce_max(mytensor, 1)

but this gives a dimension error.

I can't use
tf.constant(value = tf.reduce_max(mytensor,1) , shape = mytensor.get_shape()[1])
with a specified value because the output of reduce_max() is a tensor and not a constant.

答:
For global max, you can do:

```<code>import tensorflow as tf
inp = tf.constant([[1, 2, 3],[4,5,6]
    ])
res=tf.reduce_max(inp)
res1=inp-res
sess = tf.Session()
print(sess.run(res))
print(sess.run(res1))
</code>```

Then res is 6 and res1 is

```<code>[[-5 -4 -3]
 [-2 -1  0]]
</code>```

If you want to subtract the maximum element in each row, this will do the job:

```<code>import tensorflow as tf
inp = tf.constant([[1, 2, 3],[6,6,6]
    ])
res=tf.reduce_max(inp,1)
res1=inp-tf.reshape(res,[-1,1])
sess = tf.Session()
print(sess.run(res1))
</code>```

Then res1 is

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

Body:
For global max, you can do:

import tensorflow as tf
inp = tf.constant([[1, 2, 3],[4,5,6]
    ])
res=tf.reduce_max(inp)
res1=inp-res
sess = tf.Session()
print(sess.run(res))
print(sess.run(res1))

Then res is 6 and res1 is

[[-5 -4 -3]
 [-2 -1  0]]

If you want to subtract the maximum element in each row, this will do the job:

import tensorflow as tf
inp = tf.constant([[1, 2, 3],[6,6,6]
    ])
res=tf.reduce_max(inp,1)
res1=inp-tf.reshape(res,[-1,1])
sess = tf.Session()
print(sess.run(res1))

Then res1 is

 [[-2 -1  0]
 [ 0  0  0]]


问:
Libgdx - About 2 player game. I want each player can touch his own area with one finger
I am creating 2 players game where each player has his own area. I want each player can touch his own area with one finger. So first I limit to "2 pointers" in the "touchdown" function.

```<code>public boolean touchDown(int screenX, int screenY, int pointer, int button){
    if(pointer > 1){
        return false;
    }
    Gdx.app.log("", "pointer: "+pointer);

    return false;
}
</code>```

But the problem is if one player touch his own area with his 2 fingers another player won't be able to touch his own area. How can I resolve this problem ? Thank you.

答:
You cannot. Simple assume the players play fair and only touch their own areas. Handle the clicks based on which area they hit and then assign the action to the corresponding player number.

If you need pointer index within an area, just assign the pointer number based on the area to player 1 or 2. Delete the assignment when the pointer is touched up. So you always now which pointer numbers is assigned to which player at the current moment.

Assuming pointer 0 is player 1 and pointer 1 is player 2 just does not work.

Body:
I am creating 2 players game where each player has his own area. I want each player can touch his own area with one finger. So first I limit to "2 pointers" in the "touchdown" function.

public boolean touchDown(int screenX, int screenY, int pointer, int button){
    if(pointer > 1){
        return false;
    }
    Gdx.app.log("", "pointer: "+pointer);

    return false;
}

But the problem is if one player touch his own area with his 2 fingers another player won't be able to touch his own area. How can I resolve this problem ? Thank you.


问:
add comma after thousand amount in javascript
I am using slide input with following javascript,

```<code><script type="text/javascript">
    jQuery(document).ready(function(e){
        var val1 = 0;
        var val2 = 0;
        $("#ex1").slider();
        $("#ex1").on("slide", function(slideEvt1) {
            //$("#ex1SliderVal").text((Number(slideEvt1.value) * 2.90) + (Number(val2) * 0.30));
            val1 = Number(slideEvt1.value);

            $("#ex1SliderVal").text((Number(val1) * 0.0290) + (Number(val2) * 0.30));

            $("#ex2SliderVal").text((Number(val1) * 0.0199) + (Number(val2) * 0.15));

            $("#ex3SliderVal").text((Number(val1) * 0.0225) + (Number(val2) * 0.10));

            $("#showex1").text(Number(val1));
            //console.log(val1)
        });
});
</script>

<div class="col-xs-12">
                <input id="ex1" type="text" data-slider-min="0000" data-slider-max="8000" data-slider-step="1" data-slider-value="0"/>
                <span><span style="margin-left: 30px; font-size:14px;"id="showex1">0</span></span>
            </div>
</code>```

This is working properly. Only thing I want to add a comma after thousands.
like 2,000 80,000 170,000

Please help me add this.
Thank you+

答:
You can use Intl.NumberFormat

For example:

var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
});

$("button").on("click", function() {
  $("span").text(formatter.format(80000))
  //If you do not want to see the currenycy symbol
  // $("span").text(formatter.format(80000).substr(1))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Calculate</button>

<span></span></code>```

Body:
I am using slide input with following javascript,

                <input id="ex1" type="text" data-slider-min="0000" data-slider-max="8000" data-slider-step="1" data-slider-value="0"/>
                0

This is working properly. Only thing I want to add a comma after thousands.
like 2,000 80,000 170,000

Please help me add this.
Thank you+

Body:
You can use Intl.NumberFormat

For example:

var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
});

$("button").on("click", function() {
  $("span").text(formatter.format(80000))
  //If you do not want to see the currenycy symbol
  // $("span").text(formatter.format(80000).substr(1))
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Calculate</button>

<span></span>