问:
laravel yajra datatable how to display json data in datatable column
i have a member table that has 'poin' column with json data,
example:

{"IDR":"100", "MYR":"50", "DOLLAR":"25"}

how can i display that json data in one cell table using datatable?

```<code>Name  | Poin       |
____________________
User 1|IDR : 100   |
      |MYR : 50    |
      |DOLLAR : 25 |
____________________
User 2|IDR : 50    |
      |MYR : 80    |
      |DOLLAR : 125|
</code>```

this is the controller

```<code>public function query(Request $request)
{
    $query = DB::table('members');

    $result = DataTables::of($query)->make(true);

    return $result;
}
</code>```

here's the blade.php

```<code> var oTable = $('#datatable-responsive').DataTable({
            autoWidth: false,
            processing: true,
            serverSide: true,
            responsive: true,
            ajax: {
                url: "{{route('members.query')}}",
                method: "POST",
                data: function (d) {
                    d.search = $('input[type="search"]').val();
                }
            },
            columns: [
                {data: "name"},
                {data: "poin"},
                {data: "created_at"}
            ]
        });
</code>```

Thanks

答:
Firstly consider casting the JSON field in your Member model to an array:

```<code>class Member extends Model
{
    protected $casts = [
        'poin' => 'array',
    ];
}
</code>```

https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting

You could then write a transformer for your Model to be used when you create your Datatable to output the JSON field poin as HTML:

```<code>namespace App\Transformers\Datatables;

use League\Fractal;
use App\Models\Member;

class MemberTransformer extends Fractal\TransformerAbstract
{
    public function transform(Member $member)
    {
        return [
            'id'   => $member->id,
            'name' => $member->name,
            'poin' => "IDR: {$member->poin['IDR']} <br> MYR: {$member->poin['MYR']} <br> DOLLAR: {$member->poin['DOLLAR']}"
        ];
    }

}
</code>```

https://yajrabox.com/docs/laravel-datatables/master/response/fractal

Then apply the transformer...

```<code>public function query(Request $request)
{
    $model = Member::query();

    $result = DataTables::of($model)
        ->setTransformer('App\Transformers\Datatables\MemberTransformer')
        ->toJson();

    return $result;
}
</code>```

https://yajrabox.com/docs/laravel-datatables/master/engine/eloquent

You may need to read the docs and tinker with this code a little as I haven't tested it out, it's just to guide you to experiment with the idea of transformers.

Body:
i have a member table that has 'poin' column with json data,
example:

{"IDR":"100", "MYR":"50", "DOLLAR":"25"}

how can i display that json data in one cell table using datatable?

Name  | Poin       |
____________________
User 1|IDR : 100   |
      |MYR : 50    |
      |DOLLAR : 25 |
____________________
User 2|IDR : 50    |
      |MYR : 80    |
      |DOLLAR : 125|

this is the controller

public function query(Request $request)
{
    $query = DB::table('members');

    $result = DataTables::of($query)->make(true);

    return $result;
}

here's the blade.php

 var oTable = $('#datatable-responsive').DataTable({
            autoWidth: false,
            processing: true,
            serverSide: true,
            responsive: true,
            ajax: {
                url: "{{route('members.query')}}",
                method: "POST",
                data: function (d) {
                    d.search = $('input[type="search"]').val();
                }
            },
            columns: [
                {data: "name"},
                {data: "poin"},
                {data: "created_at"}
            ]
        });

Thanks

Body:
Firstly consider casting the JSON field in your Member model to an array:

class Member extends Model
{
    protected $casts = [
        'poin' => 'array',
    ];
}

https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting

You could then write a transformer for your Model to be used when you create your Datatable to output the JSON field poin as HTML:

namespace App\Transformers\Datatables;

use League\Fractal;
use App\Models\Member;

class MemberTransformer extends Fractal\TransformerAbstract
{
    public function transform(Member $member)
    {
        return [
            'id'   => $member->id,
            'name' => $member->name,
            'poin' => "IDR: {$member->poin['IDR']} <br> MYR: {$member->poin['MYR']} <br> DOLLAR: {$member->poin['DOLLAR']}"
        ];
    }

}

https://yajrabox.com/docs/laravel-datatables/master/response/fractal

Then apply the transformer...

public function query(Request $request)
{
    $model = Member::query();

    $result = DataTables::of($model)
        ->setTransformer('App\Transformers\Datatables\MemberTransformer')
        ->toJson();

    return $result;
}

https://yajrabox.com/docs/laravel-datatables/master/engine/eloquent

You may need to read the docs and tinker with this code a little as I haven't tested it out, it's just to guide you to experiment with the idea of transformers.


来源: stackexchange

问:
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

```<code>$ myapp -n 3,4,5,6
</code>```

or

```<code>$ myapp -n 3-6
</code>```

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

```<code>$ myapp -n 22-27, 51-64
</code>```

答:
You can use optparse library.

Example:

```<code>from optparse import OptionParser

opt_parser = OptionParser(version="%prog 0.1")
opt_parser.usage = '%prog [options]\n\nTCP protocol reengineering tool'

# Options
opt_parser.add_option('-n', default="1,2,3")
(options, args) = opt_parser.parse_args()

list = []
for s in options.n.split(","):
    list.append(int(s))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Parsing command line input for numbers

Body:
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64

Body:
You can use optparse library.

Example:

from optparse import OptionParser

opt_parser = OptionParser(version="%prog 0.1")
opt_parser.usage = '%prog [options]\n\nTCP protocol reengineering tool'

# Options
opt_parser.add_option('-n', default="1,2,3")
(options, args) = opt_parser.parse_args()

list = []
for s in options.n.split(","):
    list.append(int(s))


问:
I need to be able to able to extract parts of strings to get other strings
I need to be able to be able to break down a string and get each part of the string like so:

Example: "C:\Program Files (x86)\Mozilla Firefox\dictionaries" (I Start with this)

(and i get these four)

```<code>"/C:"
"/C:/Program Files (x86)"
"/C:/Program Files (x86)/Mozilla Firefox"
"/C:/Program Files (x86)/Mozilla Firefox/dictionaries"
</code>```

I am developing in 4Test and you might not be familiar with it but as long as theres no built in functions in the code I can reproduce it here. I am familiar with c#

Edit**** Sorry There was meant to be a slash in front of each newly reproduced string. It is possible to get a solution not involving String.Split as it is not available in language I am using, I just asked for a solution in c# without built-in functions due to the low popularity of the scripting language I am using.

答:
You could loop over the characters in the string and build up the buffer as you go. Each time you hit the delimiter add the current buffer to the results list. Best seen in code:</p>

```<code>using System;
using System.Collections.Generic;

namespace SplitString
{
    class Program
    {
        public static List<string> GetStrings(string input, char delimiter, string prefix)
        {
            // Pre-load buffer with prefix
            string buffer = prefix;
            List<string> result = new List<string>();

            foreach (var c in input)
            {
                if (c == delimiter)
                {
                    // We have hit a delimeter so we have a result
                    result.Add(buffer);
                    buffer += prefix;
                }
                else
                {
                    buffer += c;
                }
            }
            // At end of string need to add last result
            result.Add(buffer);
            return result;
        }

