问:
Google Apps Script Error: You do not have permission to call newTrigger
I have this Google apps script in my spreadsheet:

```<code>function onEdit(e) {
  var row = e.range.getRow();
  if (row == 1) {
    return;
  }
  var email = Session.getActiveUser().getEmail();
  email = email.substring(0, email.indexOf('@'));
  SpreadsheetApp.getActiveSheet().getRange(row, 2).setValue(email);
  SpreadsheetApp.getActiveSheet().getRange(row, 3).setValue(new Date());
}

function onOpen(e) {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('onEdit')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}
</code>```

Which causes this error:

Google Apps Script: You do not have permission to call newTrigger

Apparently this script has run correctly for some time and now it doesn't. I imagine some change occurred in the API that causes this?

答: You should consider creating a trigger outside the onOpen function else it will run every time you load the Google Sheet in your browser.</p>

Body:
I have this Google apps script in my spreadsheet:

function onEdit(e) {
  var row = e.range.getRow();
  if (row == 1) {
    return;
  }
  var email = Session.getActiveUser().getEmail();
  email = email.substring(0, email.indexOf('@'));
  SpreadsheetApp.getActiveSheet().getRange(row, 2).setValue(email);
  SpreadsheetApp.getActiveSheet().getRange(row, 3).setValue(new Date());
}

function onOpen(e) {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('onEdit')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}

Which causes this error:

Google Apps Script: You do not have permission to call newTrigger

Apparently this script has run correctly for some time and now it doesn't. I imagine some change occurred in the API that causes this?


来源: stackexchange

问:
Flash upload image resize client side
Does anyone got an ideia on how to get client side image resize using flash.

Example:
Client chooses an image with 1200x800 and before it uploads it flash will turn it into half of it or something.

Any thoughts?

答:
You need create a transformation matrix, then draw the original bitmap into a new one using it. Here's the idea in something i am just typing in and have not tested:

```<code>function resize(obm:BitmapData, scale:Number): BitmapData {
   var resizeMatrix:Matrix = new Matrix();
   resizeMatrix.scale(scale, scale);

   var rbm:BitmapData = new BitmapData(obm.width * scale, obm.height * scale);
   rbm.draw(obm, resizeMatrix);

   return rbm;
}
</code>```

I make no claims about the quality of the result, however. I think I remember trying this in the past, not liking the result, and punting...

OwnerDisplayName: Hugo Gameiro

ContentLicense: CC BY-SA 2.5

Title: Flash upload image resize client side

Body:
You need create a transformation matrix, then draw the original bitmap into a new one using it. Here's the idea in something i am just typing in and have not tested:

function resize(obm:BitmapData, scale:Number): BitmapData {
   var resizeMatrix:Matrix = new Matrix();
   resizeMatrix.scale(scale, scale);

   var rbm:BitmapData = new BitmapData(obm.width * scale, obm.height * scale);
   rbm.draw(obm, resizeMatrix);

   return rbm;
}

I make no claims about the quality of the result, however. I think I remember trying this in the past, not liking the result, and punting...

OwnerDisplayName: Scott Evernden


问:
How to view the source code of a .mex file
I saw online that you can just use edit rgb2gray to open up the source file, but I ran into another function in the rgb2gray.m file that I don't know how to view.

Lines 54-55 contain the following function:

```<code>if threeD
  I = images.internal.rgb2graymex(X);
</code>```

How do I view the source code for this rgb2graymex function?

答:
In general you can't see the contents of a .mex file, as @Adriaan indicates in his answer.

You mention in the comments, though, that what you really want is to find the coefficients used from the transform matrix for converting RGB to grayscale. You can find these in the code immediately below the section you quote:

```<code>  T    = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]);
  coef = T(1,:);
</code>```

That gives me:

```<code>coef =
   0.298936021293775   0.587043074451121   0.114020904255103
</code>```

Now it's true that you can't demonstrate conclusively that the .mex file is doing the same thing as this; but the .mex file is just there to speed things up when you pass in a big mxnx3 RGB image, rather than a small nx3 RGB colormap. I'd be very surprised if it was using different coefficients. A few experiments that I've just done indicate only the tiniest of numerical differences (<1e-15) between the .mex file and using the coefficients present in the code.

ContentLicense: CC BY-SA 3.0

Body:
I saw online that you can just use edit rgb2gray to open up the source file, but I ran into another function in the rgb2gray.m file that I don't know how to view.

Lines 54-55 contain the following function:

if threeD
  I = images.internal.rgb2graymex(X);

How do I view the source code for this rgb2graymex function?

Body:
In general you can't see the contents of a .mex file, as @Adriaan indicates in his answer.

You mention in the comments, though, that what you really want is to find the coefficients used from the transform matrix for converting RGB to grayscale. You can find these in the code immediately below the section you quote:

  T    = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]);
  coef = T(1,:);

That gives me:

coef =
   0.298936021293775   0.587043074451121   0.114020904255103

Now it's true that you can't demonstrate conclusively that the .mex file is doing the same thing as this; but the .mex file is just there to speed things up when you pass in a big mxnx3 RGB image, rather than a small nx3 RGB colormap. I'd be very surprised if it was using different coefficients. A few experiments that I've just done indicate only the tiniest of numerical differences (<1e-15) between the .mex file and using the coefficients present in the code.


问:
SNMP java API snmpbulkwalk
I'm studing a module to manage a router with protocol SNMP. I'm checking adventnet and snmp4j apis but I need to make some snmp calls in java via the command snmpbulkwalk. Is there any api in java to execute this command?</p>

答:
You can use SNMP4j to do SNMPBULKWALK on the router. SNMP4j provides below API to retrieve entire subtree of a given rootnode synchronously.

Class: TreeUtils.java
Method: getSubtree(targetV2, rootOID);

It also provides another method which is asynchronous.

Class: TreeUtils.java
Method: walk(targetV2, rootOIDs);

I have a github project which has the complete working code. You can clone the repo and try it.

Title: SNMP java API snmpbulkwalk


问:
Reset Password Parse Server Manually,Server Side
I want to set password of a user with email x@x.com to be "an". But the code doesn't  work.
Here is my cloud code:

```<code>  Parse.Cloud.define('testSetPasswordForUser', function(request, response) {
  Parse.Cloud.useMasterKey();

  var query = new Parse.Query(Parse.User);
 query.equalTo("email", "x@x.com");

  query.first({
  success: function(results) {
    results.setPassword("an");
    results.save();
  },
  error: function(error) {

  }
});

});
</code>```

and here is my android code:

```<code>     Map<String, String> parameters = new HashMap<String, String>();
                   ParseCloud.callFunctionInBackground("testSetPasswordForUser", parameters, new FunctionCallback<Map<String, Object>>() {
                            @Override
                            public void done(Map<String, Object> mapObject, ParseException e) {
                                if (e == null) {
//OK
                                }
                                else {
//WRONG
                                }
                            }
                        });
</code>```

答:
First off, you're gonna throw an error if there isn't a matching e-mail, since results will be undefined. So wrap the handler in an if( results ) block.

Second, you have to use the master key to change a password. Otherwise, anybody could change anybody else's password.

results.save(null, {useMasterKey:true});

The null is an optional dictionary you could be updating values in. I.e.
results.save({key1:value1, key2:value2}, {useMasterKey:true});

Body:
I want to set password of a user with email x@x.com to be "an". But the code doesn't  work.
Here is my cloud code:

  Parse.Cloud.define('testSetPasswordForUser', function(request, response) {
  Parse.Cloud.useMasterKey();

  var query = new Parse.Query(Parse.User);
 query.equalTo("email", "x@x.com");

  query.first({
  success: function(results) {
    results.setPassword("an");
    results.save();
  },
  error: function(error) {

  }
});

});

and here is my android code:

     Map<String, String> parameters = new HashMap<String, String>();
                   ParseCloud.callFunctionInBackground("testSetPasswordForUser", parameters, new FunctionCallback<Map<String, Object>>() {
                            @Override
                            public void done(Map<String, Object> mapObject, ParseException e) {
                                if (e == null) {
//OK
                                }
                                else {
//WRONG
                                }
                            }
                        });


问:
Parse a list line by line, create a new list in Powershell
I need to read in a file that contains lines of source/destination IPs and ports as well as a tag. I'm using Get-Content:

```<code>Get-Content $logFile -ReadCount 1 | % {

} | sort | get-unique | Out-File "C:\Log\logout.txt"
</code>```

This is an example of the input file:

```<code>|10.0.0.99|345|195.168.4.82|58164|spam|
|10.0.0.99|345|195.168.4.82|58164|robot|
|10.0.0.99|231|195.168.4.82|58162|spam|
|195.168.4.82|58162|10.0.0.99|231|robot|
|10.0.0.99|345|195.168.4.82|58168|spam|
|10.0.0.99|345|195.168.4.82|58169|spam|
</code>```

What I need to do is output a new list, but if the same source/destination IPs/ports are both 'spam' and 'robot' I just need to output that line as 'robot' (lines 1 and 2 above).
I need to do the same if the reverse direction of an existing connection is either 'spam' or 'robot', I just need one or the other and it would be 'robot' (lines 3 and 4 above). There will be plenty of 'spam' lines without a duplicate or reverse connection (the last couple lines above), they need to just stay the same.

This is what i've been using to create the reverse direction of the connection, but I haven't been able to figure out how to properly create the new list:

```<code>$reverse = '|' + ($_.Split("|")[3,4,1,2,5] -join '|') + '|'
</code>```

Output of the above would be:

```<code>|10.0.0.99|345|195.168.4.82|58164|robot|
|195.168.4.82|58162|10.0.0.99|231|robot|
|10.0.0.99|345|195.168.4.82|58168|spam|
|10.0.0.99|345|195.168.4.82|58169|spam|
</code>```

