问:
Global variable appears to lose value (swift)
This is my code to extract data from firebase.

listofnames(double dimensional) and  names(single dimensional) are global arrays of type String.

However, when I print listofnames an empty array is displayed in the output window whereas, if I comment the first line (self.listofnames = [[]]) the code functions properly.

I have linked ref with Firebase database

Please help.

```<code>var databasehandle:FIRDatabaseHandle?

let time = ["8AM - 9AM", "9AM - 10AM","10AM - 11AM", "11AM -12PM", "12PM - 1PM","1PM - 1:30PM","2PM - 3PM","3PM - 4PM","4PM - 5PM","5PM - 6PM","6PM - 7PM","7PM - 7:30PM"]

var ref:FIRDatabaseReference!
var day: String = "Monday"
var users :String = "First years"

func loaddata()
{
    self.listofnames = [[]]
    for x in 0...((time.count)-1)
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
            if let namesfromFirebase = snapshot.value as? [String:Any]
            {
                let y = namesfromFirebase.count
                for i in 1...y
                {
                    self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                }
            }
            self.listofnames.append(self.names)
            self.names = []
        })
    }
    print(self.listofnames)
    self.tableView.reloadData()
}
</code>```

答:
observeSingleEvent works asynchronously, the closure is called later.

There is an easy solution: Move the two lines into the closure:

```<code>func loaddata()
{
    self.listofnames = [[]]
    for x in 0..<time.count // no parentheses and math needed when using `..<`
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
                if let namesfromFirebase = snapshot.value as? [String:Any]
                {
                    let y = namesfromFirebase.count
                    for i in 1...y
                    {
                        self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                    }
                }
                self.listofnames.append(self.names)
                self.names = []
                print(self.listofnames)
                self.tableView.reloadData()
        })
    }
}
</code>```

Body:
This is my code to extract data from firebase.

listofnames(double dimensional) and  names(single dimensional) are global arrays of type String.

However, when I print listofnames an empty array is displayed in the output window whereas, if I comment the first line (self.listofnames = [[]]) the code functions properly.

I have linked ref with Firebase database

Please help.

var databasehandle:FIRDatabaseHandle?

let time = ["8AM - 9AM", "9AM - 10AM","10AM - 11AM", "11AM -12PM", "12PM - 1PM","1PM - 1:30PM","2PM - 3PM","3PM - 4PM","4PM - 5PM","5PM - 6PM","6PM - 7PM","7PM - 7:30PM"]

var ref:FIRDatabaseReference!
var day: String = "Monday"
var users :String = "First years"

func loaddata()
{
    self.listofnames = [[]]
    for x in 0...((time.count)-1)
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
            if let namesfromFirebase = snapshot.value as? [String:Any]
            {
                let y = namesfromFirebase.count
                for i in 1...y
                {
                    self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                }
            }
            self.listofnames.append(self.names)
            self.names = []
        })
    }
    print(self.listofnames)
    self.tableView.reloadData()
}

Body:
observeSingleEvent works asynchronously, the closure is called later.

There is an easy solution: Move the two lines into the closure:

func loaddata()
{
    self.listofnames = [[]]
    for x in 0..<time.count // no parentheses and math needed when using `..<`
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
                if let namesfromFirebase = snapshot.value as? [String:Any]
                {
                    let y = namesfromFirebase.count
                    for i in 1...y
                    {
                        self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                    }
                }
                self.listofnames.append(self.names)
                self.names = []
                print(self.listofnames)
                self.tableView.reloadData()
        })
    }
}


来源: stackexchange

问:
Drag and drop app icon into my widget - Android
I am curious if it's possible to make an Android home screen widget that can have app icons dropped on it? For example, say my widget is a 2x2(spaces) box on the home screen. Then a user drags and drops the app icon shortcut from another app onto my widget. Would it be possible to then recognize the dropped app icons package name or other related info?

I have researched this on my own and cannot find any way of doing this.

Thanks!

答: It's not even possible. Widget API that provides Android doesn't allow that. Just to be clear where is only few opportunities that allow RemoteViews and Widget to do. So your usecase impossible to do.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I get a total count of an int field in a List?
I have this class, variable and method used to populate it:

```<code>public class CategoryGroupWordCountVM : ObservableProperty
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
    public int TotalWordCount { get; set; }
}

List<CategoryGroupWordCountVM> categoryGroups;

categoryGroups = AS.dm.GetCategoryGroupWithWordCount();
</code>```

How can I get a total of all of the values of the TotalWordCount field using LINQ or any other method if it can be done as a one liner. I know I can do this with a "for" loop but hoping for something that could be all in one line.

答:
Use Linq,

```<code>var sum = categoryGroups.Sum(x=>x.TotalWordCount);
</code>```

Body:
I have this class, variable and method used to populate it:

public class CategoryGroupWordCountVM : ObservableProperty
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
    public int TotalWordCount { get; set; }
}

List<CategoryGroupWordCountVM> categoryGroups;

categoryGroups = AS.dm.GetCategoryGroupWithWordCount();

How can I get a total of all of the values of the TotalWordCount field using LINQ or any other method if it can be done as a one liner. I know I can do this with a "for" loop but hoping for something that could be all in one line.

Body:
Use Linq,

var sum = categoryGroups.Sum(x=>x.TotalWordCount);


问:
VestaCP: open_basedir restriction while using app/autoload.php
I deploy Symfony3 project on server (Ubuntu 16.04, PHP 7.0.18).
I use VestaCP, create symlinl public_shtml -> www/web and place project in www directory.

I execute following commands:

git clone

composer install

setfacl (from official Symfony documentation)

In error log I see that messages:

PHP Warning:  require(): open_basedir restriction in effect. File(/home/admin/web/project/www/app/autoload.php) is not within the allowed path(s): (/home/admin/web/project/public_shtml:/home/admin/tmp) in /home/admin/web/project/www/web/app.php on line 6

PHP Warning:  require(/home/admin/web/project/www/app/autoload.php): failed to open stream: Operation not permitted in /home/admin/web/project/www/web/app.php on line 6

PHP Fatal error:  require(): Failed opening required '/home/admin/web/project/www/web/../app/autoload.php' (include_path='.:/usr/share/php') in /home/admin/web/project/www/web/app.php on line 6

What do I doing wrong?

答:
You need to change open_basedir parameter in config for apache (/home/admin/conf/web/apache2.conf and /home/admin/conf/web/sapache2.conf) to point to your newly created folder /home/admin/web/project/www:

```<code><Directory /home/admin/web/project/www/web>
    AllowOverride All
    Options +Includes -Indexes +ExecCGI
    php_admin_value open_basedir /home/admin/web/project/www:/home/admin/tmp
    php_admin_value upload_tmp_dir /home/admin/tmp
    php_admin_value session.save_path /home/admin/tmp
</Directory>
</code>```

VestaCP uses open_basedir restriction to make more secure default configuration.

Also if you plan to add more websites to your server I recommend you to make special apache config template for your symfony projects at path /usr/local/vesta/data/templates/web/apache2/. You can copy default templates default.tpl and default.stpl as new files symfony.tpl and symfony.stpl where you can change open_basedir, DocumentRoot and Directory parameters. If you will not do it: every time after adding/updating configurations for your user's sites VestaCP will replace your current configuration with new generated config using default template and you will need to edit it again.

Body:
You need to change open_basedir parameter in config for apache (/home/admin/conf/web/apache2.conf and /home/admin/conf/web/sapache2.conf) to point to your newly created folder /home/admin/web/project/www:

<Directory /home/admin/web/project/www/web>
    AllowOverride All
    Options +Includes -Indexes +ExecCGI
    php_admin_value open_basedir /home/admin/web/project/www:/home/admin/tmp
    php_admin_value upload_tmp_dir /home/admin/tmp
    php_admin_value session.save_path /home/admin/tmp
</Directory>

VestaCP uses open_basedir restriction to make more secure default configuration.

Also if you plan to add more websites to your server I recommend you to make special apache config template for your symfony projects at path /usr/local/vesta/data/templates/web/apache2/. You can copy default templates default.tpl and default.stpl as new files symfony.tpl and symfony.stpl where you can change open_basedir, DocumentRoot and Directory parameters. If you will not do it: every time after adding/updating configurations for your user's sites VestaCP will replace your current configuration with new generated config using default template and you will need to edit it again.


问:
Hive query on emp table which displays ename,sal of those who are working as salesman and sal>max(sal) of clerk
I am new to hive environment, I want to find those employees who are working as salesman and also whose salary grater than maximum salary of  all clerks. I can write a query in SQL but I can't write it in hive.

Here you can find emp table that exactly I used.

答:
```<code>select tempemp.ename,tempemp.sal from emp tempemp,(select max(sal) as maxsal from emp where job='clerk') tempmax where  tempemp.sal > tempmax.maxsal and tempemp.job = 'salesman';
</code>```

The above would give you names and salary of those employees who are salesman and have their salary more than max salary of all clerks.

Tested on Hive

Body:
select tempemp.ename,tempemp.sal from emp tempemp,(select max(sal) as maxsal from emp where job='clerk') tempmax where  tempemp.sal > tempmax.maxsal and tempemp.job = 'salesman';