        static void Main(string[] args)
        {
            var strings = GetStrings(@"C:\Program Files(x86)\Mozilla Firefox\dictionaries ", '\\', "/");
            foreach (var s in strings)
            {
                Console.Out.WriteLine(s);
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to be able to be able to break down a string and get each part of the string like so:

Example: "C:\Program Files (x86)\Mozilla Firefox\dictionaries" (I Start with this)

(and i get these four)

"/C:"
"/C:/Program Files (x86)"
"/C:/Program Files (x86)/Mozilla Firefox"
"/C:/Program Files (x86)/Mozilla Firefox/dictionaries"

I am developing in 4Test and you might not be familiar with it but as long as theres no built in functions in the code I can reproduce it here. I am familiar with c#

Edit**** Sorry There was meant to be a slash in front of each newly reproduced string. It is possible to get a solution not involving String.Split as it is not available in language I am using, I just asked for a solution in c# without built-in functions due to the low popularity of the scripting language I am using.

Body:
You could loop over the characters in the string and build up the buffer as you go. Each time you hit the delimiter add the current buffer to the results list. Best seen in code:

using System;
using System.Collections.Generic;

namespace SplitString
{
    class Program
    {
        public static List<string> GetStrings(string input, char delimiter, string prefix)
        {
            // Pre-load buffer with prefix
            string buffer = prefix;
            List<string> result = new List<string>();

            foreach (var c in input)
            {
                if (c == delimiter)
                {
                    // We have hit a delimeter so we have a result
                    result.Add(buffer);
                    buffer += prefix;
                }
                else
                {
                    buffer += c;
                }
            }
            // At end of string need to add last result
            result.Add(buffer);
            return result;
        }

        static void Main(string[] args)
        {
            var strings = GetStrings(@"C:\Program Files(x86)\Mozilla Firefox\dictionaries ", '\\', "/");
            foreach (var s in strings)
            {
                Console.Out.WriteLine(s);
            }
        }
    }
}


问:
Using a var as a partial name?
Im trying to render partials based upon a variable name, according to these docs the correct method is:

Subexpressions do not resolve variables so whichPartial must be a
  function. If a simple variable has the partial name, it's possible to
  resolve it via the lookup helper.

```<code>{{> (lookup . 'myVariable') }}
</code>```

So I have tried:

```<code>{{#each index.types}}
    {{> (lookup . this.type) }}
{{/each}}
</code>```

But I get the error:

```<code>Error: The partial undefined could not be found
</code>```

I've also output the following in the loop:

```<code>{{this.type}}
</code>```

The correct partial string is being read.

答:
I had similar problem with using {{this}} as partial name. I managed to solve it by using partial block as follows:

```<code>{{#each this as |tab| }}
      {{> (tab)}}
{{/each}}
</code>```

In your case you could try:

```<code>{{#each index.types as |item| }}
  {{> (item.type)}}
{{/each}}
</code>```

Title: Using a var as a partial name?

Body:
Im trying to render partials based upon a variable name, according to these docs the correct method is:

Subexpressions do not resolve variables so whichPartial must be a
  function. If a simple variable has the partial name, it's possible to
  resolve it via the lookup helper.

{{> (lookup . 'myVariable') }}

So I have tried:

{{#each index.types}}
    {{> (lookup . this.type) }}
{{/each}}

But I get the error:

Error: The partial undefined could not be found

I've also output the following in the loop:

{{this.type}}

The correct partial string is being read.

Body:
I had similar problem with using {{this}} as partial name. I managed to solve it by using partial block as follows:

{{#each this as |tab| }}
      {{> (tab)}}
{{/each}}

In your case you could try:

{{#each index.types as |item| }}
  {{> (item.type)}}
{{/each}}


问:
Command Line Calculator in Java ONLY using if else
I've been given this question but I think there's something wrong with my code.

Write a Java Program to take in 3 command line arguments for calculation.
The first and third argument must be an Integer.
The second argument must be either + - x /
The program will print out the result of the calculation if the 3 arguments are correct. Do not use switch, only use if else.

I input the following arguments:

```<code>1 '*' 2
</code>```

And then get "You have entered an invalid operator" as a result. If I remove '*' and replace it in with just *:

```<code>1 * 2
</code>```

My code cannot work at all and I get the following error:

```<code>Exception in thread "main" java.lang.NumberFormatException:

For input string: ".project"

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at Command1.main(Unknown Source)
</code>```

Any idea how I can correct my code? I wondered if I should replace char with String instead but couldn't get the symbol to work either.

Code:

```<code>import java.util.Scanner;
public class Command1 {

public static void main(String[] args) {
    int num1 = Integer.parseInt(args[0]);
    char symbol = args[1].charAt(0);
    int num2 = Integer.parseInt(args[2]);
    System.out.println(args[0]+" "+args[1]+" "+args[2]+" = ");
    if(symbol=='+')
    {
        System.out.println(num1+num2);
    }
    else if(symbol=='-')
    {
        System.out.println(num1-num2);
    }
    else if(symbol=='*')
    {
        System.out.println(num1*num2);
    }
    else if(symbol=='/')
    {
        System.out.println(num1/num2);
    }
    else
    {
        System.out.println("You have entered an invalid operator.");
    }
    // TODO Auto-generated method stub

 }

}
</code>```

答:
Using double quotation mark for the Symbol you can get answer.
Like 4 "*" 2

Body:
I've been given this question but I think there's something wrong with my code.

Write a Java Program to take in 3 command line arguments for calculation.
The first and third argument must be an Integer.
The second argument must be either + - x /
The program will print out the result of the calculation if the 3 arguments are correct. Do not use switch, only use if else.

I input the following arguments:

1 '*' 2

And then get "You have entered an invalid operator" as a result. If I remove '*' and replace it in with just *:

1 * 2

My code cannot work at all and I get the following error:

Exception in thread "main" java.lang.NumberFormatException:

For input string: ".project"

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at Command1.main(Unknown Source)

Any idea how I can correct my code? I wondered if I should replace char with String instead but couldn't get the symbol to work either.

Code:

import java.util.Scanner;
public class Command1 {

public static void main(String[] args) {
    int num1 = Integer.parseInt(args[0]);
    char symbol = args[1].charAt(0);
    int num2 = Integer.parseInt(args[2]);
    System.out.println(args[0]+" "+args[1]+" "+args[2]+" = ");
    if(symbol=='+')
    {
        System.out.println(num1+num2);
    }
    else if(symbol=='-')
    {
        System.out.println(num1-num2);
    }
    else if(symbol=='*')
    {
        System.out.println(num1*num2);
    }
    else if(symbol=='/')
    {
        System.out.println(num1/num2);
    }
    else
    {
        System.out.println("You have entered an invalid operator.");
    }
    // TODO Auto-generated method stub

 }

}


问:
Know the nature of a URL before GETting it
Is it possible to know the nature of a URL before GETting it ?

I have one URL in particular that ends with m3u but is not a simple file I can download. This is actually a radio stream. As I expect a (finite) file, the GET method never ends. The timeout options does not works in this case (normal).

```<code>const options = {timeout: 5000};
return HTTP.call('GET', "http://av.rasset.ie/av/live/radio/junior.m3u", options);
</code>```

The safe solution should be to ask for the type of the response before actually getting the file.
How can I do that?

Thanks,
Mickael.

答:
I guess you can run a HEAD request first (instead of GET) and verify the headers. Then after making GET you will know how to react.

Unfortunately in this particular case HEAD works for the first request (which returns a redirect):

```<code> curl -v -X HEAD http://icecast1.rte.ie/junior               http://av.rasset.ie/av/live/radio/junior.m3u
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
*   Trying 104.16.107.29...
* TCP_NODELAY set
* Connected to av.rasset.ie (104.16.107.29) port 80 (#0)
> HEAD /av/live/radio/junior.m3u HTTP/1.1
> Host: av.rasset.ie
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 302 FOUND
< Date: Mon, 13 Nov 2017 11:07:33 GMT
< Content-Type: text/html; charset=utf-8
< Connection: keep-alive
< Set-Cookie: __cfduid=d89353ae357a0452208835b3092f0fbee1510571253; expires=Tue, 13-Nov-18 11:07:33 GMT; path=/; domain=.rasset.ie; HttpOnly
< Location: http://icecast1.rte.ie/junior
< X-Server-Name: djd
< Cache-Control: max-age=0
< Accept-Ranges: bytes
< X-Varnish: 2802121867
< X-Served-By: MISS: mt-www2.rte.ie
< CF-Cache-Status: MISS
< Server: cloudflare-nginx
< CF-RAY: 3bd1449d2764410c-HAM
* no chunk, no close, no size. Assume close to signal end
<
^C
</code>```

But fails for second (probably HEAD is not supported, should return 405):

```<code> curl -v -X HEAD http://icecast1.rte.ie/junior
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
*   Trying 89.207.56.171...
* TCP_NODELAY set
* Connected to icecast1.rte.ie (89.207.56.171) port 80 (#0)
> HEAD /junior HTTP/1.1
> Host: icecast1.rte.ie
> User-Agent: curl/7.51.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 400 Bad Request
< Server: Icecast 2.4.2
< Date: Mon, 13 Nov 2017 11:07:42 GMT
< Content-Type: text/html; charset=utf-8
< Cache-Control: no-cache
< Expires: Mon, 26 Jul 1997 05:00:00 GMT
< Pragma: no-cache
<
<html><head><title>Error 400</title></head><body><b>400 - unknown request</b></body></html>
* Curl_http_done: called premature == 0
* Closing connection 0
</code>```

Body:
Is it possible to know the nature of a URL before GETting it ?

I have one URL in particular that ends with m3u but is not a simple file I can download. This is actually a radio stream. As I expect a (finite) file, the GET method never ends. The timeout options does not works in this case (normal).

const options = {timeout: 5000};
return HTTP.call('GET', "http://av.rasset.ie/av/live/radio/junior.m3u", options);

The safe solution should be to ask for the type of the response before actually getting the file.
How can I do that?

Thanks,
Mickael.

Body:
I guess you can run a HEAD request first (instead of GET) and verify the headers. Then after making GET you will know how to react.

Unfortunately in this particular case HEAD works for the first request (which returns a redirect):

 curl -v -X HEAD http://icecast1.rte.ie/junior               http://av.rasset.ie/av/live/radio/junior.m3u
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
*   Trying 104.16.107.29...
* TCP_NODELAY set
* Connected to av.rasset.ie (104.16.107.29) port 80 (#0)
> HEAD /av/live/radio/junior.m3u HTTP/1.1
> Host: av.rasset.ie
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 302 FOUND
< Date: Mon, 13 Nov 2017 11:07:33 GMT
< Content-Type: text/html; charset=utf-8
< Connection: keep-alive
< Set-Cookie: __cfduid=d89353ae357a0452208835b3092f0fbee1510571253; expires=Tue, 13-Nov-18 11:07:33 GMT; path=/; domain=.rasset.ie; HttpOnly
< Location: http://icecast1.rte.ie/junior
< X-Server-Name: djd
< Cache-Control: max-age=0
< Accept-Ranges: bytes
< X-Varnish: 2802121867
< X-Served-By: MISS: mt-www2.rte.ie
< CF-Cache-Status: MISS
< Server: cloudflare-nginx
< CF-RAY: 3bd1449d2764410c-HAM
* no chunk, no close, no size. Assume close to signal end
<
^C

But fails for second (probably HEAD is not supported, should return 405):

 curl -v -X HEAD http://icecast1.rte.ie/junior
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
*   Trying 89.207.56.171...
* TCP_NODELAY set
* Connected to icecast1.rte.ie (89.207.56.171) port 80 (#0)
> HEAD /junior HTTP/1.1
> Host: icecast1.rte.ie
> User-Agent: curl/7.51.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 400 Bad Request
< Server: Icecast 2.4.2
< Date: Mon, 13 Nov 2017 11:07:42 GMT
< Content-Type: text/html; charset=utf-8
< Cache-Control: no-cache
< Expires: Mon, 26 Jul 1997 05:00:00 GMT
< Pragma: no-cache
<
<html><head><title>Error 400</title></head><body><b>400 - unknown request</b></body></html>
* Curl_http_done: called premature == 0
* Closing connection 0


问:
Embedded UITableView does not detect a swipe to delete row gesture
I have a UITableView embedded inside of a UICollectionView, the collection view scrolls horizontally so if i try a 'swipe to delete' on one of the table view rows which is inside of a collection view cell, it obviously just scrolls the collection view. Was wondering if there is a work around so that it could detect the swipe on the uitableview part of the collection view cell instead of swiping the uicollection view itself? The UITableView only takes up about a quarter of the collection view cell. I'm using a UIViewController. And i also have paging enabled on my collection view.</p>

答:
Try one of the two options:

Look at require(toFail otherGestureRecognizer: UIGestureRecognizer). Add the swipe gestures with this method to the collection view pan gesture when you create (or populate) the cells.

Try to look at shouldRequireFailure(of: otherGestureRecognizer). Subclass UICollectionView and override this method to return true when otherGestureRecognizer is actually a swipe to delete row gesture.

You just have to figure how you can identify/retrieve both of the gesture recognizers (hint: browse the gestureRecognizers property to find some PanGestureRecognizers)

And you should definitely refine that clunky design.

ContentLicense: CC BY-SA 4.0


问:
dataForm jQuery Ajax to PHP
My code does not working correctly, after 3 hours, I don't understand why it isn't working. Can anybody help me out? My goal is to sent over form fields and image to PHP with jQuery. I don't get any respond as XHR. The only thing I see is (Parameters):

```<code>-----------------------------163541139317822
Content-Disposition: form-data; name="staffnumber"

utyu
-----------------------------163541139317822
Content-Disposition: form-data; name="nameperson"

yu
-----------------------------163541139317822
Content-Disposition: form-data; name="fileupload"; filename=""
Content-Type: application/octet-stream

-----------------------------163541139317822--
</code>```

Error in console: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

HTML

```<code><form method="POST" id="formadduser" enctype="multipart/form-data">
    <div id="staffnumber" class="form-group row">
        <label for="staffnumber" class="col-sm-3 col-form-label"><strong>Personeelsnummer</strong> <img src="api/icons/info.svg"></label>
        <div class="col-sm-4">
            <input class="form-control" id="staffnumber" name="staffnumber" value="" type="text">
        </div>
    </div>
    <div id="nameperson" class="form-group row">
        <label for="nameperson" class="col-sm-3 col-form-label"><strong>Naam</strong> <img src="api/icons/info.svg"></label>
        <div class="col-sm-4">
            <input class="form-control" id="nameperson" name="nameperson" value="" type="text">
        </div>
    </div>
    <div id="rowstarttime" class="form-group row">
        <label for="starttime" class="col-sm-3 col-form-label"><strong>Afbeelding</strong></label>
        <div class="col-sm-4">
        <label class="custom-file">
            <input type="file" id="fileupload" class="custom-file-input" name="fileupload">
            <span class="custom-file-control"></span>
        </label>
        </div>
    </div>

  <div class="modal-footer">
  <button id="modaladdusersave" class="btn btn-primary mx-sm-3" type="submit">Opslaan</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
</form>
</code>```

jQuery

```<code>$("#formadduser").submit(function(e) {
    e.preventDefault();

    var formData = new FormData(this);
    alert(formData);
    alert('hoi');
    $.ajax({
        ajax_call: "add_user",
        url: '/api/add.php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            var data = $.parseJSON( data );
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

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

PHP

```<code><?php

require_once('../database.php');

if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {

$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson']; // $_GET['nameperson'];

$file = $_FILES['fileupload']['tmp_name'];
$targetPath = "upload/".$_FILES['fileupload']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

// Add record
// $queryNew = 'INSERT INTO Persons (id, name, image) VALUES ("'. $staffnumber .'", "'. $nameperson .'", "test")';
// mysqli_query($conn, $queryNew);

$data = array(
        'staffnumber'   => $staffnumber,
        'nameperson'    => $nameperson,
    );
echo json_encode($data);
exit;

}

?>
</code>```

答:
I think you should handle the return value of move_uploaded_file.

as a PHP document

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

```<code>$moved = move_uploaded_file($_FILES['fileupload']['tmp_name'],$targetPath)

if( $moved ) {
   $data = array(
    'staffnumber'   => $staffnumber,
    'nameperson'    => $nameperson,
);
   echo json_encode($data);
} else {//something went wrong
   $data = array(
    'error'   => $_FILES["file"]["error"]
    );
   echo json_encode($data);
}
</code>```

It will give you one of the following error code values 1 to 8:

UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.

Title: dataForm jQuery Ajax to PHP

Body:
My code does not working correctly, after 3 hours, I don't understand why it isn't working. Can anybody help me out? My goal is to sent over form fields and image to PHP with jQuery. I don't get any respond as XHR. The only thing I see is (Parameters):

-----------------------------163541139317822
Content-Disposition: form-data; name="staffnumber"

utyu
-----------------------------163541139317822
Content-Disposition: form-data; name="nameperson"

yu
-----------------------------163541139317822
Content-Disposition: form-data; name="fileupload"; filename=""
Content-Type: application/octet-stream

-----------------------------163541139317822--

Error in console: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.

HTML

<form method="POST" id="formadduser" enctype="multipart/form-data">

        Personeelsnummer

            <input class="form-control" id="staffnumber" name="staffnumber" value="" type="text">

        Naam

            <input class="form-control" id="nameperson" name="nameperson" value="" type="text">

        Afbeelding

            <input type="file" id="fileupload" class="custom-file-input" name="fileupload">

  <button id="modaladdusersave" class="btn btn-primary mx-sm-3" type="submit">Opslaan</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
</form>

jQuery

$("#formadduser").submit(function(e) {
    e.preventDefault();

    var formData = new FormData(this);
    alert(formData);
    alert('hoi');
    $.ajax({
        ajax_call: "add_user",
        url: '/api/add.php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            var data = $.parseJSON( data );
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

PHP

<?php

require_once('../database.php');

if(isset($_GET['ajax_call']) && $_GET['ajax_call'] == 'add_user') {

$staffnumber = $_GET['staffnumber']; // $_GET['staffnumber'];
$nameperson = $_GET['nameperson']; // $_GET['nameperson'];

$file = $_FILES['fileupload']['tmp_name'];
$targetPath = "upload/".$_FILES['fileupload']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

// Add record
// $queryNew = 'INSERT INTO Persons (id, name, image) VALUES ("'. $staffnumber .'", "'. $nameperson .'", "test")';
// mysqli_query($conn, $queryNew);

$data = array(
        'staffnumber'   => $staffnumber,
        'nameperson'    => $nameperson,
    );
echo json_encode($data);
exit;

}

?>

Body:
I think you should handle the return value of move_uploaded_file.

as a PHP document

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

$moved = move_uploaded_file($_FILES['fileupload']['tmp_name'],$targetPath)

if( $moved ) {
   $data = array(
    'staffnumber'   => $staffnumber,
    'nameperson'    => $nameperson,
);
   echo json_encode($data);
} else {//something went wrong
   $data = array(
    'error'   => $_FILES["file"]["error"]
    );
   echo json_encode($data);
}

It will give you one of the following error code values 1 to 8:

UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.


问:
Error in extract_function(initial_response) : no query results returned in elasticsearchr in R
I have an index in elastic search and want to get specific driver age people. I executed the following query to get drv_age = 63

```<code>library(elasticsearchr)

# Required variables;
index.name <- "acturial"
index.type <- "data"
col.name <- "drv_age"
value <- 63

# Path where result will be written in json form;
path <- "G:\\R Projects\\Elastic Search R\\Record.json"

myQuery <- paste0('{ "match" : {"', col.name, '" : ', value , '} } ')

# reading data from elasticSearch
data <- elastic("http://localhost:9200", index.name, index.type) %search% query(myQuery)
</code>```

It works fine but when I put drv_age = 10000 which is not in the index then It gives me

Error in extract_function(initial_response) : no query results returned

My problem is to store that error message in a variable to process it. But I am not able to do it.

答:
Using search method of the elastic package in R we can get total hits against a query. In this way, we can check whether any data is found or not. Following is the code snippet. </p>

```<code>library(elastic)

connect()

# Required variables;
index.name <- "acturial"
index.type <- "data"
col.name <- "year"
value <- "2013"

myQuery <- paste(col.name,value,sep = ":")

records.found <- Search(index.name,index.type,q=myQuery)$hits$total

if (records.found > 0){
# Your loggic;
}else{
print("No record found")
}
</code>```

Body:
I have an index in elastic search and want to get specific driver age people. I executed the following query to get drv_age = 63

library(elasticsearchr)

# Required variables;
index.name <- "acturial"
index.type <- "data"
col.name <- "drv_age"
value <- 63

# Path where result will be written in json form;
path <- "G:\\R Projects\\Elastic Search R\\Record.json"

myQuery <- paste0('{ "match" : {"', col.name, '" : ', value , '} } ')

# reading data from elasticSearch
data <- elastic("http://localhost:9200", index.name, index.type) %search% query(myQuery)

It works fine but when I put drv_age = 10000 which is not in the index then It gives me

Error in extract_function(initial_response) : no query results returned

My problem is to store that error message in a variable to process it. But I am not able to do it.

Body:
Using search method of the elastic package in R we can get total hits against a query. In this way, we can check whether any data is found or not. Following is the code snippet.

library(elastic)

connect()

# Required variables;
index.name <- "acturial"
index.type <- "data"
col.name <- "year"
value <- "2013"

myQuery <- paste(col.name,value,sep = ":")

records.found <- Search(index.name,index.type,q=myQuery)$hits$total

if (records.found > 0){
# Your loggic;
}else{
print("No record found")
}


问:
Bootstrap column on mobile positions
I have the views like this: </p>

```<code><div class="container">
    <div class="col-md-9">mymaincontent</>
    <div class="col-md-12">mygallery</>
    <div class="col-md-3">mysidebar</>
</>
</code>```

<p>I want to make my sidebar stay ontop on my desktop view
and make my gallery stay above sidebar on my mobile view </p>

答:
You may want to try CSS Flexbox : A complete guide to Flexbox, since it's the easiest way to dynamically modify content positon.

Thanks to CSS Media queries you should test the max width of the viewport :

```<code>//Default style
.container {
    display: flex;
    flex-direction: row;
}

//Adaptative style
@media (max-width: 12450px) {
    .container {
        display: flex;
        flex-direction: column; /*from row to column*/
    }
}
</code>```

Title: Bootstrap column on mobile positions

Body:
I have the views like this:

mymaincontent</>

mygallery</>

mysidebar</>
</>

I want to make my sidebar stay ontop on my desktop view
and make my gallery stay above sidebar on my mobile view

Body:
You may want to try CSS Flexbox : A complete guide to Flexbox, since it's the easiest way to dynamically modify content positon.

Thanks to CSS Media queries you should test the max width of the viewport :

//Default style
.container {
    display: flex;
    flex-direction: row;
}

//Adaptative style
@media (max-width: 12450px) {
    .container {
        display: flex;
        flex-direction: column; /*from row to column*/
    }
}


问:
How to format the value in a strongy typed view when using ASP.Net MVC's Html.TextBoxFor
I am trying to format a date rendered by ASP.Net MVC's TextBoxFor using the value of a strongly typed view. The date is nullable so if it is null I want to see a blank value, otherwise I want to see it in the format MM/dd/yyyy.

```<code><%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%>
</code>```

Thanks,

Paul Speranza

答:
I use some custom helpers and have used them successfully in MVC 2 and 3 (code also on Snipplr).  The helpers have some css logic thrown in as I use the jQuery-ui datepicker, but that can easily be removed.</p>

```<code>public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString;
        DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString());
        string value = date == new DateTime() ? String.Empty : date.ToString(format);
        RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
        string datePickerClass = "date-selector";
        if (attributes.ContainsKey("class"))
        {
            string cssClass = attributes["class"].ToString();
            attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass);
        }
        else
        {
            attributes["class"] = datePickerClass;
        }
        return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null);
    }
</code>```

Body:
I am trying to format a date rendered by ASP.Net MVC's TextBoxFor using the value of a strongly typed view. The date is nullable so if it is null I want to see a blank value, otherwise I want to see it in the format MM/dd/yyyy.

<%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%>

Thanks,

Paul Speranza

Body:
I use some custom helpers and have used them successfully in MVC 2 and 3 (code also on Snipplr).  The helpers have some css logic thrown in as I use the jQuery-ui datepicker, but that can easily be removed.

public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString;
        DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString());
        string value = date == new DateTime() ? String.Empty : date.ToString(format);
        RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
        string datePickerClass = "date-selector";
        if (attributes.ContainsKey("class"))
        {
            string cssClass = attributes["class"].ToString();
            attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass);
        }
        else
        {
            attributes["class"] = datePickerClass;
        }
        return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null);
    }


问:
Recognise Receipt data Xamarin native
Anyone knows some good lib our some source code to implement a receipt recogniser in order to get the data from it like product name, total amount, date?

I want to implement this in iOS and Android

答:
I assume you have an Image of Receipt and you want to extract some predefined text out of that Image.

You can go with Microsof't Cognitive Service (Computer Vision API), which reads text from the Image. Check for the Price per Transaction Here. However, it may not be so accurate, but you should give it a try to check if it fulfills your purpose.

This requires some string operations to get the specific result and you need to consider lot of variants of the Receipt you may be using in your app.

Check Xamarin's Blog and Sample Code Here.

Note: If your receipt can add a Barcode, containing all details you want to extract, it will be better solution rather than this string operations, I guess.

Title: Recognise Receipt data Xamarin native


问:
Stream data from browser to the mobile phone
I'm developing app that will be in Chrome (as a plugin) and Google store. When user turn on the plugin it sends JSON data every few seconds to the mobile phone based on Android OS.

In some of my projects I've used websocket to stream the data from telephone central via proxy/service to the browser. I'd like to do something like that.

I'm wondering how to implement and what of existing services to use as a layer between browser and mobile app? I don't need a broadcasting because every user/plugin has own data.

答:
You can implement Google Cloud Messaging, especially if your data payload fits into 4kB per message; you will need a server that will re-route messages from the extension endpoint to the phone endpoint though.

Extension registers with your server ID through GCM.

Phone registers with your server through GCM.

Extension sends a message upstream; your server receives it.

Your server pushes the message to the phone downstream.

Chrome natively supports GCM in extensions (but not FCM!), as does Android.


问:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
I'm following a tutorial from pluralsight with Angular fundamentals.

I think my error has something to do with this code:

```<code>   import { Component, OnInit} from '@angular/core';
   import { EventService } from "./shared/event.service";
   import { ToastrService } from '../common/toastr.service'
   import { ActivatedRoute } from "@angular/router";

   @Component({
       selector:'events-list',
       template:`
       <div>
           <h1> Upcoming Angular 2 Events </h1>

           <hr/>
           <div class="row">
              <div  *ngFor="let event of events"  class="col-md-5">
           <event-thumbnail (click)="handleThumbnailClick(event.name)" [event] = "event"> </event-thumbnail>
              </div>
          </div>
       </div>
       `
    })

    export class EventListComponent implements OnInit{
        events:any
        constructor(private eventService:EventService, private toastr:ToastrService, private route:ActivatedRoute) {

        }
        ngOnInit() {
             this.events = this.route.snapshot.data['events']
        }

        handleThumbnailClick(eventName)
        {
            this.toastr.success(eventName)
        }
    }
</code>```

I tried using events:any[] but a had the same error.
I even tried in my ngOnInit() method something like this.route.snapshot.data['events'] without using this.events

答:
Initialize the events array and make sure  this.route.snapshot.data['events'] returns an array,

```<code>events:any = [];
</code>```

Body:
I'm following a tutorial from pluralsight with Angular fundamentals.

I think my error has something to do with this code:

   import { Component, OnInit} from '@angular/core';
   import { EventService } from "./shared/event.service";
   import { ToastrService } from '../common/toastr.service'
   import { ActivatedRoute } from "@angular/router";

   @Component({
       selector:'events-list',
       template:`

 Upcoming Angular 2 Events

           <event-thumbnail (click)="handleThumbnailClick(event.name)" [event] = "event"> </event-thumbnail>

       `
    })

    export class EventListComponent implements OnInit{
        events:any
        constructor(private eventService:EventService, private toastr:ToastrService, private route:ActivatedRoute) {

        }
        ngOnInit() {
             this.events = this.route.snapshot.data['events']
        }

        handleThumbnailClick(eventName)
        {
            this.toastr.success(eventName)
        }
    }

I tried using events:any[] but a had the same error.
I even tried in my ngOnInit() method something like this.route.snapshot.data['events'] without using this.events

Body:
Initialize the events array and make sure  this.route.snapshot.data['events'] returns an array,

events:any = [];


问:
Testing AngularJS with Protractor- test fails because element is not clickable despite waiting for elementToBeClickable...?
I have encountered a strange problem while writing up one of the tests in a test suite I am developing for an AngularJS application using Protractor.

While initially developing the tests, I was using a call to browser.pause() to ensure that I manually had to tell the tests to execute each line while running through the test scripts. I am now happy that the tests that I have written so far are executing correctly & all pass/ fail correctly depending on their criteria.

I now want to remove the call to browser.pause() so that the script can run through each of the tests automatically, without the need for any user interaction. However, because the application is Angular, doing this has caused some issues with timing/ waiting for elements to load before the test steps that reference them are executed- so I am currently going through each of the tests, and trying to ensure that they are allowing the required times for elements to load/ waiting for an element before interacting with it, etc.

When I run my test script at the moment, it is failing on the second test (navigate to the Export page), which I have written as follows:

```<code>it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000).then(
        browser.actions().mouseMove(exportMenuBtn).perform().then(
            exportMenuBtn.click().then(
                function() {
                    console.log("Export page test completed ");
                    expect(browser.getCurrentUrl()).toBe(VM + '/#/export');
                }
            )
        )
    );
});
</code>```

The error message I get in the command line where I'm running my script says:

Failed: unknown error: Element ... is not clickable at point (40, 301). Other element would receive the click:

```<code><div tabindex="-1" role="dialog" class="modal fade ng-isolate-scope ult-loading modal-message ng-animate in-remove in-remove-active" ng-class="{in: animate}" ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)" modal-window="" window-class="ult-loading modal-message" size="sm" index="0" animate="animate" style="z-index: 1050; display: block;; transition-property: opacity;transition-duration: 0.15s;">...</div>
</code>```

(Session info: chrome=62.0.3202.89)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

which indicates to me that the exportMenuBtn element is not 'clickable' at the point at which my test script is trying to call .click() on it. But this doesn't make sense, since I have used the line browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000) to wait for the exportMenuBtn element to be clickable before I try to click it...

I have tried increasing the time that I wait for the element to be clickable, but this doesn't seem to have made a difference...

Can anyone explain why this test is failing? How can I ensure that the test waits for the exportMenuBtn element to be clickable before it tries to click it?

Edit

So I tried doing what @Ernst Zwingli suggested in their answer- added a function to close the dialog to my spec.js file with:

```<code>var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();
</code>```

and then updated the test script to:

```<code>it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    exportMenuBtn.click();
    browser.wait(pageLoaded, 5000);
    browser.wait(EC.urlIs(VM + '/#/export'), 5000);
});
</code>```

But my test script still fails, giving the same error message:

Failed: unknown error: Element

```<code><a href="#/export" target="_self">...</a>
</code>```

is not clickable at point (40, 301).

Other element would receive the click:

```<code><div tabindex="-1" role="dialog" class="modal fade ng-isolate-scope ult-loading modal-message ng-animate in-remove in-remove-active" ng-class="{in: animate}" ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)" modal-window="" window-class="ult-loading modal-message" size="sm" index="0" animate="animate" style="z-index: 1050; display: block;; transition-property: opacity;transition-duration: 0.15s;">...</div>
</code>```

```<code> (Session info: chrome=62.0.3202.89)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)
</code>```

The dialog that seems to be causing the issue is defined in Dialog/service.js with:

```<code>function wait(msg, progress, title) {
    // Create a wait dialog
    var dlg = dialogs.wait(
        title,
        msg,
        progress,
        {
            // Disable keyboard ESC to close dialogue instances
            keyboard: false,

            // lock the background window
            backdrop: "static",
            size: "sm",
            windowClass: "ult-loading modal-message",
            animation: false
        }
    );

    // Push the dialog into the pool
    dlgs.push(dlg);

    // Return the created dialog
    return dlg;
}
</code>```

This dialog is never actually visible when running the test/ browsing to the page manually, so it seems to be some sort of 'background task' that is run while browsing to/ loading a new page. I should also note that this dialog is defined within a factory:

```<code>.factory('DialogMgr', function($rootScope, $document, dialogs) {
    ...
    function wait(...) {
        ...
    }
});
</code>```

I'm wondering if this possibly has anything to do with the 'fade' animation that is set on the dialog? How would I resolve this?

答:
This is for 99% the same question as the one from November 10th.

How does my answer there not satisfy your question?

I added the (though commented) line browser.wait(EC.invisibilityOf(blockingElement), 5000); as the answer to your problem.

The moment, an element isClickable doesn't automatically mean, it's also on the front and there is no other object overlaying it. It just means, that the object may receive a click(), because...

element is visible and enabled such that you can click it

Read more about here. You can even inspect the source code.

UPDATE

Given your comments you're having a dialog-popup blocking input, while the page is loading. Therefore you could create your own ExpectedConditions-function, which will always wait until that blocking dialog is gone.

Here is the re-usable function to build, based on the assumption, that this blocker-element will appear on many places:

```<code>var loaded = function(){
    var EC = protractor.ExpectedConditions;
    var blockerElm = $('div[window-class="ult-loading"');
    return EC.invisibilityOf(blockerElm);
}
module.exports = new loaded();
</code>```

Here is how to call it in your test case:

```<code>var loaded = require(pathToLoaded.js);
it('should navigate to the Charts page', function() {
    console.log("Start Charts page test");
    browser.waitForAngularEnabled(false);
    browser.wait(loaded, 5000);
    chartsMenuBtn.click(); //works, if the element is defined as you said
    browser.wait(EC.urlIs(site + '/#/charts'), 5000);
})
</code>```

Body:
I have encountered a strange problem while writing up one of the tests in a test suite I am developing for an AngularJS application using Protractor.

While initially developing the tests, I was using a call to browser.pause() to ensure that I manually had to tell the tests to execute each line while running through the test scripts. I am now happy that the tests that I have written so far are executing correctly & all pass/ fail correctly depending on their criteria.

I now want to remove the call to browser.pause() so that the script can run through each of the tests automatically, without the need for any user interaction. However, because the application is Angular, doing this has caused some issues with timing/ waiting for elements to load before the test steps that reference them are executed- so I am currently going through each of the tests, and trying to ensure that they are allowing the required times for elements to load/ waiting for an element before interacting with it, etc.

When I run my test script at the moment, it is failing on the second test (navigate to the Export page), which I have written as follows:

it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000).then(
        browser.actions().mouseMove(exportMenuBtn).perform().then(
            exportMenuBtn.click().then(
                function() {
                    console.log("Export page test completed ");
                    expect(browser.getCurrentUrl()).toBe(VM + '/#/export');
                }
            )
        )
    );
});

The error message I get in the command line where I'm running my script says:

Failed: unknown error: Element ... is not clickable at point (40, 301). Other element would receive the click:

...

(Session info: chrome=62.0.3202.89)
        (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

which indicates to me that the exportMenuBtn element is not 'clickable' at the point at which my test script is trying to call .click() on it. But this doesn't make sense, since I have used the line browser.wait(EC.elementToBeClickable(exportMenuBtn), 25000) to wait for the exportMenuBtn element to be clickable before I try to click it...

I have tried increasing the time that I wait for the element to be clickable, but this doesn't seem to have made a difference...

Can anyone explain why this test is failing? How can I ensure that the test waits for the exportMenuBtn element to be clickable before it tries to click it?

Edit

So I tried doing what @Ernst Zwingli suggested in their answer- added a function to close the dialog to my spec.js file with:

var pageLoaded = function() {
    var blockingElement = $('div[window-class="ult-loading modal-message"');
    return EC.invisibilityOf(blockingElement);
}
module.exports = new pageLoaded();

and then updated the test script to:

it('should navigate to the Export page', function() {
    browser.waitForAngularEnabled(false);
    browser.wait(pageLoaded, 5000);
    exportMenuBtn.click();
    browser.wait(pageLoaded, 5000);
    browser.wait(EC.urlIs(VM + '/#/export'), 5000);
});

But my test script still fails, giving the same error message:

Failed: unknown error: Element

...

is not clickable at point (40, 301).

Other element would receive the click:

...

 (Session info: chrome=62.0.3202.89)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

The dialog that seems to be causing the issue is defined in Dialog/service.js with:

function wait(msg, progress, title) {
    // Create a wait dialog
    var dlg = dialogs.wait(
        title,
        msg,
        progress,
        {
            // Disable keyboard ESC to close dialogue instances
            keyboard: false,

            // lock the background window
            backdrop: "static",
            size: "sm",
            windowClass: "ult-loading modal-message",
            animation: false
        }
    );

    // Push the dialog into the pool
    dlgs.push(dlg);

    // Return the created dialog
    return dlg;
}

This dialog is never actually visible when running the test/ browsing to the page manually, so it seems to be some sort of 'background task' that is run while browsing to/ loading a new page. I should also note that this dialog is defined within a factory:

.factory('DialogMgr', function($rootScope, $document, dialogs) {
    ...
    function wait(...) {
        ...
    }
});

I'm wondering if this possibly has anything to do with the 'fade' animation that is set on the dialog? How would I resolve this?

Body:
This is for 99% the same question as the one from November 10th.

How does my answer there not satisfy your question?

I added the (though commented) line browser.wait(EC.invisibilityOf(blockingElement), 5000); as the answer to your problem.

The moment, an element isClickable doesn't automatically mean, it's also on the front and there is no other object overlaying it. It just means, that the object may receive a click(), because...

element is visible and enabled such that you can click it

Read more about here. You can even inspect the source code.

UPDATE

Given your comments you're having a dialog-popup blocking input, while the page is loading. Therefore you could create your own ExpectedConditions-function, which will always wait until that blocking dialog is gone.

Here is the re-usable function to build, based on the assumption, that this blocker-element will appear on many places:

var loaded = function(){
    var EC = protractor.ExpectedConditions;
    var blockerElm = $('div[window-class="ult-loading"');
    return EC.invisibilityOf(blockerElm);
}
module.exports = new loaded();

Here is how to call it in your test case:

var loaded = require(pathToLoaded.js);
it('should navigate to the Charts page', function() {
    console.log("Start Charts page test");
    browser.waitForAngularEnabled(false);
    browser.wait(loaded, 5000);
    chartsMenuBtn.click(); //works, if the element is defined as you said
    browser.wait(EC.urlIs(site + '/#/charts'), 5000);
})


问:
Why DDMS will disable ADB integration in android studio
I was confused about a new problem since yesterday. I am now using DDMS to debug my app on my android device. It used to appear that I instant run the app from android studio it notices me i need to enable ADB integration, but not often. Since last night, once I enable ADB integration, ddms will not be able to capture log from device it goes "Adb connection Error:An existing connection was forcibly closed by the remote host" in DDMS. and if I restart the DDMS, it will turn ADB integration disable which results I cant pass app to my device. if enable it, DDMS not working again. I know there must be something like port conflicted but i totally have no idea how to solve it.
BTW, I noticed there is another android monitor in studio which is not so powerful, i am not going to use it. Is it the reason due to NO TWO MONITORS AT SAME TIME?
many thanks for anyone's any help    </p>

答: Since the latest versions of Android Studio, you can explore the data by clicking on "Device File Explorer" that located at the bottom right corner. See the attached snap.


问:
javascript, how to iterate parsed json correctly
Hi I have a json response that I have to parse. I want to pull the data and insert it into inputs value (if it exists)

My json is like this:

```<code>{"id":4,"comb_name":"Monitor__C9cGTqnM7Trz","resolution":null,"attribute_val":3,"porte":4, "deleted_at":null,"created_at":"2017-11-13 10:10:25","updated_at":"2017-11-13 10:10:25"}
</code>```

The code:

```<code>    if(isset(jsobj)) {
        var parsed = JSON.parse(jsobj);
        console.log(parsed);
        for (var property in parsed) {
            if(parsed.hasOwnProperty(property)) {
                var possible_input = '#pro_' + property;
                if($(possible_input).length) {
                    var actual_input = $(possible_input);
                    actual_input.val(property);
                }
            }
        }
    }