(except that second line didn't have to be the reversed direction)

Thanks for any help!

答:
Since both direct and reverse connections are checked and their line order may not  be sequential, I would use a hashtable to store the type of both directions and do everything algorithmically:</p>

```<code>$checkPoints = @{}
$output = [ordered]@{}
$reader = [IO.StreamReader]'R:\1.txt'
while (!$reader.EndOfStream) {
    $line = $reader.ReadLine()
    $s = $line.split('|')
    $direct = [string]::Join('|', $s[1..4])
    $reverse = [string]::Join('|', ($s[3,4,1,2]))
    $type = $s[5]
    $known = $checkPoints[$direct]
    if (!$known -or ($type -eq 'robot' -and $known -eq 'spam')) {
        $checkPoints[$direct] = $checkPoints[$reverse] = $type
        $output[$direct] = $line
        $output.Remove($reverse)
    } elseif ($type -eq 'spam' -and $known -eq 'robot') {
        $output.Remove($reverse)
    }
}
$reader.Close()
Set-Content r:\2.txt -Encoding utf8 -value @($output.Values)
</code>```

Body:
I need to read in a file that contains lines of source/destination IPs and ports as well as a tag. I'm using Get-Content:

Get-Content $logFile -ReadCount 1 | % {

} | sort | get-unique | Out-File "C:\Log\logout.txt"

This is an example of the input file:

|10.0.0.99|345|195.168.4.82|58164|spam|
|10.0.0.99|345|195.168.4.82|58164|robot|
|10.0.0.99|231|195.168.4.82|58162|spam|
|195.168.4.82|58162|10.0.0.99|231|robot|
|10.0.0.99|345|195.168.4.82|58168|spam|
|10.0.0.99|345|195.168.4.82|58169|spam|

What I need to do is output a new list, but if the same source/destination IPs/ports are both 'spam' and 'robot' I just need to output that line as 'robot' (lines 1 and 2 above).
I need to do the same if the reverse direction of an existing connection is either 'spam' or 'robot', I just need one or the other and it would be 'robot' (lines 3 and 4 above). There will be plenty of 'spam' lines without a duplicate or reverse connection (the last couple lines above), they need to just stay the same.

This is what i've been using to create the reverse direction of the connection, but I haven't been able to figure out how to properly create the new list:

$reverse = '|' + ($_.Split("|")[3,4,1,2,5] -join '|') + '|'

Output of the above would be:

|10.0.0.99|345|195.168.4.82|58164|robot|
|195.168.4.82|58162|10.0.0.99|231|robot|
|10.0.0.99|345|195.168.4.82|58168|spam|
|10.0.0.99|345|195.168.4.82|58169|spam|

(except that second line didn't have to be the reversed direction)

Thanks for any help!

Body:
Since both direct and reverse connections are checked and their line order may not  be sequential, I would use a hashtable to store the type of both directions and do everything algorithmically:

$checkPoints = @{}
$output = [ordered]@{}
$reader = [IO.StreamReader]'R:\1.txt'
while (!$reader.EndOfStream) {
    $line = $reader.ReadLine()
    $s = $line.split('|')
    $direct = [string]::Join('|', $s[1..4])
    $reverse = [string]::Join('|', ($s[3,4,1,2]))
    $type = $s[5]
    $known = $checkPoints[$direct]
    if (!$known -or ($type -eq 'robot' -and $known -eq 'spam')) {
        $checkPoints[$direct] = $checkPoints[$reverse] = $type
        $output[$direct] = $line
        $output.Remove($reverse)
    } elseif ($type -eq 'spam' -and $known -eq 'robot') {
        $output.Remove($reverse)
    }
}
$reader.Close()
Set-Content r:\2.txt -Encoding utf8 -value @($output.Values)


问:
How to solve this select query
I have two tables in my MySQL Database. The one stores an amount for a month in a year for one specific channel. I have a few channels that are defined in another table.
Here are the two tables with example data:

```<code>Table income:
ID | Year | Month | amount | channelID
    example:
1  | 2017 | 05    | 7.13   | 1
2  | 2017 | 05    | 12.03  | 2
3  | 2017 | 06    | 1.56   | 1
4  | 2017 | 06    | 0.30   | 2

Table channel:
ID | title            | url
example:
1  | Affiliate Site 1 | http://url1.tld
2  | Affiliate Site 2 | http://url2.tld
</code>```

Now I want to generate a query that gives me an output like this:

```<code>Expected Output:
Year | Month | amount ch1 | amount ch2
example:
2017 | 05    | 7.13       | 12.03
2017 | 06    | 1.56       | 0.30
</code>```

I have a basic understanding of writing mysql queries but i cannot solve this thing. I thought about joining the tables together but this would not be the solution.
How can I combine two (later more) rows of one table that are identified by the Month and the Year in one output row?

答:
A query that would return what you asked:

```<code>SELECT `Year`
, `Month`
, SUM(IF(`channelID` = 1, `amount`, 0)) 'amount ch1'
, SUM(IF(`channelID` = 2, `amount`, 0)) 'amount ch2'
FROM `income`
GROUP BY `Year`, `Month`;
</code>```

A script that would return the same as the above for an arbitrary number of channels:

```<code>SET @query = (
    SELECT
        CONCAT(
            'SELECT `Year`' ,
            ', `Month`',
            GROUP_CONCAT(
                ', SUM(IF(`channelID` = ', `id`, ', `amount`, 0)) `amount ch', `id`, '` '
                SEPARATOR ''
            ),
            'FROM `income` ',
            'GROUP BY `Year`, `Month`'
        )
    FROM `channel`
);

PREPARE stmt FROM @query;

EXECUTE stmt;
</code>```

The above is generating a query based on the data in the channel table and storing it in the @query variable. Then preparing a statement with this query and executing it.

Title: How to solve this select query

Body:
I have two tables in my MySQL Database. The one stores an amount for a month in a year for one specific channel. I have a few channels that are defined in another table.
Here are the two tables with example data:

Table income:
ID | Year | Month | amount | channelID
    example:
1  | 2017 | 05    | 7.13   | 1
2  | 2017 | 05    | 12.03  | 2
3  | 2017 | 06    | 1.56   | 1
4  | 2017 | 06    | 0.30   | 2

Table channel:
ID | title            | url
example:
1  | Affiliate Site 1 | http://url1.tld
2  | Affiliate Site 2 | http://url2.tld

Now I want to generate a query that gives me an output like this:

Expected Output:
Year | Month | amount ch1 | amount ch2
example:
2017 | 05    | 7.13       | 12.03
2017 | 06    | 1.56       | 0.30

I have a basic understanding of writing mysql queries but i cannot solve this thing. I thought about joining the tables together but this would not be the solution.
How can I combine two (later more) rows of one table that are identified by the Month and the Year in one output row?

Body:
A query that would return what you asked:

SELECT `Year`
, `Month`
, SUM(IF(`channelID` = 1, `amount`, 0)) 'amount ch1'
, SUM(IF(`channelID` = 2, `amount`, 0)) 'amount ch2'
FROM `income`
GROUP BY `Year`, `Month`;

A script that would return the same as the above for an arbitrary number of channels:

SET @query = (
    SELECT
        CONCAT(
            'SELECT `Year`' ,
            ', `Month`',
            GROUP_CONCAT(
                ', SUM(IF(`channelID` = ', `id`, ', `amount`, 0)) `amount ch', `id`, '` '
                SEPARATOR ''
            ),
            'FROM `income` ',
            'GROUP BY `Year`, `Month`'
        )
    FROM `channel`
);

PREPARE stmt FROM @query;

EXECUTE stmt;

The above is generating a query based on the data in the channel table and storing it in the @query variable. Then preparing a statement with this query and executing it.


问:
Validate dates in XML Document before writing to database
I'm currently getting user input from a very large form as an XML document. I'd like to validate this XML document against a schema before any database related operations. The problem is that users input dates according to their own preferences (US standard, ISO standard, etc.) and the database expects dates to be ISO standard. Is there anyway I can validate this XML document and change the dates to ISO format before adding it to the database? I'm using Perl for the back-end, any libraries that can help me do the same?

Cheers,

答: You can have a little schema to validate your special date with a regexp, then an xslt to transform your date to other format, then a schema to validate all your xml document.</p>


答: Try need to use group by channelid and order by amount.</p>

Title: How to solve this select query


问:
Symfony: How can I add an aggregate field in generator.yml?
I am prototyping my application in Symfony 1.4 using Doctrine. I have two models, encounters and photos. One encounter can have many photos and the correct one-to-many relationship is set up in schema.yml.

I have generated a backend using ./symfony generate:app backend. Everything is working fine but I now want to add a count field to my encounters list which I think I should be able to do in generator.yml. In my Encounters.class.php I have the following method:

```<code>public function getPhotoCount() {

    return count($this->CcPhotos);
}
</code>```

My questions is how can I add a new field in generator.yml which runs this method. I tried %%photo_count%% but I think this is intended for string substitution.

```<code>generator:
  class: sfDoctrineGenerator
  param:
    model_class:           CcEncounters
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          cc_encounters
    with_doctrine_route:   true
    actions_base_class:    sfActions

config:
  actions: ~
  fields:  ~
  list: ~
  filter:  ~
  form:    ~
  edit:    ~
  new:
    display: [_camera_id, longitude, latitude, elevation, New Photos]
</code>```

答:
I resolved this. It was as simple as adding:

```<code>    display: [id, longitude, latitude, elevation, photo_count]
</code>```

Where 'photo_count' matches an accessor method called getPhotoCount

Body:
I am prototyping my application in Symfony 1.4 using Doctrine. I have two models, encounters and photos. One encounter can have many photos and the correct one-to-many relationship is set up in schema.yml.

I have generated a backend using ./symfony generate:app backend. Everything is working fine but I now want to add a count field to my encounters list which I think I should be able to do in generator.yml. In my Encounters.class.php I have the following method:

public function getPhotoCount() {

    return count($this->CcPhotos);
}

My questions is how can I add a new field in generator.yml which runs this method. I tried %%photo_count%% but I think this is intended for string substitution.

generator:
  class: sfDoctrineGenerator
  param:
    model_class:           CcEncounters
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          cc_encounters
    with_doctrine_route:   true
    actions_base_class:    sfActions

config:
  actions: ~
  fields:  ~
  list: ~
  filter:  ~
  form:    ~
  edit:    ~
  new:
    display: [_camera_id, longitude, latitude, elevation, New Photos]

Body:
I resolved this. It was as simple as adding:

    display: [id, longitude, latitude, elevation, photo_count]

Where 'photo_count' matches an accessor method called getPhotoCount


问:
Converting excel formulae to JS?
I have this formula and it uses powers e.g. '10 to the power 30'

```<code>=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)
</code>```

The problem is that I can't put ^ in JS/jQuery, I have to use Math.pow() as the equivalent.

I've tried quite a few different positions but I can't seem to get it correct, the brackets really confuse me. Which parts of the formula would I wrap the .pow within?

My attempt:  =B2*(B3/12) / Math.pow(   (1-(1+(B3/12)) ,  -B6)  )

UPDATE:
Please see this Fiddle

Fiddle code:

```<code>var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

var x = B2 * (B3 / 12) / Math.pow(1 - (1 + (B3 / 12)), -B6)

console.log(x);

//Expected/Excel result = 2,119.27
//Actual result  = 2.9884337938456618e-229 <- what's going on here?
</code>```

答:
Have not tried this, but one problem is probably that you're wrapping the two arguments in Math.pow() with a set parentheses.

In your original formula, you wrap the base and exponent in parentheses to group them together:

```<code>(1 - (1 + (B3 / 12)) ^ -B6)
</code>```

Math.pow() takes two arguments, the base, and the exponent:
Math.pow(base, exponent)

You can't use parentheses across two arguments in Javascript, and in fact you don't need to since the pow() function knows that the two arguments should be used together.

So instead of:

```<code>Math.pow((1 - (1 + (B3 / 12)), -B6))
</code>```

I think that should be more like:

```<code>Math.pow(1 - (1 + (B3 / 12)), -B6)
</code>```

Title: Converting excel formulae to JS?

Body:
I have this formula and it uses powers e.g. '10 to the power 30'

=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)

The problem is that I can't put ^ in JS/jQuery, I have to use Math.pow() as the equivalent.

I've tried quite a few different positions but I can't seem to get it correct, the brackets really confuse me. Which parts of the formula would I wrap the .pow within?

My attempt:  =B2*(B3/12) / Math.pow(   (1-(1+(B3/12)) ,  -B6)  )

UPDATE:
Please see this Fiddle

Fiddle code:

var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

var x = B2 * (B3 / 12) / Math.pow(1 - (1 + (B3 / 12)), -B6)

console.log(x);

//Expected/Excel result = 2,119.27
//Actual result  = 2.9884337938456618e-229 <- what's going on here?

Body:
Have not tried this, but one problem is probably that you're wrapping the two arguments in Math.pow() with a set parentheses.

In your original formula, you wrap the base and exponent in parentheses to group them together:

(1 - (1 + (B3 / 12)) ^ -B6)

Math.pow() takes two arguments, the base, and the exponent:
Math.pow(base, exponent)

You can't use parentheses across two arguments in Javascript, and in fact you don't need to since the pow() function knows that the two arguments should be used together.

So instead of:

Math.pow((1 - (1 + (B3 / 12)), -B6))

I think that should be more like:

Math.pow(1 - (1 + (B3 / 12)), -B6)


问:
Bluetooth app not working on devices running on Lollipop
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

```<code>private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }
</code>```

CheckBTPermissions()-

```<code>private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }
</code>```

Permissions in Manifest file-

```<code><uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
</code>```

build.gradle-

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

```<code>07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
</code>```

答: Runtime permission system was added in API 23, so you shouldn't check permissions under that API. And logcat tells you that it can't find a method that didn't existed in API 21.</p>

Body:
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }

CheckBTPermissions()-

private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }

Permissions in Manifest file-

<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />

build.gradle-

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)


问:
Grid with header row and usercontrol for rows (columns)
I have the following control, the first row is a header row. There will always be at least one additional row. (minimum of 2 total rows).

I've thought about making the content row into a UserControl but unsure about how to set the content of the UserControl into the two columns. (Stack in Column 0 and TriggerForWord in Column 1)

What is the best way to implement adding rows dynamically and setting the content? UserControl loaded into each row? Something else?

```<code>        <Grid Grid.Row="3" Margin="10,10,10,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Source={x:Static localization:Resources.WordToTriggerAction}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Source={x:Static localization:Resources.Trigger}}" Margin="12 8 2 8"  FontWeight="SemiBold" />
        <!-- dynamic part -->
        <StackPanel x:Name="Stack" Orientation="Horizontal" Grid.Row="1" Grid.Column="0" Margin="0,0,10,20" VerticalAlignment="Top">
            <telerik:RadAutoCompleteBox x:Name="WordForAction" Width="300" WatermarkContent="{Binding Source={x:Static localization:Resources.EnterWordForAction}}" Margin="0" ItemsSource="{Binding Path=Words}"
            DisplayMemberPath="word" SelectionMode="Single" AutoCompleteMode="Append" SearchTextChanged="WordForAction_SearchTextChanged" />
            <Button IsEnabled="{Binding Path=SearchText.Length, ElementName=WordForAction}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphPlus}" ToolTip="{Binding Source={x:Static localization:Resources.AddWord}}" VerticalAlignment="Bottom" />
            <Button IsEnabled="{Binding Path=SearchText.Length, ElementName=WordForAction}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphMinus}" ToolTip="{Binding Source={x:Static localization:Resources.RemoveWord}}" VerticalAlignment="Bottom" />
        </StackPanel>
        <telerik:RadComboBox x:Name="TriggerForWord" Grid.Row="1" Grid.Column="1" Width="150" EmptyText="{Binding Source={x:Static localization:Resources.Trigger}}" IsEditable="False" IsEnabled="False" SelectedValuePath="uuid" SelectionChanged="TriggerForWord_SelectionChanged"
            Height="{Binding ElementName=WordForAction, Path=ActualHeight}" Margin="10 0 0 0" ItemsSource="{Binding Path=Triggers}" DisplayMemberPath="description" VerticalAlignment="Top" />
    </Grid>
</code>```

答:
For other folks who come this way ...</p>

```<code>        <Grid Grid.Row="3" Margin="0,10,0,0" >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="310"/>
            <ColumnDefinition Width="150"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Source={x:Static localization:Resources.WordToTriggerAction}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Source={x:Static localization:Resources.Trigger}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <ItemsControl Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=WordsForAction}" x:Name="WordsForActionItems" >
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="0, 0, 0, 5">
                        <StackPanel Orientation="Horizontal" Margin="0" VerticalAlignment="Top" Width="310">
                            <telerik:RadAutoCompleteBox x:Name="WordForAction" Width="250" WatermarkContent="{Binding Source={x:Static localization:Resources.EnterWordForAction}}" Margin="0"
                                ItemsSource="{Binding Path=Words, ElementName=_this}" DisplayMemberPath="Word" SearchText="{Binding Word}"
                                SelectionMode="Single" AutoCompleteMode="Append" SearchTextChanged="WordForAction_SearchTextChanged" />
                            <Button Name="AddWord" IsEnabled="True" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphPlus}" Click="AddWord_Click" ToolTip="{Binding Source={x:Static localization:Resources.AddWord}}" VerticalAlignment="Bottom" />
                            <Button Name="RemoveWord" IsEnabled="{Binding Items.Count, ElementName=WordsForActionItems, Converter={StaticResource CountToBoolConverter}}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphMinus}" Click="RemoveWord_Click" ToolTip="{Binding Source={x:Static localization:Resources.RemoveWord}}" VerticalAlignment="Bottom" />
                        </StackPanel>
                        <telerik:RadComboBox Grid.Column="1" x:Name="TriggerForWord" Width="150" EmptyText="Trigger" IsEditable="False" IsEnabled="True" SelectionChanged="TriggerForWord_SelectionChanged"
                            Margin="0" ItemsSource="{Binding Path=Triggers, ElementName=_this}" SelectedValuePath="uuid" DisplayMemberPath="description" SelectedValue="{Binding Trigger_uuid}" />
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</code>```

Body:
I have the following control, the first row is a header row. There will always be at least one additional row. (minimum of 2 total rows).

I've thought about making the content row into a UserControl but unsure about how to set the content of the UserControl into the two columns. (Stack in Column 0 and TriggerForWord in Column 1)