The above would give you names and salary of those employees who are salesman and have their salary more than max salary of all clerks.

Tested on Hive


问:
How to find documents in database using query string
I am trying to find documents in my database using a query string:

```<code>app.get('/', (request, response) => {
  db.collection('mycollection').find(req.query).toArray((error, results) => {
    console.log(response)
  })
})
</code>```

The request looks like this:

```<code>{ userName: 'K Moe' }
</code>```

And the error I get is:

```<code>MongoError: query selector must be an object
</code>```

I've tried changing req.query to req.query.userName and req.query['userName'] but that doesn't help...

答:
Try changing
req.query from { userName: 'K Moe' } to { 'userName': 'k Moe' }

Body:
I am trying to find documents in my database using a query string:

app.get('/', (request, response) => {
  db.collection('mycollection').find(req.query).toArray((error, results) => {
    console.log(response)
  })
})

The request looks like this:

{ userName: 'K Moe' }

And the error I get is:

MongoError: query selector must be an object

I've tried changing req.query to req.query.userName and req.query['userName'] but that doesn't help...


问:
multi threaded servlet; single threaded ejb
In a traditional n tier web app with servlets for web layer and ejbs(2.0) for biz layer, what is the rationale behind making the servlet model multi threaded and the ejb model single threaded?

 i.e there is only 1 servlet instance for all requests, but for ejbs, for each request, there is a new bean instance assigned from the bean pool.

答:
I think that typically servlets present thin facade to the heavy logic implemented in EJBs. Servlets should be stateless and therefore there is no reason to create more than one instance of the same servlet.

If you are using stateless beans only I think that there is no reason to have more than one instance too. But statefull EJBs have state and therefore you need instance per simultaneous request.

I hope I did not say bullshit.

ContentLicense: CC BY-SA 2.5


问:
How to interpolate variables in strings in JavaScript, without concatenation?
I know in PHP we can do something like this:

```<code>$hello = "foo";
$my_string = "I pity the $hello";
</code>```

Output: "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

答:
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

```<code>var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
</code>```

which will replace the {0} and {1} with the array items and return the following string

```<code>"this is a test string for stringInject"
</code>```

or you could replace placeholders with object keys and values like so:

```<code>var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github"
</code>```

Body:
I know in PHP we can do something like this:

$hello = "foo";
$my_string = "I pity the $hello";

Output: "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

Body:
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

which will replace the {0} and {1} with the array items and return the following string

"this is a test string for stringInject"

or you could replace placeholders with object keys and values like so:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github"


问:
C++11 stateful allocators with std::basic_string<> g++ 6.3.0
I'm trying to get C++11 allocators working with std::basic_string<>.  My code looks something like this (this is a minimal example).  The problem I'm having is that it works on Xcode, and something similar works on Visual Studio, but I can't get it to compile on g++.  I'm using g++ 6.3.0 and I've tried with -D_GLIBCXX_USE_CXX11_ABI=1 and -D_GLIBCXX_USE_CXX11_ABI=0

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

template <class TYPE> class my_allocator
    {
    public:
        int instance;

    public:
        using value_type = TYPE;

        my_allocator(int val) : instance(val) { }
        my_allocator(const my_allocator<TYPE> &other) : instance(other.instance) { }

        bool operator==(const my_allocator<TYPE> &that) const { return instance == that.instance; }
        bool operator!=(const my_allocator<TYPE> &that) const { return instance != that.instance; }

        TYPE *allocate(const size_t number)
            {
            if (number == 0)
                return nullptr;

            if (number > (size_t)-1 / sizeof(TYPE))
                throw std::bad_array_new_length();

            TYPE *pointer = (TYPE *)::malloc(number * sizeof(TYPE));

            if (pointer == nullptr)
                throw std::bad_alloc();

            return pointer;
            }

        void deallocate(TYPE * const pointer, size_t number) const { free(pointer); }
    };

typedef std::basic_string<char, std::char_traits<char>, my_allocator<char>>my_string;

int main(void)
    {
    my_allocator<char> allocator(1);

    my_string str(allocator);
    str = "one";
    std::cout << str;

    return 0;
    }
</code>```

What I don't understand is that the error starts:

```<code>In file included from /usr/include/c++/6/string:52:0,
                 from /usr/include/c++/6/bits/locale_classes.h:40,
                 from /usr/include/c++/6/bits/ios_base.h:41,
                 from /usr/include/c++/6/ios:42,
                 from /usr/include/c++/6/ostream:38,
                 from /usr/include/c++/6/iostream:39,
                 from broken.cpp:6:
/usr/include/c++/6/bits/basic_string.h: In instantiation of ‘class std::basic_string<char, std::char_traits<char>, my_allocator<char> >’:
broken.cpp:49:25:   required from here
/usr/include/c++/6/bits/basic_string.h:2616:63: error: no class template named ‘rebind’ in ‘class my_allocator<char>’
       typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type;
                                                               ^~~~~~~~~~~~~~~~~
</code>```

Which states that basic_string.h line 2616 is being compiled - but how can that be if compiled with the flag -D_GLIBCXX_USE_CXX11_ABI=1 when one of the first lines of basic_string.h checks _GLIBCXX_USE_CXX11_ABI and does not include line 2616 in the build phase if its true?

I build with a shell script:

```<code>g++-6 -std=c++11 -Wall -D_GLIBCXX_USE_CXX11_ABI=1 broken.cpp -o broken
</code>```

The version of Ubuntu I'm using is:

```<code>Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty
</code>```

[EDIT: Everything below this line]

g++-6 -v gives:

```<code>Using built-in specs.
COLLECT_GCC=g++-6
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 6.3.0-18ubuntu2~14.04' --with-bugurl=file:///usr/share/doc/gcc-6/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-6 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=gcc4-compatible --disable-libstdcxx-dual-abi --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-6-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-6-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-6-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 6.3.0 20170519 (Ubuntu/Linaro 6.3.0-18ubuntu2~14.04)
</code>```

This is a fresh install of Ubuntu with only cmake, g++6 and git installed using sudo add-apt-repository ppa:ubuntu-toolchain-r/test and apt-get.  I get the same problem on Travis CI which is why'm trying to do it locally on a fresh Ubuntu install.

Any help is appreciated.

答:
There are several things an allocator has to implement to be usable in all contexts of the STL:

What you already have:

value_type to specify what kind of objects are allocated

allocate and deallocate

== and != to check if storage allocated through one allocator can be deallocated through the other.

Copy-constructor

What was implicitly generated:

copy-assignment operator

Move constructor, move-assignment operator

What is missing:

The rebind constructor: something like

```<code>template<typename OTHER_TYPE>
my_allocator(const my_allocator<OTHER_TYPE> &other) ...
</code>```

to allow the STL to use custom node types to store your elements, while you only provided an allocator for the element type, e.g. in a set or similar data structures

the rebind struct itself is optional if a rebind constructor is provided and your template arguments are sufficiently 'simple' (see the Allocator concept and std::allocator_traits)

Body:
I'm trying to get C++11 allocators working with std::basic_string<>.  My code looks something like this (this is a minimal example).  The problem I'm having is that it works on Xcode, and something similar works on Visual Studio, but I can't get it to compile on g++.  I'm using g++ 6.3.0 and I've tried with -D_GLIBCXX_USE_CXX11_ABI=1 and -D_GLIBCXX_USE_CXX11_ABI=0

#include <stdio.h>
#include <iostream>
#include <string>

template <class TYPE> class my_allocator
    {
    public:
        int instance;

    public:
        using value_type = TYPE;

        my_allocator(int val) : instance(val) { }
        my_allocator(const my_allocator<TYPE> &other) : instance(other.instance) { }

        bool operator==(const my_allocator<TYPE> &that) const { return instance == that.instance; }
        bool operator!=(const my_allocator<TYPE> &that) const { return instance != that.instance; }

        TYPE *allocate(const size_t number)
            {
            if (number == 0)
                return nullptr;

            if (number > (size_t)-1 / sizeof(TYPE))
                throw std::bad_array_new_length();

            TYPE *pointer = (TYPE *)::malloc(number * sizeof(TYPE));

            if (pointer == nullptr)
                throw std::bad_alloc();

            return pointer;
            }

        void deallocate(TYPE * const pointer, size_t number) const { free(pointer); }
    };

typedef std::basic_string<char, std::char_traits<char>, my_allocator<char>>my_string;

int main(void)
    {
    my_allocator<char> allocator(1);

    my_string str(allocator);
    str = "one";
    std::cout << str;

    return 0;
    }

What I don't understand is that the error starts:

In file included from /usr/include/c++/6/string:52:0,
                 from /usr/include/c++/6/bits/locale_classes.h:40,
                 from /usr/include/c++/6/bits/ios_base.h:41,
                 from /usr/include/c++/6/ios:42,
                 from /usr/include/c++/6/ostream:38,
                 from /usr/include/c++/6/iostream:39,
                 from broken.cpp:6:
/usr/include/c++/6/bits/basic_string.h: In instantiation of ‘class std::basic_string<char, std::char_traits<char>, my_allocator<char> >’:
broken.cpp:49:25:   required from here
/usr/include/c++/6/bits/basic_string.h:2616:63: error: no class template named ‘rebind’ in ‘class my_allocator<char>’
       typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type;
                                                               ^~~~~~~~~~~~~~~~~

Which states that basic_string.h line 2616 is being compiled - but how can that be if compiled with the flag -D_GLIBCXX_USE_CXX11_ABI=1 when one of the first lines of basic_string.h checks _GLIBCXX_USE_CXX11_ABI and does not include line 2616 in the build phase if its true?

I build with a shell script:

g++-6 -std=c++11 -Wall -D_GLIBCXX_USE_CXX11_ABI=1 broken.cpp -o broken

The version of Ubuntu I'm using is:

Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

[EDIT: Everything below this line]

g++-6 -v gives:

Using built-in specs.
COLLECT_GCC=g++-6
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 6.3.0-18ubuntu2~14.04' --with-bugurl=file:///usr/share/doc/gcc-6/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-6 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=gcc4-compatible --disable-libstdcxx-dual-abi --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-6-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-6-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-6-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 6.3.0 20170519 (Ubuntu/Linaro 6.3.0-18ubuntu2~14.04)

This is a fresh install of Ubuntu with only cmake, g++6 and git installed using sudo add-apt-repository ppa:ubuntu-toolchain-r/test and apt-get.  I get the same problem on Travis CI which is why'm trying to do it locally on a fresh Ubuntu install.

Any help is appreciated.

Body:
There are several things an allocator has to implement to be usable in all contexts of the STL:

What you already have:

value_type to specify what kind of objects are allocated

allocate and deallocate

== and != to check if storage allocated through one allocator can be deallocated through the other.

Copy-constructor

What was implicitly generated:

copy-assignment operator

Move constructor, move-assignment operator

What is missing:

The rebind constructor: something like

template<typename OTHER_TYPE>
my_allocator(const my_allocator<OTHER_TYPE> &other) ...

to allow the STL to use custom node types to store your elements, while you only provided an allocator for the element type, e.g. in a set or similar data structures

the rebind struct itself is optional if a rebind constructor is provided and your template arguments are sufficiently 'simple' (see the Allocator concept and std::allocator_traits)


问:
Javascript ajax return wrong value

Issue : if i call ajax function i can't able to get return value.

Below is my simple javascript and ajax file.

Javascript Ajax

```<code><script type="text/javascript">
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                return this.responseText;
            }
        };
        xhttp.open("GET", "testAjax.php", true);
        xhttp.send();
    }
    alert(loadDoc());