</code>```

It actually works, the only problem is that "property" are "attribute_val", not "3". What can I do to grab the value of the property?

答:
Just use the property name to access the value
actual_input.val(parsed[property]);

Body:
Hi I have a json response that I have to parse. I want to pull the data and insert it into inputs value (if it exists)

My json is like this:

{"id":4,"comb_name":"Monitor__C9cGTqnM7Trz","resolution":null,"attribute_val":3,"porte":4, "deleted_at":null,"created_at":"2017-11-13 10:10:25","updated_at":"2017-11-13 10:10:25"}

The code:

    if(isset(jsobj)) {
        var parsed = JSON.parse(jsobj);
        console.log(parsed);
        for (var property in parsed) {
            if(parsed.hasOwnProperty(property)) {
                var possible_input = '#pro_' + property;
                if($(possible_input).length) {
                    var actual_input = $(possible_input);
                    actual_input.val(property);
                }
            }
        }
    }

It actually works, the only problem is that "property" are "attribute_val", not "3". What can I do to grab the value of the property?


问:
Sed substitute: make a group operator optional
Let's say I want to use sed to substitute expressions like "foo", "foo(1 1)", "foo(42 1)" by "bar". I tried :

```<code>sed -i ':a;N;$!ba;s/foo([0-9]\+ [0-9]\+)\{0,1\}/bar/g' input.file
</code>```

But only replaced expressions with parenthesis after foo, not foo with no parenthesis.

Do you have any idea why ?

Example of I wish:

INPUT

```<code>foo
foo(236 124)
</code>```

OUPUT

```<code>bar
bar
</code>```

Body:
Let's say I want to use sed to substitute expressions like "foo", "foo(1 1)", "foo(42 1)" by "bar". I tried :

sed -i ':a;N;$!ba;s/foo([0-9]\+ [0-9]\+)\{0,1\}/bar/g' input.file

But only replaced expressions with parenthesis after foo, not foo with no parenthesis.

Do you have any idea why ?

Example of I wish:

INPUT

foo
foo(236 124)

OUPUT

bar
bar

Body:
With GNU sed:

sed -E 's/foo(\([0-9]+ [0-9]+\))?/bar/' file


问:
Compress-Archive Error: Cannot access the file because it is being used by another process
I would like to zip a path (with a service windows running inside).

When the service is stopped, it works perfectly, when the service is running, I have the exception:

The process cannot access the file because it is being used by another
  process.

However, when I zip with 7-zip, I don't have any exception.

My command:

```<code>Compress-Archive [PATH] -CompressionLevel Optimal -DestinationPath("[DEST_PATH]") -Force
</code>```

Do you have any idea to perform the task without this exception?

答:
A good method to access files being used by another process is by creating snapshots using Volume Shadow Copy Service.

To do so, one can simply use PowerShells WMI Cmdlets:

```<code>$Path = "C:/my/used/folder"
$directoryRoot = [System.IO.Directory]::GetDirectoryRoot($Path).ToString()

