问:
how to access the "id',"name" etc. of Loaded URL in iframe from the HTML file
I  have an Iframe.html file :

```<code><body onload="alert('frame 1 loaded');">
<div> This is frame 1 content </div>
<a id="a1" href="Sample.html"> click</a>
</body>
</code>```

Sample.html

```<code><body>
<ul id="list1">
<li name="one">one</li>
<li name="two">two</li>
</ul>
</code>```

And I calling the iframe form test.html file :

```<code>   <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    var i=10;
    $("#frame1").ready(function () {

    $('#frame1').contents().find('#a1').click(function() {
       alert("Hello");
      $('#frame1').attr('src', $('#frame1').contents().find('#a1').attr("href"));
      $('#frame1').load();
    });
    $('#frame1').contents().find('#a1').click();
</script>
    </head>
    <body onload="handleMainOnload();">
        <!--iframe id="frame1" src="about:blank"/-->
        <iframe id="frame1" src="iframe.html"/>
    </body>
</code>```

Now I tried using the content of URL loaded in iframe i.e. Sample.html in test.html as follows :

```<code>$('#frame1').contents().find('#list1 li[name=one]').click(function() {
   alert(" Clicking list....");
});

$('#frame1').contents().find('#list1 li[name=one]').click();
</code>```

But this doesn't work.. Can you please tell me From Test.html how to access Sample.html file content like(id,name,class etc.) which is loaded in iframe.html using JQuery.
Please help.

Thanks
Kamakshi

答:
```<code><html>
<head>
<title>Main Frame 2 Title </title>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
------
------
alert("frame ready");
var $value1 = $frame.contents().find('#list1 li[name=one]').html() ;
alert("loaded + " + $value1);
$frame.contents().find('#list1 li[name=one]').click(function() {
    alert("About + clicked");
});
$frame.contents().find('#list1 li[name=one]').click();
 });  });
</script>
</head>
<body>
 <iframe id="frame1" src="sample.html" />
</code>```

This works fine, if i am giving iframe src=sample.html directly instead of redirecting using another file (i.e. src=iframe.html) and keeping Sample.html in same domain as parent file (test.html).

ContentLicense: CC BY-SA 2.5

Body:
I  have an Iframe.html file :

 This is frame 1 content

 click

Sample.html

one

two

And I calling the iframe form test.html file :

Now I tried using the content of URL loaded in iframe i.e. Sample.html in test.html as follows :

$('#frame1').contents().find('#list1 li[name=one]').click(function() {
   alert(" Clicking list....");
});

$('#frame1').contents().find('#list1 li[name=one]').click();

But this doesn't work.. Can you please tell me From Test.html how to access Sample.html file content like(id,name,class etc.) which is loaded in iframe.html using JQuery.
Please help.

Thanks
Kamakshi

Body:
<html>
<head>
<title>Main Frame 2 Title </title>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
------
------
alert("frame ready");
var $value1 = $frame.contents().find('#list1 li[name=one]').html() ;
alert("loaded + " + $value1);
$frame.contents().find('#list1 li[name=one]').click(function() {
    alert("About + clicked");
});
$frame.contents().find('#list1 li[name=one]').click();
 });  });
</script>
</head>
<body>
 <iframe id="frame1" src="sample.html" />

This works fine, if i am giving iframe src=sample.html directly instead of redirecting using another file (i.e. src=iframe.html) and keeping Sample.html in same domain as parent file (test.html).


来源: stackexchange

问:
I keep getting UnicodeErrors opening a CSV file although adding utf-8 encoding
I know the questions sounds generic but here is my problem.
I have a csv file that will always cause UnicodeErrors and errors like csv.empty although I am opening the file with utf-8
like this

    with open(csv_filename, 'r', encoding='utf-8') as csvfile:
```

A workaround I found is to open the file I want, copy the lines and save to a new file(with visual code studio) everything works fine.

Someone told me that I have to use pandas. Is it true?
Is there a difference between opening a file with CSV and Pandas?

答:
Pandas will load the contents of the csv file into a dataframe

The csv module has methods like reader and DictReader that will return generators that let you move through the file.

With Pandas:

```<code>import pandas as pd

df=pd.read_csv('file.csv')
df.to_csv('new_file.csv',index=False)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know the questions sounds generic but here is my problem.
I have a csv file that will always cause UnicodeErrors and errors like csv.empty although I am opening the file with utf-8
like this

    with open(csv_filename, 'r', encoding='utf-8') as csvfile:

A workaround I found is to open the file I want, copy the lines and save to a new file(with visual code studio) everything works fine.

Someone told me that I have to use pandas. Is it true?
Is there a difference between opening a file with CSV and Pandas?

Body:
Pandas will load the contents of the csv file into a dataframe

The csv module has methods like reader and DictReader that will return generators that let you move through the file.

With Pandas:

import pandas as pd

df=pd.read_csv('file.csv')
df.to_csv('new_file.csv',index=False)


问:
How to split a complex string in Python
Given the following string:

```<code>my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"
</code>```

How can I split it such that I get the following output:

```<code>[
  fan_num=2,
  fan1=0,
  fan2=0,
  chain_xtime8={X0=8,X1=3,X2=11},
  chain_offside_6=0,
  chain_offside_7=0,
  chain_offside_8=0,
  chain_opencore_6=0,
  chain_opencore_7=0,
  chain_opencore_8=0
]
</code>```

I've tried:

```<code>output = my_string.split(',')
</code>```

However, that splits the chain_xtime8 value which is not what I want. I am using Python 2.7.

答:
Through a series of convoluted replacements, I converted this style into JSON. Then using json.loads you can convert it into a Python dict. This ASSUMES you do not use the characters being replaced and you continue only using integers as values

This can obviously be tightened up but I wanted to leave it readable

```<code>import json

my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"

my_string = '{"' + my_string + '"}'
my_string = my_string.replace('=', '":"')
my_string = my_string.replace(',', '","')
my_string = my_string.replace('"{', '{"')
my_string = my_string.replace('}"', '"}')
myDict = json.loads(my_string)
</code>```

pprint of myDict results :

```<code>{'chain_offside_6': '0',
 'chain_offside_7': '0',
 'chain_offside_8': '0',
 'chain_opencore_6': '0',
 'chain_opencore_7': '0',
 'chain_opencore_8': '0',
 'chain_xtime8': {'X0': '8', 'X1': '3', 'X2': '11'},
 'fan1': '0',
 'fan2': '0',
 'fan_num': '2'}
</code>```

Also one more example -

```<code>print(myDict['chain_xtime8']['X0'])
>> 8
</code>```

Title: How to split a complex string in Python

Body:
Given the following string:

my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"

How can I split it such that I get the following output:

[
  fan_num=2,
  fan1=0,
  fan2=0,
  chain_xtime8={X0=8,X1=3,X2=11},
  chain_offside_6=0,
  chain_offside_7=0,
  chain_offside_8=0,
  chain_opencore_6=0,
  chain_opencore_7=0,
  chain_opencore_8=0
]

I've tried:

output = my_string.split(',')

However, that splits the chain_xtime8 value which is not what I want. I am using Python 2.7.

Body:
Through a series of convoluted replacements, I converted this style into JSON. Then using json.loads you can convert it into a Python dict. This ASSUMES you do not use the characters being replaced and you continue only using integers as values

This can obviously be tightened up but I wanted to leave it readable

import json

my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"

my_string = '{"' + my_string + '"}'
my_string = my_string.replace('=', '":"')
my_string = my_string.replace(',', '","')
my_string = my_string.replace('"{', '{"')
my_string = my_string.replace('}"', '"}')
myDict = json.loads(my_string)

pprint of myDict results :

{'chain_offside_6': '0',
 'chain_offside_7': '0',
 'chain_offside_8': '0',
 'chain_opencore_6': '0',
 'chain_opencore_7': '0',
 'chain_opencore_8': '0',
 'chain_xtime8': {'X0': '8', 'X1': '3', 'X2': '11'},
 'fan1': '0',
 'fan2': '0',
 'fan_num': '2'}

Also one more example -

print(myDict['chain_xtime8']['X0'])
>> 8


问:
How can I create a header without margin in pdf created with snappy twig (Symfony 4)?
I create a pdf in Symfony via snappy from a twig template:

So this is my Controller, where I am creating the pdf:

```<code> /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request, Pdf $snappy)
  {

    $snappy->setOption("encoding","UTF-8");

    $html = $this->renderView("default/pdf.html.twig",array(
      "title" => "pdf"
    ));

    $filename = "mypdf";
    return new Response(
      $snappy->getOutputFromHtml($html),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
      )
    );

  }
</code>```

And here is the html template, where I create the header
pdf.html.twig:

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.header {
  overflow: hidden;
  background-color: #000;
  padding: 20px 10px;
}

.header-right {
  float: right;
}

}
</style>
</head>
<body>

<div class="header">
  <a href="#default" class="logo">Logo</a>

</div>

<div style="padding-left:20px">
  <h1>headline</h1>
  <p>Some text</p>
  <p>Some content..</p>
</div>

</body>
</html>
</code>```

I try that the black header fits into the page without border. But there is still a white border. It does not go to the edge.

答:
The issue is that wkhtmltopdf defaults to non-zero left & right margins. If you modify your executable to wkhtmltopdf -R 0 -L 0 ... the black will extend to the width of the page. See this.

Btw, you may want to remove the extra brace } at the line immediately above </style>

Body:
I create a pdf in Symfony via snappy from a twig template:

So this is my Controller, where I am creating the pdf:

 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request, Pdf $snappy)
  {

    $snappy->setOption("encoding","UTF-8");

    $html = $this->renderView("default/pdf.html.twig",array(
      "title" => "pdf"
    ));

    $filename = "mypdf";
    return new Response(
      $snappy->getOutputFromHtml($html),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
      )
    );

  }

And here is the html template, where I create the header
pdf.html.twig:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

  Logo

headline

Some text

Some content..

I try that the black header fits into the page without border. But there is still a white border. It does not go to the edge.


问:
Flutter assets error: EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE
flutter can not find my images assets, what can I be doing wrong?

I got the error on debugger:

Launching lib/main.dart on XT1097 in debug mode...
Built build/app/outputs/apk/debug/app-debug.apk.

```<code>I/flutter (  876): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══
I/flutter (  876): Unable to load asset: assets/images/user/background.jpg
I/flutter (  876): "assets/images/user/background.jpg", scale: 1.0)
</code>```

My pubspec.yml:

```<code>environment:
    sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
    sqflite: any
    path_provider: '>=0.3.0'
    charts_flutter: any
    cupertino_icons: ^0.1.2
    material_search: ^0.2.8
    dio: ^1.0.3
    flutter:
        sdk: flutter

dev_dependencies:
    flutter_test:
        sdk: flutter

flutter:
    uses-material-design: true
    assets:
        - assets/images/
</code>```

and the code:

```<code>                new UserAccountsDrawerHeader(
                    decoration : BoxDecoration(
                        image: new DecorationImage(
                            image: AssetImage('assets/images/user/background.jpg'),
                            fit: BoxFit.cover
                        ),
                        color: Colors.blue,
                    ),
                    accountName: new Text('Diego Botelho'),
                    accountEmail: new Text('dibmartins@gmail.com'),
                    currentAccountPicture: new GestureDetector(
                        onTap: () => print('Toque na imagem'),
                        child: new CircleAvatar(
                            backgroundImage: AssetImage('assets/images/user/avatar.png'),
                        )
                    )
                ),