</script>
</code>```

PHP

```<code><?php
    echo "Hello World !!!";
?>
</code>```

Can synchronous or asynchronous concept are useful to this problem ?

Thank you.

答:
You need to change your logic like this:

```<code>function doJobWhenAjaxResultIsReturned(ajaxData){
    // alrt(ajaxData);
}
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      doJobWhenAjaxResultIsReturned(this.responseText);
    }
  };
  xhttp.open("GET", "testAjax.php", true);
  xhttp.send();
}
loadDoc();
</code>```

then do what you want in doJobWhenAjaxResultIsReturned().

Title: Javascript ajax return wrong value

Body:
Issue : if i call ajax function i can't able to get return value.

Below is my simple javascript and ajax file.

Javascript Ajax

PHP

<?php
    echo "Hello World !!!";
?>

Can synchronous or asynchronous concept are useful to this problem ?

Thank you.

Body:
You need to change your logic like this:

function doJobWhenAjaxResultIsReturned(ajaxData){
    // alrt(ajaxData);
}
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      doJobWhenAjaxResultIsReturned(this.responseText);
    }
  };
  xhttp.open("GET", "testAjax.php", true);
  xhttp.send();
}
loadDoc();

then do what you want in doJobWhenAjaxResultIsReturned().


问:
Angular 4 PipeTransform not applied
My custom pipe to shorten a string isn't working. I have included it in my app.module declarations and imported it in my component. The code is below.

 import { Pipe, PipeTransform } from '@angular/core';
/*
  Takes a string and replaces it with a shortend version based on the length you give it if its greater than 14 char for Example
  someString = "hey whats up my name is Bob and im from Bob town"
  {{value | shortString : length of new string}}
  {{someString | shortString: 10}}
*/
@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    console.log('expected new string '+value.slice(0,length)+'...');
    return (value.length()>14)?value.slice(0,length)+'...': value;
  }
}`
```

答:
First in your Pipe

@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    return (value.length()>14)?value.slice(0,length)+'...': value; // remove the length() it will be value.length
  }
}
```

Working plunker of the same

https://plnkr.co/edit/Xz528J1sCi7GlDeWELph?p=preview

ContentLicense: CC BY-SA 4.0

Title: Angular 4 PipeTransform not applied

Body:
First in your Pipe

@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    return (value.length()>14)?value.slice(0,length)+'...': value; // remove the length() it will be value.length
  }
}

Working plunker of the same

https://plnkr.co/edit/Xz528J1sCi7GlDeWELph?p=preview


答:
The problem is the asynchronous nature of ajax requests and the execution flow of code. The callback that is invoked when the conditions of onreadystatechange are met is not guaranteed to complete before the end of the main function has been reached. To achieve a return from the ajax function you need to use Promises

```<code>let oPromise = new Promise( ( resolve, reject ) => {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resolve( this.response );
        }
    };
    xhttp.open('GET', 'testAjax.php', true);
    xhttp.send();
});

oPromise.then( ( data ) => {
  alert('Whoohoo! -> ' + data );
});
</code>```

To some  the syntax of the above will be unfamiliar and perhaps a little confusing - it could be rewritten in a more familar/tradional way like this:

```<code>let oPromise = new Promise( function( resolve,reject ){
    var xhr = new XMLHttpRequest();
    xhr.onload=function(){
        resolve( this.response )
    };
    xhr.onerror=function(){
        reject( this.readyState )
    };
    xhr.open('GET', 'testAjax.php', true);
    xhr.send();
});
oPromise.then( function( response ){
     alert('Whoohoo! -> ' + response );
});
</code>```

Title: Javascript ajax return wrong value

Body:
The problem is the asynchronous nature of ajax requests and the execution flow of code. The callback that is invoked when the conditions of onreadystatechange are met is not guaranteed to complete before the end of the main function has been reached. To achieve a return from the ajax function you need to use Promises

let oPromise = new Promise( ( resolve, reject ) => {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resolve( this.response );
        }
    };
    xhttp.open('GET', 'testAjax.php', true);
    xhttp.send();
});

oPromise.then( ( data ) => {
  alert('Whoohoo! -> ' + data );
});

To some  the syntax of the above will be unfamiliar and perhaps a little confusing - it could be rewritten in a more familar/tradional way like this:

let oPromise = new Promise( function( resolve,reject ){
    var xhr = new XMLHttpRequest();
    xhr.onload=function(){
        resolve( this.response )
    };
    xhr.onerror=function(){
        reject( this.readyState )
    };
    xhr.open('GET', 'testAjax.php', true);
    xhr.send();
});
oPromise.then( function( response ){
     alert('Whoohoo! -> ' + response );
});


问:
Last seen a user in django
How can i show the time of last seen(be online)of user in django?
Is there any default function or library to import it to do that?

Or if there any code inn github tell me please

**Note : ** when a user close page or disconnect the time update

答:
There is few options.

you can add a code to your views to check for user or session id (depends on how do you want it to work. for registered users or every users or ... ) and every time a user request for a page, you can update that this user has been active on the site on this time.
but this option seem to be usable when you need to track a user in a small project with few pages.

another option which seem more right to do is to use middleware. by using middleware you don't need to change your code in all of your views. simply make a custom middleware and everything will be done with few lines of code

you can check an example of this middleware here:

Django: How can I check the last activity time of user if user didn't log out?

or

Django get last user visit date

and for disconnected part i think you can't do much with django. and also you can't be sure when user closed the page.

the best option here is to use a javascript code to run like every 10 sec and tell django that the user is still on the page.

Title: Last seen a user in django


问:
Modal Window with MVVM pattern
I am trying to make modal dialog window for let user know some error messages, or let user edit some values.
I am using MVVM pattern, so my mainwindow has some control part and workspace part. In workspace part, i am opening viewmodels tight with datatemplate to views (defined as usercontrols). From one of these views i want to open modal dialog window. I was following this answer Error window show modal in MVVM WPF. As described in that answer, i have implemented the DialogClass in an InvoiceViewModel. But i have problem with showing the content of the modal window. If I set the content of the window to ViewModel class, output is simple text with namespace path to that ViewModel. (ViewModel attached to the View with datatemplate.) If I set content to the View - it is working - view is showed but, i am disobeing MVVM pattern (opening View from ViewModel as ViewModel has no reference to View).

```<code>        ErrorViewModel newErrorViewModel = new ErrorViewModel();
        ErrorView newErrorView = new ErrorView();
        DialogWindow dialogWindow = new DialogWindow();
        //Not Working
        //dialogWindow.Content = newErrorViewModel;

        //Working But, breaking MVVM
        dialogWindow.Content = newErrorView;
        dialogWindow.ShowDialog();
</code>```