What is the best way to implement adding rows dynamically and setting the content? UserControl loaded into each row? Something else?

        <Grid Grid.Row="3" Margin="10,10,10,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Source={x:Static localization:Resources.WordToTriggerAction}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Source={x:Static localization:Resources.Trigger}}" Margin="12 8 2 8"  FontWeight="SemiBold" />

        <StackPanel x:Name="Stack" Orientation="Horizontal" Grid.Row="1" Grid.Column="0" Margin="0,0,10,20" VerticalAlignment="Top">
            <telerik:RadAutoCompleteBox x:Name="WordForAction" Width="300" WatermarkContent="{Binding Source={x:Static localization:Resources.EnterWordForAction}}" Margin="0" ItemsSource="{Binding Path=Words}"
            DisplayMemberPath="word" SelectionMode="Single" AutoCompleteMode="Append" SearchTextChanged="WordForAction_SearchTextChanged" />
            <Button IsEnabled="{Binding Path=SearchText.Length, ElementName=WordForAction}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphPlus}" ToolTip="{Binding Source={x:Static localization:Resources.AddWord}}" VerticalAlignment="Bottom" />
            <Button IsEnabled="{Binding Path=SearchText.Length, ElementName=WordForAction}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphMinus}" ToolTip="{Binding Source={x:Static localization:Resources.RemoveWord}}" VerticalAlignment="Bottom" />
        </StackPanel>
        <telerik:RadComboBox x:Name="TriggerForWord" Grid.Row="1" Grid.Column="1" Width="150" EmptyText="{Binding Source={x:Static localization:Resources.Trigger}}" IsEditable="False" IsEnabled="False" SelectedValuePath="uuid" SelectionChanged="TriggerForWord_SelectionChanged"
            Height="{Binding ElementName=WordForAction, Path=ActualHeight}" Margin="10 0 0 0" ItemsSource="{Binding Path=Triggers}" DisplayMemberPath="description" VerticalAlignment="Top" />
    </Grid>

Body:
For other folks who come this way ...

        <Grid Grid.Row="3" Margin="0,10,0,0" >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="310"/>
            <ColumnDefinition Width="150"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Source={x:Static localization:Resources.WordToTriggerAction}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Source={x:Static localization:Resources.Trigger}}" Margin="2 8 2 8"  FontWeight="SemiBold" />
        <ItemsControl Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=WordsForAction}" x:Name="WordsForActionItems" >
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="0, 0, 0, 5">
                        <StackPanel Orientation="Horizontal" Margin="0" VerticalAlignment="Top" Width="310">
                            <telerik:RadAutoCompleteBox x:Name="WordForAction" Width="250" WatermarkContent="{Binding Source={x:Static localization:Resources.EnterWordForAction}}" Margin="0"
                                ItemsSource="{Binding Path=Words, ElementName=_this}" DisplayMemberPath="Word" SearchText="{Binding Word}"
                                SelectionMode="Single" AutoCompleteMode="Append" SearchTextChanged="WordForAction_SearchTextChanged" />
                            <Button Name="AddWord" IsEnabled="True" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphPlus}" Click="AddWord_Click" ToolTip="{Binding Source={x:Static localization:Resources.AddWord}}" VerticalAlignment="Bottom" />
                            <Button Name="RemoveWord" IsEnabled="{Binding Items.Count, ElementName=WordsForActionItems, Converter={StaticResource CountToBoolConverter}}" IsTabStop="False" Height="{Binding Path=ActualHeight, ElementName=WordForAction}" FontFamily="{StaticResource TelerikWebUI}" FontSize="15" Content="{StaticResource GlyphMinus}" Click="RemoveWord_Click" ToolTip="{Binding Source={x:Static localization:Resources.RemoveWord}}" VerticalAlignment="Bottom" />
                        </StackPanel>
                        <telerik:RadComboBox Grid.Column="1" x:Name="TriggerForWord" Width="150" EmptyText="Trigger" IsEditable="False" IsEnabled="True" SelectionChanged="TriggerForWord_SelectionChanged"
                            Margin="0" ItemsSource="{Binding Path=Triggers, ElementName=_this}" SelectedValuePath="uuid" DisplayMemberPath="description" SelectedValue="{Binding Trigger_uuid}" />
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>


问:
3D object pose from single image using object CAD
I'm working on a commercial product where I need to estimate the 6DOF pose of a known 3D CAD (closed 2-manifold triangular mesh) in a single 2D image. In general, this a difficult problem but under our operational conditions, we can impose the following constraints simplifying the problem:

The CAD object is known and we do NOT aim for generality like recognizing the class of all chairs.

We could get the user to position the camera approximately to a specific pose (distance from the object, general orientation +/-15deg, etc.)

If possible, we would use only the edges of the image (like Canny) to find and match against the object viewed from a given position.

This would be used in an industrial environment with manmade objects (pipes, valves, junctions, etc) without much texture.

All these constraints lead me to think that even relatively old and somewhat basic techniques could work.  For example, in the Sonka and al. book, section 12.3.2 Goad's algorithm explains a 1986 paper from Goad C. "Fast 3D model-based vision" which could work relatively well under our assumptions with its top-down "hypothesize-and-verify" approach.
I also know that the industrial vision and robotics community have tackled this problem and its generalization for a long time so there is bound to be something usable out there.

Would somebody know of a commercially usable implementation (like OpenCV, etc.) solving this problem?

More specifically:

I'm NOT looking for deep learning stuff needing an offline learning phase with thousands of viewpoints from our CAD models.

I'm NOT looking for RGB-D techniques relying on depth sensors. The color is also irrelevant as the CAD is colorless.

"Old" techniques out of research fashion are OK, even preferred as we will be running on a low performance computer.

Ideally, using C or C++ (may depend on OpenCV for example).

Usable commercially (licensed under BSD, MIT, BOOST, etc.), not GPL.

Thanks in advance for any leads anybody could offer.

答:
I would try to create many rendered images of your CAD models and subtract the real image and try to minimize the difference.

To minimize the search space you could think of creating a bounding box of the foreground object first, if that is feasible.


问:
How to find nouns and singularize using nlp-compromise
For example, if I have "hearts attack", I'd like to first find noun "hearts", and then convert to "heart", but still keep "heart attack"

How can I do this in NLP-compromise?

I've tried

```<code>doc.match("#Noun").nouns().toSingular().out('text')
</code>```

or

```<code>doc.nouns().toSingular().out('text')
</code>```

This will simply generate "heart" but lose "attack"

答:
Just get it work.

Simply try:

```<code>doc.nouns().toSingular()
var input2 = doc.out('text')
</code>```

But it puzzled me, what's the difference?

Body:
For example, if I have "hearts attack", I'd like to first find noun "hearts", and then convert to "heart", but still keep "heart attack"

How can I do this in NLP-compromise?

I've tried

doc.match("#Noun").nouns().toSingular().out('text')

or

doc.nouns().toSingular().out('text')

This will simply generate "heart" but lose "attack"

Body:
Just get it work.

Simply try:

doc.nouns().toSingular()
var input2 = doc.out('text')

But it puzzled me, what's the difference?


问:
How to check a net.Conn is closed?
Or how to check it is available for Read or Write in loop? If the conn is closed or not available, we should stop the loop.

For example:

```<code>package main

import "net"

func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:1111")
    defer conn.Close()
    for {
        buf := make([]byte, 1, 1)
        n, err := conn.Read(buf)
        if err != nil {
            // currently we can only stop the loop
            // when occur any errors
            log.Fatal(err)
        }
    }
}
</code>```

答:
You can get a number of errors, depending on how the connection was closed. The only error that you can count on receiving from a Read is an io.EOF. io.EOF is the value use to indicate that a connection was closed normally.

Other errors can be checked against the net.Error interface for its Timeout and Temporary methods. These are usually of the type net.OpError. Any non-temporary error returned from a Write is fatal, as it indicates the write couldn't succeed, but note that due to the underlying network API, writes returning no error still aren't guaranteed to have succeeded.

In general you can just follow the io.Reader api.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.

If there was data read, you handle that first. After you handle the data, you can break from the loop on any error. If it was io.EOF, the connection is closed normally, and any other errors you can handle as you see fit.

Title: How to check a net.Conn is closed?

Body:
Or how to check it is available for Read or Write in loop? If the conn is closed or not available, we should stop the loop.

For example:

package main

import "net"

func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:1111")
    defer conn.Close()
    for {
        buf := make([]byte, 1, 1)
        n, err := conn.Read(buf)
        if err != nil {
            // currently we can only stop the loop
            // when occur any errors
            log.Fatal(err)
        }
    }
}