</code>```

答:
I had the same error. In my case it was because the emulator of the phone that I am using does not have access to the internet.

Run the application on a physical mobile device and it worked immediately.

Solution connect the emulator to the internet.

Body:
flutter can not find my images assets, what can I be doing wrong?

I got the error on debugger:

Launching lib/main.dart on XT1097 in debug mode...
Built build/app/outputs/apk/debug/app-debug.apk.

I/flutter (  876): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══
I/flutter (  876): Unable to load asset: assets/images/user/background.jpg
I/flutter (  876): "assets/images/user/background.jpg", scale: 1.0)

My pubspec.yml:

environment:
    sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
    sqflite: any
    path_provider: '>=0.3.0'
    charts_flutter: any
    cupertino_icons: ^0.1.2
    material_search: ^0.2.8
    dio: ^1.0.3
    flutter:
        sdk: flutter

dev_dependencies:
    flutter_test:
        sdk: flutter

flutter:
    uses-material-design: true
    assets:
        - assets/images/

and the code:

                new UserAccountsDrawerHeader(
                    decoration : BoxDecoration(
                        image: new DecorationImage(
                            image: AssetImage('assets/images/user/background.jpg'),
                            fit: BoxFit.cover
                        ),
                        color: Colors.blue,
                    ),
                    accountName: new Text('Diego Botelho'),
                    accountEmail: new Text('dibmartins@gmail.com'),
                    currentAccountPicture: new GestureDetector(
                        onTap: () => print('Toque na imagem'),
                        child: new CircleAvatar(
                            backgroundImage: AssetImage('assets/images/user/avatar.png'),
                        )
                    )
                ),


问:
Why is my palindrome checker always evaluating to true? I tried to debug, and my results are different
Just trying to check if the input is a palindrome. Code keeps evaluating to true, but upon debugging, my answers are false;

Maybe I'm confused with == vs .equals?

```<code>class Solution {
    public boolean isPalindrome(int x) {
        int orig = x;
        String result = x + "";
        char[] original = result.toCharArray();
        String compare = "";

        if(orig < 10) {
            return true;
        }

        for(int i = original.length-1; i >= 0; i--) {
            compare += original[i];
        }

        //System.out.println(result); -121
        //System.out.println(compare); 121
        if(result == compare) {
            return true;
        } else {
            return false;
        }
    }
}
</code>```

答:
Assuming you used (result==compare)
Replace it with result.equals(compare)

Body:
Just trying to check if the input is a palindrome. Code keeps evaluating to true, but upon debugging, my answers are false;

Maybe I'm confused with == vs .equals?

class Solution {
    public boolean isPalindrome(int x) {
        int orig = x;
        String result = x + "";
        char[] original = result.toCharArray();
        String compare = "";

        if(orig < 10) {
            return true;
        }

        for(int i = original.length-1; i >= 0; i--) {
            compare += original[i];
        }

        //System.out.println(result); -121
        //System.out.println(compare); 121
        if(result == compare) {
            return true;
        } else {
            return false;
        }
    }
}


问:
Cosmos DB internal error when fetching documents
Using the Azure Cosmos DB Data Explorer shows me no values, even though I know there's data in it. When using my web app, I can see it inserts data. I can also verify this by querying db.files.stats().count from a local GUI. However at  any point in the UI where I try to read from the DB, it breaks -- seemingly the same issue as what I see in the GUIs I've tried to use.

Looking at the network tab in Chrome, I can see a failed request being sent to the https://portal-prod-northeurope-mongo.portal-prod-northeurope.p.azurewebsites.net endpoint whenever I try to refresh the result set.
The response it comes back with is

Command find failed: Unknown server error occurred when processing this request..

I get the same error when I query the db with a local GUI so I assume it's not directly related to the Azure Portal.
I have tried to delete and recreate the collections but to no avail.
When I run all this locally on the Cosmos DB emulator, it works just fine.

Collections are defined as such:

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'files' `
                                  --db-name $db `
                                  --partition-key-path '/p'

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'users' `
                                  --db-name $db

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'projects' `
                                  --db-name $db `
                                  --partition-key-path '/cb'
```

<p>and an example object is the following:</p>

<pre class="lang-cs prettyprint-override"><code>internal class File
{
    [JsonProperty(PropertyName = "id")]
    public Guid Id { get; set; }

    [JsonProperty(PropertyName = "of")]
    public string OriginalFilename { get; set; }

    [JsonProperty(PropertyName = "if")]
    public string InternalFilename { get; set; }

    [JsonProperty(PropertyName = "ua")]
    public DateTime UploadedAt { get; set; }

    [JsonProperty(PropertyName = "p")]
    public Guid ProjectId { get; set; }

    [JsonProperty(PropertyName = "su")]
    public string StorageUri { get; set; }

    [JsonProperty(PropertyName = "t")]
    public byte Type { get; set; }

    public override string ToString() => JsonConvert.SerializeObject(this);
}
</code>```

答:
As per the comments, the reason you are facing this issue is because you are using Cosmos DB SDK on a Mongo API account. Both the Portal and GUI are trying to consume the data through a Mongo client, and your data is being saved through a different API.

Cosmos DB SDK uses the SQL API to save documents. Mongo API accounts are meant to be used and consumed through Mongo Clients / Drivers.

If your application requires Mongo, then use Mongo Clients / Drivers to store the documents, don't use the Cosmos DB SDK.