In ErrorView.xaml i have attached ErrorViewModel like this.

```<code><DataTemplate DataType="{x:Type vm:ErrorViewModel}">
    <vw:ErrorView/>
</DataTemplate>
</code>```

What am i doing wrong?

Thanks.

答:
Got it.

I have placed code for wiring up model and view in ErrorView.xaml. This is my mistake of course. I have replaced these lines into app.xaml resource and it is working lika a charm.

Title: Modal Window with MVVM pattern

Body:
I am trying to make modal dialog window for let user know some error messages, or let user edit some values.
I am using MVVM pattern, so my mainwindow has some control part and workspace part. In workspace part, i am opening viewmodels tight with datatemplate to views (defined as usercontrols). From one of these views i want to open modal dialog window. I was following this answer Error window show modal in MVVM WPF. As described in that answer, i have implemented the DialogClass in an InvoiceViewModel. But i have problem with showing the content of the modal window. If I set the content of the window to ViewModel class, output is simple text with namespace path to that ViewModel. (ViewModel attached to the View with datatemplate.) If I set content to the View - it is working - view is showed but, i am disobeing MVVM pattern (opening View from ViewModel as ViewModel has no reference to View).

        ErrorViewModel newErrorViewModel = new ErrorViewModel();
        ErrorView newErrorView = new ErrorView();
        DialogWindow dialogWindow = new DialogWindow();
        //Not Working
        //dialogWindow.Content = newErrorViewModel;

        //Working But, breaking MVVM
        dialogWindow.Content = newErrorView;
        dialogWindow.ShowDialog();

In ErrorView.xaml i have attached ErrorViewModel like this.

<DataTemplate DataType="{x:Type vm:ErrorViewModel}">
    <vw:ErrorView/>
</DataTemplate>

What am i doing wrong?

Thanks.


问:
Rails - How to load nested attributes by condition while loading parent?
I have two models namely Invoice and InvoiceDetails. An invoice has many invoiceDetails.

Now when I load an invoice, it also loads up the invoiceDetails attributes by association. The invoiceDetails model has an attribute is_hide, I want to load these nested attributes where is_hide = 0, while loading an invoice.

The Invoice Controller:

```<code>class Api::V1::InvoicesController < ApplicationController
  respond_to :json

  def index
    company_id = params[:company_id]
    if company_id
      invoices = Invoice.where(company_id: company_id)
      render json: invoices, status: 200
    else
      render json: { errors: "Company ID is NULL" }, status: 422
    end
  end

  def show
    cust_id = params[:customer_id]
    invoice_id = params[:id]
    if cust_id && invoice_id
      invoice = Invoice.where(:id => invoice_id, :customer_id => cust_id)
      render json: invoice, include: '**', status: 200
    else
      render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
    end
  end

  def create
    Rails.logger.debug invoice_params.inspect
    invoice = Invoice.new(invoice_params)
    if invoice.save
      render json: invoice, status: 201
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end
end
</code>```

This is how I load an invoice :

```<code>getInvoice : {
        url:'/api/v1/companies/:company_id/customers/:customer_id/invoices/:id',
        method: 'GET',
        isArray: true
      }
</code>```

How can this be done in Rails 5?

答:
Assuming it is the show action that you are hitting, you can add a where clause like

```<code>def show
  cust_id = params[:customer_id]
  invoice_id = params[:id]
  if cust_id && invoice_id
    invoice = Invoice.includes(:invoice_details).where(:id => invoice_id, :customer_id => cust_id, 'invoice_details.is_hide' => 0)
    render json: invoice, include: '**', status: 200
  else
    render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
  end
end
</code>```

Body:
I have two models namely Invoice and InvoiceDetails. An invoice has many invoiceDetails.

Now when I load an invoice, it also loads up the invoiceDetails attributes by association. The invoiceDetails model has an attribute is_hide, I want to load these nested attributes where is_hide = 0, while loading an invoice.

The Invoice Controller:

class Api::V1::InvoicesController < ApplicationController
  respond_to :json

  def index
    company_id = params[:company_id]
    if company_id
      invoices = Invoice.where(company_id: company_id)
      render json: invoices, status: 200
    else
      render json: { errors: "Company ID is NULL" }, status: 422
    end
  end

  def show
    cust_id = params[:customer_id]
    invoice_id = params[:id]
    if cust_id && invoice_id
      invoice = Invoice.where(:id => invoice_id, :customer_id => cust_id)
      render json: invoice, include: '**', status: 200
    else
      render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
    end
  end

  def create
    Rails.logger.debug invoice_params.inspect
    invoice = Invoice.new(invoice_params)
    if invoice.save
      render json: invoice, status: 201
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end
end

This is how I load an invoice :

getInvoice : {
        url:'/api/v1/companies/:company_id/customers/:customer_id/invoices/:id',
        method: 'GET',
        isArray: true
      }

How can this be done in Rails 5?

Body:
Assuming it is the show action that you are hitting, you can add a where clause like

def show
  cust_id = params[:customer_id]
  invoice_id = params[:id]
  if cust_id && invoice_id
    invoice = Invoice.includes(:invoice_details).where(:id => invoice_id, :customer_id => cust_id, 'invoice_details.is_hide' => 0)
    render json: invoice, include: '**', status: 200
  else
    render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
  end
end


问:
Custom underline effect, other than creating a background image for it
is there a better way to create this style of "underline" through CSS, other than creating a background image for it?

To be clear, I'm only interested in the "duplicated line" effect, a thicker and shorter line sitting directly atop a thinner and longer line of a different color. Thanks!

答:
Try this

HTML

```<code><div class="text">
  <span>our</span>
  Services
</div>
</code>```

CSS

```<code>.text{
  font-weight:600;
  font-size:25px;
  color:red;
  position: relative;
  display:inline-block;
}
.text::after,
.text::before{
  content:"";
  position: absolute;
  left: 0;
  right: 0;
  bottom: -5px;
  margin:auto;
  border-radius:5px;
  height:0px;
}

.text::before{
  width:100%;
  border:1px solid #ccc;
}
.text::after{
  width:50%;
  border:2px solid red;
  bottom:-6px;
}

.text span{
  color:#000000;
}
</code>```

Link for reference

hope this helps..

Body:
Try this

HTML

<div class="text">
  <span>our</span>
  Services
</div>

CSS

.text{
  font-weight:600;
  font-size:25px;
  color:red;
  position: relative;
  display:inline-block;
}
.text::after,
.text::before{
  content:"";
  position: absolute;
  left: 0;
  right: 0;
  bottom: -5px;
  margin:auto;
  border-radius:5px;
  height:0px;
}

.text::before{
  width:100%;
  border:1px solid #ccc;
}
.text::after{
  width:50%;
  border:2px solid red;
  bottom:-6px;
}

.text span{
  color:#000000;
}

Link for reference

hope this helps..


问:
Neo4J Match & Set Multiple Relationships/Nodes in One Query
I'm currently running the following query to update the properties on two nodes and relationships.

I'd like to be able to update 1,000 nodes and the corresponding relationships in one query.

```<code>MATCH (p1:Person)-[r1:OWNS_CAR]->(c1:Car) WHERE id(r1) = 3018
MATCH (p2:Person)-[r2:OWNS_CAR]->(c2:Car) WHERE id(r2) = 3019
SET c1.serial_number = 'SERIAL027436', c1.signature = 'SIGNATURE728934',
r1.serial_number = 'SERIAL78765', r1.signature = 'SIGNATURE749532',
c2.serial_number = 'SERIAL027436', c2.signature = 'SIGNATURE728934',
r2.serial_number = 'SERIAL78765', r2.signature = 'SIGNATURE749532'
</code>```

This query has issues when you run it in larger quantities. Is there a better way?

Thank you.

答:
You could work with a LOAD CSV. Your input would contain the keys (not the ids, using the ids is not recommended) for Person and Car and whatever properties you need to set. For example

```<code>personId, carId, serial_number, signature
00001, 00045, SERIAL78765, SIGNATURE728934
00002, 00046, SERIAL78665, SIGNATURE724934
</code>```

Your query would then be something like :

```<code>USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///input.csv' AS row
MATCH (p:Person {personId: row.PersonId})-[r:OWNS_CAR]->(c:Car {carId: row.carId})
SET r.serial_number = row.serialnumber, c.signature = row.signature
</code>```

Note that you should have unique constraints on Person and Car to make that work. You can do thousands (even millions) like that very quickly ...

Hope this helps,
Tom

Body:
I'm currently running the following query to update the properties on two nodes and relationships.

I'd like to be able to update 1,000 nodes and the corresponding relationships in one query.

MATCH (p1:Person)-[r1:OWNS_CAR]->(c1:Car) WHERE id(r1) = 3018
MATCH (p2:Person)-[r2:OWNS_CAR]->(c2:Car) WHERE id(r2) = 3019
SET c1.serial_number = 'SERIAL027436', c1.signature = 'SIGNATURE728934',
r1.serial_number = 'SERIAL78765', r1.signature = 'SIGNATURE749532',
c2.serial_number = 'SERIAL027436', c2.signature = 'SIGNATURE728934',
r2.serial_number = 'SERIAL78765', r2.signature = 'SIGNATURE749532'