问:
Not show Correct Scores java
in my code , i have 2 array name and score and length of both is 2

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

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}
</code>```

when i input names and scores, in output only show second scores for both names.

```<code>Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18
</code>```

this is my problem how can i fix it?

答:
For the second iteration - pertaining to the second name - you are overwriting the first set of scores that were inputted. You need to make the score array a 2d array of dimension 2x2.

```<code>int[][] score = new int[2][2];
</code>```

Then, in the nested for loops, reference score like this:

```<code>for(int i = 0; i < names.length; i++) {
     ...
     for(int j = 0; j < score[0].length; j++) {
          score[i][j] // score referenced like this
     }
     ...
}
</code>```

This way we have two separate arrays of length two for each name.

Title: Not show Correct Scores java

Body:
in my code , i have 2 array name and score and length of both is 2

import java.util.Scanner;

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}

when i input names and scores, in output only show second scores for both names.

Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18

this is my problem how can i fix it?

Body:
For the second iteration - pertaining to the second name - you are overwriting the first set of scores that were inputted. You need to make the score array a 2d array of dimension 2x2.

int[][] score = new int[2][2];

Then, in the nested for loops, reference score like this:

for(int i = 0; i < names.length; i++) {
     ...
     for(int j = 0; j < score[0].length; j++) {
          score[i][j] // score referenced like this
     }
     ...
}

This way we have two separate arrays of length two for each name.


问:
ActiveRecord: sort of complicated query with nested associations and sorting
Alrigth, so I'm not sure if this isn't too specific... But I really don't have a clue how to construct such a query, neither in AR, nor in SQL. So here's the situation:

I have a User model. User has_many Projects. A Project, in turn, have a following associations:

Project has_one BasicEvent

Project had_many AdditionalEvents

BasicEvent and AdditionalEvent classes are built on inheritance from a AR model class, Event

Now, the goal is this: on my view, I need:

access to all Projects count per User

access to all Events count, where happened_at attribute in nil

have all the Users sorted, by the count of Events, where happened_at attribute in nil

I made a couple of attempts at it so far, but didn't really get too far... I will appreciate any help with this complicated (at least from my perspective) query.

答:
You can start from code like:

```<code># -*- frozen-string-literal: true -*-
class UserStatService
  SELECT_CLAUSE = <<~SQL
    (SELECT count(1) FROM projects WHERE user_id=users.id) AS projects_count,
    (SELECT count(1) FROM events WHERE (happened_at IS NULL)
      AND (project_id IN (SELECT id FROM projects WHERE user_id=users.id)
    ) AS events_count,
    users.*
  SQL

  def call
    User
      .select( SELECT_CLAUSE )
      .order( 'events_count' )
  end
end
</code>```

Each User instance in resultset will have projects_count and events_count attributes.

Also any kind of cache (counter_cache or handmade) is recommended. Because the query is not expected to be fast.

Body:
You can start from code like:

# -*- frozen-string-literal: true -*-
class UserStatService
  SELECT_CLAUSE = <<~SQL
    (SELECT count(1) FROM projects WHERE user_id=users.id) AS projects_count,
    (SELECT count(1) FROM events WHERE (happened_at IS NULL)
      AND (project_id IN (SELECT id FROM projects WHERE user_id=users.id)
    ) AS events_count,
    users.*
  SQL

  def call
    User
      .select( SELECT_CLAUSE )
      .order( 'events_count' )
  end
end

Each User instance in resultset will have projects_count and events_count attributes.

Also any kind of cache (counter_cache or handmade) is recommended. Because the query is not expected to be fast.


问:
Private class variables won't change when function is called
I have problem when i try to change my 2 private class variables in FBullCowGame.h .It seems like constructor is calling function Reset() [Located in FBullCowGame.cpp] but Reset() function wont change integers MyMaxTries & MyCurrentTry.I'm new to c++ so probably it's something obvious but i can't find it .

This is main.cpp

```<code>#include <iostream>
#include <string>
#include "FBullCowGame.h"

using FText = std::string;

void PrintIntro();
void PlayGame();

FText GetGuess();
FText PrintGuess();

FBullCowGame BCGame;//Dodeljujemo naziv u main-u FBullCowGame-u , takodje ako ima neki kod u constructoru on ga izvrsava pri ovaj deklaraciji

bool AskToPlayAgain();

int main()
{

    bool bPlayAgain = false;
    do {
        PrintIntro();
        PlayGame();
        bPlayAgain = AskToPlayAgain();
        }
    while (bPlayAgain);

        return 0;
}

void PrintIntro()
{
    //Define constant var
    constexpr int WORD_LENGHT = 6;

    //Welcome to the player and asking the guess
    std::cout << "Welcome to Bulls and Cows\n";
    std::cout << "Can you guess my " << WORD_LENGHT;
    std::cout << " letter isogram word?\n";
}

void PlayGame()
{
    BCGame.Reset();
    int MaxTries = BCGame.GetMaxTries();
    //Looping for guesses
    for (int i = 1; i <= MaxTries; i++)
    {
        FText Guess = GetGuess();
        //Repeat the guess back to them
        std::cout << "Your guess is: " << Guess << std::endl;
        std::cout << std::endl;
    }
    return;
}

FText GetGuess()
{
    int CurrentTry = BCGame.GetCurrentTry();

    //Player enters their guess
    std::cout << std::endl << "Try " << CurrentTry << ".What is your guess?\n";
    FText Guess = "";
    std::getline(std::cin, Guess);

    return Guess;
}

bool AskToPlayAgain()
{
    FText Response = "";
    std::cout << "Do you want to play again (y/n) ?" << std::endl;
    std::getline(std::cin, Response);

    return (Response[0] == 'y') || (Response[0] == 'Y');

}
</code>```

FBullCowGame.h /

```<code>#pragma once
#include <string>

class FBullCowGame {
public:
    FBullCowGame();//Constructor izvrsava se kod u njemu pri deklaraciji BCGame u nasem slucaju

    int GetMaxTries() const;
    int GetCurrentTry()const;
    bool IsGameWon()const;

    void Reset();
    bool CheckGuessValidity(std::string);

private:
    //Compile time values gets overwritten by run time values in Constructor
    int MyMaxTries;
    int MyCurrentTry;

};
</code>```

And FBullCowGame.cpp /

```<code>#include "FBullCowGame.h"

FBullCowGame::FBullCowGame()
{
    //Run time values
    Reset();
}

void FBullCowGame::Reset()
{

    constexpr int MAX_TRIES = 8;
    int MyMaxTries = MAX_TRIES;
    int MyCurrentTry = 1;

    return;
}

int FBullCowGame::GetMaxTries ()const
{
    return MyMaxTries;
}

int FBullCowGame::GetCurrentTry ()const
{

    return MyCurrentTry;
}

bool FBullCowGame::IsGameWon ()const
{
    return false;
}

bool FBullCowGame::CheckGuessValidity(std::string)
{
    return false;
}
</code>```

答:
You are shadowing your member variables with function-local variables that happen to have the exact same name.

```<code>void FBullCowGame::Reset()
{

    constexpr int MAX_TRIES = 8;
    int MyMaxTries = MAX_TRIES;
    int MyCurrentTry = 1;

    return;
}
</code>```

Just assign to your member variables, but don't redeclare them

```<code>void FBullCowGame::Reset()
{
    constexpr int MAX_TRIES = 8;
    MyMaxTries = MAX_TRIES;
    MyCurrentTry = 1;
}
</code>```

Body:
I have problem when i try to change my 2 private class variables in FBullCowGame.h .It seems like constructor is calling function Reset() [Located in FBullCowGame.cpp] but Reset() function wont change integers MyMaxTries & MyCurrentTry.I'm new to c++ so probably it's something obvious but i can't find it .

This is main.cpp

#include <iostream>
#include <string>
#include "FBullCowGame.h"

using FText = std::string;

void PrintIntro();
void PlayGame();

FText GetGuess();
FText PrintGuess();

FBullCowGame BCGame;//Dodeljujemo naziv u main-u FBullCowGame-u , takodje ako ima neki kod u constructoru on ga izvrsava pri ovaj deklaraciji

bool AskToPlayAgain();

int main()
{

    bool bPlayAgain = false;
    do {
        PrintIntro();
        PlayGame();
        bPlayAgain = AskToPlayAgain();
        }
    while (bPlayAgain);

        return 0;
}

void PrintIntro()
{
    //Define constant var
    constexpr int WORD_LENGHT = 6;

    //Welcome to the player and asking the guess
    std::cout << "Welcome to Bulls and Cows\n";
    std::cout << "Can you guess my " << WORD_LENGHT;
    std::cout << " letter isogram word?\n";
}

void PlayGame()
{
    BCGame.Reset();
    int MaxTries = BCGame.GetMaxTries();
    //Looping for guesses
    for (int i = 1; i <= MaxTries; i++)
    {
        FText Guess = GetGuess();
        //Repeat the guess back to them
        std::cout << "Your guess is: " << Guess << std::endl;
        std::cout << std::endl;
    }
    return;
}

FText GetGuess()
{
    int CurrentTry = BCGame.GetCurrentTry();

    //Player enters their guess
    std::cout << std::endl << "Try " << CurrentTry << ".What is your guess?\n";
    FText Guess = "";
    std::getline(std::cin, Guess);

    return Guess;
}

bool AskToPlayAgain()
{
    FText Response = "";
    std::cout << "Do you want to play again (y/n) ?" << std::endl;
    std::getline(std::cin, Response);

    return (Response[0] == 'y') || (Response[0] == 'Y');

}

FBullCowGame.h /

#pragma once
#include <string>

class FBullCowGame {
public:
    FBullCowGame();//Constructor izvrsava se kod u njemu pri deklaraciji BCGame u nasem slucaju

    int GetMaxTries() const;
    int GetCurrentTry()const;
    bool IsGameWon()const;

    void Reset();
    bool CheckGuessValidity(std::string);

private:
    //Compile time values gets overwritten by run time values in Constructor
    int MyMaxTries;
    int MyCurrentTry;

};

And FBullCowGame.cpp /

#include "FBullCowGame.h"

FBullCowGame::FBullCowGame()
{
    //Run time values
    Reset();
}

void FBullCowGame::Reset()
{

    constexpr int MAX_TRIES = 8;
    int MyMaxTries = MAX_TRIES;
    int MyCurrentTry = 1;

    return;
}

int FBullCowGame::GetMaxTries ()const
{
    return MyMaxTries;
}

int FBullCowGame::GetCurrentTry ()const
{

    return MyCurrentTry;
}

bool FBullCowGame::IsGameWon ()const
{
    return false;
}

bool FBullCowGame::CheckGuessValidity(std::string)
{
    return false;
}

Body:
You are shadowing your member variables with function-local variables that happen to have the exact same name.

void FBullCowGame::Reset()
{

    constexpr int MAX_TRIES = 8;
    int MyMaxTries = MAX_TRIES;
    int MyCurrentTry = 1;

    return;
}

Just assign to your member variables, but don't redeclare them

void FBullCowGame::Reset()
{
    constexpr int MAX_TRIES = 8;
    MyMaxTries = MAX_TRIES;
    MyCurrentTry = 1;
}


问:
How can I get the depth intensity from kinect depth image since it respresents distance of pixel from sensor
Recently i read a paper , they extract depth intensity and distance of pixel from camera using depth image. But, as far I know, each pixel value in depth image represents distance in mm [range:0-65536] then how can they extract depth intensity within a range [0 to 255] from depth image. I don't understand it. kinect sensor returns uint16 depth frame which includes the each pixel distance from sensor. It does not return any intensity value, then how can the paper demonstrates that they extract depth intensity . I am really confused.

Here is the paper link

This is the graph what I want to extract(collected from the paper:

答:
Since there is no an answer for this question , i will suggest you approach for getting your own depth image data .

One simple way can be scaling the image based on following formula:

```<code>    Pixel_value=Pixel_value/4500*65535
</code>```

If you want see the exact image that you get from uint8 ; I guess the following steps will work for you.

Probably while casting the image to uint8 matlab firstly clip the values above some threshold lets say  4095=2**12-1 (i'm not sure about value) and then it makes right shifts (4 shifts in our case) to make it inside the range of 0-255.

So i guess multiplying the value of uint8 with 256 and casting it as uint16 will help you get the same image

```<code>        Pixel_uint16_value= Pixel_uint8_value*256 //or Pixel_uint16_value= Pixel_uint8_value<<8
        //dont forget to cast the result as uint16
</code>```

The other way to converting raw data to depth image in millimeters.

The depth image
should be stored in millimeters and as 16 bit unsigned
integers. The following two formulas can be used for
converting raw-data to millimeters .

```<code>distance = 1000/ (− 0.00307 ∗ rawDisparity + 3.33 )
distance = 123.6 ∗ tan ( rawDisparity/2842.5 + 1.1863 )
</code>```

Save each distance value to coressponding rawdisparty pixel. Save them as 16 bit unsigned grayscale png images. Check this link for details.

Body:
Since there is no an answer for this question , i will suggest you approach for getting your own depth image data .

One simple way can be scaling the image based on following formula:

    Pixel_value=Pixel_value/4500*65535

If you want see the exact image that you get from uint8 ; I guess the following steps will work for you.

Probably while casting the image to uint8 matlab firstly clip the values above some threshold lets say  4095=2**12-1 (i'm not sure about value) and then it makes right shifts (4 shifts in our case) to make it inside the range of 0-255.

So i guess multiplying the value of uint8 with 256 and casting it as uint16 will help you get the same image

        Pixel_uint16_value= Pixel_uint8_value*256 //or Pixel_uint16_value= Pixel_uint8_value<<8
        //dont forget to cast the result as uint16

The other way to converting raw data to depth image in millimeters.

The depth image
should be stored in millimeters and as 16 bit unsigned
integers. The following two formulas can be used for
converting raw-data to millimeters .

distance = 1000/ (− 0.00307 ∗ rawDisparity + 3.33 )
distance = 123.6 ∗ tan ( rawDisparity/2842.5 + 1.1863 )

Save each distance value to coressponding rawdisparty pixel. Save them as 16 bit unsigned grayscale png images. Check this link for details.


问:
Get "Adj Close" using pandas DataReader
I just switched from pandas.io to pandas_datareader and I'm having difficulties pulling in just Adjusted Close prices. before I could use the following code

```<code>pd.io.data.get_data_yahoo(stock, start, end)['Adj Close']
</code>```

now when I try the datareader (imported as web) it does not work.

```<code>web.get_data_yahoo(stock, start, end)['Adj Close']
</code>```

I've tried to find documentation to see if there is a new argument that the pandas_datareader uses, but I have had no luck. Is there anyway to pull in just Adjusted Close data using the new pandas library?

答:
This solution is no longer viable. When I run:

```<code>import pandas_datareader.data as web
web.get_data_yahoo('AAPL')
</code>```

This yields:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='ichart.finance.yahoo.com', port=80): Max retries exceeded with url: /table.csv?a=0&ignore=.csv&s=AAPL&b=1&e=7&d=6&g=d&f=2017&c=2010 (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

Looks like Quanld could provide a better solution

Title: Get "Adj Close" using pandas DataReader

Body:
I just switched from pandas.io to pandas_datareader and I'm having difficulties pulling in just Adjusted Close prices. before I could use the following code

pd.io.data.get_data_yahoo(stock, start, end)['Adj Close']

now when I try the datareader (imported as web) it does not work.

web.get_data_yahoo(stock, start, end)['Adj Close']

I've tried to find documentation to see if there is a new argument that the pandas_datareader uses, but I have had no luck. Is there anyway to pull in just Adjusted Close data using the new pandas library?

Body:
This solution is no longer viable. When I run:

import pandas_datareader.data as web
web.get_data_yahoo('AAPL')

This yields:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='ichart.finance.yahoo.com', port=80): Max retries exceeded with url: /table.csv?a=0&ignore=.csv&s=AAPL&b=1&e=7&d=6&g=d&f=2017&c=2010 (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

Looks like Quanld could provide a better solution


问:
Return a tuple with the most common elements from list of lists
I have a list:

```<code>list = [{"maamaks kaotada", "pensione tõsta", "kaitsekulutusi tõsta"},
        {"lasteaiaõpetajate palku tõsta", "kindlustada tasuta hambaravi kuni 30-aastastele"},
        {"sisserännet piirata", "pensione tõsta", "kaitsekulutusi tõsta"},
        set()]
</code>```

I need to create a tuple ((0, 2) in this case) which has the most common elements. list with index 0 and list with index 2 have the most common elements, so the tuple must be (0, 2). How can I do this?

答:
You've already created your list:

```<code>>>> my_list = [{"maamaks kaotada", "pensione tõsta", "kaitsekulutusi tõsta"},
...         {"lasteaiaõpetajate palku tõsta", "kindlustada tasuta hambaravi kuni 30-aastastele"},
...         {"sisserännet piirata", "pensione tõsta", "kaitsekulutusi tõsta"},
...         set()]
</code>```

After that the first step would be to count the number of occurences of each string:

```<code>>>> counts = {}
>>> for dict in myList:
...     for key in dict:
...         counts[key] = counts.get(key,0) + 1
...
>>> counts
{'pensione tõsta': 2, 'maamaks kaotada': 1, 'kindlustada tasuta hambaravi kuni 30-aastastele': 1, 'kaitsekulutusi tõsta': 2, 'sisserännet piirata': 1, 'lasteaiaõpetajate palku tõsta': 1}
</code>```

You can now find the number of counts for the most frequent item[s]:

```<code>>>> frequent_count = max([counts[i] for i in counts])
>>> frequent_count
2
</code>```

and generate a list of the most frequent item[s]:

```<code>>>> frequent = []
>>> for key in counts:
...     if counts[key] == max([counts[i] for i in counts]):
...         frequent += [key]
...
>>> frequent
['pensione tõsta', 'kaitsekulutusi tõsta']
</code>```

and finally get the list of sets containing any of your most frequent strings:

```<code>>>> final_list = []
>>> for i in ,y_list:
...     if any(item in i for item in frequent):
...         final_list += [i]
...
>>> tuple(final_list)
({'pensione tõsta', 'maamaks kaotada', 'kaitsekulutusi tõsta'}, {'pensione tõsta', 'kaitsekulutusi tõsta', 'sisserännet piirata'})
</code>```

or if you want the indices:

```<code>>>> final_list = []
>>> for i in range(len(my_list)):
...     if any(item in my_list[i] for item in frequent):
...         final_list += [i]
...
>>> tuple(final_list)
(0, 2)
</code>```

Body:
I have a list:

list = [{"maamaks kaotada", "pensione tõsta", "kaitsekulutusi tõsta"},
        {"lasteaiaõpetajate palku tõsta", "kindlustada tasuta hambaravi kuni 30-aastastele"},
        {"sisserännet piirata", "pensione tõsta", "kaitsekulutusi tõsta"},
        set()]

I need to create a tuple ((0, 2) in this case) which has the most common elements. list with index 0 and list with index 2 have the most common elements, so the tuple must be (0, 2). How can I do this?

Body:
You've already created your list:

>>> my_list = [{"maamaks kaotada", "pensione tõsta", "kaitsekulutusi tõsta"},
...         {"lasteaiaõpetajate palku tõsta", "kindlustada tasuta hambaravi kuni 30-aastastele"},
...         {"sisserännet piirata", "pensione tõsta", "kaitsekulutusi tõsta"},
...         set()]

After that the first step would be to count the number of occurences of each string:

>>> counts = {}
>>> for dict in myList:
...     for key in dict:
...         counts[key] = counts.get(key,0) + 1
...
>>> counts
{'pensione tõsta': 2, 'maamaks kaotada': 1, 'kindlustada tasuta hambaravi kuni 30-aastastele': 1, 'kaitsekulutusi tõsta': 2, 'sisserännet piirata': 1, 'lasteaiaõpetajate palku tõsta': 1}

You can now find the number of counts for the most frequent item[s]:

>>> frequent_count = max([counts[i] for i in counts])
>>> frequent_count
2

and generate a list of the most frequent item[s]:

>>> frequent = []
>>> for key in counts:
...     if counts[key] == max([counts[i] for i in counts]):
...         frequent += [key]
...
>>> frequent
['pensione tõsta', 'kaitsekulutusi tõsta']

and finally get the list of sets containing any of your most frequent strings:

>>> final_list = []
>>> for i in ,y_list:
...     if any(item in i for item in frequent):
...         final_list += [i]
...
>>> tuple(final_list)
({'pensione tõsta', 'maamaks kaotada', 'kaitsekulutusi tõsta'}, {'pensione tõsta', 'kaitsekulutusi tõsta', 'sisserännet piirata'})

or if you want the indices:

>>> final_list = []
>>> for i in range(len(my_list)):
...     if any(item in my_list[i] for item in frequent):
...         final_list += [i]
...
>>> tuple(final_list)
(0, 2)


问:
Should I compress the data being exposed via wcf service?
I'm creating a WCF service which exposes an object graph which is expected to grow in size while the service is up and running.  In playing with some test data (85k), smaller that would be expected when live, I hit the default 65k message size limit.  A quick look on the net showed that it was simple enough to extend this in the config.

As I'm creating the service and the client which consumes it, I wondered if there was added value in compressing the data before I sent it.  Having run a brief test, the test data shrunk to around 7k, so this looks like it will aid in the time for the message to be sent over the wire and increase the amount of data I could send.

The service pre-prepares the data before the first call is made and so there is no initial overhead on every call due to the compression.

Is it a good idea to do this for the sake of scalability, and trying to optimise performance, or is this adding complexity where it is not needed?

答: As long as you're not using an obscure compression format, I don't think you're adding any appreciable complexity. One or two lines of code. Perhaps you could add a parameter to the service call which lets the client choose compressed or uncompressed data.</p>


问:
Clic and slide at the same time - Protractor
Hello the community !

I'm coding a test for e2e, and I would like to slide the right circle to the extreme left for testing the price tool on my website.

I would like to click and slide the slider at the same time (check on picture).

The problem is that for sliding, the mouse has to be on the slide during all the action with the click activate.

I would like to know how to do it with Protractor :)

Thank you !!!
Price slider

答:
I have had one of these sliders in one of my projects, and I did it via simple drag and drop code. Here is the one that I used (thanks alecxe for this)

```<code>   var slider = element(by.id('slider'));

   browser.actions().dragAndDrop(
      slider,
      {x:100, y:0}
      ).perform();
</code>```

where x,y are the coordinates to which I have to move the slider.

Body:
I have had one of these sliders in one of my projects, and I did it via simple drag and drop code. Here is the one that I used (thanks alecxe for this)

   var slider = element(by.id('slider'));

   browser.actions().dragAndDrop(
      slider,
      {x:100, y:0}
      ).perform();

where x,y are the coordinates to which I have to move the slider.


问:
SSMA "Required mdb-file $accessFileName is not loaded"
Hello Stackoverflow this is my first time here so please be easy on me.

I am trying to use a SSMA (SQL Server Migration Assistant) to import a .accdb Microsoft access file type to a SQL server. However when I try to import the file I get an error that says

Required mdb-file $fileName is not loaded

I know .mdb is the file type of access <=2007 however I am using access 2016. I am told that SSMA is the best way to import a .accdb over to a SQL server but can I if it needs to be a .mdb?

If I can import a .accdb using an SSMA what am I doing wrong to get this error and if I can't what program should I be using to do the import?

答: I have fixed the issue by installing Access runtime even with the full version of access on the computer it still needed runtime for external programs to use apparently  </p>


问:
How can I add a new row at the top of my datatable in JSF?
Every time I add a new row in my datatable (via commandbutton "new Feedback") it is added at the bottom of the datatable. How can I add it and make sure that it will appear at the top?</p>

```<code><h:form>
    <h:inputText value="#{helloBean.content}" ></h:inputText>
    <h:commandButton value="send message"
        action="#{helloBean.multiAufruf}">
    </h:commandButton>
    <h:commandButton value="new Feedback"
        action="#{helloBean.gettingFeedbackMulti}">
    </h:commandButton>

    <h:dataTable value="#{helloBean.sentMessagesList}" var="message">
        <h:column>
            <h:inputText value="#{message.content}"></h:inputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.time}"></h:outputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.idList}"></h:outputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.feedbackz}"></h:outputText>
        </h:column>
    </h:dataTable>