If your application does not require Mongo (since you are using the Cosmos DB SDK it doesn't sound like it), create a Core API(SQL) account.

Body:
Using the Azure Cosmos DB Data Explorer shows me no values, even though I know there's data in it. When using my web app, I can see it inserts data. I can also verify this by querying db.files.stats().count from a local GUI. However at  any point in the UI where I try to read from the DB, it breaks -- seemingly the same issue as what I see in the GUIs I've tried to use.

Looking at the network tab in Chrome, I can see a failed request being sent to the https://portal-prod-northeurope-mongo.portal-prod-northeurope.p.azurewebsites.net endpoint whenever I try to refresh the result set.
The response it comes back with is

Command find failed: Unknown server error occurred when processing this request..

I get the same error when I query the db with a local GUI so I assume it's not directly related to the Azure Portal.
I have tried to delete and recreate the collections but to no avail.
When I run all this locally on the Cosmos DB emulator, it works just fine.

Collections are defined as such:

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'files' `
                                  --db-name $db `
                                  --partition-key-path '/p'

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'users' `
                                  --db-name $db

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'projects' `
                                  --db-name $db `
                                  --partition-key-path '/cb'

and an example object is the following:

internal class File
{
    [JsonProperty(PropertyName = "id")]
    public Guid Id { get; set; }

    [JsonProperty(PropertyName = "of")]
    public string OriginalFilename { get; set; }

    [JsonProperty(PropertyName = "if")]
    public string InternalFilename { get; set; }

    [JsonProperty(PropertyName = "ua")]
    public DateTime UploadedAt { get; set; }

    [JsonProperty(PropertyName = "p")]
    public Guid ProjectId { get; set; }

    [JsonProperty(PropertyName = "su")]
    public string StorageUri { get; set; }

    [JsonProperty(PropertyName = "t")]
    public byte Type { get; set; }

    public override string ToString() => JsonConvert.SerializeObject(this);
}


问:
animating multiple CALayers, but not in the same time space
I have several CALayers that I'm trying to animate to a new zPosition with each layer slightly delayed from the others.

Each animation should take 0.25 seconds and start 0.05 seconds after the previous animation started. At the end of each animation the layer will be removed from the layer tree.

I've successfully been using the -animationDidStop:finished: delegate method to remove my layers as they finish but I've not been able to order the animations properly.

Is it possible to schedule animations in this way, and how?

答:
I'd still like to hear others suggestions but I think I've solved this.

I'm now creating specific CAAnimation objects and specifying their beginTime property. I was doing this earlier and it wasn't working, what I finally realized is that for the beginTime property to be honored the animation has to be added to an CAAnimationGroup.

So, my code looks like this:

```<code>NSArray *layers = /* layers to be animated away */
CGFloat startOffset = 0.01;

for (NSInteger index = 0; index < layers.count; index++) {
    CALayer *layer = [layers objectAtIndex:index];

    CABasicAnimation *zoomOut = [CABasicAnimation animationWithKeyPath:@"zPosition"];
    zoomOut.toValue = [NSNumber numberWithDouble:400.0];
    zoomOut.beginTime = index * startOffset;

    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = [NSArray arrayWithObject:zoomOut];
    group.delegate = self;

    [layer addAnimation:group forKey:@"zoomAway"];
}
</code>```

OwnerDisplayName: Ashley Clark

LastEditorDisplayName: Chris Hanson

Body:
I'd still like to hear others suggestions but I think I've solved this.

I'm now creating specific CAAnimation objects and specifying their beginTime property. I was doing this earlier and it wasn't working, what I finally realized is that for the beginTime property to be honored the animation has to be added to an CAAnimationGroup.

So, my code looks like this:

NSArray *layers = /* layers to be animated away */
CGFloat startOffset = 0.01;

for (NSInteger index = 0; index < layers.count; index++) {
    CALayer *layer = [layers objectAtIndex:index];

    CABasicAnimation *zoomOut = [CABasicAnimation animationWithKeyPath:@"zPosition"];
    zoomOut.toValue = [NSNumber numberWithDouble:400.0];
    zoomOut.beginTime = index * startOffset;

    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = [NSArray arrayWithObject:zoomOut];
    group.delegate = self;

    [layer addAnimation:group forKey:@"zoomAway"];
}


问:
How to extract images from a pdf using the poppler library in Python?
I've got a pdf from which I want to extract some images using Python. I can easily extract images from the Linux command line using the pdfimages from the poppler-utils library like this:

```<code>pdfimages my_file.pdf /tmp/image
</code>```

Next I found a Python binding for it here, and installed it using the usual sudo apt-get install python-poppler. In the python interpreter I can now do this:

```<code>>>> import poppler
>>> dir(poppler)
['ACTION_GOTO_DEST', 'ACTION_GOTO_REMOTE', 'ACTION_JAVASCRIPT', 'ACTION_LAUNCH', 'ACTION_MOVIE', 'ACTION_NAMED', 'ACTION_NONE', 'ACTION_OCG_STATE', 'ACTION_RENDITION', 'ACTION_UNKNOWN', 'ACTION_URI', 'ANNOT_3D', 'ANNOT_CARET', 'ANNOT_CIRCLE', 'ANNOT_EXTERNAL_DATA_MARKUP_3D', 'ANNOT_EXTERNAL_DATA_MARKUP_UNKNOWN', 'ANNOT_FILE_ATTACHMENT', 'ANNOT_FLAG_HIDDEN', 'ANNOT_FLAG_INVISIBLE', 'ANNOT_FLAG_LOCKED', 'ANNOT_FLAG_LOCKED_CONTENTS', 'ANNOT_FLAG_NO_ROTATE', 'ANNOT_FLAG_NO_VIEW', 'ANNOT_FLAG_NO_ZOOM', 'ANNOT_FLAG_PRINT', 'ANNOT_FLAG_READ_ONLY', 'ANNOT_FLAG_TOGGLE_NO_VIEW', 'ANNOT_FLAG_UNKNOWN', 'ANNOT_FREE_TEXT', 'ANNOT_FREE_TEXT_QUADDING_CENTERED', 'ANNOT_FREE_TEXT_QUADDING_LEFT_JUSTIFIED', 'ANNOT_FREE_TEXT_QUADDING_RIGHT_JUSTIFIED', 'ANNOT_HIGHLIGHT', 'ANNOT_INK', 'ANNOT_LINE', 'ANNOT_LINK', 'ANNOT_MARKUP_REPLY_TYPE_GROUP', 'ANNOT_MARKUP_REPLY_TYPE_R', 'ANNOT_MOVIE', 'ANNOT_POLYGON', 'ANNOT_POLY_LINE', 'ANNOT_POPUP', 'ANNOT_PRINTER_MARK', 'ANNOT_SCREEN', 'ANNOT_SOUND', 'ANNOT_SQUARE', 'ANNOT_SQUIGGLY', 'ANNOT_STAMP', 'ANNOT_STRIKE_OUT', 'ANNOT_TEXT', 'ANNOT_TEXT_STATE_ACCEPTED', 'ANNOT_TEXT_STATE_CANCELLED', 'ANNOT_TEXT_STATE_COMPLETED', 'ANNOT_TEXT_STATE_MARKED', 'ANNOT_TEXT_STATE_NONE', 'ANNOT_TEXT_STATE_REJECTED', 'ANNOT_TEXT_STATE_UNKNOWN', 'ANNOT_TEXT_STATE_UNMARKED', 'ANNOT_TRAP_NET', 'ANNOT_UNDERLINE', 'ANNOT_UNKNOWN', 'ANNOT_WATERMARK', 'ANNOT_WIDGET', 'Action', 'ActionAny', 'ActionGotoDest', 'ActionGotoRemote', 'ActionLaunch', 'ActionMovie', 'ActionNamed', 'ActionType', 'ActionUri', 'Annot', 'AnnotCalloutLine', 'AnnotExternalDataType', 'AnnotFlag', 'AnnotFreeText', 'AnnotFreeTextQuadding', 'AnnotMapping', 'AnnotMarkup', 'AnnotMarkupReplyType', 'AnnotText', 'AnnotTextState', 'AnnotType', 'Attachment', 'BACKEND_CAIRO', 'BACKEND_SPLASH', 'BACKEND_UNKNOWN', 'Backend', 'Color', 'DEST_FIT', 'DEST_FITB', 'DEST_FITBH', 'DEST_FITBV', 'DEST_FITH', 'DEST_FITR', 'DEST_FITV', 'DEST_NAMED', 'DEST_UNKNOWN', 'DEST_XYZ', 'Dest', 'DestType', 'Document', 'ERROR_BAD_CATALOG', 'ERROR_DAMAGED', 'ERROR_ENCRYPTED', 'ERROR_INVALID', 'ERROR_OPEN_FILE', 'Error', 'FONT_TYPE_CID_TYPE0', 'FONT_TYPE_CID_TYPE0C', 'FONT_TYPE_CID_TYPE0COT', 'FONT_TYPE_CID_TYPE2', 'FONT_TYPE_CID_TYPE2OT', 'FONT_TYPE_TRUETYPE', 'FONT_TYPE_TRUETYPEOT', 'FONT_TYPE_TYPE1', 'FONT_TYPE_TYPE1C', 'FONT_TYPE_TYPE1COT', 'FONT_TYPE_TYPE3', 'FONT_TYPE_UNKNOWN', 'FORM_BUTTON_CHECK', 'FORM_BUTTON_PUSH', 'FORM_BUTTON_RADIO', 'FORM_CHOICE_COMBO', 'FORM_CHOICE_LIST', 'FORM_FIELD_BUTTON', 'FORM_FIELD_CHOICE', 'FORM_FIELD_SIGNATURE', 'FORM_FIELD_TEXT', 'FORM_FIELD_UNKNOWN', 'FORM_TEXT_FILE_SELECT', 'FORM_TEXT_MULTILINE', 'FORM_TEXT_NORMAL', 'FontInfo', 'FontType', 'FontsIter', 'FormButtonType', 'FormChoiceType', 'FormField', 'FormFieldMapping', 'FormFieldType', 'FormTextType', 'ImageMapping', 'IndexIter', 'Layer', 'LayersIter', 'LinkMapping', 'ORIENTATION_LANDSCAPE', 'ORIENTATION_PORTRAIT', 'ORIENTATION_SEASCAPE', 'ORIENTATION_UPSIDEDOWN', 'Orientation', 'PAGE_LAYOUT_ONE_COLUMN', 'PAGE_LAYOUT_SINGLE_PAGE', 'PAGE_LAYOUT_TWO_COLUMN_LEFT', 'PAGE_LAYOUT_TWO_COLUMN_RIGHT', 'PAGE_LAYOUT_TWO_PAGE_LEFT', 'PAGE_LAYOUT_TWO_PAGE_RIGHT', 'PAGE_LAYOUT_UNSET', 'PAGE_MODE_FULL_SCREEN', 'PAGE_MODE_NONE', 'PAGE_MODE_UNSET', 'PAGE_MODE_USE_ATTACHMENTS', 'PAGE_MODE_USE_OC', 'PAGE_MODE_USE_OUTLINES', 'PAGE_MODE_USE_THUMBS', 'PAGE_TRANSITION_BLINDS', 'PAGE_TRANSITION_BOX', 'PAGE_TRANSITION_COVER', 'PAGE_TRANSITION_DISSOLVE', 'PAGE_TRANSITION_FADE', 'PAGE_TRANSITION_FLY', 'PAGE_TRANSITION_GLITTER', 'PAGE_TRANSITION_HORIZONTAL', 'PAGE_TRANSITION_INWARD', 'PAGE_TRANSITION_OUTWARD', 'PAGE_TRANSITION_PUSH', 'PAGE_TRANSITION_REPLACE', 'PAGE_TRANSITION_SPLIT', 'PAGE_TRANSITION_UNCOVER', 'PAGE_TRANSITION_VERTICAL', 'PAGE_TRANSITION_WIPE', 'PERMISSIONS_FULL', 'PERMISSIONS_OK_TO_ADD_NOTES', 'PERMISSIONS_OK_TO_ASSEMBLE', 'PERMISSIONS_OK_TO_COPY', 'PERMISSIONS_OK_TO_EXTRACT_CONTENTS', 'PERMISSIONS_OK_TO_FILL_FORM', 'PERMISSIONS_OK_TO_MODIFY', 'PERMISSIONS_OK_TO_PRINT', 'PERMISSIONS_OK_TO_PRINT_HIGH_RESOLUTION', 'PSFile', 'Page', 'PageLayout', 'PageMode', 'PageTransition', 'PageTransitionAlignment', 'PageTransitionDirection', 'PageTransitionType', 'Permissions', 'Rectangle', 'SELECTION_GLYPH', 'SELECTION_LINE', 'SELECTION_WORD', 'SelectionStyle', 'VIEWER_PREFERENCES_CENTER_WINDOW', 'VIEWER_PREFERENCES_DIRECTION_RTL', 'VIEWER_PREFERENCES_DISPLAY_DOC_TITLE', 'VIEWER_PREFERENCES_FIT_WINDOW', 'VIEWER_PREFERENCES_HIDE_MENUBAR', 'VIEWER_PREFERENCES_HIDE_TOOLBAR', 'VIEWER_PREFERENCES_HIDE_WINDOWUI', 'VIEWER_PREFERENCES_UNSET', 'ViewerPreferences', '__doc__', '__file__', '__name__', '__package__', '__version__', 'document_new_from_data', 'document_new_from_file', 'get_backend', 'get_version', 'pypoppler_version']
>>>
</code>```

From here I'm kinda lost though. In this list I can't find anything resembling the pdfimages name, or anything related. In the source files of python-poppler I can't even find a .py file.

Does anybody know how I could use the poppler pdfimages tool from within Python? All tips are welcome!

答:
Explore ImageMapping and there you would find what you are looking for. An ImageMapping object contains an identifier(integer) for the image which is required for image retrieval plus the area of the image in paper coordinates.

This is something borrowed from the glib backend of poppler. I have tested the C version(poppler-glib) version of theImageMapping and it works fine.

Please note that poppler bindings that rely on C++/Qt lack this functionality.

ContentLicense: CC BY-SA 3.0

Body:
I've got a pdf from which I want to extract some images using Python. I can easily extract images from the Linux command line using the pdfimages from the poppler-utils library like this:

pdfimages my_file.pdf /tmp/image

Next I found a Python binding for it here, and installed it using the usual sudo apt-get install python-poppler. In the python interpreter I can now do this:

>>> import poppler
>>> dir(poppler)
['ACTION_GOTO_DEST', 'ACTION_GOTO_REMOTE', 'ACTION_JAVASCRIPT', 'ACTION_LAUNCH', 'ACTION_MOVIE', 'ACTION_NAMED', 'ACTION_NONE', 'ACTION_OCG_STATE', 'ACTION_RENDITION', 'ACTION_UNKNOWN', 'ACTION_URI', 'ANNOT_3D', 'ANNOT_CARET', 'ANNOT_CIRCLE', 'ANNOT_EXTERNAL_DATA_MARKUP_3D', 'ANNOT_EXTERNAL_DATA_MARKUP_UNKNOWN', 'ANNOT_FILE_ATTACHMENT', 'ANNOT_FLAG_HIDDEN', 'ANNOT_FLAG_INVISIBLE', 'ANNOT_FLAG_LOCKED', 'ANNOT_FLAG_LOCKED_CONTENTS', 'ANNOT_FLAG_NO_ROTATE', 'ANNOT_FLAG_NO_VIEW', 'ANNOT_FLAG_NO_ZOOM', 'ANNOT_FLAG_PRINT', 'ANNOT_FLAG_READ_ONLY', 'ANNOT_FLAG_TOGGLE_NO_VIEW', 'ANNOT_FLAG_UNKNOWN', 'ANNOT_FREE_TEXT', 'ANNOT_FREE_TEXT_QUADDING_CENTERED', 'ANNOT_FREE_TEXT_QUADDING_LEFT_JUSTIFIED', 'ANNOT_FREE_TEXT_QUADDING_RIGHT_JUSTIFIED', 'ANNOT_HIGHLIGHT', 'ANNOT_INK', 'ANNOT_LINE', 'ANNOT_LINK', 'ANNOT_MARKUP_REPLY_TYPE_GROUP', 'ANNOT_MARKUP_REPLY_TYPE_R', 'ANNOT_MOVIE', 'ANNOT_POLYGON', 'ANNOT_POLY_LINE', 'ANNOT_POPUP', 'ANNOT_PRINTER_MARK', 'ANNOT_SCREEN', 'ANNOT_SOUND', 'ANNOT_SQUARE', 'ANNOT_SQUIGGLY', 'ANNOT_STAMP', 'ANNOT_STRIKE_OUT', 'ANNOT_TEXT', 'ANNOT_TEXT_STATE_ACCEPTED', 'ANNOT_TEXT_STATE_CANCELLED', 'ANNOT_TEXT_STATE_COMPLETED', 'ANNOT_TEXT_STATE_MARKED', 'ANNOT_TEXT_STATE_NONE', 'ANNOT_TEXT_STATE_REJECTED', 'ANNOT_TEXT_STATE_UNKNOWN', 'ANNOT_TEXT_STATE_UNMARKED', 'ANNOT_TRAP_NET', 'ANNOT_UNDERLINE', 'ANNOT_UNKNOWN', 'ANNOT_WATERMARK', 'ANNOT_WIDGET', 'Action', 'ActionAny', 'ActionGotoDest', 'ActionGotoRemote', 'ActionLaunch', 'ActionMovie', 'ActionNamed', 'ActionType', 'ActionUri', 'Annot', 'AnnotCalloutLine', 'AnnotExternalDataType', 'AnnotFlag', 'AnnotFreeText', 'AnnotFreeTextQuadding', 'AnnotMapping', 'AnnotMarkup', 'AnnotMarkupReplyType', 'AnnotText', 'AnnotTextState', 'AnnotType', 'Attachment', 'BACKEND_CAIRO', 'BACKEND_SPLASH', 'BACKEND_UNKNOWN', 'Backend', 'Color', 'DEST_FIT', 'DEST_FITB', 'DEST_FITBH', 'DEST_FITBV', 'DEST_FITH', 'DEST_FITR', 'DEST_FITV', 'DEST_NAMED', 'DEST_UNKNOWN', 'DEST_XYZ', 'Dest', 'DestType', 'Document', 'ERROR_BAD_CATALOG', 'ERROR_DAMAGED', 'ERROR_ENCRYPTED', 'ERROR_INVALID', 'ERROR_OPEN_FILE', 'Error', 'FONT_TYPE_CID_TYPE0', 'FONT_TYPE_CID_TYPE0C', 'FONT_TYPE_CID_TYPE0COT', 'FONT_TYPE_CID_TYPE2', 'FONT_TYPE_CID_TYPE2OT', 'FONT_TYPE_TRUETYPE', 'FONT_TYPE_TRUETYPEOT', 'FONT_TYPE_TYPE1', 'FONT_TYPE_TYPE1C', 'FONT_TYPE_TYPE1COT', 'FONT_TYPE_TYPE3', 'FONT_TYPE_UNKNOWN', 'FORM_BUTTON_CHECK', 'FORM_BUTTON_PUSH', 'FORM_BUTTON_RADIO', 'FORM_CHOICE_COMBO', 'FORM_CHOICE_LIST', 'FORM_FIELD_BUTTON', 'FORM_FIELD_CHOICE', 'FORM_FIELD_SIGNATURE', 'FORM_FIELD_TEXT', 'FORM_FIELD_UNKNOWN', 'FORM_TEXT_FILE_SELECT', 'FORM_TEXT_MULTILINE', 'FORM_TEXT_NORMAL', 'FontInfo', 'FontType', 'FontsIter', 'FormButtonType', 'FormChoiceType', 'FormField', 'FormFieldMapping', 'FormFieldType', 'FormTextType', 'ImageMapping', 'IndexIter', 'Layer', 'LayersIter', 'LinkMapping', 'ORIENTATION_LANDSCAPE', 'ORIENTATION_PORTRAIT', 'ORIENTATION_SEASCAPE', 'ORIENTATION_UPSIDEDOWN', 'Orientation', 'PAGE_LAYOUT_ONE_COLUMN', 'PAGE_LAYOUT_SINGLE_PAGE', 'PAGE_LAYOUT_TWO_COLUMN_LEFT', 'PAGE_LAYOUT_TWO_COLUMN_RIGHT', 'PAGE_LAYOUT_TWO_PAGE_LEFT', 'PAGE_LAYOUT_TWO_PAGE_RIGHT', 'PAGE_LAYOUT_UNSET', 'PAGE_MODE_FULL_SCREEN', 'PAGE_MODE_NONE', 'PAGE_MODE_UNSET', 'PAGE_MODE_USE_ATTACHMENTS', 'PAGE_MODE_USE_OC', 'PAGE_MODE_USE_OUTLINES', 'PAGE_MODE_USE_THUMBS', 'PAGE_TRANSITION_BLINDS', 'PAGE_TRANSITION_BOX', 'PAGE_TRANSITION_COVER', 'PAGE_TRANSITION_DISSOLVE', 'PAGE_TRANSITION_FADE', 'PAGE_TRANSITION_FLY', 'PAGE_TRANSITION_GLITTER', 'PAGE_TRANSITION_HORIZONTAL', 'PAGE_TRANSITION_INWARD', 'PAGE_TRANSITION_OUTWARD', 'PAGE_TRANSITION_PUSH', 'PAGE_TRANSITION_REPLACE', 'PAGE_TRANSITION_SPLIT', 'PAGE_TRANSITION_UNCOVER', 'PAGE_TRANSITION_VERTICAL', 'PAGE_TRANSITION_WIPE', 'PERMISSIONS_FULL', 'PERMISSIONS_OK_TO_ADD_NOTES', 'PERMISSIONS_OK_TO_ASSEMBLE', 'PERMISSIONS_OK_TO_COPY', 'PERMISSIONS_OK_TO_EXTRACT_CONTENTS', 'PERMISSIONS_OK_TO_FILL_FORM', 'PERMISSIONS_OK_TO_MODIFY', 'PERMISSIONS_OK_TO_PRINT', 'PERMISSIONS_OK_TO_PRINT_HIGH_RESOLUTION', 'PSFile', 'Page', 'PageLayout', 'PageMode', 'PageTransition', 'PageTransitionAlignment', 'PageTransitionDirection', 'PageTransitionType', 'Permissions', 'Rectangle', 'SELECTION_GLYPH', 'SELECTION_LINE', 'SELECTION_WORD', 'SelectionStyle', 'VIEWER_PREFERENCES_CENTER_WINDOW', 'VIEWER_PREFERENCES_DIRECTION_RTL', 'VIEWER_PREFERENCES_DISPLAY_DOC_TITLE', 'VIEWER_PREFERENCES_FIT_WINDOW', 'VIEWER_PREFERENCES_HIDE_MENUBAR', 'VIEWER_PREFERENCES_HIDE_TOOLBAR', 'VIEWER_PREFERENCES_HIDE_WINDOWUI', 'VIEWER_PREFERENCES_UNSET', 'ViewerPreferences', '__doc__', '__file__', '__name__', '__package__', '__version__', 'document_new_from_data', 'document_new_from_file', 'get_backend', 'get_version', 'pypoppler_version']
>>>

From here I'm kinda lost though. In this list I can't find anything resembling the pdfimages name, or anything related. In the source files of python-poppler I can't even find a .py file.

Does anybody know how I could use the poppler pdfimages tool from within Python? All tips are welcome!


问:
how to split a pandas row into several rows and process some of their values?
I am trying to write a function that splits a pandas row into several rows AND updates some values at a particular column.

The problem would look like this;

```<code>   Id  Values
 0  A    2000
 1  B     600
</code>```

and the expected results after splitting only those Ids with a Value larger than 800 into smaller quantities. That would be;

```<code>  Id  Values
0  A     800
1  A     800
2  A     400
3  B     600
</code>```

The logic to split the values is not so relevant. For example;

```<code>2000 = 800 + 800 + 400
2000 = 700 + 700 + 600
</code>```

any ideas on how to tack this problem?

答:
This quick solution should give the required results, the code still needs optimization</p>

```<code>max_val = 800

def split_x (x):
  lst=[]
  while x > max_val:
    x=x-max_val
    lst.append(max_val)
  if x != 0:
    lst.append(x)
  return lst

data = {'id':['A', 'B'],
        'value':[2000,600]}
df = pd.DataFrame(data)
df_new=pd.DataFrame({'id':[],'value':[]})

for i in range(len(df)):

  d=df.loc[i]['value']
  id=df.loc[i]['id']
  s=split_x(d)
  for i in range(len(s)):
    print (i,s[i])
    df_new=df_new.append({'id':id,'value':s[i]},ignore_index=True)

>>> df_new
  id  value
0  A  800.0
1  A  800.0
2  A  400.0
3  B  600.0
</code>```

Body:
I am trying to write a function that splits a pandas row into several rows AND updates some values at a particular column.

The problem would look like this;

   Id  Values
 0  A    2000
 1  B     600

and the expected results after splitting only those Ids with a Value larger than 800 into smaller quantities. That would be;

  Id  Values
0  A     800
1  A     800
2  A     400
3  B     600

The logic to split the values is not so relevant. For example;

2000 = 800 + 800 + 400
2000 = 700 + 700 + 600

any ideas on how to tack this problem?

Body:
This quick solution should give the required results, the code still needs optimization

max_val = 800

def split_x (x):
  lst=[]
  while x > max_val:
    x=x-max_val
    lst.append(max_val)
  if x != 0:
    lst.append(x)
  return lst

data = {'id':['A', 'B'],
        'value':[2000,600]}
df = pd.DataFrame(data)
df_new=pd.DataFrame({'id':[],'value':[]})

for i in range(len(df)):

  d=df.loc[i]['value']
  id=df.loc[i]['id']
  s=split_x(d)
  for i in range(len(s)):
    print (i,s[i])
    df_new=df_new.append({'id':id,'value':s[i]},ignore_index=True)

>>> df_new
  id  value
0  A  800.0
1  A  800.0
2  A  400.0
3  B  600.0


问:
How do I convert a string to a number in PHP?
I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?

```<code>Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545
</code>```

答:
There is a way:

```<code>$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);
</code>```

Using is_* won't work, since the variable is a: string.

Using the combination of json_encode() and then json_decode() it's converted to it's "true" form. If it's a true string then it would output wrong.

```<code>$num = "Me";
$int = (int)$num;
$float = (float)$num;