$shadow = (Get-WmiObject -List Win32_ShadowCopy).Create($directoryRoot, "ClientAccessible")
$shadowCopy = Get-WmiObject Win32_ShadowCopy | ? { $_.ID -eq $shadow.ShadowID }
$snapshotPath = $shadowCopy.DeviceObject + "\" + $Path.Replace($directoryRoot, "")
</code>```

Now you can use the $snapshotPath as -Path for your Compress-Archive call.

This method can also be used to create backups with symlinks.
From there on you can use the linked folders to copy backed up files, or to compress them without those Access exceptions.

I created a similiar function and a small Cmdlet in this Gist: Backup.ps1

Body:
I would like to zip a path (with a service windows running inside).

When the service is stopped, it works perfectly, when the service is running, I have the exception:

The process cannot access the file because it is being used by another
  process.

However, when I zip with 7-zip, I don't have any exception.

My command:

Compress-Archive [PATH] -CompressionLevel Optimal -DestinationPath("[DEST_PATH]") -Force

Do you have any idea to perform the task without this exception?

Body:
A good method to access files being used by another process is by creating snapshots using Volume Shadow Copy Service.

To do so, one can simply use PowerShells WMI Cmdlets:

$Path = "C:/my/used/folder"
$directoryRoot = [System.IO.Directory]::GetDirectoryRoot($Path).ToString()

$shadow = (Get-WmiObject -List Win32_ShadowCopy).Create($directoryRoot, "ClientAccessible")
$shadowCopy = Get-WmiObject Win32_ShadowCopy | ? { $_.ID -eq $shadow.ShadowID }
$snapshotPath = $shadowCopy.DeviceObject + "\" + $Path.Replace($directoryRoot, "")

Now you can use the $snapshotPath as -Path for your Compress-Archive call.

This method can also be used to create backups with symlinks.
From there on you can use the linked folders to copy backed up files, or to compress them without those Access exceptions.

I created a similiar function and a small Cmdlet in this Gist: Backup.ps1


问:
How to get Create Account Link in Liferay 7 or DXP form themeDisplay
In Liferay 6 it was possible to get various types of links, for example you could get CreateAccount link from themeDiplay by using themeDisplay.getURLCreateAccount().toString(). Check this link

Recently I've migrated to Liferay 7. In my custom theme when I am working with .ftl files I'd like to have create account link but I can't find any suitable methods for it. Although you can find getURLSignIn() and getURLSignOut. Check this link

Is there any chance to find a create account url by themeDisplay? If not what should I do?

答:
Use action commands in Liferay 7 to call the create account in the JSP

Example :

https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/mvc-action-command


问:
Objective C NSThread and anonymous function
Trying to use NSThread::detachNewThreadSelector with anonymous function

```<code>void (^testA)(void) = ^
{
 NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];

 NSLog(@"in threadA",nil);

 [oPool release];
};