</h:form>
</code>```

答:
In your action method for the command gettingFeedbackMulti, you are probably doing something like this

```<code>sentMessagesList.add(message);
</code>```

Just change it to use add() with index argument like this

```<code>sentMessagesList.add(0, message);
</code>```

This will add it to index 0 of your list

Body:
Every time I add a new row in my datatable (via commandbutton "new Feedback") it is added at the bottom of the datatable. How can I add it and make sure that it will appear at the top?

<h:form>
    <h:inputText value="#{helloBean.content}" ></h:inputText>
    <h:commandButton value="send message"
        action="#{helloBean.multiAufruf}">
    </h:commandButton>
    <h:commandButton value="new Feedback"
        action="#{helloBean.gettingFeedbackMulti}">
    </h:commandButton>

    <h:dataTable value="#{helloBean.sentMessagesList}" var="message">
        <h:column>
            <h:inputText value="#{message.content}"></h:inputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.time}"></h:outputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.idList}"></h:outputText>
        </h:column>
        <h:column>
            <h:outputText value="#{message.feedbackz}"></h:outputText>
        </h:column>
    </h:dataTable>
</h:form>

Body:
In your action method for the command gettingFeedbackMulti, you are probably doing something like this

sentMessagesList.add(message);

Just change it to use add() with index argument like this

sentMessagesList.add(0, message);

This will add it to index 0 of your list


问:
Share OpenGL code between Emscripten and Qt
I'd like to share rendering code between my Emscripten-based frontend (Webgl2 aka GLES3.0) and my Qt frontend (OGL3.3, but wouldn't mind GLES3.0 there too, if feasible).
Both use exactly the same GL-calls, so i would like to move all calls to helper-functions that are then called from the frontend.

The problem is that to be portable, i want to call the functions from GLES3/gl3.h in the emscripten-part, while using QOpenGLFunctions in the Qt-part (or another, equally portable solution):

guiwrapper.cpp:

```<code>#include <GLES3/gl3.h>
void drawStuff(){
    glDrawArrays(...); // taken from <GLES3/gl3.h>
}
</code>```

emscripten.cpp:

```<code>#include <guiwrapper.h>
void someDrawFunc(){
    drawStuff(); // glDrawArrays pulled from <GLES3/gl3.h>
    glDrawArrays(...); // also correctly uses <GLES3/gl3.h> version
}
</code>```

qt.cpp:

```<code>class guiwidget: public QOpenGLWidget, protected QOpenGLFunctions{
public:
    void paintGL(void);
}
void guiwidget::paintGL(){
     glDrawArrays(...); // correctly calls QOpenGLFunctions::glDrawArrays
     drawStuff(); // still uses <GLES3/gl3.h>
}
</code>```

Is there a possibility to achieve this without writing all helper-functions as macros?

答:
I now found a satisfying solution, that's not completely devoid of preprocessor-magic, but at least there are neither macros nor code-duplication.
Maybe it helps someone:

guiwrapper.h:

```<code>#ifdef __EMSCRIPTEN__
#include <GLES3/gl3.h>
class GuiWrapper
#else
#include <QOpenGLFunctions>
class GuiWrapper: protected QOpenGLFunctions
#endif
{
    void drawStuff(void); // cpp decides between free and member-functions
};
</code>```

emscripten.cpp:

```<code>#include <guiwrapper.h>
void someFunc(void){
    GuiWrapper gui;
    gui.drawStuff(); // calls <GLES3/gl3.h>
}
</code>```

glwidget.cpp:

```<code>#include <guiwrapper.h>
#include <QOpenGLWidget>
class GLWidget: public QOpenGLWidget, private GuiWrapper{
    public:
        void paintGL(void){
            drawStuff(); // calls <QOpenGLFunctions>
        }
};
</code>```

Body:
I'd like to share rendering code between my Emscripten-based frontend (Webgl2 aka GLES3.0) and my Qt frontend (OGL3.3, but wouldn't mind GLES3.0 there too, if feasible).
Both use exactly the same GL-calls, so i would like to move all calls to helper-functions that are then called from the frontend.

The problem is that to be portable, i want to call the functions from GLES3/gl3.h in the emscripten-part, while using QOpenGLFunctions in the Qt-part (or another, equally portable solution):

guiwrapper.cpp:

#include <GLES3/gl3.h>
void drawStuff(){
    glDrawArrays(...); // taken from <GLES3/gl3.h>
}

emscripten.cpp:

#include <guiwrapper.h>
void someDrawFunc(){
    drawStuff(); // glDrawArrays pulled from <GLES3/gl3.h>
    glDrawArrays(...); // also correctly uses <GLES3/gl3.h> version
}

qt.cpp:

class guiwidget: public QOpenGLWidget, protected QOpenGLFunctions{
public:
    void paintGL(void);
}
void guiwidget::paintGL(){
     glDrawArrays(...); // correctly calls QOpenGLFunctions::glDrawArrays
     drawStuff(); // still uses <GLES3/gl3.h>
}

Is there a possibility to achieve this without writing all helper-functions as macros?

Body:
I now found a satisfying solution, that's not completely devoid of preprocessor-magic, but at least there are neither macros nor code-duplication.
Maybe it helps someone:

guiwrapper.h:

#ifdef __EMSCRIPTEN__
#include <GLES3/gl3.h>
class GuiWrapper
#else
#include <QOpenGLFunctions>
class GuiWrapper: protected QOpenGLFunctions
#endif
{
    void drawStuff(void); // cpp decides between free and member-functions
};

emscripten.cpp:

#include <guiwrapper.h>
void someFunc(void){
    GuiWrapper gui;
    gui.drawStuff(); // calls <GLES3/gl3.h>
}

glwidget.cpp:

#include <guiwrapper.h>
#include <QOpenGLWidget>
class GLWidget: public QOpenGLWidget, private GuiWrapper{
    public:
        void paintGL(void){
            drawStuff(); // calls <QOpenGLFunctions>
        }
};


问:
Repair corrupted Git repository
My Git repository got corrupted after a couple of hard reboots due to power supply issues and now I'm unable to fix it (I was in the middle of staging some files at the last power failure):

```<code>$ git status
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git fsck
fatal: failed to read object 24377c609184c192f3f3c1733bac7115c1080758: Invalid argument
$ git branch -a
(...works, lists branches...)
$ git checkout someotherbranch
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git log
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git log someotherbranch
(...works, shows commits...)
</code>```

So, as you can see, my current branch is pretty screwed up, and I don't seem to be able to fix it. What can I try to repair this?

答:
Another alternative which worked for me was to reset the Git head and index to its previous state using:

```<code>git reset --keep
</code>```

I also tried the following commands, but they did not work for me, but they might for you:

```<code>git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all
</code>```

ContentLicense: CC BY-SA 4.0

Title: Repair corrupted Git repository

Body:
My Git repository got corrupted after a couple of hard reboots due to power supply issues and now I'm unable to fix it (I was in the middle of staging some files at the last power failure):

$ git status
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git fsck
fatal: failed to read object 24377c609184c192f3f3c1733bac7115c1080758: Invalid argument
$ git branch -a
(...works, lists branches...)
$ git checkout someotherbranch
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git log
fatal: failed to read object 3d18855708b0f127d40c13c679559d7679228b69: Invalid argument
$ git log someotherbranch
(...works, shows commits...)

So, as you can see, my current branch is pretty screwed up, and I don't seem to be able to fix it. What can I try to repair this?

Body:
Another alternative which worked for me was to reset the Git head and index to its previous state using:

git reset --keep

I also tried the following commands, but they did not work for me, but they might for you:

git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all


问:
Programmatically generating BigQuery schema in Beam pipeline
I have a collection of homogeneous dicts, how do I write them to BigQuery without knowing the schema?

The BigQuerySink requires that I specify the schema when I construct it. But, I don't know the schema: it's defined by the keys of the dicts I'm trying to write.

Is there a way to have my pipeline infer the schema, and then provide it back (as a sideinput?) to the sink?

For example:

```<code># Create a PCollection of dicts, something like
# {'field1': 'myval', 'field2': 10}
data = (p | 'generate_data' >> beam.ParDo(CreateData())

# Infer the schema from the data
# Generates a string for each element (ok to assume all dict keys equal)
# "field1:STRING, field2:INTEGER"
schema = (data
  | 'infer_schema' >> beam.ParDo(InferSchema())
  | 'sample_one'   >> beam.combiners.Sample.FixedSizeGlobally(1))
</code>```

But then, how do I feed the schema as a parameter to the BigQuerySink, and use that in a beam.io.Write?

I know this isn't correct, but what I want to do is:

```<code>sink = BigQuerySink(tablename, dataset, project, schema=Materialize(schema))
p | 'write_bigquery' >> beam.io.Write(sink)
</code>```

tl;dr
Is there a way to create and write a bigquery table from apache beam programmatically inferring the schema from the data?

答:
For now the best solution I've come up with is explicitly hardcoding a mapping of dict keys to BigQuery schema. Two benefits -- it works around the must-specify-schema issue and it lets me filter elements out of the dict I don't want in the BigQuery.</p>

```<code>SCHEMA = {
  'field1': 'INTEGER',
  'field2': 'STRING',
  ...
}
schema_str = ','.join(['%s:%s' % (k, v) for k,v in SCHEMA.iteritems()])

sink = BigQuerySink(tablename,
        dataset=dataset,
        project=project,
        schema=schema_str,
        write_disposition=BigQueryDisposition.WRITE_TRUNCATE)

(pipeline
  # filters just the keys of each dict to the keys of SCHEMA.
  | 'filter_fields' >> beam.ParDo(FilterFieldKeysDoFn(SCHEMA))
  | 'to_bigquery' >> beam.io.Write(sink))
</code>```

Body:
I have a collection of homogeneous dicts, how do I write them to BigQuery without knowing the schema?

The BigQuerySink requires that I specify the schema when I construct it. But, I don't know the schema: it's defined by the keys of the dicts I'm trying to write.

Is there a way to have my pipeline infer the schema, and then provide it back (as a sideinput?) to the sink?

For example:

# Create a PCollection of dicts, something like
# {'field1': 'myval', 'field2': 10}
data = (p | 'generate_data' >> beam.ParDo(CreateData())

# Infer the schema from the data
# Generates a string for each element (ok to assume all dict keys equal)
# "field1:STRING, field2:INTEGER"
schema = (data
  | 'infer_schema' >> beam.ParDo(InferSchema())
  | 'sample_one'   >> beam.combiners.Sample.FixedSizeGlobally(1))

But then, how do I feed the schema as a parameter to the BigQuerySink, and use that in a beam.io.Write?

I know this isn't correct, but what I want to do is:

sink = BigQuerySink(tablename, dataset, project, schema=Materialize(schema))
p | 'write_bigquery' >> beam.io.Write(sink)

tl;dr
Is there a way to create and write a bigquery table from apache beam programmatically inferring the schema from the data?

Body:
For now the best solution I've come up with is explicitly hardcoding a mapping of dict keys to BigQuery schema. Two benefits -- it works around the must-specify-schema issue and it lets me filter elements out of the dict I don't want in the BigQuery.

SCHEMA = {
  'field1': 'INTEGER',
  'field2': 'STRING',
  ...
}
schema_str = ','.join(['%s:%s' % (k, v) for k,v in SCHEMA.iteritems()])

sink = BigQuerySink(tablename,
        dataset=dataset,
        project=project,
        schema=schema_str,
        write_disposition=BigQueryDisposition.WRITE_TRUNCATE)

(pipeline
  # filters just the keys of each dict to the keys of SCHEMA.
  | 'filter_fields' >> beam.ParDo(FilterFieldKeysDoFn(SCHEMA))
  | 'to_bigquery' >> beam.io.Write(sink))


问:
Display a Backbone collection with HTML formatting
I have a Marionette CollectionView displaying some data from a collection. It's all working fine BUT some items in my collection has HTML tags.

To make it easier, here is only two items:

```<code>var topics = [
  { content: 'This is a <strong>bold</strong> content' },
  { content: 'This is a <i>italic</i> content' }
];
</code>```

On screen is being displayed:

This is a bold content

This is a italic content

instead of

This is a bold content

This is a italic content

There is some Marionette native attribute to allow HTML formatting or should I write a function to convert the HTML entities?
Thank you for advance.

答:
Assuming you are using Underscore/JS templates, you just need to make sure you are interpolating the values (using <%=):

```<code><div><%= content %></div>
</code>```

vs HTML-escaping:

```<code><div><%- content %></div>
</code>```

The following fiddle shows a more complete example: https://jsfiddle.net/8m7ot074/

If you are using handlebars to handle your templating, you'd need to use the 'triple-stache': {{{content}}}

Body:
I have a Marionette CollectionView displaying some data from a collection. It's all working fine BUT some items in my collection has HTML tags.

To make it easier, here is only two items:

var topics = [
  { content: 'This is a bold content' },
  { content: 'This is a italic content' }
];

On screen is being displayed:

This is a bold content

This is a italic content

instead of

This is a bold content

This is a italic content

There is some Marionette native attribute to allow HTML formatting or should I write a function to convert the HTML entities?
Thank you for advance.

Body:
Assuming you are using Underscore/JS templates, you just need to make sure you are interpolating the values (using <%=):

<div><%= content %></div>

vs HTML-escaping:

<div><%- content %></div>

The following fiddle shows a more complete example: https://jsfiddle.net/8m7ot074/

If you are using handlebars to handle your templating, you'd need to use the 'triple-stache': {{{content}}}


问:
Escaping characters from unicode string
I am trying to store u'\U0001f381' string in Azure sql server from python 2.7.11 in ubuntu 14.04 LTS. I have set the column type as nvarchar(MAX) so that it will accept unicode strings.
following is the python script:

```<code>import pymssql
from creds import *
conn = pymssql.connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE)
cursor = conn.cursor()