var_dump($num, $int, $float);
</code>```

Will output: string(2) "Me" int(0) float(0)

Body:
I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545

Body:
There is a way:

$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);

Using is_* won't work, since the variable is a: string.

Using the combination of json_encode() and then json_decode() it's converted to it's "true" form. If it's a true string then it would output wrong.

$num = "Me";
$int = (int)$num;
$float = (float)$num;

var_dump($num, $int, $float);

Will output: string(2) "Me" int(0) float(0)


问:
AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'
I am dealing with error

"AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'"

while running silhouette analysis.

The original code was taken from here. I have added the line that shows the error:

```<code>color = cm.nipy_spectral(float(i) / n_clusters)
</code>```

答:
The problem was that you were assigning cm to some other array. Correct way is not to assign cm to any other array or change the code to

```<code>matplotlib.cm.nipy_spectral(float(i) / n_clusters)
</code>```

Change it at all the places where cm is used.

Body:
I am dealing with error

"AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'"

while running silhouette analysis.

The original code was taken from here. I have added the line that shows the error:

color = cm.nipy_spectral(float(i) / n_clusters)

Body:
The problem was that you were assigning cm to some other array. Correct way is not to assign cm to any other array or change the code to

matplotlib.cm.nipy_spectral(float(i) / n_clusters)

Change it at all the places where cm is used.


问:
Whats NDK (side-by-side) in android sdk?
There's a ndk (side-by-side) at <img src="https://i.stack.imgur.com/UO8KE.jpg" alt="the sdk manager">.
Is it needed to install or just need to install the ndk? </p>

答:
This is how it looks like in my Android Studio 3.5 beta2:

You can see that I don't hide obsolete packages and request package details. Now we see that the old NDK package is replaced by the new NDK (Side by side), which allows to keep both NDK r19 and r20.

The reason why they are making the change is that switching to the latest version of NDK is not always painless, and many developers prefer to stay with an older version, at least for some projects.

The bottom line is that it is OK to use the NDK that you have installed, but it will be replaced with the new package some time later when you upgrade the Android Studio.

Body:
There's a ndk (side-by-side) at .
Is it needed to install or just need to install the ndk?


问:
How to iterate through a list of dictionaries
My code is

index = 0
for key in dataList[index]:
    print(dataList[index][key])
```

Seems to work fine for printing the values of dictionary keys for index = 0. However, I can't figure out how to iterate through an unknown number of dictionaries in dataList.

Body:
My code is

index = 0
for key in dataList[index]:
    print(dataList[index][key])

Seems to work fine for printing the values of dictionary keys for index = 0. However, I can't figure out how to iterate through an unknown number of dictionaries in dataList.