[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];
</code>```

when I'm trying to run application I got error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'
</code>```

can anyone give me a hand with that?

答:
To use that NSThread API, you mist have an object and a selector. While a block is technically an object, it doesn't have any methods that you can invoke. As such, there's nothing you could pass in the action parameter that would make this work.

If you want to execute a block asynchronously, there are a couple ways you can do it:

Use Grand Central Dispatch's dispatch_async() function, or one of the appropriate variants.

Give the block to an NSBlockOperation, and hand that off to an NSOperationQueue.

Create a method on an object that takes a block parameter and simply executes it, and then pass that object and selector, along with the block, to the NSThread API. Don't forget to -copy the block first, or you'll probably crash.

Body:
Trying to use NSThread::detachNewThreadSelector with anonymous function

void (^testA)(void) = ^
{
 NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];

 NSLog(@"in threadA",nil);

 [oPool release];
};

[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];

when I'm trying to run application I got error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'

can anyone give me a hand with that?


问:
implementing a callback in android with Activities
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.</p>

```<code>public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}
</code>```

答:
For this purpose I use Singleton approach.

```<code>class ActivityCommunication {
private static ActivityCommunication instance = null;
private MainCallback mainCallback = null;

private ActivityCommunication() {
}

public static ActivityCommunication getInstance() {
    if (instance == null) {
        instance = new ActivityCommunication();
    }
    return instance;
}

public void setMainCallBackListener(MainCallback mainCallback) {
    this.mainCallback = mainCallback;
}

public void sendDataToMainActivity(Data data) {
    if (mainCallback != null) {
        mainCallback.onMainCallBack(data);
    }
}

public interface MainCallback {
    void onMainCallBack(Data data);
}
}
</code>```