lst = [u'2017-07-04', u'\U0001f3e8', 1.0, 0.0, 0.0, 9.0]

print lst
placeholder = '%s,' * len(lst)

query = 'INSERT INTO Example_SearchAnalytics VALUES ( '+placeholder.rstrip(',')+ ')'

cursor.execute(query,tuple(lst))

conn.commit()

conn.close()
</code>```

But I am getting following error when I execute above script from ubuntu environment.

pymssql.OperationalError: (105, "Unclosed quotation mark after the
  character string ''.DB-Lib error message 20018, severity 15:\nGeneral
  SQL Server error: Check messages from the SQL Server\nDB-Lib error
  message 20018, severity 15:\nGeneral SQL Server error: Check messages
  from the SQL Server\n")

I don't get any error when I execute same script from windows environment. I think I need to escape any character from unicode string but I am not sure which.
Please help.

答:
Repeat quotation marks or use CHAR(39) as explained on below thread:

Escaping single quote in SQL Server

Hope this helps.

Regards,

Alberto Morillo

Title: Escaping characters from unicode string

Body:
I am trying to store u'\U0001f381' string in Azure sql server from python 2.7.11 in ubuntu 14.04 LTS. I have set the column type as nvarchar(MAX) so that it will accept unicode strings.
following is the python script:

import pymssql
from creds import *
conn = pymssql.connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE)
cursor = conn.cursor()

lst = [u'2017-07-04', u'\U0001f3e8', 1.0, 0.0, 0.0, 9.0]

print lst
placeholder = '%s,' * len(lst)

query = 'INSERT INTO Example_SearchAnalytics VALUES ( '+placeholder.rstrip(',')+ ')'

cursor.execute(query,tuple(lst))

conn.commit()

conn.close()

But I am getting following error when I execute above script from ubuntu environment.

pymssql.OperationalError: (105, "Unclosed quotation mark after the
  character string ''.DB-Lib error message 20018, severity 15:\nGeneral
  SQL Server error: Check messages from the SQL Server\nDB-Lib error
  message 20018, severity 15:\nGeneral SQL Server error: Check messages
  from the SQL Server\n")

I don't get any error when I execute same script from windows environment. I think I need to escape any character from unicode string but I am not sure which.
Please help.


问:
What does "application/json'" really mean
I don't know application's mean in "application/json", and can I replace it with "text/json". so application = text ?</p>

答:
I think you are meaning content type

Application : Represents any kind of binary data.

Text : Represents any document that contains text and is theoretically human readable

For more info visit here