Body:
use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
for dic in use:
    for val,cal in dic.items():
        print(f'{val} is {cal}')


问:
can't get the value of an input
I have a function in which I create an input like

```<code>tr = document.createElement("tr");
td1 = document.createElement("td");
td2 = document.createElement("td");
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(document.createElement("input"));
td2.setAttribute("id", "nr");
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
</code>```

Afterward, I want to get the value of it in another function with:

```<code>var nr = document.getElementById("nr").value;
</code>```

it will know the nr element but the value is undefined

答:
As @takendarkk said, the  tag doesn't have a value attribute.

In your code, define in a different variable the input creation so you can give it an id to referrer later, like this:

```<code>let tr = document.createElement("tr");
let td1 = document.createElement("td");
let td2 = document.createElement("td");
let input = document.createElement("input"); // Created input
input.setAttribute("id","nr"); // Given an id
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(input); // Appended the input element previously created
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
</code>```

As @AlexeyZelenin suggested, you should use let or var on variable definitions to prevent modifying another variable outside the current scope.

Look at an example:

Press the button to get the value of the input.

const table = document.querySelector("table");

function createRow() {
  let tr = document.createElement("tr");
  let td1 = document.createElement("td");
  let td2 = document.createElement("td");
  let input = document.createElement("input");
  input.setAttribute("id","nr");
  td1.appendChild(document.createTextNode("Number:"));
  td2.appendChild(input);
  tr.appendChild(td1);
  tr.appendChild(td2);
  table.appendChild(tr);
}

createRow();

function showValue(){
  console.log(document.getElementById("nr").value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table></table><button onclick="showValue()">Show value</button></code>```

Title: can't get the value of an input

Body:
I have a function in which I create an input like

tr = document.createElement("tr");
td1 = document.createElement("td");
td2 = document.createElement("td");
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(document.createElement("input"));
td2.setAttribute("id", "nr");
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);

Afterward, I want to get the value of it in another function with:

var nr = document.getElementById("nr").value;

it will know the nr element but the value is undefined

Body:
As @takendarkk said, the <td> tag doesn't have a value attribute.

In your code, define in a different variable the input creation so you can give it an id to referrer later, like this:

let tr = document.createElement("tr");
let td1 = document.createElement("td");
let td2 = document.createElement("td");
let input = document.createElement("input"); // Created input
input.setAttribute("id","nr"); // Given an id
td1.appendChild(document.createTextNode("Number:"));
td2.appendChild(input); // Appended the input element previously created
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);

As @AlexeyZelenin suggested, you should use let or var on variable definitions to prevent modifying another variable outside the current scope.

Look at an example:

Press the button to get the value of the input.

const table = document.querySelector("table");

function createRow() {
  let tr = document.createElement("tr");
  let td1 = document.createElement("td");
  let td2 = document.createElement("td");
  let input = document.createElement("input");
  input.setAttribute("id","nr");
  td1.appendChild(document.createTextNode("Number:"));
  td2.appendChild(input);
  tr.appendChild(td1);
  tr.appendChild(td2);
  table.appendChild(tr);
}

createRow();

function showValue(){
  console.log(document.getElementById("nr").value);
}

<table></table><button onclick="showValue()">Show value</button>


问:
python : Replacing a HTML element depending on its content
I have an html document, in which some elements contains stuff that I want to hide (like the Chinese government is doing, except that I just want to hide confidential information). For example say I have :

```<code><div>
    <span> bkhiu jknd o so so so  yui iou 789 </span>
    <span>
        bkhiu
        <div> 56 898tr SECRET oij890 </div>
    </span>
</div>
</code>```

And I want to get all the elements that contain the string SECRET, and just replace their whole content by ### :

```<code><div>
    <span> bkhiu jknd o so so so  yui iou 789 </span>
    <span>
        bkhiu
        <div>###</div>
    </span>
</div>
</code>```

I have thought of using minidom and re with something like :

```<code>xmldoc = minidom.parseString(my_html_string)
# filtering nodes by their content
sensitive_nodes = filter(lambda n: re.search('SECRET', n.nodeValue),
    xmldoc.getElementsByTagName())
# replacing content
for node in sensitive_nodes:
    node.nodeValue = '###'
# output
my_html_string = xmldoc.toxml()
</code>```

But first the parsing doesn't even succeeds :

```<code>ExpatError: mismatched tag: line 27, column 6
</code>```

And .getElementsByTagName() needs a tagName parameter ... while I don't care about the tag name and need ALL the nodes (in order to filter by their content). Well basically that code doesn't work at all, but is just to try to explain what I wanna achieve.

Any idea how I could do that easily ? With minidom or something completely different ?

答:
Ok ... I have found a very simple way, using BeautifulSoup :</p>

```<code>import re
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(my_html)
nodes_to_censor = soup.findAll(text=re.compile('.*SECRET.*'))
for node in nodes_to_censor:
    node.replaceWith('###')
</code>```

Body:
I have an html document, in which some elements contains stuff that I want to hide (like the Chinese government is doing, except that I just want to hide confidential information). For example say I have :

     bkhiu jknd o so so so  yui iou 789

        bkhiu

 56 898tr SECRET oij890

And I want to get all the elements that contain the string SECRET, and just replace their whole content by ### :

     bkhiu jknd o so so so  yui iou 789

        bkhiu

###

I have thought of using minidom and re with something like :

xmldoc = minidom.parseString(my_html_string)
# filtering nodes by their content
sensitive_nodes = filter(lambda n: re.search('SECRET', n.nodeValue),
    xmldoc.getElementsByTagName())
# replacing content
for node in sensitive_nodes:
    node.nodeValue = '###'
# output
my_html_string = xmldoc.toxml()

But first the parsing doesn't even succeeds :

ExpatError: mismatched tag: line 27, column 6

And .getElementsByTagName() needs a tagName parameter ... while I don't care about the tag name and need ALL the nodes (in order to filter by their content). Well basically that code doesn't work at all, but is just to try to explain what I wanna achieve.

Any idea how I could do that easily ? With minidom or something completely different ?

Body:
Ok ... I have found a very simple way, using BeautifulSoup :

import re
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(my_html)
nodes_to_censor = soup.findAll(text=re.compile('.*SECRET.*'))
for node in nodes_to_censor:
    node.replaceWith('###')


问:
How do I ensure I am actually pulling a different release?
I am getting frustrated because I have a friend that is telling me the app of a certain branch off Bitbucket is working a certain way for him. I had a newer release.

So I decided to do:

git checkout -b release/3.5.1

and

git pull origin release/3.5.1

and I got this response:

```<code> * branch              release/3.5.1 -> FETCH_HEAD
Already up to date.
</code>```

I have never pulled this branch before, how can it be up to date?

答:
Just doing git checkout release/3.5.1 would do the trick if you are using git >= 1.6.6

"git checkout frotz" when there is no local branch "frotz" but there
  is only one remote tracking branch "frotz" is taken as a request to
  start the named branch at the corresponding remote tracking branch.

So this will:

create a new local branch at the start of the remote branch

set it to follow the remote branch

Taken from this original answer.

NOTE: isherwood's answer git checkout origin/release/3.5.1 idea should be better if you don't want to keep a branch locally.

Body:
I am getting frustrated because I have a friend that is telling me the app of a certain branch off Bitbucket is working a certain way for him. I had a newer release.

So I decided to do:

git checkout -b release/3.5.1

and

git pull origin release/3.5.1

and I got this response:

 * branch              release/3.5.1 -> FETCH_HEAD
Already up to date.

I have never pulled this branch before, how can it be up to date?


问:
Is it possible to combine three rows having the same color together?
Here is an Image to support explanation.

Column D values are highlighted with the same color if the entries are identical in this column.

In this case, for each "group" of color I should:

add all the values of column E for a given color and enter the amount in the column J.

As you see in the picture, the amount in the column J is perfect when the given color occurs only in two rows (works perfectly for color red and green).
But as soon as the color covers more than two rows, the sum doesn't reflect the sum of all the rows, but the sum of two entries at a time only.

Here is the code I wrote for this calculation:

```<code>Sub test()

    Dim LastRow As Long, I As Long, j As Long
    Dim arr As Variant
    Dim Total_Payments As Single
    Dim Total_CashBalance As Single

    With ThisWorkbook.Worksheets("Master")

        'Find Last row of column L
        LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row

        'Set array starting from row 2 to LastRow of column L
        arr = .Range("D2:D" & LastRow)

        For I = LBound(arr) To UBound(arr)

            If .Range("D" & I).Interior.Pattern <> xlNone Then

                For j = LBound(arr) To UBound(arr)

                    If (.Range("D" & j).Interior.Pattern <> xlNone) And (I <> j) Then

                        If .Range("D" & I).Interior.Color = .Range("D" & j).Interior.Color Then

                                .Range("N" & I).Value = "Cell L" & I & " has the same background color with cell/s L" & j

                                Total_Payments = .Range("E" & I).Value + .Range("E" & j).Value
                                Range("J" & I).Value = Total_Payments

                        End If

                    End If

                Next j

            End If

        Next I

    End With

End Sub
</code>```

I would be really happy if you could tell me how to make this work for a number of cells in one group greater than 2 :) Thank you!!

答:
You can use a SUMIF formula, inserted via VBA if necessary.

Formula in C1 copied down

```<code>=SUMIF($A$1:A11,A1,$B$1:$B$11)
</code>```

Body:
Here is an Image to support explanation.

Column D values are highlighted with the same color if the entries are identical in this column.

In this case, for each "group" of color I should:

add all the values of column E for a given color and enter the amount in the column J.

As you see in the picture, the amount in the column J is perfect when the given color occurs only in two rows (works perfectly for color red and green).
But as soon as the color covers more than two rows, the sum doesn't reflect the sum of all the rows, but the sum of two entries at a time only.

Here is the code I wrote for this calculation:

Sub test()

    Dim LastRow As Long, I As Long, j As Long
    Dim arr As Variant
    Dim Total_Payments As Single
    Dim Total_CashBalance As Single

    With ThisWorkbook.Worksheets("Master")

        'Find Last row of column L
        LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row

        'Set array starting from row 2 to LastRow of column L
        arr = .Range("D2:D" & LastRow)

        For I = LBound(arr) To UBound(arr)

            If .Range("D" & I).Interior.Pattern <> xlNone Then

                For j = LBound(arr) To UBound(arr)

                    If (.Range("D" & j).Interior.Pattern <> xlNone) And (I <> j) Then

                        If .Range("D" & I).Interior.Color = .Range("D" & j).Interior.Color Then

                                .Range("N" & I).Value = "Cell L" & I & " has the same background color with cell/s L" & j

                                Total_Payments = .Range("E" & I).Value + .Range("E" & j).Value
                                Range("J" & I).Value = Total_Payments

                        End If

                    End If

                Next j

            End If

        Next I

    End With

End Sub

I would be really happy if you could tell me how to make this work for a number of cells in one group greater than 2 :) Thank you!!

Body:
You can use a SUMIF formula, inserted via VBA if necessary.

Formula in C1 copied down

=SUMIF($A$1:A11,A1,$B$1:$B$11)


问:
How to get left table values only (left join)
I have two tables:

bloodrequest (id,name,Rphone,bloodtype) as:

reacheduser (id,Rphonw,Dphone) as:

I want to read all data in bloodrequest if bloodrequest.id is not equal to reachedusers.id where reachedusers.Dphone!="618159985"

I have tried left join , subquery  but unfortunately nothing work
hear is some code i tried:

```<code>SELECT bloodrequest.id, bloodrequest.magac, bloodrequest.bloodType
FROM bloodrequest
LEFT JOIN reachedusers on bloodrequest.id != reachedusers.id
WHERE reachedusers.Dphone != "618159985"
</code>```

i want to check if request id in table bloodrequest  is in reached table where Dphone ="618159985"

if the id is exist but but dphone is not 618159985 i want to read otherwise not

答:
You can use NOT IN (subquery) to find the rows you want, as in:

```<code>SELECT
  id, magac, bloodType
FROM bloodrequest
WHERE id NOT IN (
  SELECT id
  FROM reachedusers
  WHERE Dphone = "618159985"
)
</code>```

Body:
I have two tables:

bloodrequest (id,name,Rphone,bloodtype) as:

reacheduser (id,Rphonw,Dphone) as:

I want to read all data in bloodrequest if bloodrequest.id is not equal to reachedusers.id where reachedusers.Dphone!="618159985"

I have tried left join , subquery  but unfortunately nothing work
hear is some code i tried:

SELECT bloodrequest.id, bloodrequest.magac, bloodrequest.bloodType
FROM bloodrequest
LEFT JOIN reachedusers on bloodrequest.id != reachedusers.id
WHERE reachedusers.Dphone != "618159985"

i want to check if request id in table bloodrequest  is in reached table where Dphone ="618159985"

if the id is exist but but dphone is not 618159985 i want to read otherwise not

Body:
You can use NOT IN (subquery) to find the rows you want, as in:

SELECT
  id, magac, bloodType
FROM bloodrequest
WHERE id NOT IN (
  SELECT id
  FROM reachedusers
  WHERE Dphone = "618159985"
)


问:
inline function choose criteria
I have the following:

```<code>//a.cpp
inline int f(int x) { return x; }
int g(int x) { return f(x); }

//b.cpp
#include <iostream>
inline int f(int x) { return x + 1; }
extern int g(int);
int main() {
    std::cout << g(2) << f(2) << std::endl;
}
</code>```

The output is 22 (MSVC and GCC), that is, a.cpp f function is been inlined instead of b.cpp one. What's the criteria to choose the f function in this case?

答:
You break ODR (One Definition Rule) here and have ill formed program, no diagnostic required.

Each inline definition should be identical.

Title: inline function choose criteria

Body:
I have the following:

//a.cpp
inline int f(int x) { return x; }
int g(int x) { return f(x); }

//b.cpp
#include <iostream>
inline int f(int x) { return x + 1; }
extern int g(int);
int main() {
    std::cout << g(2) << f(2) << std::endl;
}

The output is 22 (MSVC and GCC), that is, a.cpp f function is been inlined instead of b.cpp one. What's the criteria to choose the f function in this case?


问:
How to fix input with Parse.Console.ReadLine();?
```<code>struct Snaga
{
    public int Napad;
    public int Odbrana;
    public int FizickaSprema;
    public int Kontola;
    public int Psiha;
}

Snaga.Napad = Console.ReadLine();
</code>```

This dont work.

How to fix this.

答:
That property is an int, you need to convert it.

```<code>snaga.Napad = Convert.ToInt32(Console.ReadLine());
</code>```

Fiddle: https://dotnetfiddle.net/dBErGg

Body:
struct Snaga
{
    public int Napad;
    public int Odbrana;
    public int FizickaSprema;
    public int Kontola;
    public int Psiha;
}

Snaga.Napad = Console.ReadLine();

This dont work.

How to fix this.

Body:
That property is an int, you need to convert it.

snaga.Napad = Convert.ToInt32(Console.ReadLine());

Fiddle: https://dotnetfiddle.net/dBErGg


问:
Setting up the emission via script for a particle system
I have a problem with particle emission.
I have a gun that shoots smoke when a button is pressed. I have set up the particle system in a way that it looks ok when its emitting (in the particle system settings) (first picture).

The problem now lies that when I try to emit the particle only by the code it completely changes how the emission looks.

According to the particle effect I have 1500 particles with smoke.emit(30); which is way more than the 1000 set up by the emitter option.

But it appears it just clumps the particles together and just increases the number of particles on the same position as others.

Is there any way I can achieve a similar graphical setting as the emitter shows?

Thank you.

答:
You can do this via the ParticleSystem.emission module of the ParticleSystem and set the EmissionModule.rateOverTime and EmissionModule.rateOverDistance

```<code>particleSystem.emission.rateOverTime = 1000;
particleSystem.emission.rateOverDistance = 25;
</code>```

Body:
You can do this via the ParticleSystem.emission module of the ParticleSystem and set the EmissionModule.rateOverTime and EmissionModule.rateOverDistance

particleSystem.emission.rateOverTime = 1000;
particleSystem.emission.rateOverDistance = 25;


答:
Your code is ill-formed, no diagnostic required.  All inline function definitions need to be the same in all translations units.

Since you do not do that the code is ill-formed, but it is allowed to compile and it is not required to cause any sort of warning or error.

Title: inline function choose criteria


问:
Where is kill_proc_info defined?
what is header file for the kernel API function kill_proc_info(int sig, struct siginfo *info, pid_t pid)</p>

答:
[edit]

man won't work - however, man kill_proc_info into your favorite search engine will. note too that posting a page that doesn't render correctly in somebodies browser will also result in a downvote.

[/edit]

man is your friend

[edit]

google is your friend (which is how I found the first answer - in the comments below) but we're not allowed to use that as an answer here.  Better to have a repository of lazy people than to request they attempt to use the tools that they are given - IOW, better to give a man a fish than teach him how to fish

[/edit]

Title: Where is kill_proc_info defined?


问:
Parsing nested collection in scala
I have a collection structure as shown below. I need to build the statement based on k,v pairs in the map. The level of nesting is not known prior and code needs to parse it dynamically.

Structure:

```<code>case class Step(id: Option[String], stepId: Option[String], parameters: Option[Map[String, Any]])

    val sample = Step(id = Some("a1"), Some("case"), Some(
        Map(
            "CONDITIONAL" -> List(
                Map("comparison" -> List(
                    Map("comparision" -> List(
                        Map("comparision" -> List(
                            Map("comparator" -> List(
                                Map(
                                    "EVAL" -> "c11",
                                    "OPERATION" -> "equals to",
                                    "WHEN" -> List("A")),
                                Map(
                                    "eval" -> "c12",
                                    "operation" -> "in",
                                    "when" -> List("B")),
                                Map(
                                    "eval" -> "c13",
                                    "operation" -> "starts with",
                                    "when" -> List("C")
                                )),
                                "operator" -> "OR"
                            ),
                            Map("comparator" -> List(
                                Map(
                                    "EVAL" -> "c21",
                                    "OPERATION" -> "equals to",
                                    "WHEN" -> List("A")),
                                Map(
                                    "eval" -> "c22",
                                    "operation" -> "in",
                                    "when" -> List("B")
                                )),
                                "operator" -> "OR"
                            )),
                            "operator" -> "AND"
                        ),
                        Map("comparator" -> List(
                            Map(
                                "EVAL" -> "c31",
                                "OPERATION" -> "equals to",
                                "WHEN" -> List("A")),
                            Map(
                                "EVAL" -> "c32",
                                "OPERATION" -> "in",
                                "WHEN" -> List("B")),
                            Map(
                                "EVAL" -> "c33",
                                "OPERATION" -> "starts with",
                                "WHEN" -> List("C")
                            )),
                            "operator" -> "OR"
                        )),
                        "operator" -> "OR"
                    )),
                    "THEN" -> "result"
                )),
            "ELSE" -> "default"
        ))
    )

val stepsLower = sample.parameters.get.map(p => p._1.toLowerCase -> p._2)

val comparisons = stepsLower("conditional").asInstanceOf[List[Map[String, Any]]]
</code>```

Now I need to parse data under the conditional (in comparisons) by evaluating the structure.

The result should be ((c11 OR c12 OR c13 ) AND (c21 OR c22)) OR (c31 OR c32 OR c33 OR c34)

答:
Here is the code snippet that should work for all your use cases.

```<code>case class Step(id: Option[String], stepId: Option[String], parameters: Option[Map[String, Any]])

val sample1 = Step(id = Some("a1"), Some("case"), Some(Map(
    "CONDITIONAL" -> List(
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparison" -> List(
            Map("comparator" -> List(
              Map(
                "eval" -> "c11",
                "operation" -> "equals to",
                "when" -> List("A")),
              Map(
                "eval" -> "c12",
                "operation" -> "in",
                "when" -> List("B")),
              Map(
                "eval" -> "c13",
                "operation" -> "starts with",
                "when" -> List("C")
              )),
              "operator" -> "OR"
            ),
            Map("comparator" -> List(
              Map(
                "eval" -> "c21",
                "operation" -> "equals to",
                "when" -> List("A")),
              Map(
                "eval" -> "c22",
                "operation" -> "in",
                "when" -> List("B")
              )),
              "operator" -> "OR"
            )),
            "operator" -> "AND"
          ),
          Map("comparator" -> List(
            Map(
              "eval" -> "c31",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c32",
              "operation" -> "in",
              "when" -> List("B")),
            Map(
              "eval" -> "c33",
              "operation" -> "starts with",
              "when" -> List("C")
            )),
            "operator" -> "OR"
          )),
          "operator" -> "OR"
        )),
        "then" -> "result"
      )),
    "else" -> "default"
  ))
)

