问:
Task always on status Waiting for Activation (finding all serial devices)
Currently i have a problem that this piece of code gives me a task that is always on waiting for activation status.

```<code>public static void GetAvailablePorts(List<string> ports, int timeOut)
    {
        var selector = SerialDevice.GetDeviceSelector();
        var task = DeviceInformation.FindAllAsync(selector).AsTask();
        Int64 i = 0;
        bool done = false;
        while (!done)
        {
            Debug.WriteLine(String.Format("Index: {0}, State: {1}, Id: {2}", i, task.Status.ToString(), task.Id));
            i++;
            if(TaskStatus.RanToCompletion == task.Status)
                done = true;
        }

        var devices = task.Result;
        foreach (var d in devices)
        {
            ports.Add(d.Id);
        }
    }
</code>```

Here are some debug information while running this piece on my end. Does anyone know what the problem is.

In debug output(the end):

```<code> Index: 7496, State: WaitingForActivation, Id: 21
 Index: 7497, State: WaitingForActivation, Id: 21
 Index: 7498, State: WaitingForActivation, Id: 21
 Index: 7499, State: WaitingForActivation, Id: 21
 Index: 7500, State: WaitingForActivation, Id: 21
 Index: 7501, State: WaitingForActivation, Id: 21
 Index: 7502, State: WaitingForActivation, Id: 21
 Index: 7503, State: WaitingForActivation, Id: 21
</code>```

Task window of a different run but should serve the same purpose:
Task Window

Update:

If i do this it doesn't go into the continueWith 90% of the time. Bit weird.

```<code>var selector = SerialDevice.GetDeviceSelector();
        return DeviceInformation.FindAllAsync(selector).AsTask().ContinueWith((Task<DeviceInformationCollection> previous) =>
        {
            var devices = previous.Result;
            foreach (var d in devices)
            {
                ports.Add(d.Id);
            }
            string b = "";
        });
</code>```

update 2:

After some time. 15 min? i get this error back:

A COM call (IID: {45180254-082E-5274-B2E7-AC0517F44D07}, method index: 8) to an ASTA (thread 9164) appears deadlocked and was timed out.)

Anyone know what is going on?

答:
You will need some changes in your code.

Instead of public static void GetAvailablePorts you should write public async Task GetAvailablePorts

Then later on instead of var devices = task.Result; you should write var devices = await task;

A good reference to understand the async / await pattern can be found here: https://markheath.net/post/async-antipatterns

Body:
Currently i have a problem that this piece of code gives me a task that is always on waiting for activation status.

public static void GetAvailablePorts(List<string> ports, int timeOut)
    {
        var selector = SerialDevice.GetDeviceSelector();
        var task = DeviceInformation.FindAllAsync(selector).AsTask();
        Int64 i = 0;
        bool done = false;
        while (!done)
        {
            Debug.WriteLine(String.Format("Index: {0}, State: {1}, Id: {2}", i, task.Status.ToString(), task.Id));
            i++;
            if(TaskStatus.RanToCompletion == task.Status)
                done = true;
        }

        var devices = task.Result;
        foreach (var d in devices)
        {
            ports.Add(d.Id);
        }
    }

Here are some debug information while running this piece on my end. Does anyone know what the problem is.

In debug output(the end):

 Index: 7496, State: WaitingForActivation, Id: 21
 Index: 7497, State: WaitingForActivation, Id: 21
 Index: 7498, State: WaitingForActivation, Id: 21
 Index: 7499, State: WaitingForActivation, Id: 21
 Index: 7500, State: WaitingForActivation, Id: 21
 Index: 7501, State: WaitingForActivation, Id: 21
 Index: 7502, State: WaitingForActivation, Id: 21
 Index: 7503, State: WaitingForActivation, Id: 21

Task window of a different run but should serve the same purpose:
Task Window

Update:

If i do this it doesn't go into the continueWith 90% of the time. Bit weird.

var selector = SerialDevice.GetDeviceSelector();
        return DeviceInformation.FindAllAsync(selector).AsTask().ContinueWith((Task<DeviceInformationCollection> previous) =>
        {
            var devices = previous.Result;
            foreach (var d in devices)
            {
                ports.Add(d.Id);
            }
            string b = "";
        });

update 2:

After some time. 15 min? i get this error back:

A COM call (IID: {45180254-082E-5274-B2E7-AC0517F44D07}, method index: 8) to an ASTA (thread 9164) appears deadlocked and was timed out.)

Anyone know what is going on?


来源: stackexchange

问:
How do i use a variable in the columns section of an ajax request for data tables
I'm trying to add dynamic values for the column section in an ajax request so that the users can have control over what fields are in the data tables.

I tried with default values and it worked but when i changed to use dynamic values from a variable, the ajax field gives me errors

this works fine;

```<code>$(function() {
            $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: [
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'address', name: 'address' },
                    { data: 'contact', name: 'contact' },
                    { data: 'nationality', name: 'nationality' },
                    { data: 'dob', name: 'dob' },
                    { data: 'hometown', name: 'hometown' },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });
        });
</code>```

this is where the problem comes in;

```<code>$(function() {
            $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: [
                    var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
                    for(var i = 0; i < memberFields.length; i++){
                        { data: memberFields[i], name: memberFields[i] };
                    },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });
        });
</code>```

答:
Thats because column property wants an array .
And your structure to build array is incorrect .

Do this :

```<code>$(function() {

    var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
    var columnArray = [];//To save for value into an Array
    for(var i = 0; i < memberFields.length; i++){
        columnArray.push({ data: memberFields[i], name: memberFields[i] });//push valuse to array
    },
    columnArray.push({ data: 'action', name: 'action', orderable: false, searchable: false });//push last value

    $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: columnArray ,  //just say Array name !
    });

});
</code>```

Didnt test but hope works

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add dynamic values for the column section in an ajax request so that the users can have control over what fields are in the data tables.

I tried with default values and it worked but when i changed to use dynamic values from a variable, the ajax field gives me errors

this works fine;

$(function() {
            $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: [
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'address', name: 'address' },
                    { data: 'contact', name: 'contact' },
                    { data: 'nationality', name: 'nationality' },
                    { data: 'dob', name: 'dob' },
                    { data: 'hometown', name: 'hometown' },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });
        });

this is where the problem comes in;

$(function() {
            $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: [
                    var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
                    for(var i = 0; i < memberFields.length; i++){
                        { data: memberFields[i], name: memberFields[i] };
                    },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });
        });

Body:
Thats because column property wants an array .
And your structure to build array is incorrect .

Do this :

$(function() {

    var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
    var columnArray = [];//To save for value into an Array
    for(var i = 0; i < memberFields.length; i++){
        columnArray.push({ data: memberFields[i], name: memberFields[i] });//push valuse to array
    },
    columnArray.push({ data: 'action', name: 'action', orderable: false, searchable: false });//push last value

    $('#myTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('members.create') }}',
                columns: columnArray ,  //just say Array name !
    });

});

Didnt test but hope works


问:
Using Docker in interactive mode using an official Microsoft .Net Core SDK image
I'm trying to enter interactive mode using an official Microsoft .Net Core image and use typical .Net commands such as 'dotnet build', but all I get is an '>' cursor. What am I doing wrong?

I'm using the following command:

```<code>docker run -it -v $(pwd):/app' -w '/app' -p 8000:80 mcr.microsoft.com/dotnet/core/sdk /bin/bash
</code>```

I was hoping to get a root command prompt, but all I'm getting is '>'

答:
```<code>Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a
                             container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format:
                             <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container
</code>```

After running your container, run command docker ps to take [Container ID]

And after you are able to run the command like there docker exec -it [Container ID] bash .

Body:
I'm trying to enter interactive mode using an official Microsoft .Net Core image and use typical .Net commands such as 'dotnet build', but all I get is an '>' cursor. What am I doing wrong?

I'm using the following command:

docker run -it -v $(pwd):/app' -w '/app' -p 8000:80 mcr.microsoft.com/dotnet/core/sdk /bin/bash

I was hoping to get a root command prompt, but all I'm getting is '>'

Body:
Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a
                             container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format:
                             <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container

After running your container, run command docker ps to take [Container ID]

And after you are able to run the command like there docker exec -it [Container ID] bash .


问:
Can we run SQL script using code first migrations?
Can we run sql script using code first migrations?

I am new to code first and if I want to save my changes to a SQL script file before update-database command of migration, is it possible?

If possible then please provide steps to get it done. Also if script is generated then is it possible that I can run that script using migration?