This query has issues when you run it in larger quantities. Is there a better way?

Thank you.

Body:
You could work with a LOAD CSV. Your input would contain the keys (not the ids, using the ids is not recommended) for Person and Car and whatever properties you need to set. For example

personId, carId, serial_number, signature
00001, 00045, SERIAL78765, SIGNATURE728934
00002, 00046, SERIAL78665, SIGNATURE724934

Your query would then be something like :

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///input.csv' AS row
MATCH (p:Person {personId: row.PersonId})-[r:OWNS_CAR]->(c:Car {carId: row.carId})
SET r.serial_number = row.serialnumber, c.signature = row.signature

Note that you should have unique constraints on Person and Car to make that work. You can do thousands (even millions) like that very quickly ...

Hope this helps,
Tom


问:
Incremental update of docs in solr
I have a table called as EMP with ID and Name as fields and it has 2 records. I have formed the xml doc as

```<code><add>
  <doc>
    <field name="ID">1</field>
    <field name="Name">Name1</field>
  </doc>
  <doc>
    <field name="ID">2</field>
    <field name="Name">Name2</field>
  </doc>
</add>
</code>```

I have indexed the above xml file to solr for the first time. But When a 3rd record gets created in the table, should I go for a xml file that has only the third record i.e

```<code><add>
  <doc>
    <field name="ID">3</field>
    <field name="Name">Name3</field>
  </doc>
</add>
</code>```

and index this xml file separately?

OR should I add the new 3rd record to the original xml file i.e

```<code><add>
  <doc>
    <field name="ID">1</field>
    <field name="Name">Name1</field>
  </doc>
  <doc>
    <field name="ID">2</field>
    <field name="Name">Name2</field>
  </doc>
  <doc>
    <field name="ID">3</field>
    <field name="Name">Name3</field>
  </doc>
</add>
</code>```

and Index this newly created xml file again? But here when there are millions of record the generating a xml file will take time and also indexing all the docs will also take time.

So, How do I need to handle the incremental indexing/updation scenario?

答:
Creating a new XML file that contains the delta (i.e. new or changed rows) solves your problem, and you are correct that it is more efficient than doing a full export/import.

If you want to circumvent creating your XML file, you should look into the DataImportHandler, which lets you import data from (for instance) a JDBC source. It's included as a contrib to Solr.

Title: Incremental update of docs in solr

Body:
I have a table called as EMP with ID and Name as fields and it has 2 records. I have formed the xml doc as

<add>
  <doc>
    <field name="ID">1</field>
    <field name="Name">Name1</field>
  </doc>
  <doc>
    <field name="ID">2</field>
    <field name="Name">Name2</field>
  </doc>
</add>

I have indexed the above xml file to solr for the first time. But When a 3rd record gets created in the table, should I go for a xml file that has only the third record i.e

<add>
  <doc>
    <field name="ID">3</field>
    <field name="Name">Name3</field>
  </doc>
</add>

and index this xml file separately?

OR should I add the new 3rd record to the original xml file i.e

<add>
  <doc>
    <field name="ID">1</field>
    <field name="Name">Name1</field>
  </doc>
  <doc>
    <field name="ID">2</field>
    <field name="Name">Name2</field>
  </doc>
  <doc>
    <field name="ID">3</field>
    <field name="Name">Name3</field>
  </doc>
</add>

and Index this newly created xml file again? But here when there are millions of record the generating a xml file will take time and also indexing all the docs will also take time.

So, How do I need to handle the incremental indexing/updation scenario?


问:
Gradle DSL method not found: 'compile()'
I had this gradle error.

Error:(9, 0) Gradle DSL method not found: 'compile()'

I have tried refering to similar questions but it did not work.

Android gradle build Error:(9, 0) Gradle DSL method not found: 'compile()'.

Getting Error "Gradle DSL method not found: 'compile()'" when Syncing Build.Gradle

Unsupported Gradle DSL method found: 'compile()'!

My build.gradle code is here

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
        compile 'com.android.support:appcompat-v7:20.+'
        compile 'com.google.android.gms:play-services:6.5.+'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