val sample2 = Step(id = Some("a1"), Some("case"), Some(
  Map(
    "conditional" -> List(
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparator" -> List(
            Map(
              "eval" -> "c11",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c12",
              "operation" -> "in",
              "when" -> List("B", "b"))),
            "operator" -> "AND"),
          Map("comparator" -> List(
            Map("eval" -> "c21",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map("eval" -> "c31",
              "operation" -> "equals to",
              "when" -> List("A"))),
            "operator" -> "OR")),
          "operator" -> "OR")),
        "then" -> "something"
      ),
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparator" -> List(
            Map(
              "eval" -> "c111",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c121",
              "operation" -> "in",
              "when" -> List("B", "b"))
          ),
            "operator" -> "AND"),
          Map("comparator" -> List(
            Map(
              "eval" -> "c212",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c313",
              "operation" -> "equals to",
              "when" -> List("A"))
          ),
            "operator" -> "OR")),
          "operator" -> "AND")),
        "then" -> "somethingelse")
    ),
    "else" -> "default"
  )
))

def constructCase(c: List[Map[String, Any]], parentOp: Option[String] = None, parentThen: Option[String] = None): String = {

  val result = c.map { x =>
    val currentOp: Option[String] = x.get("operator").asInstanceOf[Option[String]]
    val currentThen: Option[String] = x.get("then").asInstanceOf[Option[String]]

    if (x contains "comparator") {
      "(" + x("comparator").asInstanceOf[List[Map[String, Any]]].map(x => s"${x("eval")} ${x("operation")} ${x("when").asInstanceOf[List[String]].mkString(",")}").mkString(" " + currentOp.getOrElse("") + " ") + ")"
    } else {
      val tmp = constructCase(x("comparison").asInstanceOf[List[Map[String, Any]]], currentOp, currentThen)
      if (tmp contains "WHEN") tmp else "(" + tmp + ")"
    }
  }.mkString(if (parentOp.isDefined) s" ${parentOp.get} " else "")

  if (parentThen.isDefined) s"WHEN $result THEN ${parentThen.get}\n" else result.trim
}