答:
For .NET Core and EF Core you can do something like this in migrations</p>

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
   var schema = "starter_core";
   migrationBuilder.Sql($"INSERT INTO [{schema}].[Roles] ([Name]) VALUES ('transporter')");
}
</code>```

Body:
For .NET Core and EF Core you can do something like this in migrations

protected override void Up(MigrationBuilder migrationBuilder)
{
   var schema = "starter_core";
   migrationBuilder.Sql($"INSERT INTO [{schema}].[Roles] ([Name]) VALUES ('transporter')");
}


问:
PHP sort by arbitrary order
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

```<code>public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}
</code>```

答:
```<code>public static function sortWords($inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    $sorted_array = array_diff($inputArray,$order);
    sort($sorted_array);
    $rest_array = array_intersect($order,$inputArray);
    $result = array_merge($rest_array,$sorted_array);
    return $result;
}
</code>```

Haven't tested but try this.

ContentLicense: CC BY-SA 3.0

Title: PHP sort by arbitrary order

Body:
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}

Body:
public static function sortWords($inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    $sorted_array = array_diff($inputArray,$order);
    sort($sorted_array);
    $rest_array = array_intersect($order,$inputArray);
    $result = array_merge($rest_array,$sorted_array);
    return $result;
}

Haven't tested but try this.


问:
Julia DataFrames equivalent of pandas pct_change()
Currently, I have written the below function for percent change calculation:

```<code>function pct_change(input::AbstractVector{<:Number})::AbstractVector{Number}
    result = [NaN]
    for i in 2:length(input)
        push!(result, (input[i] - input[i-1])/abs(input[i-1]))
    end
    return result
end
</code>```

This works as expected. But wanted to know whether there is a built-in function for Julia DataFrames similar to pandas pct_change which I can use directly? Or any other better way or improvements that I can make to my function above?

答:
This is a very specific function and is not provided in DataFrames.jl, but rather TimeSeries.jl. Here is an example:

```<code>julia> using TimeSeries, Dates

julia> ta = TimeArray(Date(2018, 1, 1):Day(1):Date(2018, 12, 31), 1:365);

julia> percentchange(ta);
</code>```

(there are some more options to what should be calculated)

The drawback is that it accepts only TimeArray objects and that it drops periods for which percent change cannot be calculated (as they are retained in Python).

If you want your custom definition consider denoting the first value as missing rather than NaN, as missing. Also your function will not produce the most accurate representation of the numbers (e.g. if you wanted to use BigFloat or exact calculations using Rational type they will be converted to Float64). Here are example alternative function implementations that avoid these problems:

```<code>function pct_change(input::AbstractVector{<:Number})
    res = @view(input[2:end]) ./ @view(input[1:end-1]) .- 1
    [missing; res]
end
</code>```

or

```<code>function pct_change(input::AbstractVector{<:Number})
    [i == 1 ? missing : (input[i]-input[i-1])/input[i-1] for i in eachindex(input)]
end
</code>```

And now you have in both cases:

```<code>julia> pct_change(1:10)
10-element Array{Union{Missing, Float64},1}:
  missing
 1.0
 0.5
 0.33333333333333326
 0.25
 0.19999999999999996
 0.16666666666666674
 0.1428571428571428
 0.125
 0.11111111111111116

julia> pct_change(big(1):10)
10-element Array{Union{Missing, BigFloat},1}:
  missing
 1.0
 0.50
 0.3333333333333333333333333333333333333333333333333333333333333333333333333333391
 0.25
 0.2000000000000000000000000000000000000000000000000000000000000000000000000000069
 0.1666666666666666666666666666666666666666666666666666666666666666666666666666609
 0.1428571428571428571428571428571428571428571428571428571428571428571428571428547
 0.125
 0.111111111111111111111111111111111111111111111111111111111111111111111111111113