build.gradle(Module.app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    defaultConfig {
        applicationId "com.example.simplemaker.pushtest"
        minSdkVersion 9
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}
</code>```

What's wrong with my code?

答: A simple mistake can cause this problem too, don't include classpath dependencies to build.gradle(Module:app)

Body:
I had this gradle error.

Error:(9, 0) Gradle DSL method not found: 'compile()'

I have tried refering to similar questions but it did not work.

Android gradle build Error:(9, 0) Gradle DSL method not found: 'compile()'.

Getting Error "Gradle DSL method not found: 'compile()'" when Syncing Build.Gradle

Unsupported Gradle DSL method found: 'compile()'!

My build.gradle code is here

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
        compile 'com.android.support:appcompat-v7:20.+'
        compile 'com.google.android.gms:play-services:6.5.+'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

build.gradle(Module.app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    defaultConfig {
        applicationId "com.example.simplemaker.pushtest"
        minSdkVersion 9
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

What's wrong with my code?


问:
How to make grid Responsive Overlapping Content
Hello there i have made a grid for my website and the issue I am having is the grid overlaps the footer element I have been trying everything from setting the grid container to height Auto to see if it automatically adjusts I can't give it a set height as the website is responsive any help would be appreciated attached is my HTML and CSS code for the grid :)

```<code>    <html>
<head>
<link href="/styles.css" rel="stylesheet" type="text/css">
<link href="/services-styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="header">
<div class="nav">
<ul>
<li><a href="/index.html">Home</a></li>
<li><a href="/services.html">Services</a></li>
<li><a href="/aboutus.html">About us</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</div>
</div>
<div class="content">
<div class="title logo">
<h1>Logo's</h1>
</div>

<div class="title">
<h1>"Just a Glimpse of what we can do for you and your business"</h1>
    </div>
<div class="Grid1">
<div class="Gallery1">
<a href="Images/logo1.jpg">
<img src="/Images/logo1.jpg" style="width:100%; height:100%;">
    </a>
    </div>
<div class="Gallery1">
<a href="Images/logo2.png">
<img src="/Images/logo2.png"style="width:100%; height:100%;">
    </a>
    </div>
<div class="Gallery1">
<a href="Images/logo3.jpg">
<img src="/Images/logo3.jpg" style="width:100%; height:100%;">
    </a>
    </div>
    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

        <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>

    </div>
    </div>
    </div>
    <footer>
<div class="Footer-Nav">
<ul>
<li><a href="/index.html">Home</a></li>
<li><a href="/services.html">Services</a></li>
<li><a href="/aboutus.html">About us</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</div>
</footer>
    </div>
</body>
</html>
</code>```

Here is code from main styles for all pages

```<code>    .Gallery1{
 margin:5px;
float: left;
width:300px;
height:200px;
position:relative;
border: 1px solid #ccc;
}

.Grid1{
max-width:945px;
position: relative;
height:auto;
margin:0 auto;
margin-top: 25px;
}

div.logo{
 margin-top: 15px;
 text-align: center;
 font-size: 40px;
 font-family: Monospace;
 padding: 5px;

}
div.Gallery1:hover{
border-color:#777;
}
.title{
position: relative;
text-align: center;
margin-top:25px;
font-family: Monospace;
}

@media screen and (max-width:928px){
div.Grid1 {
width:308px;
margin:0 auto;
 }

}
@media screen and (max-width:487px){
div.Gallery1{
width:100%;
 }
div.Grid1{
width:90%;
 }
.title{
 margin:25px;
 }

}
.Grid1{
height: auto;
position: relative;
}
.content{
height:100%;
margin: 0;
padding: 0;
position: relative;
}
</code>```

Media Queries

```<code>    @media screen and (max-width:928px){
   div.Grid1 {
   width:308px;
   margin:0 auto;
   }

   }

   @media screen and (max-width:487px){
   div.Gallery1{
   width:100%;
   }
</code>```

答:
so I solved the issue I was having myself here is the snippet of code to where I solved the issue I basically had to recode my footer and added a height dimension to solve the issue if anyone is having this issue hope it helps :) </p>

```<code>    Footer{
    width: 100%;
   height: 76px;
 background-color:#404040;
 margin-top: 76px;
}
.footer-nav{
width:403px;
height: 21px;
position: relative;
 margin-top: 25px;
 margin-left:10px;
}
.footer-nav ul li{
display: block;
 float: left;
 padding-left:15px;
 padding-right:15px;
}
.footer-nav ul li a{
text-decoration: none;
color:white;
font-family:monospace;
font-size: 14px;
}
</code>```

Body:
Hello there i have made a grid for my website and the issue I am having is the grid overlaps the footer element I have been trying everything from setting the grid container to height Auto to see if it automatically adjusts I can't give it a set height as the website is responsive any help would be appreciated attached is my HTML and CSS code for the grid :)

<link href="/styles.css" rel="stylesheet" type="text/css">
<link href="/services-styles.css" rel="stylesheet" type="text/css">

Home

Services

About us

Contact

Logo's

"Just a Glimpse of what we can do for you and your business"

Home

Services

About us

Contact

Here is code from main styles for all pages

    .Gallery1{
 margin:5px;
float: left;
width:300px;
height:200px;
position:relative;
border: 1px solid #ccc;
}

.Grid1{
max-width:945px;
position: relative;
height:auto;
margin:0 auto;
margin-top: 25px;
}

div.logo{
 margin-top: 15px;
 text-align: center;
 font-size: 40px;
 font-family: Monospace;
 padding: 5px;

}
div.Gallery1:hover{
border-color:#777;
}
.title{
position: relative;
text-align: center;
margin-top:25px;
font-family: Monospace;
}

@media screen and (max-width:928px){
div.Grid1 {
width:308px;
margin:0 auto;
 }

}
@media screen and (max-width:487px){
div.Gallery1{
width:100%;
 }
div.Grid1{
width:90%;
 }
.title{
 margin:25px;
 }

}
.Grid1{
height: auto;
position: relative;
}
.content{
height:100%;
margin: 0;
padding: 0;
position: relative;
}

Media Queries

    @media screen and (max-width:928px){
   div.Grid1 {
   width:308px;
   margin:0 auto;
   }

   }

   @media screen and (max-width:487px){
   div.Gallery1{
   width:100%;
   }

Body:
so I solved the issue I was having myself here is the snippet of code to where I solved the issue I basically had to recode my footer and added a height dimension to solve the issue if anyone is having this issue hope it helps :)

    Footer{
    width: 100%;
   height: 76px;
 background-color:#404040;
 margin-top: 76px;
}
.footer-nav{
width:403px;
height: 21px;
position: relative;
 margin-top: 25px;
 margin-left:10px;
}
.footer-nav ul li{
display: block;
 float: left;
 padding-left:15px;
 padding-right:15px;
}
.footer-nav ul li a{
text-decoration: none;
color:white;
font-family:monospace;
font-size: 14px;
}


问:
Javascript logic not working
The if condition is not working while the else if and else are working:

function userchk() {
  var un = $('#user_name').val();
  if (un.length < 3 && un.length != 0) {
    $("#validateUser").html("User Name Shoul Be Greater Then 3.");
  }
  else if (un.length == 0) {
    $('#validationUser').html(" User Name Cannot Be Empty.");
  }
  else {
    $('#validationUser').html("");
  }
}

$('#btnTest').on('click', function() {
  userchk();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  width: 100%;
  margin-top: 20px;
  float: left;
}

button {
  font-size: 20px;
  background-color: #555;
  color: #fff;
  padding: 10px 30px;
}</code>```

<button id="btnTest">Test userchk()</button>

<input type="text" name="user_name" id="user_name" onBlur="userchk()" class="form-control" placeholder="Username" />

```

答:
Your if condition results in an element with id #validateUser being selected and manipulated.

Your else if and else target #validationUser

The Javascript logic conditions are sound but you are not getting your expected results because you are targeting a different element in your if block.

Title: Javascript logic not working

Body:
The if condition is not working while the else if and else are working:

function userchk() {
  var un = $('#user_name').val();
  if (un.length < 3 && un.length != 0) {
    $("#validateUser").html("User Name Shoul Be Greater Then 3.");
  }
  else if (un.length == 0) {
    $('#validationUser').html(" User Name Cannot Be Empty.");
  }
  else {
    $('#validationUser').html("");
  }
}

$('#btnTest').on('click', function() {
  userchk();
});

input {
  width: 100%;
  margin-top: 20px;
  float: left;
}

button {
  font-size: 20px;
  background-color: #555;
  color: #fff;
  padding: 10px 30px;
}

<button id="btnTest">Test userchk()</button>

<input type="text" name="user_name" id="user_name" onBlur="userchk()" class="form-control" placeholder="Username" />


问:
What is devops?
What is devops?  It has something to do with combining dev and ops but I don't get it.</p>

答: It's not exactly combining Dev and Ops, but rather providing the platform, tools, knowledge, and resources for these two teams to work better together. With the increase of agile development, IT operations have become a bottle neck in most organizations, and are not capable of deploying applications into the data center on-time and error-free. There is a lot of movement around application release automation (such as Nolio ASAP), and provisioning automation (Puppet, Chef, etc.).</p>

Title: What is devops?


问:
TextView in RelativeLayout improper alignment
I need to implement the following UI:

For this, I am using the following layout:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white">
    <ImageView
        android:id="@+id/news_image0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="@dimen/news_cell0_imageview_min_height"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
    <RelativeLayout
        android:id="@+id/news0_cell_image_overlay_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/news_image0"
        android:layout_alignTop="@+id/news_image0"
        android:layout_alignLeft="@+id/news_image0"
        android:layout_alignStart="@+id/news_image0"
        android:layout_alignEnd="@+id/news_image0"
        android:layout_alignRight="@+id/news_image0"
        android:background="@drawable/news_cell0_overlay_gradient">
        <TextView
            android:id="@+id/news_title0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center_vertical|start"
            android:layout_alignParentBottom="true"
            android:maxLines="3"
            android:ellipsize="end"
            android:textColor="@color/colorNewsCellType0TitleText"
            android:layout_margin="@dimen/news_cell0_textview_margin"
            android:textSize="@dimen/news_cell0_title_text_size"
            android:typeface="monospace" />
    </RelativeLayout>
</RelativeLayout>
</code>```

Into the ImageView I am loading image using Picasso from a URL. I am getting output correctly in most of the devices, but in some of the devices running android less than Lollipop, this shows up like the screenshot below. The text shows up at the top, instead of bottom. But I have set android:layout_alignParentBottom="true" for the TextView. The RelativeLayout is rendered correctly, and it fits the image(it has a background gradient, which can clearly be seen at the bottom of the image).

What is causing this problem and how can I solve this?

答:
You can try with FRAMELAYOUT

FrameLayout is designed to block out an area on the screen to display
  a single item. Generally, FrameLayout should be used to hold a single
  child view, because it can be difficult to organize child views in a
  way that's scalable to different screen sizes without the children
  overlapping each other.

```<code> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">

   <ImageView
      android:src="@drawable/ic_launcher"
      android:scaleType="fitCenter"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent"/>

   <TextView
      android:text="Hi.."
      android:textSize="17sp"
      android:textStyle="bold"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent"
      android:gravity="center|bottom"/>
</FrameLayout>
</code>```

Body:
I need to implement the following UI:

For this, I am using the following layout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white">
    <ImageView
        android:id="@+id/news_image0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="@dimen/news_cell0_imageview_min_height"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
    <RelativeLayout
        android:id="@+id/news0_cell_image_overlay_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/news_image0"
        android:layout_alignTop="@+id/news_image0"
        android:layout_alignLeft="@+id/news_image0"
        android:layout_alignStart="@+id/news_image0"
        android:layout_alignEnd="@+id/news_image0"
        android:layout_alignRight="@+id/news_image0"
        android:background="@drawable/news_cell0_overlay_gradient">
        <TextView
            android:id="@+id/news_title0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center_vertical|start"
            android:layout_alignParentBottom="true"
            android:maxLines="3"
            android:ellipsize="end"
            android:textColor="@color/colorNewsCellType0TitleText"
            android:layout_margin="@dimen/news_cell0_textview_margin"
            android:textSize="@dimen/news_cell0_title_text_size"
            android:typeface="monospace" />
    </RelativeLayout>
</RelativeLayout>

Into the ImageView I am loading image using Picasso from a URL. I am getting output correctly in most of the devices, but in some of the devices running android less than Lollipop, this shows up like the screenshot below. The text shows up at the top, instead of bottom. But I have set android:layout_alignParentBottom="true" for the TextView. The RelativeLayout is rendered correctly, and it fits the image(it has a background gradient, which can clearly be seen at the bottom of the image).

What is causing this problem and how can I solve this?

Body:
You can try with FRAMELAYOUT

FrameLayout is designed to block out an area on the screen to display
  a single item. Generally, FrameLayout should be used to hold a single
  child view, because it can be difficult to organize child views in a
  way that's scalable to different screen sizes without the children
  overlapping each other.

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">

   <ImageView
      android:src="@drawable/ic_launcher"
      android:scaleType="fitCenter"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent"/>

   <TextView
      android:text="Hi.."
      android:textSize="17sp"
      android:textStyle="bold"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent"
      android:gravity="center|bottom"/>
</FrameLayout>


答:
You can try this layout,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white">

    <ImageView
        android:id="@+id/news_image0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:minHeight="100dp"
        android:scaleType="fitXY"/>

    <TextView
        android:id="@+id/news_title0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/news_image0"
        android:layout_centerHorizontal="true"
        android:ellipsize="end"
        android:maxLines="3"
        android:padding="12dp"
        android:text="fsdsdfdsdsfsdfsdf"
        android:textColor="#f00"
        android:typeface="monospace"/>
</RelativeLayout>
</code>```

Title: TextView in RelativeLayout improper alignment

Body:
You can try this layout,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white">

    <ImageView
        android:id="@+id/news_image0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:minHeight="100dp"
        android:scaleType="fitXY"/>

    <TextView
        android:id="@+id/news_title0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/news_image0"
        android:layout_centerHorizontal="true"
        android:ellipsize="end"
        android:maxLines="3"
        android:padding="12dp"
        android:text="fsdsdfdsdsfsdfsdf"
        android:textColor="#f00"
        android:typeface="monospace"/>
</RelativeLayout>


问:
Create chinese xml ruby nokogiri
I am facing issue with nokogiri xml builder with Chinese characters.
This is working fine for
<adjustment_type>temporary</adjustment_type>

and fails for

```<code><調整類型>temporary</調整類型>
</code>```

I am doing it with

```<code>a = Nokogiri::XML::Builder.new do |xml|
  xml.send "調整類型", "abc"
end
</code>```

答:
Fixed with use of insert</p>

```<code>xml.send :insert , "<#{entity.name}>#{entity_value.value}</#{entity.name}>"
</code>```

Title: Create chinese xml ruby nokogiri

Body:
I am facing issue with nokogiri xml builder with Chinese characters.
This is working fine for
<adjustment_type>temporary</adjustment_type>

and fails for

<調整類型>temporary</調整類型>

I am doing it with

a = Nokogiri::XML::Builder.new do |xml|
  xml.send "調整類型", "abc"
end

Body:
Fixed with use of insert

xml.send :insert , "<#{entity.name}>#{entity_value.value}</#{entity.name}>"


问:
Creating a form that subscribes to events from a blocking thread
So I have to update a program to use a newer version of Awesomium, specifically 1.7.5

Well with the update Awesomium now has to operate on it's own thread, and it's blocking.

I can queue work to the blocking thread using WebCore.QueueWork() and this will complete the action passed on the thread WebCore.Run() was called. I made sure to give it it's own thread so the rest of my application isn't blocking.

The way the program used to function was by creating a worker object that had a constructor which instantiated a WebView and WebSession using the WebCore library. It then created a form which accepts a worker object as an argument which allows the form to subscribe to events from the WebCore library.

```<code>var worker = new Worker();
var debugForm = new PBForm(worker);
debugForm.Show();
</code>```

The worker constructor has this line of code which calls the function SurfaceIsDirty whenever the view is updated.

```<code>((ImageSurface)_view.Surface).Updated += (s, e) => { if (webView_SurfaceIsDirty != null) webView_SurfaceIsDirty(s, e); };
</code>```

This function is assigned in the form constructor:

```<code>this.worker.webView_SurfaceIsDirty = (sender, e) =>
{
    ImageSurface buffer = (ImageSurface)this.worker._view.Surface;
    pictureBox1.Image = buffer.Image;
};
</code>```

So the form picture updates whenever the WebView is updated.

This used to be able to run in the WebCore thread but now since the WebCore thread is blocking I can't get this form to work properly on it.

So this is where I'm stuck. I need to run the Form in a separate thread so it doesn't just hang because it's stuck with the WebCore thread which is blocking.

My idea is as follows:

When a worker is created create a form in a new thread as a property of the worker instance.

When a WebCore event occurs the worker instance should be able to update it's Form.

It's compiling, the form is responsive, yet the picture is not updating and I suspect it's related to the form being in a different thread now. Here's the relevant code I have right now:

I added this property to the worker class:

```<code>public PBForm2 DebugForm;
</code>```

I instantiate the worker class in the WebCore blocking thread:

```<code>WebCore.QueueWork(AddWorker);
</code>```

In the AddWorker method I make a new thread and run a Form while attaching it to the worker property:

```<code>static void AddWorker()
{
    var worker = new Worker();
    Workers.Add(worker);
    new Thread(() =>
    {
        worker.DebugForm = new PBForm2(worker.Id);
        var debugForm = new PBForm2(worker.Id);

        Application.Run(debugForm);
        Application.DoEvents();

    }).Start();
}
</code>```

And finally the worker event itself is now:

```<code>((ImageSurface)_view.Surface).Updated += (s, e) =>
{
    ImageSurface buffer = (ImageSurface)_view.Surface;
    DebugForm.pictureBox1.Image = buffer.Image;
    DebugForm.pictureBox1.Refresh();
};
</code>```

It seems very close to working, the form responds to user interaction and the workers are doing their thing and triggering events, but the picture isn't changing in the form. The event is getting hit and the new image is there, I suspect the fact that the form is in a different thread is causing the image on the form to not update.

This was a very long post so if you are reading this thank you for taking the time to get through it all. I'm very much a novice when it comes to threading and any suggestions or links or even what exactly to search up to solve this issue would be greatly appreciated.

答:
You are creating 2 of the same forms:

```<code>worker.DebugForm = new PBForm2(worker.Id);
var debugForm = new PBForm2(worker.Id);
</code>```

then loading debugForm, but your updates are being done to DebugForm.picturebox1 so your updates will not be seen. Updates would need to be done to debugForm.picturebox1, but you should only have one created.

Without seeing all the code, why not just load the one in the worker class or point one to the other?

```<code>Application.Run(worker.DebugForm);
Application.DoEvents();
</code>```

or

```<code>worker.DebugForm = new PBForm2(worker.Id);
var debugForm = worker.DebugForm;

Application.Run(debugForm);
Application.DoEvents();
</code>```

Body:
So I have to update a program to use a newer version of Awesomium, specifically 1.7.5

Well with the update Awesomium now has to operate on it's own thread, and it's blocking.

I can queue work to the blocking thread using WebCore.QueueWork() and this will complete the action passed on the thread WebCore.Run() was called. I made sure to give it it's own thread so the rest of my application isn't blocking.

The way the program used to function was by creating a worker object that had a constructor which instantiated a WebView and WebSession using the WebCore library. It then created a form which accepts a worker object as an argument which allows the form to subscribe to events from the WebCore library.

var worker = new Worker();
var debugForm = new PBForm(worker);
debugForm.Show();

The worker constructor has this line of code which calls the function SurfaceIsDirty whenever the view is updated.

((ImageSurface)_view.Surface).Updated += (s, e) => { if (webView_SurfaceIsDirty != null) webView_SurfaceIsDirty(s, e); };

This function is assigned in the form constructor:

this.worker.webView_SurfaceIsDirty = (sender, e) =>
{
    ImageSurface buffer = (ImageSurface)this.worker._view.Surface;
    pictureBox1.Image = buffer.Image;
};

So the form picture updates whenever the WebView is updated.

This used to be able to run in the WebCore thread but now since the WebCore thread is blocking I can't get this form to work properly on it.

So this is where I'm stuck. I need to run the Form in a separate thread so it doesn't just hang because it's stuck with the WebCore thread which is blocking.

My idea is as follows:

When a worker is created create a form in a new thread as a property of the worker instance.

When a WebCore event occurs the worker instance should be able to update it's Form.

It's compiling, the form is responsive, yet the picture is not updating and I suspect it's related to the form being in a different thread now. Here's the relevant code I have right now:

I added this property to the worker class:

public PBForm2 DebugForm;

I instantiate the worker class in the WebCore blocking thread:

WebCore.QueueWork(AddWorker);

In the AddWorker method I make a new thread and run a Form while attaching it to the worker property:

static void AddWorker()
{
    var worker = new Worker();
    Workers.Add(worker);
    new Thread(() =>
    {
        worker.DebugForm = new PBForm2(worker.Id);
        var debugForm = new PBForm2(worker.Id);

        Application.Run(debugForm);
        Application.DoEvents();

    }).Start();
}

And finally the worker event itself is now:

((ImageSurface)_view.Surface).Updated += (s, e) =>
{
    ImageSurface buffer = (ImageSurface)_view.Surface;
    DebugForm.pictureBox1.Image = buffer.Image;
    DebugForm.pictureBox1.Refresh();
};

It seems very close to working, the form responds to user interaction and the workers are doing their thing and triggering events, but the picture isn't changing in the form. The event is getting hit and the new image is there, I suspect the fact that the form is in a different thread is causing the image on the form to not update.

This was a very long post so if you are reading this thank you for taking the time to get through it all. I'm very much a novice when it comes to threading and any suggestions or links or even what exactly to search up to solve this issue would be greatly appreciated.

Body:
You are creating 2 of the same forms:

worker.DebugForm = new PBForm2(worker.Id);
var debugForm = new PBForm2(worker.Id);

then loading debugForm, but your updates are being done to DebugForm.picturebox1 so your updates will not be seen. Updates would need to be done to debugForm.picturebox1, but you should only have one created.

Without seeing all the code, why not just load the one in the worker class or point one to the other?

Application.Run(worker.DebugForm);
Application.DoEvents();

or

worker.DebugForm = new PBForm2(worker.Id);
var debugForm = worker.DebugForm;

Application.Run(debugForm);
Application.DoEvents();


问:
Inserting Blank Rows while Appending
I have two tables which i have written into excel using write.table using append argument but these two table are coming one by one but I want them to come leaving one or two blank rows between them.
I am using this command:

```<code>write.table(df1, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE)
write.table(df2, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE)
</code>```

How are they coming:

```<code>Gender  Col1 Col2
Male    18  13
Female  3   3
Grids   Col1 Col2
6 to 12     2   0
12 to 24    6   6
</code>```

How I want them to append:

```<code>Gender  Col1    Col2
Male    18  13
Female  3   3

Grids     Col1  Col2
6 to 12     2   0
12 to 24    6   6
</code>```

i.e. to have space of blank rows in between. How should I do that?

答:
We create a row in the first dataset

```<code>df1 <- rbind(df1, setNames(replicate(3, "", simplify = FALSE), names(df1)))
</code>```

and then do the write.table

```<code>write.table(df1, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE, quote = FALSE)
write.table(df2, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE, quote = FALSE)
</code>```

The output we get in opening the file is

Title: Inserting Blank Rows while Appending

Body:
I have two tables which i have written into excel using write.table using append argument but these two table are coming one by one but I want them to come leaving one or two blank rows between them.
I am using this command:

write.table(df1, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE)
write.table(df2, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE)

How are they coming:

Gender  Col1 Col2
Male    18  13
Female  3   3
Grids   Col1 Col2
6 to 12     2   0
12 to 24    6   6

How I want them to append:

Gender  Col1    Col2
Male    18  13
Female  3   3

Grids     Col1  Col2
6 to 12     2   0
12 to 24    6   6

i.e. to have space of blank rows in between. How should I do that?

Body:
We create a row in the first dataset

df1 <- rbind(df1, setNames(replicate(3, "", simplify = FALSE), names(df1)))

and then do the write.table

write.table(df1, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE, quote = FALSE)
write.table(df2, file = "filename.csv",sep = ", ",row.names=FALSE,append=TRUE, quote = FALSE)

The output we get in opening the file is


问:
How to convert JSON array to use in RecyclerView
I have a news API JSON link which I want to convert to string array so that I can use them in recycled view.

I am a new to Java, kindly help me to know the way to do it.

I am trying to use Android Networking Library and GSON for this purpose.

```<code>package in.apptonic.lalit.newsapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.apptonic.lalit.newsapplication.model.News;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerView.Adapter adapter;
    List<News> newsList = new ArrayList<>();
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.setDateFormat("M/d/yy hh:mm a");
        gson = gsonbuilder.create();

        AndroidNetworking.initialize(getApplicationContext());

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new AdapterNews(newsList);
        recyclerView.setAdapter(adapter);
        downloadNews();
    }

    private void downloadNews() {

        AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {

                        List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));

                        //TODO How to convert JSON values n String so that I can send them in adapter for recycler view
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });

    }
}
</code>```

答:
Create a method inside your AdapterNews class something like this

```<code>public void updateNewsList(List<News> list){
    this.newsList = list;  // newsList is the list which holds news data inside your adapter.
    notifyDataSetChanged();
}
</code>```

Call this method in onResponse of your network request.

```<code>AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
            .build()
            .getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {

                    List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));
                    adapter.updateNewsList(news);
                }

                @Override
                public void onError(ANError anError) {
                }
            });