val samples = Set(sample1, sample2)
samples.foreach { sample =>
  val stepsLower = sample.parameters.get.map(p => p._1.toLowerCase -> p._2)

  val comparisons = stepsLower("conditional").asInstanceOf[List[Map[String, Any]]]

  println("CASE \n" + constructCase(comparisons) + s"\nELSE ${stepsLower("else")}")
  println("")
}
</code>```

Here is the result

```<code>CASE
WHEN (((c11 equals to A OR c12 in B OR c13 starts with C) AND (c21 equals to A OR c22 in B)) OR (c31 equals to A OR c32 in B OR c33 starts with C)) THEN result
ELSE default

CASE
WHEN ((c11 equals to A AND c12 in B,b) OR (c21 equals to A OR c31 equals to A)) THEN something
WHEN ((c111 equals to A AND c121 in B,b) AND (c212 equals to A OR c313 equals to A)) THEN somethingelse
ELSE default
</code>```

Let me know if it doesn't work for any of your use case.

Title: Parsing nested collection in scala

Body:
I have a collection structure as shown below. I need to build the statement based on k,v pairs in the map. The level of nesting is not known prior and code needs to parse it dynamically.

Structure:

case class Step(id: Option[String], stepId: Option[String], parameters: Option[Map[String, Any]])

    val sample = Step(id = Some("a1"), Some("case"), Some(
        Map(
            "CONDITIONAL" -> List(
                Map("comparison" -> List(
                    Map("comparision" -> List(
                        Map("comparision" -> List(
                            Map("comparator" -> List(
                                Map(
                                    "EVAL" -> "c11",
                                    "OPERATION" -> "equals to",
                                    "WHEN" -> List("A")),
                                Map(
                                    "eval" -> "c12",
                                    "operation" -> "in",
                                    "when" -> List("B")),
                                Map(
                                    "eval" -> "c13",
                                    "operation" -> "starts with",
                                    "when" -> List("C")
                                )),
                                "operator" -> "OR"
                            ),
                            Map("comparator" -> List(
                                Map(
                                    "EVAL" -> "c21",
                                    "OPERATION" -> "equals to",
                                    "WHEN" -> List("A")),
                                Map(
                                    "eval" -> "c22",
                                    "operation" -> "in",
                                    "when" -> List("B")
                                )),
                                "operator" -> "OR"
                            )),
                            "operator" -> "AND"
                        ),
                        Map("comparator" -> List(
                            Map(
                                "EVAL" -> "c31",
                                "OPERATION" -> "equals to",
                                "WHEN" -> List("A")),
                            Map(
                                "EVAL" -> "c32",
                                "OPERATION" -> "in",
                                "WHEN" -> List("B")),
                            Map(
                                "EVAL" -> "c33",
                                "OPERATION" -> "starts with",
                                "WHEN" -> List("C")
                            )),
                            "operator" -> "OR"
                        )),
                        "operator" -> "OR"
                    )),
                    "THEN" -> "result"
                )),
            "ELSE" -> "default"
        ))
    )

val stepsLower = sample.parameters.get.map(p => p._1.toLowerCase -> p._2)

val comparisons = stepsLower("conditional").asInstanceOf[List[Map[String, Any]]]

Now I need to parse data under the conditional (in comparisons) by evaluating the structure.

The result should be ((c11 OR c12 OR c13 ) AND (c21 OR c22)) OR (c31 OR c32 OR c33 OR c34)

Body:
Here is the code snippet that should work for all your use cases.

case class Step(id: Option[String], stepId: Option[String], parameters: Option[Map[String, Any]])

val sample1 = Step(id = Some("a1"), Some("case"), Some(Map(
    "CONDITIONAL" -> List(
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparison" -> List(
            Map("comparator" -> List(
              Map(
                "eval" -> "c11",
                "operation" -> "equals to",
                "when" -> List("A")),
              Map(
                "eval" -> "c12",
                "operation" -> "in",
                "when" -> List("B")),
              Map(
                "eval" -> "c13",
                "operation" -> "starts with",
                "when" -> List("C")
              )),
              "operator" -> "OR"
            ),
            Map("comparator" -> List(
              Map(
                "eval" -> "c21",
                "operation" -> "equals to",
                "when" -> List("A")),
              Map(
                "eval" -> "c22",
                "operation" -> "in",
                "when" -> List("B")
              )),
              "operator" -> "OR"
            )),
            "operator" -> "AND"
          ),
          Map("comparator" -> List(
            Map(
              "eval" -> "c31",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c32",
              "operation" -> "in",
              "when" -> List("B")),
            Map(
              "eval" -> "c33",
              "operation" -> "starts with",
              "when" -> List("C")
            )),
            "operator" -> "OR"
          )),
          "operator" -> "OR"
        )),
        "then" -> "result"
      )),
    "else" -> "default"
  ))
)

val sample2 = Step(id = Some("a1"), Some("case"), Some(
  Map(
    "conditional" -> List(
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparator" -> List(
            Map(
              "eval" -> "c11",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c12",
              "operation" -> "in",
              "when" -> List("B", "b"))),
            "operator" -> "AND"),
          Map("comparator" -> List(
            Map("eval" -> "c21",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map("eval" -> "c31",
              "operation" -> "equals to",
              "when" -> List("A"))),
            "operator" -> "OR")),
          "operator" -> "OR")),
        "then" -> "something"
      ),
      Map("comparison" -> List(
        Map("comparison" -> List(
          Map("comparator" -> List(
            Map(
              "eval" -> "c111",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c121",
              "operation" -> "in",
              "when" -> List("B", "b"))
          ),
            "operator" -> "AND"),
          Map("comparator" -> List(
            Map(
              "eval" -> "c212",
              "operation" -> "equals to",
              "when" -> List("A")),
            Map(
              "eval" -> "c313",
              "operation" -> "equals to",
              "when" -> List("A"))
          ),
            "operator" -> "OR")),
          "operator" -> "AND")),
        "then" -> "somethingelse")
    ),
    "else" -> "default"
  )
))

def constructCase(c: List[Map[String, Any]], parentOp: Option[String] = None, parentThen: Option[String] = None): String = {

  val result = c.map { x =>
    val currentOp: Option[String] = x.get("operator").asInstanceOf[Option[String]]
    val currentThen: Option[String] = x.get("then").asInstanceOf[Option[String]]

    if (x contains "comparator") {
      "(" + x("comparator").asInstanceOf[List[Map[String, Any]]].map(x => s"${x("eval")} ${x("operation")} ${x("when").asInstanceOf[List[String]].mkString(",")}").mkString(" " + currentOp.getOrElse("") + " ") + ")"
    } else {
      val tmp = constructCase(x("comparison").asInstanceOf[List[Map[String, Any]]], currentOp, currentThen)
      if (tmp contains "WHEN") tmp else "(" + tmp + ")"
    }
  }.mkString(if (parentOp.isDefined) s" ${parentOp.get} " else "")

  if (parentThen.isDefined) s"WHEN $result THEN ${parentThen.get}\n" else result.trim
}

val samples = Set(sample1, sample2)
samples.foreach { sample =>
  val stepsLower = sample.parameters.get.map(p => p._1.toLowerCase -> p._2)

  val comparisons = stepsLower("conditional").asInstanceOf[List[Map[String, Any]]]

  println("CASE \n" + constructCase(comparisons) + s"\nELSE ${stepsLower("else")}")
  println("")
}

Here is the result

CASE
WHEN (((c11 equals to A OR c12 in B OR c13 starts with C) AND (c21 equals to A OR c22 in B)) OR (c31 equals to A OR c32 in B OR c33 starts with C)) THEN result
ELSE default

CASE
WHEN ((c11 equals to A AND c12 in B,b) OR (c21 equals to A OR c31 equals to A)) THEN something
WHEN ((c111 equals to A AND c121 in B,b) AND (c212 equals to A OR c313 equals to A)) THEN somethingelse
ELSE default

Let me know if it doesn't work for any of your use case.


问:
JSON API automatic reverse links
Is it a violation of the JSON-API spec to allow reverse relationships to be created automatically?

I need to create resources that, when I link A to B in a relationship, automatically links B to A. In this way I can traverse A to find all of its Bs and can find the parent A from a B. However, I don't want to POST/PATCH to 2 relationships to get this right. I want to establish the relationship once.

Now I know that it is an implementation detail as to how the server maintains link/references as well as how the behaviour is established but I want to build the API in such a way that it doesn't violate the spec.

Assuming I have resources Books and Authors. Books have Authors and Authors have Books. The question is, once I relate an Author to a Book, I need the reverse relationship to be created as well. Is it a violation of the spec in any way to assume that this reverse relationship can be automatically created by simply doing one POST to the Books resource's relationship?

By way of example, starting with the book.

```<code>{
    "data": {
        "type": "books", "id": 123, "attributes": ...,
        "links": { "self": "/books/123" },
        "relationships": {
            "self": "/books/123/relationships/authors",
            "related": "/books/123/authors"
        }
     }
}
</code>```

And the author

```<code>{
    "data": {
        "type": "authors", "id": 456, "attributes": ...,
        "links": { "self": "/authors/456" },
        "relationships": {
            "self": "/authors/456/relationships/books",
            "related": "/authors/456/books"
        }
     }
}
</code>```

If I establish the link from a book to an author with a POST to /books/123/relationships/authors

```<code>{
    "data": [{ "data": "authors", "id": "456" }]
}
</code>```

Do I need to explicitly do the same for the Author 456 as a POST to /authors/456/relationships/books?

```<code>{
    "data": [{ "data": "books", "id": "123" }]
}
</code>```

Or can I let the server build the relationship for me so that I can avoid the second POST and just see the automatic reverse relationship at GET /authors/456/relationships/books?

答:
From the perspective of the spec this is only one relationship represented from two different sides. author and book have a many-to-many relationship. This relationship could be represented in author's resource object as well as book's resource object and of course also via there relationship links. Actually it would be a violation of the spirit of the specification if representations wouldn't match. Having one-sided relationships is another story but in that case one side wouldn't know about the relationships at all (e.g. a book is associated with an author but the author model does not know which books are associated with it).

A post to either one side of that relationship creates the relationship between the two records. It shouldn't matter which side is used to create that relationship and if it's created as part of a creation / update to a resource via it's resource object or via a relationship link representing that relationship. The same applies to deletion of that relationship.

Maybe an example would make that even more clear. Let's assume a book is created with a POST to /books?include=author having these payload:

```<code>{
  "data": {
    "type": "books",
    "relationships": {
      "author": {
        "data": {
          "type": "authors",
          "id": "1"
        }
      }
    }
  }
}
</code>```

The response may look like this:

```<code>{
  "data": {
    "type": "books",
    "id": "7",
    "relationships": {
      "author": {
        "data": { "type": "authors", "id": "1" }
      }
    }
  },
  "included": [
    {
      "type": "authors",
      "id": "1",
      "relationships": {
        "books": {
          "data": [
            { "type": "books", "id": "7" }
          ]
        }
      }
    }
  ]
}
</code>```

Title: JSON API automatic reverse links

Body:
Is it a violation of the JSON-API spec to allow reverse relationships to be created automatically?

I need to create resources that, when I link A to B in a relationship, automatically links B to A. In this way I can traverse A to find all of its Bs and can find the parent A from a B. However, I don't want to POST/PATCH to 2 relationships to get this right. I want to establish the relationship once.

Now I know that it is an implementation detail as to how the server maintains link/references as well as how the behaviour is established but I want to build the API in such a way that it doesn't violate the spec.

Assuming I have resources Books and Authors. Books have Authors and Authors have Books. The question is, once I relate an Author to a Book, I need the reverse relationship to be created as well. Is it a violation of the spec in any way to assume that this reverse relationship can be automatically created by simply doing one POST to the Books resource's relationship?

By way of example, starting with the book.

{
    "data": {
        "type": "books", "id": 123, "attributes": ...,
        "links": { "self": "/books/123" },
        "relationships": {
            "self": "/books/123/relationships/authors",
            "related": "/books/123/authors"
        }
     }
}

And the author

{
    "data": {
        "type": "authors", "id": 456, "attributes": ...,
        "links": { "self": "/authors/456" },
        "relationships": {
            "self": "/authors/456/relationships/books",
            "related": "/authors/456/books"
        }
     }
}

If I establish the link from a book to an author with a POST to /books/123/relationships/authors

{
    "data": [{ "data": "authors", "id": "456" }]
}

Do I need to explicitly do the same for the Author 456 as a POST to /authors/456/relationships/books?

{
    "data": [{ "data": "books", "id": "123" }]
}

Or can I let the server build the relationship for me so that I can avoid the second POST and just see the automatic reverse relationship at GET /authors/456/relationships/books?

Body:
From the perspective of the spec this is only one relationship represented from two different sides. author and book have a many-to-many relationship. This relationship could be represented in author's resource object as well as book's resource object and of course also via there relationship links. Actually it would be a violation of the spirit of the specification if representations wouldn't match. Having one-sided relationships is another story but in that case one side wouldn't know about the relationships at all (e.g. a book is associated with an author but the author model does not know which books are associated with it).

A post to either one side of that relationship creates the relationship between the two records. It shouldn't matter which side is used to create that relationship and if it's created as part of a creation / update to a resource via it's resource object or via a relationship link representing that relationship. The same applies to deletion of that relationship.

Maybe an example would make that even more clear. Let's assume a book is created with a POST to /books?include=author having these payload:

{
  "data": {
    "type": "books",
    "relationships": {
      "author": {
        "data": {
          "type": "authors",
          "id": "1"
        }
      }
    }
  }
}

The response may look like this:

{
  "data": {
    "type": "books",
    "id": "7",
    "relationships": {
      "author": {
        "data": { "type": "authors", "id": "1" }
      }
    }
  },
  "included": [
    {
      "type": "authors",
      "id": "1",
      "relationships": {
        "books": {
          "data": [
            { "type": "books", "id": "7" }
          ]
        }
      }
    }
  ]
}


问:
Using HLL_COUNT.MERGE outside of SQL
I can use the following query to general all the HLL sketches of the distinct counts:

```<code>SELECT category, count(distinct city), HLL_COUNT.INIT(city) FROM `table`
GROUP BY category
</code>```

And I get something like this:

While I would normally use the HLL_COUNT.merge(...) function to get the total count, for example:

```<code>select 'all -- hll', HLL_COUNT.MERGE(x), null from (select category, count(distinct city), HLL_COUNT.INIT(city) x from `datadocs-163219.010ff92f6a62438aa47c10005fe98fc9.inv` group by category) _
</code>```

For various reasons, I need to do the MERGE outside of SQL/BigQuery. Is there some sort of library/open source library where I could do something like the following:

```<code>>>> hll_set
>>> {'CHAQMBgCIAuCBz8QFBgPIBQyN8hxlqEBvMMBnLMBgWnD5gTB3AH+ROgD/YMEpM8Jr70C6Q2LwwfZlQ3QMNu8AYDSBKf7AbOSqgE=',  'CHAQDhgCIAuCBxwQBxgPIBQyFP3PBMBtibMR3sgC77oViasKwfMF', 'CHAQJxgCIAuCBzIQEBgPIBQyKshxlqEBvMMBzfECh6gJxJABoNwF/rEGwf0PgYYFvOoFmzjJPZwg2y3nbw==', 'CHAQBBgCIAuCBw4QAhgPIBQyBpSJAfapKA==', 'CHAQBRgCIAuCBxEQAxgPIBQyCbaJBfqsH57tBw==', 'CHAQGBgCIAuCBykQDRgPIBQyId6SAtNvwJ0XgO8Ct/EFlvUOskG1E87ZA7/OApwg2y3nbw==', 'CHAQZhgCIAuCB2MQIxgPIBQyW5SJAcqJAbzDAcvcAoIV2xSMFsTyA42IAYkl+Wvj/AHqdJxRlEGbywG/WNjoAqS9BP3CAuPrBNSFAfdDt+YEoeIBr+ICmIYF6CL/MaLNAqKdA8k9rxntBrPVrAE=', 'CHAQEBgCIAuCByQQChgPIBQyHN6SAqjtArAJ/esCj9wSg+8KiVKNygHrpgXIogU=', 'CHAQpgkYAiALggfZAhChARgPIBQyzwKPBMwRkAzxP+wPogyqC8qJAeBo8BHsSOypAbAJriL+MYYR/1jnKqIyzR3wJIkI/QXkecNH7WCzQZgMuDvxFLh+xkboA7QB12akDhu5E+4+3KgBjAZ4nxLBRMw0xRWvIPZYszt+v1gnz2a0BZoF4wzQggHqOewsJeAxgguGErUCjGG3KuhKgUyfCtItkjOMZZwCpi3phgHlA+wRknEhwiq1Os4slgmhELEWl1f1rgH+B6e4AdCtAdkE4R7fK/gihHSRFqipAbYY9BmqP5oBgqsBvhrvEKGRAcpj7XHEVaAUrY8BylLRDgWn1wGpT6IS6irPHewb/AbKHqgQjQPyAeU82zuSHpgQ04UBzwqkFIADiBD4X6ABjBihFsIy6wmovgHNKssPsQOvGcADrQOQevMQvxKMBtANizqbP7l21+kB0UDxY92rVYCBMcD5H8CiEA=='}