On MainActivity set the listener

```<code> ActivityCommunication.getInstance().setMainCallBackListener();
</code>```

On from ActivityB, send the data when you need

```<code> ActivityCommunication.getInstance().sendDataToMainActivity(myData);
</code>```

Implemented onMainCallBack method will be then called.

Body:
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.

public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}

Body:
For this purpose I use Singleton approach.

class ActivityCommunication {
private static ActivityCommunication instance = null;
private MainCallback mainCallback = null;

private ActivityCommunication() {
}

public static ActivityCommunication getInstance() {
    if (instance == null) {
        instance = new ActivityCommunication();
    }
    return instance;
}

public void setMainCallBackListener(MainCallback mainCallback) {
    this.mainCallback = mainCallback;
}

public void sendDataToMainActivity(Data data) {
    if (mainCallback != null) {
        mainCallback.onMainCallBack(data);
    }
}

public interface MainCallback {
    void onMainCallBack(Data data);
}
}

On MainActivity set the listener

 ActivityCommunication.getInstance().setMainCallBackListener();

On from ActivityB, send the data when you need

 ActivityCommunication.getInstance().sendDataToMainActivity(myData);

Implemented onMainCallBack method will be then called.


问:
build/install/<project>-shadow directory -- what is it?
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

build file:

```<code>plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}
</code>```