</code>```

Body:
I have a news API JSON link which I want to convert to string array so that I can use them in recycled view.

I am a new to Java, kindly help me to know the way to do it.

I am trying to use Android Networking Library and GSON for this purpose.

package in.apptonic.lalit.newsapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.apptonic.lalit.newsapplication.model.News;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerView.Adapter adapter;
    List<News> newsList = new ArrayList<>();
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.setDateFormat("M/d/yy hh:mm a");
        gson = gsonbuilder.create();

        AndroidNetworking.initialize(getApplicationContext());

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new AdapterNews(newsList);
        recyclerView.setAdapter(adapter);
        downloadNews();
    }

    private void downloadNews() {

        AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {

                        List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));

                        //TODO How to convert JSON values n String so that I can send them in adapter for recycler view
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });

    }
}

Body:
Create a method inside your AdapterNews class something like this

public void updateNewsList(List<News> list){
    this.newsList = list;  // newsList is the list which holds news data inside your adapter.
    notifyDataSetChanged();
}

Call this method in onResponse of your network request.

AndroidNetworking.get("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=hidden")
            .build()
            .getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {

                    List<News> news = Arrays.asList(gson.fromJson(String.valueOf(response), News[].class));
                    adapter.updateNewsList(news);
                }

                @Override
                public void onError(ANError anError) {
                }
            });


问:
How can I get a total count of an int field in a List?
I have this class, variable and method used to populate it:

```<code>public class CategoryGroupWordCountVM : ObservableProperty
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
    public int TotalWordCount { get; set; }
}