>>> hll_merge_method(hll_set)
>>> 193
</code>```

Is it possible to do this in any way using a library outside of BQ with the hash generated from it?

答:
That's a feature request you might already find in the issue tracker: the current hash is Google proprietary, but one day BigQuery could use an open one. Vote that request up.

https://issuetracker.google.com/issues/62153424

There might be news soon, and subscribing to the issue will keep you updated.

2019 Update: Find the open source version of BigQuery's HyperLogLog++ at:

https://github.com/google/zetasketch

Title: Using HLL_COUNT.MERGE outside of SQL

Body:
I can use the following query to general all the HLL sketches of the distinct counts:

SELECT category, count(distinct city), HLL_COUNT.INIT(city) FROM `table`
GROUP BY category

And I get something like this:

While I would normally use the HLL_COUNT.merge(...) function to get the total count, for example:

select 'all -- hll', HLL_COUNT.MERGE(x), null from (select category, count(distinct city), HLL_COUNT.INIT(city) x from `datadocs-163219.010ff92f6a62438aa47c10005fe98fc9.inv` group by category) _

For various reasons, I need to do the MERGE outside of SQL/BigQuery. Is there some sort of library/open source library where I could do something like the following:

>>> hll_set
>>> {'CHAQMBgCIAuCBz8QFBgPIBQyN8hxlqEBvMMBnLMBgWnD5gTB3AH+ROgD/YMEpM8Jr70C6Q2LwwfZlQ3QMNu8AYDSBKf7AbOSqgE=',  'CHAQDhgCIAuCBxwQBxgPIBQyFP3PBMBtibMR3sgC77oViasKwfMF', 'CHAQJxgCIAuCBzIQEBgPIBQyKshxlqEBvMMBzfECh6gJxJABoNwF/rEGwf0PgYYFvOoFmzjJPZwg2y3nbw==', 'CHAQBBgCIAuCBw4QAhgPIBQyBpSJAfapKA==', 'CHAQBRgCIAuCBxEQAxgPIBQyCbaJBfqsH57tBw==', 'CHAQGBgCIAuCBykQDRgPIBQyId6SAtNvwJ0XgO8Ct/EFlvUOskG1E87ZA7/OApwg2y3nbw==', 'CHAQZhgCIAuCB2MQIxgPIBQyW5SJAcqJAbzDAcvcAoIV2xSMFsTyA42IAYkl+Wvj/AHqdJxRlEGbywG/WNjoAqS9BP3CAuPrBNSFAfdDt+YEoeIBr+ICmIYF6CL/MaLNAqKdA8k9rxntBrPVrAE=', 'CHAQEBgCIAuCByQQChgPIBQyHN6SAqjtArAJ/esCj9wSg+8KiVKNygHrpgXIogU=', 'CHAQpgkYAiALggfZAhChARgPIBQyzwKPBMwRkAzxP+wPogyqC8qJAeBo8BHsSOypAbAJriL+MYYR/1jnKqIyzR3wJIkI/QXkecNH7WCzQZgMuDvxFLh+xkboA7QB12akDhu5E+4+3KgBjAZ4nxLBRMw0xRWvIPZYszt+v1gnz2a0BZoF4wzQggHqOewsJeAxgguGErUCjGG3KuhKgUyfCtItkjOMZZwCpi3phgHlA+wRknEhwiq1Os4slgmhELEWl1f1rgH+B6e4AdCtAdkE4R7fK/gihHSRFqipAbYY9BmqP5oBgqsBvhrvEKGRAcpj7XHEVaAUrY8BylLRDgWn1wGpT6IS6irPHewb/AbKHqgQjQPyAeU82zuSHpgQ04UBzwqkFIADiBD4X6ABjBihFsIy6wmovgHNKssPsQOvGcADrQOQevMQvxKMBtANizqbP7l21+kB0UDxY92rVYCBMcD5H8CiEA=='}

>>> hll_merge_method(hll_set)
>>> 193

Is it possible to do this in any way using a library outside of BQ with the hash generated from it?


问:
how to edit xml file in C#
```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

答:
One possibility is to use XSLT and grouping by keys. In this case it is complicated by the use of mixed content for "category" and "name"; it makes the key construction non-obvious:

normalize-space(./node()[1]) The first child node of FamilyCategory is assumed to be a text node that contains the category name,; it is further trimmed w.r.t. white space.

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes" />

<xsl:key name="category" match="FamilyCategory" use="normalize-space(./node()[1])" />
<xsl:template match="Family_Inventory">
    <xsl:copy>
        <xsl:for-each
            select="FamilyCategory[count(. | key('category', normalize-space(./node()[1]))[1]) = 1]">
            <xsl:copy>
                <xsl:value-of select="normalize-space(./node()[1])" />
                <xsl:for-each select="key('category', normalize-space(./node()[1]))/FamilyName">
                    <xsl:copy-of select="."/>
                </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code>```

A good explanation of how it works is found here: http://www.jenitennison.com/xslt/grouping/muenchian.xml

Title: how to edit xml file in C#

Body:
<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

Body:
One possibility is to use XSLT and grouping by keys. In this case it is complicated by the use of mixed content for "category" and "name"; it makes the key construction non-obvious:

normalize-space(./node()[1]) The first child node of FamilyCategory is assumed to be a text node that contains the category name,; it is further trimmed w.r.t. white space.

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes" />

<xsl:key name="category" match="FamilyCategory" use="normalize-space(./node()[1])" />
<xsl:template match="Family_Inventory">
    <xsl:copy>
        <xsl:for-each
            select="FamilyCategory[count(. | key('category', normalize-space(./node()[1]))[1]) = 1]">
            <xsl:copy>
                <xsl:value-of select="normalize-space(./node()[1])" />
                <xsl:for-each select="key('category', normalize-space(./node()[1]))/FamilyName">
                    <xsl:copy-of select="."/>
                </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

A good explanation of how it works is found here: http://www.jenitennison.com/xslt/grouping/muenchian.xml