project after aborted runShadow:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

```<code>thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$
</code>```

(The wi-fi can be a bit flaky.)

答:
Your problem is unclear to me, as far as I can see error msg is quite clear what is wrong.

Not sure what is the workaround you posted as well, I said in the comment to run clean, because presumably, that's what the plugin demands, just check the source code of the plugin if interested why.

Anyway.

The Shadow plugin will also configure distribution tasks when in the presence of the application plugin. The plugin will create shadowDistZip and shadowDistTar which creates Zip and Tar distributions respectively. Each distribution will contain the shadowed JAR file along with the necessary start scripts to launch the application.

Additionally, the plugin will create the installShadowDist and startShadowScripts tasks which stages the necessary files for a distribution to build/install/-shadow/.

Another thing is that mainClassName

Just like the normal jar task, when the application plugin is applied, the shadowJar manifest will be configured to contain the Main-Class attribute with the value specified in the project’s mainClassName attribute.

runShadow is a javaExec task probably needs configuring?

```<code>runShadow {
  // classpath = sourceSets.main.runtimeClasspath

  main = 'net.bounceme.dur.gradle.hello.App'

  // arguments to pass to the application
  // args 'appArg1'
}
</code>```

When applied along with the application plugin, the runShadow task will be created for starting the application from the shadowed JAR. The runShadow task is a JavaExec task that is configured to execute java -jar myproject-all.jar. It can be configured the same as any other JavaExec task.

ShadowJar Documentation

Body:
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$

build file:

plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}

project after aborted runShadow:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$

(The wi-fi can be a bit flaky.)

Body:
Your problem is unclear to me, as far as I can see error msg is quite clear what is wrong.

Not sure what is the workaround you posted as well, I said in the comment to run clean, because presumably, that's what the plugin demands, just check the source code of the plugin if interested why.

Anyway.

The Shadow plugin will also configure distribution tasks when in the presence of the application plugin. The plugin will create shadowDistZip and shadowDistTar which creates Zip and Tar distributions respectively. Each distribution will contain the shadowed JAR file along with the necessary start scripts to launch the application.

Additionally, the plugin will create the installShadowDist and startShadowScripts tasks which stages the necessary files for a distribution to build/install/-shadow/.

Another thing is that mainClassName

Just like the normal jar task, when the application plugin is applied, the shadowJar manifest will be configured to contain the Main-Class attribute with the value specified in the project’s mainClassName attribute.

runShadow is a javaExec task probably needs configuring?

runShadow {
  // classpath = sourceSets.main.runtimeClasspath

  main = 'net.bounceme.dur.gradle.hello.App'

  // arguments to pass to the application
  // args 'appArg1'
}

When applied along with the application plugin, the runShadow task will be created for starting the application from the shadowed JAR. The runShadow task is a JavaExec task that is configured to execute java -jar myproject-all.jar. It can be configured the same as any other JavaExec task.

ShadowJar Documentation


问:
Event sourcing: denormalizing relationships in projections
I'm working on a CQRS/ES architecture. We run multiple asynchronous projections into the read stores in parallel because some projections might be much slower than others and we want to stay more in sync with the write side for the faster projections.

I'm trying to understand the approaches on how I can generate the read models and how much data-duplication this might entail.

Let's take an order with items as a simplified example. An order can have multiple items, each item has a name. Items and orders are separate aggregates.