julia> pct_change(1//1:10)
10-element Array{Union{Missing, Rational{Int64}},1}:
   missing
 1//1
 1//2
 1//3
 1//4
 1//5
 1//6
 1//7
 1//8
 1//9
</code>```

with proper values returned.

Body:
Currently, I have written the below function for percent change calculation:

function pct_change(input::AbstractVector{<:Number})::AbstractVector{Number}
    result = [NaN]
    for i in 2:length(input)
        push!(result, (input[i] - input[i-1])/abs(input[i-1]))
    end
    return result
end

This works as expected. But wanted to know whether there is a built-in function for Julia DataFrames similar to pandas pct_change which I can use directly? Or any other better way or improvements that I can make to my function above?

Body:
This is a very specific function and is not provided in DataFrames.jl, but rather TimeSeries.jl. Here is an example:

julia> using TimeSeries, Dates

julia> ta = TimeArray(Date(2018, 1, 1):Day(1):Date(2018, 12, 31), 1:365);

julia> percentchange(ta);

(there are some more options to what should be calculated)

The drawback is that it accepts only TimeArray objects and that it drops periods for which percent change cannot be calculated (as they are retained in Python).

If you want your custom definition consider denoting the first value as missing rather than NaN, as missing. Also your function will not produce the most accurate representation of the numbers (e.g. if you wanted to use BigFloat or exact calculations using Rational type they will be converted to Float64). Here are example alternative function implementations that avoid these problems:

function pct_change(input::AbstractVector{<:Number})
    res = @view(input[2:end]) ./ @view(input[1:end-1]) .- 1
    [missing; res]
end

or

function pct_change(input::AbstractVector{<:Number})
    [i == 1 ? missing : (input[i]-input[i-1])/input[i-1] for i in eachindex(input)]
end

And now you have in both cases:

julia> pct_change(1:10)
10-element Array{Union{Missing, Float64},1}:
  missing
 1.0
 0.5
 0.33333333333333326
 0.25
 0.19999999999999996
 0.16666666666666674
 0.1428571428571428
 0.125
 0.11111111111111116

julia> pct_change(big(1):10)
10-element Array{Union{Missing, BigFloat},1}:
  missing
 1.0
 0.50
 0.3333333333333333333333333333333333333333333333333333333333333333333333333333391
 0.25
 0.2000000000000000000000000000000000000000000000000000000000000000000000000000069
 0.1666666666666666666666666666666666666666666666666666666666666666666666666666609
 0.1428571428571428571428571428571428571428571428571428571428571428571428571428547
 0.125
 0.111111111111111111111111111111111111111111111111111111111111111111111111111113

julia> pct_change(1//1:10)
10-element Array{Union{Missing, Rational{Int64}},1}:
   missing
 1//1
 1//2
 1//3
 1//4
 1//5
 1//6
 1//7
 1//8
 1//9

with proper values returned.


问:
The bootstrap features of checkbox not working when done using jquery append
The Bootstrap works perfectly fine in html section for the checkbox, but when I use it in the JavaScript section to append a tag, it doesn't work.

I am unable to find any solution.
I want the way it works in html, it to work in the same way when adding with java script.

The bootstrap is not getting used for the checkbox

```<code>let addItem = (value) => {
  $("#todo").append(`<li>
  <div class="custom-control custom-checkbox mb-3">
  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  <label class="custom-control-label" for="customCheck">${value}</label>
  <button type="button" class="btn btn-danger" id="delete"><i class="fas fa-trash"></i></button>
  </div>
  </li>`);
}
</code>```

答: The reason is that bootstrap has already been applied when the html was rendered and it does not reapply after your javasript executes (adding the section)</p>

Body:
The Bootstrap works perfectly fine in html section for the checkbox, but when I use it in the JavaScript section to append a tag, it doesn't work.

I am unable to find any solution.
I want the way it works in html, it to work in the same way when adding with java script.

The bootstrap is not getting used for the checkbox

let addItem = (value) => {
  $("#todo").append(`

  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  ${value}
  <button type="button" class="btn btn-danger" id="delete"></button>

`);
}


问:
Registering a ContentObserver in a Android Service
I am working on parental control/adult content filtering application. This app continuously monitors the calls and smses on a child's mobile and logs all the activity onto a server. For this I am starting a service (MyService.java)
on BOOT_COMPLETED and in the onCreate method of the service I register a contentobserver for the callLog and sms uri ( refer to the code snippet below ) .

Now the issue is, Since I want to monitor every outgoing, incoming call s and sms I want the service to be continuously running ( without being  stopped/killed) . Moreover this Service is being just used for registering content observers and not doing any other processing(its OnstartCommand method is dummy ) , so android OS kills the service after sometime. How do I ensure that the service runs continuously and keeps the contentobserver object alive ?

```
public class MyService extends Service {

    private CallLogObserver clLogObs = null;
    public void onCreate() {
        super.onCreate();
        try{
            clLogObs = new CallLogObserver(this);
            this.getContentResolver().registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI, true, clLogObs);
         }catch(Exception ex)
         {
             Log.e("CallLogData", ex.toString());
         }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
        if( clLogObs !=null  )
        {
            this.getContentResolver().unregisterContentObserver(clLogObs);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return Service.START_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
```

答:
You cannot ensure your service to be running continuously on Android.

For the use-case you mention, it is better to rely on Broadcast receiver like ACTION_NEW_OUTGOING_CALL & SMS_RECEIVED.

If you feel, above supported Broadcast receivers doesn't cover all your use-cases. Use AlaramManager to periodically start your SERVICE and look into CALL_LOGS and SMS table for any change in data and take appropriate action (this may involve check marking the last visited data on CALL_LOGS and SMS table).

Body:
I am working on parental control/adult content filtering application. This app continuously monitors the calls and smses on a child's mobile and logs all the activity onto a server. For this I am starting a service (MyService.java)
on BOOT_COMPLETED and in the onCreate method of the service I register a contentobserver for the callLog and sms uri ( refer to the code snippet below ) .

Now the issue is, Since I want to monitor every outgoing, incoming call s and sms I want the service to be continuously running ( without being  stopped/killed) . Moreover this Service is being just used for registering content observers and not doing any other processing(its OnstartCommand method is dummy ) , so android OS kills the service after sometime. How do I ensure that the service runs continuously and keeps the contentobserver object alive ?

public class MyService extends Service {

    private CallLogObserver clLogObs = null;
    public void onCreate() {
        super.onCreate();
        try{
            clLogObs = new CallLogObserver(this);
            this.getContentResolver().registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI, true, clLogObs);
         }catch(Exception ex)
         {
             Log.e("CallLogData", ex.toString());
         }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
        if( clLogObs !=null  )
        {
            this.getContentResolver().unregisterContentObserver(clLogObs);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return Service.START_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }


问:
Nested query in Reactive Component - ReactJS
I try to update query of the component by using setQuery() prop. My data is structured like this.

```<code>{
    root : {
        category 1: {
            item 1 {...},
            item 2 {...},
        },
        category 2: {
            item 1 {...},
            item 2 {...},
        },
        ...
    }
}
</code>```

I need to get item 1 under the category 1. When user select item 1 I update query like this. But it doesn't work.

```<code>this.props.setQuery({
    "query": {
        "bool": {
        "must": [
            {
            "query_string": {
                "query": 'category 1 AND item 1',
                "fields": ["item", "category", "keywords"],
                "analyzer": "standard"

            }
            }
        ]
        }
    }
});
</code>```

I try find out how to solve this using nested query. But I couldn't find any use full thing. Please give me any clue to achieve this.

答:
I found a solution for this.

```<code>this.props.setQuery({
        query: {
          bool: {
            must: [
              {
                terms: {
                  'parentName': ['category 1']
                },
              },
              {
                terms: {
                  'childName': 'item 1',
                },
              },
            ],
          },
        },
      });
</code>```

I think this will helps to someone.

Body:
I try to update query of the component by using setQuery() prop. My data is structured like this.

{
    root : {
        category 1: {
            item 1 {...},
            item 2 {...},
        },
        category 2: {
            item 1 {...},
            item 2 {...},
        },
        ...
    }
}

I need to get item 1 under the category 1. When user select item 1 I update query like this. But it doesn't work.

this.props.setQuery({
    "query": {
        "bool": {
        "must": [
            {
            "query_string": {
                "query": 'category 1 AND item 1',
                "fields": ["item", "category", "keywords"],
                "analyzer": "standard"

            }
            }
        ]
        }
    }
});

I try find out how to solve this using nested query. But I couldn't find any use full thing. Please give me any clue to achieve this.

Body:
I found a solution for this.

this.props.setQuery({
        query: {
          bool: {
            must: [
              {
                terms: {
                  'parentName': ['category 1']
                },
              },
              {
                terms: {
                  'childName': 'item 1',
                },
              },
            ],
          },
        },
      });

I think this will helps to someone.


问:
Get the total number of group names where there are multiple group names in a single cell surrounded by random text
This is regarding an export of a list from a Sharepoint site where I do not have access to exporting feature, but I can refresh the information in order to gather new information when is added on the Sharepoint site.
The excel list has several columns, out of which one of them is containing names of groups that were created.

There are several thousands of rows, with cells where each cell might contain this kind of data.
I want to be able to only count the number of groups in my excel sheet.

I was initially thinking to find a way to export somehow the data as text and to then try to remove any parts in the string BEFORE the rows (again, all these rows are in the same cell) in order to make the data uniform and to have only the name of the groups and then to try count in a different column the number of items in each cell and to have a sum.

```<code>"Please delete following CORP group:

PRD.12.SYOS.EXOA.XW12LAPP0171.TWSUSERS
PRD.12.SYOS.XW12LAPP0171.Administrators
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSAGENT
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSUSERS
PRD.12.SYOS.VM4P.XW12LAPP0063.ADMINISTRATORS
PRD.12.SYOS.VM4P.XW12LAPP0063.RDP
PRD.12.SYOS.XW12LAPP0063.Administrators"
</code>```

I am a beginner in excel and in coding. I tried using functions in excel like RIGHT, LEFT, MID, LEN but I am still unable to produce anything close to what I need.

I need the total number of the groups in the sheet.

答:
with a helper column you could extract the part after the last dot with

```<code>=MID(A1,LOOKUP(9^9,FIND(".",A1,ROW(1:999)))+1,50)
</code>```

and then count the number of unique group names, which occur with

```<code>=SUMPRODUCT((E1:E99<>"")/COUNTIF(E1:E99,E1:E99&""))
</code>```

Be aware of the fact, that each Administrators and Administrators" get counted as a unique group. You need to strip off unnecessary chars with SUBSTITUTE if you dont want that behaviour.

Body:
This is regarding an export of a list from a Sharepoint site where I do not have access to exporting feature, but I can refresh the information in order to gather new information when is added on the Sharepoint site.
The excel list has several columns, out of which one of them is containing names of groups that were created.

There are several thousands of rows, with cells where each cell might contain this kind of data.
I want to be able to only count the number of groups in my excel sheet.

I was initially thinking to find a way to export somehow the data as text and to then try to remove any parts in the string BEFORE the rows (again, all these rows are in the same cell) in order to make the data uniform and to have only the name of the groups and then to try count in a different column the number of items in each cell and to have a sum.

"Please delete following CORP group:

PRD.12.SYOS.EXOA.XW12LAPP0171.TWSUSERS
PRD.12.SYOS.XW12LAPP0171.Administrators
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSAGENT
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSUSERS
PRD.12.SYOS.VM4P.XW12LAPP0063.ADMINISTRATORS
PRD.12.SYOS.VM4P.XW12LAPP0063.RDP
PRD.12.SYOS.XW12LAPP0063.Administrators"

I am a beginner in excel and in coding. I tried using functions in excel like RIGHT, LEFT, MID, LEN but I am still unable to produce anything close to what I need.

I need the total number of the groups in the sheet.

Body:
with a helper column you could extract the part after the last dot with

=MID(A1,LOOKUP(9^9,FIND(".",A1,ROW(1:999)))+1,50)

and then count the number of unique group names, which occur with

=SUMPRODUCT((E1:E99<>"")/COUNTIF(E1:E99,E1:E99&""))

Be aware of the fact, that each Administrators and Administrators" get counted as a unique group. You need to strip off unnecessary chars with SUBSTITUTE if you dont want that behaviour.


问:
Google Maps zoom out to GPS and markers
I am trying to show three things on map :
GPS (the current location) , Marker 1 , Marker 2, but I am not sure I am doing it right or not ! Here is my code :

```<code> self.startMarker.position = CLLocationCoordinate2D(latitude: self.startLatitude, longitude: self.startLongitude)
 self.startMarker.icon = #imageLiteral(resourceName: "Pin Start")
 self.startMarker.map = self.mapView

 self.endMarker.position = CLLocationCoordinate2D(latitude: self.endLatitude, longitude: self.endLongitude)
 self.endMarker.icon = #imageLiteral(resourceName: "Pin End")
 self.endMarker.map = self.mapView

 let southWest = CLLocationCoordinate2DMake(self.startLatitude,self.startLongitude)
 let northEast = CLLocationCoordinate2DMake(self.endLatitude,self.endLongitude)
 let bounds = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
 let camera = self.mapView.camera(for: bounds, insets:.zero)
 self.mapView.camera = camera!
</code>```

More Code :

```<code>  // MARK: - Google Map

private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            if status == CLAuthorizationStatus.authorizedWhenInUse {
                mapView.isMyLocationEnabled = true
            }
          }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let newLocation = locations.last
            mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14)
            mapView.isMyLocationEnabled = true
        }
</code>```

The result is like this :

What I need :

EDITED

```<code>if let myLocation = self.mapView.myLocation {

let path = GMSMutablePath()
path.add(myLocation.coordinate)
path.add(self.startMarker.position)
path.add(self.endMarker.position)

let bounds = GMSCoordinateBounds(path: path)
                                        self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 40))
</code>```

}

答:
For someone who is looking for solution with Objective-C, This might help</p>

```<code>//Locations
CLLocationCoordinate2D source = CLLocationCoordinate2DMake(19.2880, 72.1587);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake(19.1780, 72.9577);
CLLocationCoordinate2D destination = CLLocationCoordinate2DMake(19.0760, 72.8777);

//Create a GMSMutablePath
GMSMutablePath *path = [GMSMutablePath new];
[path addCoordinate:source];
[path addCoordinate:userLocation];
[path addCoordinate:destination];

//Create bounds
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithPath:path];