List<CategoryGroupWordCountVM> categoryGroups;

categoryGroups = AS.dm.GetCategoryGroupWithWordCount();
</code>```

How can I get a total of all of the values of the TotalWordCount field using LINQ or any other method if it can be done as a one liner. I know I can do this with a "for" loop but hoping for something that could be all in one line.

答:
You can do LINQ to Objects and the use LINQ to calculate the totals:

```<code>decimal totalSum = (from od in categoryGroups
select od.TotalWordCount ).Sum();
</code>```

You can also use lambda-expressions to do this, which is a bit "cleaner".

```<code>decimal totalSum  = categoryGroups.Sum(x => x.TotalWordCount);
</code>```

Body:
I have this class, variable and method used to populate it:

public class CategoryGroupWordCountVM : ObservableProperty
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
    public int TotalWordCount { get; set; }
}

List<CategoryGroupWordCountVM> categoryGroups;

categoryGroups = AS.dm.GetCategoryGroupWithWordCount();

How can I get a total of all of the values of the TotalWordCount field using LINQ or any other method if it can be done as a one liner. I know I can do this with a "for" loop but hoping for something that could be all in one line.

Body:
You can do LINQ to Objects and the use LINQ to calculate the totals:

decimal totalSum = (from od in categoryGroups
select od.TotalWordCount ).Sum();

You can also use lambda-expressions to do this, which is a bit "cleaner".

decimal totalSum  = categoryGroups.Sum(x => x.TotalWordCount);


问:
Finding PowerPoint slide number & slide title in VSTO
I am writing a small plugin on ASP.NET C# VSTO and I want to be able to capture slide number and title of the slides when a slideshow is happening.

Can someone share sample code to capture title of the slide and slide number?

答:
Presentation pres = Globals.ThisAddIn.Application.ActivePresentation;

```<code>        foreach (Slide s in pres.Slides)
        {

            MessageBox.Show(s.SlideIndex);
        }
</code>```

The Slide title I don't know, yet

Body:
Presentation pres = Globals.ThisAddIn.Application.ActivePresentation;

        foreach (Slide s in pres.Slides)
        {

            MessageBox.Show(s.SlideIndex);
        }

The Slide title I don't know, yet


问:
junit test cases for this custom reader
I am new in writing junit test cases.

I have one custom item reader ,which is reading files from directory and returning pojo. Can you plz tell me how to write junit test cases for this custom reader.

Thanks in advance

答:
First of all - you should finalize the scope of your unit test & know that unit test for a Spring batch reader are no different than that of any regular Java class.

if test scope includes reading & verifying actual file data then you need to take care of that in code so that your tests don't fail anywhere i.e. you should modify logic in reader to something like ,

A. You keep a unit test file on classpath & some kind of flag that can be set from outside to know if read has to happen from claspath or disk

B. You can make your reader configurable enough to set file location from either classpath or disk then from your unit tests , you set file path to be classpath.

Eventually, what I am trying to say is that - Don't write your unit tests which will work on files from disk or any other external source.

If unit test scope is not about reading & verifying an actual file , you can simply encapsulate that part in some kind of service & inject as dependency in reader and mock it using some mocking framework.

Rest would be to construct an instance of reader and call read() method.

Answer by Niraj can be used to do overall job testing & individual step tests and I wouldn't call that a unit test for reader reading data from files.

Title: junit test cases for this custom reader


问:
Syntax error , insert "EnumBody" to complete EnumDeclaration
I was in middle of coding and accidentally put the following line of code at the part of class where we declare instance variables. but i checked and it gives the same error anywhere by anywhere i mean : inside a static block, inside constructor, inside any class method. except when private; is put as the first line of the class it gives
Syntax error, insert "EnumBody" to complete ClassBodyDeclarations (as written by @chaitanya10 in comments below and also verified by me on my workspace) error in eclipse tooltip when we hover cursor over it.

I understand there is error.

but I dont understand the error message when i hover cursor over the error. what is the meaning of this message?

why does it expecting EnumBody ?

Below is the screenshot.

答:
This was happening to me in Eclipse too even though my code  was correct. Happened because I wrote some code without adding a jar first (aspectJ JARs) and after I added the JAR this issue came about.

At first I copied the code, deleted it, and pasted it back in and thought that worked as the red line went away but errors were thrown at runtime. I did however get it to work by deleting the class, recreating it, and typing the same exact code again and it worked. Copy paste probably would have worked after deleting the class, but I typed it out to be sure.

Definitely a weird problem. I knew the code was right because I was copying it out of a book (Spring in action 4th edition - a good read btw). Anyway, hope this helps you or someone in the future! drove me crazy for about an hour