I could either try to save the read models in a more normalized fashion, where I create an entity or document for each item and order and then reference them - or I maybe would like to save it in a more denormalized manner where I have an order which contains items.

Normalized

```<code>{
  Id: Order1,
  Items: [Item1, Item2]
}

{
  Id: Item1,
  Name: "Foosaver 9000"
}

{
  Id: Item2,
  Name: "Foosaver 7500"
}
</code>```

Using a more normalized format would allow a single projection to process events that affect/effect item and orders and update the corresponding objects. It would also mean that any changes to the item name affect all orders. A customer might get a delivery note for different items than the corresponding invoice for example (so obviously that model might not be good enough and lead us to the same issues as denormalizing...)

Denormalized

```<code>{
  Id: Order1,
  Items: [
    {Id: Item1, Name: "Foosaver 9000"},
    {Id: Item2, Name: "Foosaver 7500"},
  ]
}
</code>```

Denormalizing however would require some source where I can look up the current related data - such as the item. This means that I either have to transport all the information I might need in the event, or I'll have to keep track of the data that I source for my denormalization. This would also mean that I might have to do this once for each projection - i.e. I might need a denormalized ItemForOrder as well as a denormalized ItemForSomethingElse - both only containing the bare minimum properties that each of the denormalized entities or documents need (whenever they are created or modified).

If I would share the same Item in the read store, I could end up mixing item definitions from different points of time, because the projections for items and orders might not run at the same pace. In the worst case, the projection for items might not have yet created the item I need to source for its properties.

Generally, what approaches do I have when processing relationships from an event stream?

update 2016-06-17

Currently, I'm solving this by running a single projection per denormalised read model and its related data. If I have multiple read models that have to share the same related data, then I might put them into the same projection to avoid duplicating the same related data I need for the lookup.

These related models might even be somewhat normalised, optimised for however I have to access them. My projection is the only thing that reads and writes to them, so I know exactly how they are read.

```<code>// related data
public class Item
{
  public Guid Id {get; set;}
  public string Name {get; set;}
  /* and whatever else is needed but not provided by events */
}

// denormalised info for document
public class ItemInfo
{
  public Guid Id {get; set;}
  public string Name {get; set;}
}

// denormalised data as document
public class ItemStockLevel
{
  public ItemInfo Item {get; set;} // when this is a document
  public decimal Quantity {get; set;}
}

// or for RDBMS
public class ItemStockLevel
{
  public Guid ItemId {get; set;}
  public string ItemName {get; set;}
  public decimal Quantity {get; set;}
}
</code>```

However, the more hidden issue here is that of when to update which related data. This is heavily dependent on the business process.

For example, I wouldn't want to change the item descriptions of an order after it has been placed. I must only update the data that changed according to the business process when the projection processes an event.

Therefore, the argument could be made towards putting this information into the event (and using the data as the client sent it?). If we find that we need additional data later, then we might have to fall back to projecting the related data from the event stream and read it from there...

This could be seen as a similar issue for pure CQRS architectures: when do you update the denormalised data in your documents? When do you refresh the data before presenting it to the user? Again, the business process might drive this decision.

答: I also had this problem and tried diferent things. I read this suggestion and while I did not tried it yet, I think it may be the best way to go. Just enrich events before publishing them.</p>

Body:
I'm working on a CQRS/ES architecture. We run multiple asynchronous projections into the read stores in parallel because some projections might be much slower than others and we want to stay more in sync with the write side for the faster projections.

I'm trying to understand the approaches on how I can generate the read models and how much data-duplication this might entail.

Let's take an order with items as a simplified example. An order can have multiple items, each item has a name. Items and orders are separate aggregates.

I could either try to save the read models in a more normalized fashion, where I create an entity or document for each item and order and then reference them - or I maybe would like to save it in a more denormalized manner where I have an order which contains items.

Normalized

{
  Id: Order1,
  Items: [Item1, Item2]
}

{
  Id: Item1,
  Name: "Foosaver 9000"
}

{
  Id: Item2,
  Name: "Foosaver 7500"
}

Using a more normalized format would allow a single projection to process events that affect/effect item and orders and update the corresponding objects. It would also mean that any changes to the item name affect all orders. A customer might get a delivery note for different items than the corresponding invoice for example (so obviously that model might not be good enough and lead us to the same issues as denormalizing...)

Denormalized

{
  Id: Order1,
  Items: [
    {Id: Item1, Name: "Foosaver 9000"},
    {Id: Item2, Name: "Foosaver 7500"},
  ]
}

Denormalizing however would require some source where I can look up the current related data - such as the item. This means that I either have to transport all the information I might need in the event, or I'll have to keep track of the data that I source for my denormalization. This would also mean that I might have to do this once for each projection - i.e. I might need a denormalized ItemForOrder as well as a denormalized ItemForSomethingElse - both only containing the bare minimum properties that each of the denormalized entities or documents need (whenever they are created or modified).

If I would share the same Item in the read store, I could end up mixing item definitions from different points of time, because the projections for items and orders might not run at the same pace. In the worst case, the projection for items might not have yet created the item I need to source for its properties.

Generally, what approaches do I have when processing relationships from an event stream?

update 2016-06-17

Currently, I'm solving this by running a single projection per denormalised read model and its related data. If I have multiple read models that have to share the same related data, then I might put them into the same projection to avoid duplicating the same related data I need for the lookup.

These related models might even be somewhat normalised, optimised for however I have to access them. My projection is the only thing that reads and writes to them, so I know exactly how they are read.

// related data
public class Item
{
  public Guid Id {get; set;}
  public string Name {get; set;}
  /* and whatever else is needed but not provided by events */
}

// denormalised info for document
public class ItemInfo
{
  public Guid Id {get; set;}
  public string Name {get; set;}
}

// denormalised data as document
public class ItemStockLevel
{
  public ItemInfo Item {get; set;} // when this is a document
  public decimal Quantity {get; set;}
}

// or for RDBMS
public class ItemStockLevel
{
  public Guid ItemId {get; set;}
  public string ItemName {get; set;}
  public decimal Quantity {get; set;}
}

However, the more hidden issue here is that of when to update which related data. This is heavily dependent on the business process.

For example, I wouldn't want to change the item descriptions of an order after it has been placed. I must only update the data that changed according to the business process when the projection processes an event.

Therefore, the argument could be made towards putting this information into the event (and using the data as the client sent it?). If we find that we need additional data later, then we might have to fall back to projecting the related data from the event stream and read it from there...

This could be seen as a similar issue for pure CQRS architectures: when do you update the denormalised data in your documents? When do you refresh the data before presenting it to the user? Again, the business process might drive this decision.


问:
Using Delete method to delete substring with special char and numbers in java
I am trying to write a small functionality to delete the irregular expression that are generated while copying text from old browsers. I have to specifically use StringBuilder delete() method for this.
Below a sample code snippet that I wrote. While it identifies the correct characters its deleting just the next iteration
`

```<code>    String input = buff.readLine();
            StringBuilder sb = new StringBuilder(input);
            Pattern p = Pattern.compile("[0-9/$&+,:;=?@#/]");
            Matcher m = p.matcher(input);
                while(m.find()){

                    sb.delete(m.start(), m.end());
                }

            System.out.println("Formatted content\n"+sb);
//input: this is &^4567 matcher
//expected output: this is matcher
//output: this is ^46 acher
</code>```

`

答:
Basically, when you have removed one character from the string buffer, the index available with matcher are no longer accurate. You can verify this by printing out the string before and after the call to sb.delete...
Add following line of code after sb.delete() to fix it.This will ensure that matcher searched for pattern again  and has the correctr indices.</p>

```<code> m = p.matcher(sb);
</code>```

Body:
I am trying to write a small functionality to delete the irregular expression that are generated while copying text from old browsers. I have to specifically use StringBuilder delete() method for this.
Below a sample code snippet that I wrote. While it identifies the correct characters its deleting just the next iteration
`

    String input = buff.readLine();
            StringBuilder sb = new StringBuilder(input);
            Pattern p = Pattern.compile("[0-9/$&+,:;=?@#/]");
            Matcher m = p.matcher(input);
                while(m.find()){

                    sb.delete(m.start(), m.end());
                }

            System.out.println("Formatted content\n"+sb);
//input: this is &^4567 matcher
//expected output: this is matcher
//output: this is ^46 acher

`

Body:
Basically, when you have removed one character from the string buffer, the index available with matcher are no longer accurate. You can verify this by printing out the string before and after the call to sb.delete...
Add following line of code after sb.delete() to fix it.This will ensure that matcher searched for pattern again  and has the correctr indices.

 m = p.matcher(sb);