//Update the camera position
[mapview animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds]];
</code>```

Title: Google Maps zoom out to GPS and markers

Body:
I am trying to show three things on map :
GPS (the current location) , Marker 1 , Marker 2, but I am not sure I am doing it right or not ! Here is my code :

 self.startMarker.position = CLLocationCoordinate2D(latitude: self.startLatitude, longitude: self.startLongitude)
 self.startMarker.icon = #imageLiteral(resourceName: "Pin Start")
 self.startMarker.map = self.mapView

 self.endMarker.position = CLLocationCoordinate2D(latitude: self.endLatitude, longitude: self.endLongitude)
 self.endMarker.icon = #imageLiteral(resourceName: "Pin End")
 self.endMarker.map = self.mapView

 let southWest = CLLocationCoordinate2DMake(self.startLatitude,self.startLongitude)
 let northEast = CLLocationCoordinate2DMake(self.endLatitude,self.endLongitude)
 let bounds = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
 let camera = self.mapView.camera(for: bounds, insets:.zero)
 self.mapView.camera = camera!

More Code :

  // MARK: - Google Map

private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            if status == CLAuthorizationStatus.authorizedWhenInUse {
                mapView.isMyLocationEnabled = true
            }
          }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let newLocation = locations.last
            mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14)
            mapView.isMyLocationEnabled = true
        }

The result is like this :

What I need :

EDITED

if let myLocation = self.mapView.myLocation {

let path = GMSMutablePath()
path.add(myLocation.coordinate)
path.add(self.startMarker.position)
path.add(self.endMarker.position)

let bounds = GMSCoordinateBounds(path: path)
                                        self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 40))

}

Body:
For someone who is looking for solution with Objective-C, This might help

//Locations
CLLocationCoordinate2D source = CLLocationCoordinate2DMake(19.2880, 72.1587);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake(19.1780, 72.9577);
CLLocationCoordinate2D destination = CLLocationCoordinate2DMake(19.0760, 72.8777);

//Create a GMSMutablePath
GMSMutablePath *path = [GMSMutablePath new];
[path addCoordinate:source];
[path addCoordinate:userLocation];
[path addCoordinate:destination];

//Create bounds
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithPath:path];

//Update the camera position
[mapview animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds]];


问:
problem with paths after installing z3 without being root
I have installed Z3 on a remote server where I am not Root. I changed the prefix during the installation to my directory where I have write access, The installation went smoothly and now I have two directories in my home directory one for the project and one where I unzipped/build/installed z3. when I want to execute a python script that includes:

```<code> from z3 import *
</code>```

I receive this error:

```<code>ModuleNotFoundError: No module named 'z3'
</code>```

I think it's a problem related to paths and my python file can't get to the z3 module, I don't know how to fix this especially that python3 was installed by the root and not by me.

答:
One work around for this is by importing packages using their paths, like

```<code>from ~/z3_folder import *
</code>```

Please share if it works.

Body:
I have installed Z3 on a remote server where I am not Root. I changed the prefix during the installation to my directory where I have write access, The installation went smoothly and now I have two directories in my home directory one for the project and one where I unzipped/build/installed z3. when I want to execute a python script that includes:

 from z3 import *

I receive this error:

ModuleNotFoundError: No module named 'z3'

I think it's a problem related to paths and my python file can't get to the z3 module, I don't know how to fix this especially that python3 was installed by the root and not by me.

Body:
One work around for this is by importing packages using their paths, like

from ~/z3_folder import *

Please share if it works.


问:
How can I push a branch to remote after resolving rebase conflicts without using force push?
I have a Git branch with an open pull request in GitHub. But I can't merge it because GitHub complains that there are some conflicting files with latest master. Then I pull master and rebase master to my local branch and during rebase, I got conflicts. So I resolved the conflicts and when trying to push the branch to origin, my push was rejected and error says that the tip of my current branch is behind. However when I do force push it will get accepted. Anyway I can achieve this without using force push?</p>

答:
Since rebasing alters history, some sort of force-push is required.

Luckily, there's git push --force-with-lease, which will still reject the push if another commit was added to the branch in the meanwhile.


问:
AWS AppSync onUpdate Subscription not working on simulator
I am trying to run the subscription on Android. I am able to make all other queries run like create, update, list, etc on the android client but not subscription. However, on AWS Appsync console I can open two console tabs and create a subscription and add new objects, it's working there, I get callbacks.

None of the methods are triggered on client when I add objects from console(Android simulator).

I am using client key for auth mode.

Below is my code:

```<code> private void subscribeNew(){
        OnCreateRtGuestSubscription subscription = OnCreateRtGuestSubscription.builder().build();
        subscriptionWatcher = mAWSAppSyncClient.subscribe(subscription);
        subscriptionWatcher.execute(new AppSyncSubscriptionCall.Callback() {
            @Override
            public void onResponse(@Nonnull Response response) {
                Log.i("Response", response.data().toString());

            }

            @Override
            public void onFailure(@Nonnull ApolloException e) {
                Log.i("Response", e.toString());

            }

            @Override
            public void onCompleted() {
                Log.i("Response","");

            }
        });
    }
 private AppSyncSubscriptionCall.Callback<OnUpdateRtGuestSubscription> subscriptionCallBack= new AppSyncSubscriptionCall.Callback<OnUpdateRtGuestSubscription>() {
        @Override
        public void onResponse(@Nonnull Response<OnUpdateRtGuestSubscription> response) {
                            Log.i("Response", "");

        }

        @Override
        public void onFailure(@Nonnull ApolloException e) {
                            Log.i("Response", "");

        }

        @Override
        public void onCompleted() {
                            Log.i("Response", "");

        }
    };

    private void subscribeEdit(){
        OnUpdateRtGuestSubscription subscription = OnUpdateRtGuestSubscription.builder().build();
        AppSyncSubscriptionCall subscriptionWatcher=this.mAWSAppSyncClient.subscribe(subscription);
        subscriptionWatcher.execute(subscriptionCallBack);
    }
</code>```

2019-05-27 14:45:55.540 1362-1384/? W/audio_hw_generic: Not supplying
  enough data to HAL, expected position 13086062 , only wrote 13086000
  2019-05-27 14:45:55.548 12881-13064/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Adding
  listener [com.example.umarfarooque.rtdbtest.MainActivity$2@361b720] to
  SubscriptionObject:
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  got:
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  2019-05-27 14:45:55.548 12881-13064/com.example.umarfarooque.rtdbtest
  V/SubscriptionObject: Adding listener to
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@926e8d9
  2019-05-27 14:45:55.551 12881-13063/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Adding
  listener [com.example.umarfarooque.rtdbtest.MainActivity$1@3f740ef] to
  SubscriptionObject:
  com.amazonaws.amplify.generated.graphql.OnUpdateRtGuestSubscription@836217f
  got:
  com.amazonaws.amplify.generated.graphql.OnUpdateRtGuestSubscription@836217f
  2019-05-27 14:45:55.551 12881-13063/com.example.umarfarooque.rtdbtest
  V/SubscriptionObject: Adding listener to
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@47b254c
  2019-05-27 14:45:55.564 12881-13067/com.example.umarfarooque.rtdbtest
  D/RetryInterceptor: Retry Interceptor called 2019-05-27 14:45:55.564
  12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Signer Interceptor called 2019-05-27
  14:45:55.566 12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Subscriber ID is
  61c60911-18ea-4ac2-8a7f-79f13d7b03e6 2019-05-27 14:45:55.773
  12881-13067/com.example.umarfarooque.rtdbtest I/RetryInterceptor:
  Returning network response: success 2019-05-27 14:45:55.775
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: subscribe
  called for
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  2019-05-27 14:45:55.776 12881-13065/com.example.umarfarooque.rtdbtest
  D/RealSubscriptionManager: Subscription Infrastructure: Adding
  subscription object
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@926e8d9
  to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d.
  Total subscription objects: 2 2019-05-27 14:45:55.776
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Attempting to
  make [1] MQTT clients] 2019-05-27 14:45:56.779
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.779
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:56.780 12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.780
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:56.780 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Connecting
  with Client ID[tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.780
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Calling MQTT
  Connect with actual endpoint for client ID[tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:57.143 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Register alarmreceiver to
  MqttServiceMqttService.pingSender.tgvihzfuync35pl4m6ihy6gidu
  2019-05-27 14:45:57.145 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Schedule next alarm at 1558961187145 2019-05-27
  14:45:57.146 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Alarm scheule using setExactAndAllowWhileIdle,
  next: 30000 2019-05-27 14:45:57.151
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Connection
  successful for clientID [tgvihzfuync35pl4m6ihy6gidu]. Will subscribe
  up to 2 topics 2019-05-27 14:45:57.151
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Subscribing to
  MQTT
  topic:[443301200413/eytajgboqjcllkyv6jkqycc4me/onUpdateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d]
  2019-05-27 14:45:57.151 12881-12881/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@5c66981Subscription
  Infrastructure: Attempting to subscribe to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onUpdateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d
  on clientID [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Subscribing to
  MQTT
  topic:[443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d]
  2019-05-27 14:45:57.152 12881-12881/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@5c66981Subscription
  Infrastructure: Attempting to subscribe to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d
  on clientID [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Made [1] MQTT
  clients 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Unmuting the
  new clients [1] in total 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to true for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to true for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:57.152 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Muting the old
  clients [ 1] in total 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [7aybllsw45gfnbuahn3khahrr4] 2019-05-27 14:45:57.153
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [7aybllsw45gfnbuahn3khahrr4]
  2019-05-27 14:45:57.153 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Closing the
  old clients [1] in total 2019-05-27 14:45:57.153
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Closing
  client:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@90ffefa
  2019-05-27 14:45:57.153 12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Closing MQTT client
  [7aybllsw45gfnbuahn3khahrr4 2019-05-27 14:45:57.163
  12881-13067/com.example.umarfarooque.rtdbtest D/RetryInterceptor:
  Retry Interceptor called 2019-05-27 14:45:57.163
  12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Signer Interceptor called 2019-05-27
  14:45:57.163 12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Subscriber ID is
  61c60911-18ea-4ac2-8a7f-79f13d7b03e6 2019-05-27 14:45:57.199
  12881-13040/com.example.umarfarooque.rtdbtest D/AlarmPingSender:
  Unregister alarmreceiver to MqttService7aybllsw45gfnbuahn3khahrr4

答: Try to put the watcher as a class level variable and not declare inside your method.</p>

Body:
I am trying to run the subscription on Android. I am able to make all other queries run like create, update, list, etc on the android client but not subscription. However, on AWS Appsync console I can open two console tabs and create a subscription and add new objects, it's working there, I get callbacks.

None of the methods are triggered on client when I add objects from console(Android simulator).

I am using client key for auth mode.

Below is my code:

 private void subscribeNew(){
        OnCreateRtGuestSubscription subscription = OnCreateRtGuestSubscription.builder().build();
        subscriptionWatcher = mAWSAppSyncClient.subscribe(subscription);
        subscriptionWatcher.execute(new AppSyncSubscriptionCall.Callback() {
            @Override
            public void onResponse(@Nonnull Response response) {
                Log.i("Response", response.data().toString());

            }

            @Override
            public void onFailure(@Nonnull ApolloException e) {
                Log.i("Response", e.toString());

            }

            @Override
            public void onCompleted() {
                Log.i("Response","");

            }
        });
    }
 private AppSyncSubscriptionCall.Callback<OnUpdateRtGuestSubscription> subscriptionCallBack= new AppSyncSubscriptionCall.Callback<OnUpdateRtGuestSubscription>() {
        @Override
        public void onResponse(@Nonnull Response<OnUpdateRtGuestSubscription> response) {
                            Log.i("Response", "");

        }

        @Override
        public void onFailure(@Nonnull ApolloException e) {
                            Log.i("Response", "");

        }

        @Override
        public void onCompleted() {
                            Log.i("Response", "");

        }
    };

    private void subscribeEdit(){
        OnUpdateRtGuestSubscription subscription = OnUpdateRtGuestSubscription.builder().build();
        AppSyncSubscriptionCall subscriptionWatcher=this.mAWSAppSyncClient.subscribe(subscription);
        subscriptionWatcher.execute(subscriptionCallBack);
    }

2019-05-27 14:45:55.540 1362-1384/? W/audio_hw_generic: Not supplying
  enough data to HAL, expected position 13086062 , only wrote 13086000
  2019-05-27 14:45:55.548 12881-13064/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Adding
  listener [com.example.umarfarooque.rtdbtest.MainActivity$2@361b720] to
  SubscriptionObject:
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  got:
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  2019-05-27 14:45:55.548 12881-13064/com.example.umarfarooque.rtdbtest
  V/SubscriptionObject: Adding listener to
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@926e8d9
  2019-05-27 14:45:55.551 12881-13063/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Adding
  listener [com.example.umarfarooque.rtdbtest.MainActivity$1@3f740ef] to
  SubscriptionObject:
  com.amazonaws.amplify.generated.graphql.OnUpdateRtGuestSubscription@836217f
  got:
  com.amazonaws.amplify.generated.graphql.OnUpdateRtGuestSubscription@836217f
  2019-05-27 14:45:55.551 12881-13063/com.example.umarfarooque.rtdbtest
  V/SubscriptionObject: Adding listener to
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@47b254c
  2019-05-27 14:45:55.564 12881-13067/com.example.umarfarooque.rtdbtest
  D/RetryInterceptor: Retry Interceptor called 2019-05-27 14:45:55.564
  12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Signer Interceptor called 2019-05-27
  14:45:55.566 12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Subscriber ID is
  61c60911-18ea-4ac2-8a7f-79f13d7b03e6 2019-05-27 14:45:55.773
  12881-13067/com.example.umarfarooque.rtdbtest I/RetryInterceptor:
  Returning network response: success 2019-05-27 14:45:55.775
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: subscribe
  called for
  com.amazonaws.amplify.generated.graphql.OnCreateRtGuestSubscription@b3f4623
  2019-05-27 14:45:55.776 12881-13065/com.example.umarfarooque.rtdbtest
  D/RealSubscriptionManager: Subscription Infrastructure: Adding
  subscription object
  com.amazonaws.mobileconnectors.appsync.subscription.SubscriptionObject@926e8d9
  to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d.
  Total subscription objects: 2 2019-05-27 14:45:55.776
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Attempting to
  make [1] MQTT clients] 2019-05-27 14:45:56.779
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.779
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:56.780 12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.780
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:56.780 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Connecting
  with Client ID[tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:56.780
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Calling MQTT
  Connect with actual endpoint for client ID[tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:57.143 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Register alarmreceiver to
  MqttServiceMqttService.pingSender.tgvihzfuync35pl4m6ihy6gidu
  2019-05-27 14:45:57.145 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Schedule next alarm at 1558961187145 2019-05-27
  14:45:57.146 12881-13072/com.example.umarfarooque.rtdbtest
  D/AlarmPingSender: Alarm scheule using setExactAndAllowWhileIdle,
  next: 30000 2019-05-27 14:45:57.151
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Connection
  successful for clientID [tgvihzfuync35pl4m6ihy6gidu]. Will subscribe
  up to 2 topics 2019-05-27 14:45:57.151
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Subscribing to
  MQTT
  topic:[443301200413/eytajgboqjcllkyv6jkqycc4me/onUpdateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d]
  2019-05-27 14:45:57.151 12881-12881/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@5c66981Subscription
  Infrastructure: Attempting to subscribe to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onUpdateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d
  on clientID [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-12881/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Subscribing to
  MQTT
  topic:[443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d]
  2019-05-27 14:45:57.152 12881-12881/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@5c66981Subscription
  Infrastructure: Attempting to subscribe to topic
  443301200413/eytajgboqjcllkyv6jkqycc4me/onCreateRTGuest/08388b10f697efc944dc0f96750be6b366bb7d1e9b6305769ea132320fa7470d
  on clientID [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Made [1] MQTT
  clients 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Unmuting the
  new clients [1] in total 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to true for client
  [tgvihzfuync35pl4m6ihy6gidu] 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to true for client [tgvihzfuync35pl4m6ihy6gidu]
  2019-05-27 14:45:57.152 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Muting the old
  clients [ 1] in total 2019-05-27 14:45:57.152
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set
  subscription message transmitting to false for client
  [7aybllsw45gfnbuahn3khahrr4] 2019-05-27 14:45:57.153
  12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Subscription Infrastructure: Set Connection
  transmitting to false for client [7aybllsw45gfnbuahn3khahrr4]
  2019-05-27 14:45:57.153 12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Closing the
  old clients [1] in total 2019-05-27 14:45:57.153
  12881-13065/com.example.umarfarooque.rtdbtest
  V/RealSubscriptionManager: Subscription Infrastructure: Closing
  client:
  com.amazonaws.mobileconnectors.appsync.subscription.mqtt.MqttSubscriptionClient@90ffefa
  2019-05-27 14:45:57.153 12881-13065/com.example.umarfarooque.rtdbtest
  V/MqttSubscriptionClient: Closing MQTT client
  [7aybllsw45gfnbuahn3khahrr4 2019-05-27 14:45:57.163
  12881-13067/com.example.umarfarooque.rtdbtest D/RetryInterceptor:
  Retry Interceptor called 2019-05-27 14:45:57.163
  12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Signer Interceptor called 2019-05-27
  14:45:57.163 12881-13067/com.example.umarfarooque.rtdbtest
  D/AppSyncSigV4SignerInterceptor: Subscriber ID is
  61c60911-18ea-4ac2-8a7f-79f13d7b03e6 2019-05-27 14:45:57.199
  12881-13040/com.example.umarfarooque.rtdbtest D/AlarmPingSender:
  Unregister alarmreceiver to MqttService7aybllsw45gfnbuahn3khahrr4


问:
How to set up a mysql2 connection before an http server starts accepting requests?
```<code>const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
    // error handler
    // handlers
    // req.on('data' ...
    // req.on('end' ...

}).listen(config_private.localPort, async function (err){
    // error handler
};
</code>```

Where in there above code should I put

```<code>mysql2Conn= await mysql2.createConnection({..params..});
</code>```

to get have the server to .listen and have http.createServer's eventHandler accept http request AFTER the sqlConn1 is ready?

答:
You could listen after connecting to db, like:

```<code>const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
  // error handler
  // handlers
  // req.on('data' ...
  // req.on('end' ...
});

async function init() {
  try {
    mysql2Conn= await mysql2.createConnection({..params..});
    httpServer.listen(config_private.localPort, async function (err){
      // error handler
    });
  } catch(e) {
    console.log('db connection failed');
  }
}

init();
</code>```

Body:
const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
    // error handler
    // handlers
    // req.on('data' ...
    // req.on('end' ...

}).listen(config_private.localPort, async function (err){
    // error handler
};

Where in there above code should I put

mysql2Conn= await mysql2.createConnection({..params..});

to get have the server to .listen and have http.createServer's eventHandler accept http request AFTER the sqlConn1 is ready?

Body:
You could listen after connecting to db, like:

const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
  // error handler
  // handlers
  // req.on('data' ...
  // req.on('end' ...
});

async function init() {
  try {
    mysql2Conn= await mysql2.createConnection({..params..});
    httpServer.listen(config_private.localPort, async function (err){
      // error handler
    });
  } catch(e) {
    console.log('db connection failed');
  }
}

init();


问:
pg_dump & pg_restore password using python module subprocess
Problem: Use the PSQL pg_dump and pg_restore in a Python script and using the subprocess module.

Background: I am using the following python 2.7 script from the localhost (i.e. Ubuntu 14.04.5 LTS) to create a backup of a table in a PSQL server (i.e. PostgreSQL 9.4.11) and restore it into the remote host (i.e. Ubuntu 16.04.2 LTS) in a newer version of PSQL server (i.e. PostgreSQL 9.6.2).

```<code>#!/usr/bin/python

from subprocess import PIPE,Popen

def dump_table(host_name,database_name,user_name,database_password,table_name):

    command = 'pg_dump -h {0} -d {1} -U {2} -p 5432 -t public.{3} -Fc -f /tmp/table.dmp'\
    .format(host_name,database_name,user_name,table_name)

    p = Popen(command,shell=True,stdin=PIPE)

    return p.communicate('{}\n'.format(database_password))

def restore_table(host_name,database_name,user_name,database_password):

    command = 'pg_restore -h {0} -d {1} -U {2} < /tmp/table.dmp'\
    .format(host_name,database_name,user_name)

    p = Popen(command,shell=True,stdin=PIPE)

    return p.communicate('{}\n'.format(database_password))

def main():
    dump_table('localhost','testdb','user_name','passwd','test_tbl')
    restore_table('remotehost','new_db','user_name','passwd')

if __name__ == "__main__":
    main()
</code>```

When I use the functions sequentially as above the dump_table() function finishes successfully and creates the /tmp/table.sql file but the restore_table() function returns the following error:

('', 'Password: \npg_restore: [archiver (db)] connection to database
  "database_name" failed: FATAL: password authentication failed for user
  "username"\nFATAL: password authentication failed for user
  "username"\n')*

I have checked the credentials & outputs by executing the commands for pg_restore in the shell and I have also included the credentials to .pgpass (although not relevant since I am passing the password in p.communicate())

Anyone had similar experience? I am pretty much stuck!

Regards,
D.

答:
You can use environment variables https://www.postgresql.org/docs/11/libpq-envars.html and "--no-password" option for pg_dump.

    def dump_schema(host, dbname, user, password, **kwargs):
        command = f'pg_dump --host={host} ' \
            f'--dbname={dbname} ' \
            f'--username={user} ' \
            f'--no-password ' \
            f'--format=c ' \
            f'--file=/tmp/schema.dmp '

        proc = Popen(command, shell=True, env={
            'PGPASSWORD': password
        })
        proc.wait()
```

Body:
Problem: Use the PSQL pg_dump and pg_restore in a Python script and using the subprocess module.

Background: I am using the following python 2.7 script from the localhost (i.e. Ubuntu 14.04.5 LTS) to create a backup of a table in a PSQL server (i.e. PostgreSQL 9.4.11) and restore it into the remote host (i.e. Ubuntu 16.04.2 LTS) in a newer version of PSQL server (i.e. PostgreSQL 9.6.2).

#!/usr/bin/python

from subprocess import PIPE,Popen

def dump_table(host_name,database_name,user_name,database_password,table_name):

    command = 'pg_dump -h {0} -d {1} -U {2} -p 5432 -t public.{3} -Fc -f /tmp/table.dmp'\
    .format(host_name,database_name,user_name,table_name)

    p = Popen(command,shell=True,stdin=PIPE)

    return p.communicate('{}\n'.format(database_password))

def restore_table(host_name,database_name,user_name,database_password):

    command = 'pg_restore -h {0} -d {1} -U {2} < /tmp/table.dmp'\
    .format(host_name,database_name,user_name)

    p = Popen(command,shell=True,stdin=PIPE)

    return p.communicate('{}\n'.format(database_password))

def main():
    dump_table('localhost','testdb','user_name','passwd','test_tbl')
    restore_table('remotehost','new_db','user_name','passwd')

if __name__ == "__main__":
    main()

When I use the functions sequentially as above the dump_table() function finishes successfully and creates the /tmp/table.sql file but the restore_table() function returns the following error:

('', 'Password: \npg_restore: [archiver (db)] connection to database
  "database_name" failed: FATAL: password authentication failed for user
  "username"\nFATAL: password authentication failed for user
  "username"\n')*

I have checked the credentials & outputs by executing the commands for pg_restore in the shell and I have also included the credentials to .pgpass (although not relevant since I am passing the password in p.communicate())

Anyone had similar experience? I am pretty much stuck!

Regards,
D.


问:
how to obtain a proportions table based on info from 2 different tables in R
I have 2 tables: one for my study population, and one for my source population. They are based on 2 DFs with the same variables : patientID, center, year of start of treatment. They each give me the number of patients per center and per year

```<code>tb1 = table(ART_source$PROGRAM, ART_source$ART_Y)

tb2 = table(ART_study$PROGRAM, ART_study$ART_Y)
</code>```

I need a 3rd table, which shows the proportion of patients in the study population (based on the source population). So something like this:
t3 = table (t2 / t1)
except that of course this doesn't work.
I could do it manually on excel, but I think there must be a more clever way to do it in R. Your help is much appreciated,

Body:
I have 2 tables: one for my study population, and one for my source population. They are based on 2 DFs with the same variables : patientID, center, year of start of treatment. They each give me the number of patients per center and per year

tb1 = table(ART_source$PROGRAM, ART_source$ART_Y)

tb2 = table(ART_study$PROGRAM, ART_study$ART_Y)

I need a 3rd table, which shows the proportion of patients in the study population (based on the source population). So something like this:
t3 = table (t2 / t1)
except that of course this doesn't work.
I could do it manually on excel, but I think there must be a more clever way to do it in R. Your help is much appreciated,

Body:
Edited to reflect a column that shouldn't be divided:

library(dplyr)

df1 <- data.frame(id = c("patient1", "patient2", "patient3", "patient4", "patient5"), replicate(5,sample(1:50,5,rep=TRUE)))
df2 <- data.frame(id = c("patient1", "patient2", "patient3", "patient4", "patient5"), replicate(5,sample(1:50,5,rep=TRUE)))

df3 <- data.frame(df1$id, df1[, c(2:6)] / df2[, c(2:6)])

> df1
        id X1 X2 X3 X4 X5
1 patient1 15 18  5 49 47
2 patient2 13 32 13 33 21
3 patient3 20 42 32  5 25
4 patient4 32  8 26 32 18
5 patient5 48 49 13 44 13
> df2
        id X1 X2 X3 X4 X5
1 patient1 48 12  6 21 25
2 patient2 18 43  1 14 13
3 patient3 10 18 37 25 13
4 patient4 37  4 47  3 28
5 patient5  9  2 50  1 13
> df3
    df1.id        X1        X2         X3        X4        X5
1 patient1 0.3125000  1.500000  0.8333333  2.333333 1.8800000
2 patient2 0.7222222  0.744186 13.0000000  2.357143 1.6153846
3 patient3 2.0000000  2.333333  0.8648649  0.200000 1.9230769
4 patient4 0.8648649  2.000000  0.5531915 10.666667 0.6428571
5 patient5 5.3333333 24.500000  0.2600000 44.000000 1.0000000


问:
jQuery - exclude inputs with certain value from selector
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

```<code>$('#mydiv input:not(val("100")').val(myvariable);
</code>```

how to do that, is it possible in simple selector?
thanks

答:
you can also use the each function.</p>

```<code>$('#mydiv :input').each(function(){

    if($(this).val() != '100')
       $(this).val(myvariable);
});
</code>```

Body:
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

$('#mydiv input:not(val("100")').val(myvariable);

how to do that, is it possible in simple selector?
thanks

Body:
you can also use the each function.

$('#mydiv :input').each(function(){

    if($(this).val() != '100')
       $(this).val(myvariable);
});


问:
Sqoop command with --query in Scala using Process("<sqoop command>").! not working
I am trying to run a Sqoop command having --query option on Scala shell using Process("<sqoop command>").! but it is showing an error described below.

If I use --table instead of --query, it works like a charm.

But for my requirement, I need to use --query.

The error it gives is :

```<code>ERROR tool.BaseSqoopTool: Error parsing arguments for import:
ERROR tool.BaseSqoopTool: Unrecognized argument: *
ERROR tool.BaseSqoopTool: Unrecognized argument: from
</code>```

etc.

Thanks in advance

The below code works properly in Spark-Scala shell.

```<code>Process("""sqoop import <queuename> --connect <connection-string-db2> --
    username <username> --password <password> --table "<database.table>" --
    target-dir <target directory> --delete-target-dir --fields-terminated-by
    '\\001' --lines-terminated-by '\\n' --null-string '\\\\N' --null-non-
    string '\\\\N' --hive-drop-import-delims -m 1""").!
</code>```

But when I change --table by --query (and use whatever basic query in it e.g. "SELECT * FROM DATABASE.TABLE"), it doesn't work... Below is the command which doesn't work:

```<code>Process("""sqoop import <queuename> --connect <connection-string-db2> --
    username <username> --password <password> --query "SELECT * FROM
    DATABASE.TABLE AND \$CONDITIONS" --target-dir <target directory> --
    delete-target-dir --fields-terminated-by '\\001' --lines-terminated-by
    '\\n' --null-string '\\\\N' --null-non-string '\\\\N' --hive-drop-
    import-delims -m 1""").!
</code>```

答: I think you need to escape the double quotes after --query .</p>

Body:
I am trying to run a Sqoop command having --query option on Scala shell using Process("<sqoop command>").! but it is showing an error described below.

If I use --table instead of --query, it works like a charm.

But for my requirement, I need to use --query.

The error it gives is :

ERROR tool.BaseSqoopTool: Error parsing arguments for import:
ERROR tool.BaseSqoopTool: Unrecognized argument: *
ERROR tool.BaseSqoopTool: Unrecognized argument: from

etc.

Thanks in advance

The below code works properly in Spark-Scala shell.

Process("""sqoop import <queuename> --connect <connection-string-db2> --
    username <username> --password <password> --table "<database.table>" --
    target-dir <target directory> --delete-target-dir --fields-terminated-by
    '\\001' --lines-terminated-by '\\n' --null-string '\\\\N' --null-non-
    string '\\\\N' --hive-drop-import-delims -m 1""").!

But when I change --table by --query (and use whatever basic query in it e.g. "SELECT * FROM DATABASE.TABLE"), it doesn't work... Below is the command which doesn't work:

Process("""sqoop import <queuename> --connect <connection-string-db2> --
    username <username> --password <password> --query "SELECT * FROM
    DATABASE.TABLE AND \$CONDITIONS" --target-dir <target directory> --
    delete-target-dir --fields-terminated-by '\\001' --lines-terminated-by
    '\\n' --null-string '\\\\N' --null-non-string '\\\\N' --hive-drop-
    import-delims -m 1""").!


问:
Solve highmaps-highcharts conflict when creating map, column and radar charts
I am able to create highcharts column and radar charts in my Ruby on Rails app by requiring in the application.js:

```<code>//= require jquery3
//= require highcharts
//= require highcharts/highcharts-more
</code>```

Then, I need to add a highcharts map. However, calling the map generation function Highcharts.mapChart('container', {... raises:

```<code>Uncaught TypeError: Highcharts.mapChart is not a function
</code>```

I seem to resolve the error by replacing //= require highcharts with //= require highmaps and adding //= require highcharts/modules/map. Now I have both column chart and map. But removing //= require highcharts results in errors while calling radar chart: Uncaught ReferenceError: Highcharts is not defined. I cannot require both highcharts and highmaps together due to the conflict that raises:

```<code>Uncaught Error: Highcharts error #16: Highcharts already defined in the page
This error happens if the Highcharts namespace already exists when loading Highcharts or Highstock.
</code>```

Trying to place //= require highmaps before //= require highcharts/highcharts-more fixes the error but raises two new errors: Uncaught TypeError: Cannot read property 'prototype' of undefined and Uncaught TypeError: Cannot read property 'updateCenter' of undefined.
How can I get column, radar and map together in the same app?

答:
You should not use Highmaps and map module together. You can use the map modlue as a plugin with Highcharts:

```<code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>
</code>```

Live demo: http://jsfiddle.net/BlackLabel/gbduyLo9/

Docs: https://www.highcharts.com/docs/maps/getting-started

Body:
I am able to create highcharts column and radar charts in my Ruby on Rails app by requiring in the application.js:

//= require jquery3
//= require highcharts
//= require highcharts/highcharts-more

Then, I need to add a highcharts map. However, calling the map generation function Highcharts.mapChart('container', {... raises:

Uncaught TypeError: Highcharts.mapChart is not a function

I seem to resolve the error by replacing //= require highcharts with //= require highmaps and adding //= require highcharts/modules/map. Now I have both column chart and map. But removing //= require highcharts results in errors while calling radar chart: Uncaught ReferenceError: Highcharts is not defined. I cannot require both highcharts and highmaps together due to the conflict that raises:

Uncaught Error: Highcharts error #16: Highcharts already defined in the page
This error happens if the Highcharts namespace already exists when loading Highcharts or Highstock.

Trying to place //= require highmaps before //= require highcharts/highcharts-more fixes the error but raises two new errors: Uncaught TypeError: Cannot read property 'prototype' of undefined and Uncaught TypeError: Cannot read property 'updateCenter' of undefined.
How can I get column, radar and map together in the same app?

Body:
You should not use Highmaps and map module together. You can use the map modlue as a plugin with Highcharts:

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>

Live demo: http://jsfiddle.net/BlackLabel/gbduyLo9/

Docs: https://www.highcharts.com/docs/maps/getting-started


问:
Convert large xml values into double type json?
I'm forming an xml whose snippet is -

```<code><cache-properties>
  <list-cache-hit-rate>
    <units>hits/sec</units>
    <value>1.5308452E6</value>
  </list-cache-hit-rate>
  <list-cache-miss-rate>
    <units>misses/sec</units>
    <value>25422.167</value>
  </list-cache-miss-rate>
  <compressed-tree-cache-hit-rate>
    <units>hits/sec</units>
    <value>970.2339</value>
</code>```

Notice the value 1.5308452E6 is big enough that the values are stored as exponent while performing fn:sum() behind the scene.

Later, I'm converting the xml to json by the following function -

```<code>let $arr := json:to-array(local:tojson($data))
return (($data))
</code>```

and value converted looks like this -

```<code>cache-properties": {
  "list-cache-hit-rate": {
    "units": "hits/sec",
    "value": 1.5308452E6
  },
  "list-cache-miss-rate": {
    "units": "misses/sec",
    "value": "25422.167"
  },
  "compressed-tree-cache-hit-rate": {
    "units": "hits/sec",
    "value": "970.2339"
  },
</code>```

Notice the values are enclosed in quotes except 1.5308452E6 this value. This is not in quotes. What correction is needed here ? Or is this correct? I'd rather have all values in quotes. This is my custom transform function-

```<code>declare function local:tojson($func){
let $custom := let $config := json:config("custom")
                let $_ := map:put( $config, "whitespace", "ignore" )
                let $_ := map:put( $config, "array-element-names", "Video" )
                return $config
return json:transform-to-json($func,$custom)
};
</code>```

答:
Take a look at the xml schema.  Your snippets appear to be similar or identical to marklogic system status xml schema however you mention 'fn:sum in the background' so Im guessing you have applied a transformation which has changed the xsd type.
The json transformation code uses the XSD type if in scope to determine the typed output in JSON (for XML numeric types).  Also if the number is 'too large' it can convert to string to avoid JavaScript issue.

( it basically uses fn:data(value) to convert )

If needed you can either force a string type onto your xml, or you can specialize the transformation by overriding one of the json-custom: primitives in json/custom.xqy by supplying the appropriate mapping in the config.  Look into the source for the full list of overridable functions.   They are not fully documented as they are not with full generality in mind and may not be obvious, easy or possibly to change behaviour in every conceivable way.

The strategies are to either
Use an XML with schema in scope that types atomic values explicitly (in your case as xs:string),
Override one of the low level functions in custom.xqy
Convert the JSON by post-processing and 'stringify' the desired elements
Roll your own (not too difficult with the samples show)
All of the above

Body:
I'm forming an xml whose snippet is -

<cache-properties>
  <list-cache-hit-rate>
    <units>hits/sec</units>
    <value>1.5308452E6</value>
  </list-cache-hit-rate>
  <list-cache-miss-rate>
    <units>misses/sec</units>
    <value>25422.167</value>
  </list-cache-miss-rate>
  <compressed-tree-cache-hit-rate>
    <units>hits/sec</units>
    <value>970.2339</value>

Notice the value 1.5308452E6 is big enough that the values are stored as exponent while performing fn:sum() behind the scene.

Later, I'm converting the xml to json by the following function -

let $arr := json:to-array(local:tojson($data))
return (($data))

and value converted looks like this -

cache-properties": {
  "list-cache-hit-rate": {
    "units": "hits/sec",
    "value": 1.5308452E6
  },
  "list-cache-miss-rate": {
    "units": "misses/sec",
    "value": "25422.167"
  },
  "compressed-tree-cache-hit-rate": {
    "units": "hits/sec",
    "value": "970.2339"
  },

Notice the values are enclosed in quotes except 1.5308452E6 this value. This is not in quotes. What correction is needed here ? Or is this correct? I'd rather have all values in quotes. This is my custom transform function-

declare function local:tojson($func){
let $custom := let $config := json:config("custom")
                let $_ := map:put( $config, "whitespace", "ignore" )
                let $_ := map:put( $config, "array-element-names", "Video" )
                return $config
return json:transform-to-json($func,$custom)
};


问:
How can I compress every X subfolder in a folder as a separate rar file
I am really new to Powershell coding and need your help please

I'm on Windows 10 with Powershell 5.1 and  trying to work it out with Winrar. The Main  folder contains 5000 subFolders I would like to specify how many folders should be included per archive and compress every X of them as a separate rar files.

create text files and for each rar file a .txt  file with all subfoldernames in each rar

For example:
first:
specify how many folders should be included per archive

the folder name with the 5000 subfolders has the name "Project"

all rar files should have the same name as the main folder with consecutive numbering: in this case

```<code>Project - 01.rar
Project - 02.rar
Project - 03.rar
Project - 04.rar
Project - 05.rar
etc....
</code>```

and for each rar file a txt file which lists the contents of the rar file

```<code>Project - 01.txt
Project - 02.txt
Project - 03.txt
Project - 04.txt
Project - 05.txt
etc...
</code>```

Is there a way to not do it manually?

答:
This is my script and it works so far

```<code>param
(
    # The input folder containing the files to zip
    [Parameter(Mandatory = $true)]
    [string] $InputFolder,

    # The output folder that will contain the zip files
    [Parameter(Mandatory = $true)]
    [string] $OutputFolder
)

Set-Variable SET_SIZE -option Constant -value 10
$i = 0
$zipSet = 0

Get-ChildItem $InputFolder | ForEach-Object {
    $zipSetName = "archive" + ($zipSet + 1) + ".zip"
    Compress-Archive -Path $_.FullName -Update -DestinationPath "$OutputFolder\$zipSetName"
    $i++;

    if ($i -eq $SET_SIZE) {
        $i = 0;
        $zipSet++;
    }
}
</code>```

Now I need some help to add the above mentioned options and

set Input and Output to Path of currently executing powershell script
In a batch file I would do: %~d0%~p0

create a folder "Done"in  the main folder and move all the Subfolders which have already been added to an archive to "done"

always use rar if rar support is given otherwise use zip

thanks

Body:
I am really new to Powershell coding and need your help please

I'm on Windows 10 with Powershell 5.1 and  trying to work it out with Winrar. The Main  folder contains 5000 subFolders I would like to specify how many folders should be included per archive and compress every X of them as a separate rar files.

create text files and for each rar file a .txt  file with all subfoldernames in each rar

For example:
first:
specify how many folders should be included per archive

the folder name with the 5000 subfolders has the name "Project"

all rar files should have the same name as the main folder with consecutive numbering: in this case

Project - 01.rar
Project - 02.rar
Project - 03.rar
Project - 04.rar
Project - 05.rar
etc....

and for each rar file a txt file which lists the contents of the rar file

Project - 01.txt
Project - 02.txt
Project - 03.txt
Project - 04.txt
Project - 05.txt
etc...

Is there a way to not do it manually?

Body:
This is my script and it works so far

param
(
    # The input folder containing the files to zip
    [Parameter(Mandatory = $true)]
    [string] $InputFolder,

    # The output folder that will contain the zip files
    [Parameter(Mandatory = $true)]
    [string] $OutputFolder
)

Set-Variable SET_SIZE -option Constant -value 10
$i = 0
$zipSet = 0

Get-ChildItem $InputFolder | ForEach-Object {
    $zipSetName = "archive" + ($zipSet + 1) + ".zip"
    Compress-Archive -Path $_.FullName -Update -DestinationPath "$OutputFolder\$zipSetName"
    $i++;

    if ($i -eq $SET_SIZE) {
        $i = 0;
        $zipSet++;
    }
}

Now I need some help to add the above mentioned options and

set Input and Output to Path of currently executing powershell script
In a batch file I would do: %~d0%~p0

create a folder "Done"in  the main folder and move all the Subfolders which have already been added to an archive to "done"

always use rar if rar support is given otherwise use zip

thanks


问:
How to create a rule to ignore all form request validation?
I'm a beginner on Laravel. I have a form with validation, but that form can be saved as a draft. In this case, I need a way to ignore all validation rules. Someone could help me with this?

class ValidacaoProcesso extends FormRequest {

```<code>/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize() {
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules() {
    return [
        'NUP' => 'required:T_PROCESSO',
        'dt_recebimento' => 'required',
        'hora_recebimento' => 'required',
        'CPF' => 'required',
        'nome' => 'required',
        'sentenca_judicial' => 'required',
        'tipo_pessoa' => 'required',
        'prioridade' => 'required',
    ];
}
}
</code>```

答:
Thank you for the help. I didn't know that I could use input request inside the Class. I solved using something like this:</p>

```<code>public function rules() {
    if ($this->draft == "Y") {
        return [];
    }
    return [
        'NUP' => 'required:T_PROCESSO',
        'dt_recebimento' => 'required',
        'hora_recebimento' => 'required',
        'CPF' => 'required',
        'nome' => 'required',
        'sentenca_judicial' => 'required',
        'tipo_pessoa' => 'required',
        'prioridade' => 'required',
    ];
}
</code>```

Body:
I'm a beginner on Laravel. I have a form with validation, but that form can be saved as a draft. In this case, I need a way to ignore all validation rules. Someone could help me with this?

class ValidacaoProcesso extends FormRequest {

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize() {
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules() {
    return [
        'NUP' => 'required:T_PROCESSO',
        'dt_recebimento' => 'required',
        'hora_recebimento' => 'required',
        'CPF' => 'required',
        'nome' => 'required',
        'sentenca_judicial' => 'required',
        'tipo_pessoa' => 'required',
        'prioridade' => 'required',
    ];
}
}

Body:
Thank you for the help. I didn't know that I could use input request inside the Class. I solved using something like this:

public function rules() {
    if ($this->draft == "Y") {
        return [];
    }
    return [
        'NUP' => 'required:T_PROCESSO',
        'dt_recebimento' => 'required',
        'hora_recebimento' => 'required',
        'CPF' => 'required',
        'nome' => 'required',
        'sentenca_judicial' => 'required',
        'tipo_pessoa' => 'required',
        'prioridade' => 'required',
    ];
}


问:
need a good tutorial for eclipse java ee for beginning web app development
I need a good tutorial using Eclipse Java EE for beginning web application development/servlets development. Like a Hello World web app. I searched the net but I find all tutorials for plain java version of Eclipse.

答:
Check out Softwarepassion blog, especially http://www.softwarepassion.com/java-ee-6-getting-started-maven-cdi-and-persistence-ready-project/

Its a maven based J2EE 6 tutorial with eclipse screenshots.


问:
How do deal with Collection caching and i18n?
I am trying to internationalize my Rails app. I dont know how do deal with Collection caching.

I know that we can do this for one active record object :

```<code><% cache([I18n.locale, product]) do %>
  <!-- here the markup for a single product -->
  <%= render partial:'products/product', locals: { product: product } %>
<% end %>
</code>```

But how to do it for collection caching? :

```<code><%= render partial: 'products/product', collection: @products, as: :product, cached: true %>
</code>```

Thanks for your incoming help

答:
You can use this :</p>

```<code><%= render partial: 'products/product', collection: @products, as: :product, cached: -> product { [I18n.locale, product] } %>
</code>```

Body:
I am trying to internationalize my Rails app. I dont know how do deal with Collection caching.

I know that we can do this for one active record object :

<% cache([I18n.locale, product]) do %>

  <%= render partial:'products/product', locals: { product: product } %>
<% end %>

But how to do it for collection caching? :

<%= render partial: 'products/product', collection: @products, as: :product, cached: true %>

Thanks for your incoming help

Body:
You can use this :

<%= render partial: 'products/product', collection: @products, as: :product, cached: -> product { [I18n.locale, product] } %>