问:
Update Child table Whose Parent Table has duplicates
I have duplicate data in Contact Table.
Using Rank() function i am identifying duplicates.
I also have to update the id of contact in child table activity.

I want to update contact id in activity table by contact id of rank 1 where rank 2 or above are there.

Using this query to find duplicate contact

```<code>(SELECT
    ExternalContactID,
    RANK() OVER (PARTITION BY ExternalAccountId, Name, Email, MailingCity,
    MailingCountry, MailingState, MailingStreet, Phone ORDER BY
    ExternalContactID) AS rank

FROM
    contact)
</code>```

Table: Contact

```<code>ExternalContactID | Rank
    101           |  1
    102           |  2
</code>```

Child table: Activity

```<code>ActivityID    |    ContactID
    1         |        101
    2         |        102
</code>```

Before deleting contact(s) which have rank > 1, I need to update the child table "Activity" with rank 1 contact id.

Result:

Contact with id = 102 is deleted and Activity Record with id = 2 now has contact id = 101

答:
You've used RANK to identify groups of duplicates and the one in each group you wish to keep.  This is your mechanism for doing a self-join to relate every row to the "keeper" (the member of the duplicate group you wish to keep).

```<code>WITH cte AS (
  {Query with Rank column}
)
  SELECT ...
  FROM cte a
  INNER JOIN cte b
    ON {all the partitioning columns being equal}
    AND a.Rank=1
    AND b.Rank<>1
</code>```

With the psuedocode above,  you've got all the rows in the table joined to the row that is going to be the "keeper" after you delete the duplicates.   JOIN to this structure in your UPDATE to set the FK to the PK of the "Keeper" that is related to it.

Body:
I have duplicate data in Contact Table.
Using Rank() function i am identifying duplicates.
I also have to update the id of contact in child table activity.

I want to update contact id in activity table by contact id of rank 1 where rank 2 or above are there.

Using this query to find duplicate contact

(SELECT
    ExternalContactID,
    RANK() OVER (PARTITION BY ExternalAccountId, Name, Email, MailingCity,
    MailingCountry, MailingState, MailingStreet, Phone ORDER BY
    ExternalContactID) AS rank

FROM
    contact)

Table: Contact

ExternalContactID | Rank
    101           |  1
    102           |  2

Child table: Activity

ActivityID    |    ContactID
    1         |        101
    2         |        102

Before deleting contact(s) which have rank > 1, I need to update the child table "Activity" with rank 1 contact id.

Result:

Contact with id = 102 is deleted and Activity Record with id = 2 now has contact id = 101

Body:
You've used RANK to identify groups of duplicates and the one in each group you wish to keep.  This is your mechanism for doing a self-join to relate every row to the "keeper" (the member of the duplicate group you wish to keep).

WITH cte AS (
  {Query with Rank column}
)
  SELECT ...
  FROM cte a
  INNER JOIN cte b
    ON {all the partitioning columns being equal}
    AND a.Rank=1
    AND b.Rank<>1

With the psuedocode above,  you've got all the rows in the table joined to the row that is going to be the "keeper" after you delete the duplicates.   JOIN to this structure in your UPDATE to set the FK to the PK of the "Keeper" that is related to it.


来源: stackexchange

问:
ERROR TypeError: Cannot read property '...' of undefined
Not sure why this is happening here, I am getting this error from my component:

```<code>ERROR TypeError: Cannot read property 'timezone_offset' of undefined
at Object.eval [as updateRenderer] (SettingsComponent.html:16)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14377)
at checkAndUpdateView (core.js:13513)
at callViewAction (core.js:13858)
at execComponentViewsAction (core.js:13790)
at checkAndUpdateView (core.js:13514)
at callViewAction (core.js:13858)
at execEmbeddedViewsAction (core.js:13816)
at checkAndUpdateView (core.js:13509)
at callViewAction (core.js:13858)
</code>```

Interestingly enough it still displays the correct string in the template and there are no errors in ng-cli. Here is the code for the component producing the error:

```<code>import { Component, OnInit } from '@angular/core';
import { GetProfileService } from '../../services/get-profile.service';

@Component({
    selector: 'app-settings',
    templateUrl: './settings.component.html'
})
export class SettingsComponent implements OnInit {

    results: any;
    profile: any;

    constructor(private getProfileService: GetProfileService) { }

    ngOnInit() {

        this.getProfileService.profileAPI().subscribe(
            data => {
                this.results = data
                this.profile = this.results
                console.log(this.profile)
            }
        );

    }

}
</code>```

I am for now just using {{ profile.timezone_offset }} as the only thing on my template...

答:
It seems that your data has not been loaded within the profile object at the time when it was rendered. Only after the completion of asynchronous operation data is set within the profile object. ?. should be used when your object is operating on asynchronous call. timezone_offset will be evaluated only when the profile object is defined.

Due to asynchronous operation, you might be getting that error. Try the following

{{ profile?.timezone_offset }}

ContentLicense: CC BY-SA 3.0

Body:
Not sure why this is happening here, I am getting this error from my component:

ERROR TypeError: Cannot read property 'timezone_offset' of undefined
at Object.eval [as updateRenderer] (SettingsComponent.html:16)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14377)
at checkAndUpdateView (core.js:13513)
at callViewAction (core.js:13858)
at execComponentViewsAction (core.js:13790)
at checkAndUpdateView (core.js:13514)
at callViewAction (core.js:13858)
at execEmbeddedViewsAction (core.js:13816)
at checkAndUpdateView (core.js:13509)
at callViewAction (core.js:13858)

Interestingly enough it still displays the correct string in the template and there are no errors in ng-cli. Here is the code for the component producing the error:

import { Component, OnInit } from '@angular/core';
import { GetProfileService } from '../../services/get-profile.service';

@Component({
    selector: 'app-settings',
    templateUrl: './settings.component.html'
})
export class SettingsComponent implements OnInit {

    results: any;
    profile: any;

    constructor(private getProfileService: GetProfileService) { }

    ngOnInit() {

        this.getProfileService.profileAPI().subscribe(
            data => {
                this.results = data
                this.profile = this.results
                console.log(this.profile)
            }
        );

    }

}

I am for now just using {{ profile.timezone_offset }} as the only thing on my template...


问:
NumberFormatter - ObjectiveC
How do I create a number formatter for formatting large numbers with commas?

For example, 2389378.289 should become 2,389,378.289

Note that there is not always three decimal places, nor is there always a decimal at all. Please use NSNumberFormatter.

Thanks!

答:
The format for that would be @"#,##0.###". Take a look at the Unicode number format guide for a full explanation of how to construct format strings.

(Also note that this works correctly in locales where commas and dots are reversed, or where other characters are used.)

ContentLicense: CC BY-SA 2.5

Title: NumberFormatter - ObjectiveC


答:
Use the ?. safe navigation operator <= documentation

```<code>{{ profile?.timezone_offset }}
</code>```

It checks if profile exists before trying to access values from it. This is usefull if profile is loaded asynchronous.

Title: ERROR TypeError: Cannot read property '...' of undefined

Body:
Use the ?. safe navigation operator <= documentation

{{ profile?.timezone_offset }}

It checks if profile exists before trying to access values from it. This is usefull if profile is loaded asynchronous.


问:
The OLE way of doing drag&drop in wxPython
I have wxPython app which is running on MS Windows and I'd like it to support drag&drop between its instances (so the user opens my app 3 times and drags data from one instance to another).

The simple drag&drop in wxPython works that way:

User initiates drag: The source window packs necessary data in wx.DataObject(), creates new wx.DropSource, sets its data and calls dropSource.DoDragDrop()

User drops data onto target window:  The drop target calls library function GetData() which transfers actual data to its wx.DataObject instance and finally - dataObject.GetData() unpacks the actual data.

I'd like to have some more sophisticated drag&drop which would allow user to choose what data is dragged after he drops.

Scenario of my dreams:

User initiates drag: Only some pointer to the source window is packed (some function or object).

User drops data onto target window: Nice dialog is displayed which asks user which drag&drop mode he chooses (like - dragging only song title, or song title and the artists name or whole album of the dragged artist).

Users chooses drag&drop mode: Drop target calls some function on the dragged data object, which then retrieves data from the drag source and transfers it to the drop target.

The scenario of my dreams seems doable in MS Windows, but the docs for wxWidgets and wxPython are pretty complex and ambigious. Not all wx.DataObject classes are available in wxPython (only wx.PySimpleDataObject), so I'd like someone to share his experience with such approach. Can such behaviour be implemented in wxPython without having to code it directly in winAPI?

EDIT:
Toni Ruža gave an answer with working drag&drop example, but that's not exactly the scenario of my dreams. His code manipulates data when it's dropped (the HandleDrop() shows popup menu), but data is prepared when drag is initiated (in On_ElementDrag()). In my application there should be three different drag&drop modes, and some of them require time-consuming data preparation. That's why I want to postpone data retrieval to the moment user drops data and chooses (potentially costly) d&d mode.

And for memory protection issue - I want to use OLE mechanisms for inter-process communication, like MS Office does. You can copy Excel diagram and paste it into MS-Word where it will behave like an image (well, sort of). Since it works I believe it can be done in winAPI. I just don't know if I can code it in wxPython.

答:
Since you can't use one of the standard data formats to store references to python objects I would recommend you use a text data format for storing the parameters you need for your method calls rather than making a new data format. And anyway, it would be no good to pass a reference to an object from one app to another as the object in question would not be accessible (remember memory protection?).

Here is a simple example for your requirements:

```<code>import wx

class TestDropTarget(wx.TextDropTarget):
    def OnDropText(self, x, y, text):
        wx.GetApp().TopWindow.HandleDrop(text)

    def OnDragOver(self, x, y, d):
        return wx.DragCopy

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.numbers = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)
        self.field = wx.TextCtrl(self)

        sizer = wx.FlexGridSizer(2, 2, 5, 5)
        sizer.AddGrowableCol(1)
        sizer.AddGrowableRow(0)
        self.SetSizer(sizer)
        sizer.Add(wx.StaticText(self, label="Drag from:"))
        sizer.Add(self.numbers, flag=wx.EXPAND)
        sizer.Add(wx.StaticText(self, label="Drag to:"), flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(self.field)

        for i in range(100):
            self.numbers.InsertStringItem(self.numbers.GetItemCount(), str(i))

        self.numbers.Bind(wx.EVT_LIST_BEGIN_DRAG, self.On_ElementDrag)
        self.field.SetDropTarget(TestDropTarget())

        menu_id1 = wx.NewId()
        menu_id2 = wx.NewId()
        self.menu = wx.Menu()
        self.menu.AppendItem(wx.MenuItem(self.menu, menu_id1, "Simple copy"))
        self.menu.AppendItem(wx.MenuItem(self.menu, menu_id2, "Mess with it"))
        self.Bind(wx.EVT_MENU, self.On_SimpleCopy, id=menu_id1)
        self.Bind(wx.EVT_MENU, self.On_MessWithIt, id=menu_id2)

    def On_ElementDrag(self, event):
        data = wx.TextDataObject(self.numbers.GetItemText(event.Index))
        source = wx.DropSource(self.numbers)
        source.SetData(data)
        source.DoDragDrop()

    def HandleDrop(self, text):
        self._text = text
        self.PopupMenu(self.menu)

    def On_SimpleCopy(self, event):
        self.field.Value = self._text

    def On_MessWithIt(self, event):
        self.field.Value = "<-%s->" % "".join([int(c)*c for c in self._text])

app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
</code>```

Methods like On_SimpleCopy and On_MessWithIt get executed after the drop so any lengthy operations you might want to do you can do there based on the textual or some other standard type of data you transfered with the drag (self._text in my case), and look... no OLE :)

OwnerDisplayName: Abgan

LastEditorDisplayName: Abgan

Body:
Since you can't use one of the standard data formats to store references to python objects I would recommend you use a text data format for storing the parameters you need for your method calls rather than making a new data format. And anyway, it would be no good to pass a reference to an object from one app to another as the object in question would not be accessible (remember memory protection?).

Here is a simple example for your requirements:

import wx

class TestDropTarget(wx.TextDropTarget):
    def OnDropText(self, x, y, text):
        wx.GetApp().TopWindow.HandleDrop(text)

    def OnDragOver(self, x, y, d):
        return wx.DragCopy

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.numbers = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)
        self.field = wx.TextCtrl(self)

        sizer = wx.FlexGridSizer(2, 2, 5, 5)
        sizer.AddGrowableCol(1)
        sizer.AddGrowableRow(0)
        self.SetSizer(sizer)
        sizer.Add(wx.StaticText(self, label="Drag from:"))
        sizer.Add(self.numbers, flag=wx.EXPAND)
        sizer.Add(wx.StaticText(self, label="Drag to:"), flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(self.field)

        for i in range(100):
            self.numbers.InsertStringItem(self.numbers.GetItemCount(), str(i))

        self.numbers.Bind(wx.EVT_LIST_BEGIN_DRAG, self.On_ElementDrag)
        self.field.SetDropTarget(TestDropTarget())

        menu_id1 = wx.NewId()
        menu_id2 = wx.NewId()
        self.menu = wx.Menu()
        self.menu.AppendItem(wx.MenuItem(self.menu, menu_id1, "Simple copy"))
        self.menu.AppendItem(wx.MenuItem(self.menu, menu_id2, "Mess with it"))
        self.Bind(wx.EVT_MENU, self.On_SimpleCopy, id=menu_id1)
        self.Bind(wx.EVT_MENU, self.On_MessWithIt, id=menu_id2)

    def On_ElementDrag(self, event):
        data = wx.TextDataObject(self.numbers.GetItemText(event.Index))
        source = wx.DropSource(self.numbers)
        source.SetData(data)
        source.DoDragDrop()

    def HandleDrop(self, text):
        self._text = text
        self.PopupMenu(self.menu)

    def On_SimpleCopy(self, event):
        self.field.Value = self._text

    def On_MessWithIt(self, event):
        self.field.Value = "<-%s->" % "".join([int(c)*c for c in self._text])

app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()

Methods like On_SimpleCopy and On_MessWithIt get executed after the drop so any lengthy operations you might want to do you can do there based on the textual or some other standard type of data you transfered with the drag (self._text in my case), and look... no OLE :)

OwnerDisplayName: Toni Ruža

LastEditorDisplayName: Toni Ruža


问:
Java or Python for math?
I'm trying to write a pretty heavy duty math-based project, which will parse through about 100MB+ data several times a day, so, I need a fast language that's pretty easy to use. I would have gone with C, but, getting a large project done in C is very difficult, especially with the low level programming getting in your way. So, I was about python or java. Both are well equiped with OO features, so I don't mind that. Now, here are my pros for choosing python:

Very easy to use language

Has a pretty large library of useful stuff

Has an easy to use plotting library

Here are the cons:

Not exactly blazing

There isn't a native python neural network library that is active

I can't close source my code without going through quite a bit of trouble

Deploying python code on clients computers is hard to deal with, especially when clients are idiots.

Here are the pros for choosing Java:

Huge library

Well supported

Easy to deploy

Pretty fast, possibly even comparable to C++

The Encog Neural Network Library is really active and pretty awesome

Networking support is really good

Strong typing

Here are the cons for Java:

I can't find a good graphing library like matplotlib for python

No built in support for big integers, that means another dependency (I mean REALLY big integers, not just math.BigInteger size)

File IO is kind of awkward compared to Python

Not a ton of array manipulating or "make programming easy" type of features that python has.

So, I was hoping you guys can tell me what to use. I'm equally familiar with both languages. Also, suggestions for other languages is great too.

EDIT: WOW! you guys are fast! 30 mins at 10 responses!

答:
The Apache Commons Math picked up where JAMA left off.  They are quite capable for scientific computing.

So is Python - NumPy and SciPy are excellent.  I also like the fact that Python is a hybrid of object-orientation and functional programming.  Functional programming is awfully handy for numerical methods.

I'd recommend using the one that you know best, but if the choice is a toss up I might lean towards Python.

Title: Java or Python for math?


问:
Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

```<code>String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
</code>```

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

答:
Use BigInteger to avoid numeric limits of primitive int and long:

```<code>BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16);                             // Radix 16 indicates hex
System.out.println(x16);
</code>```

The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.

Demo.

Body:
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

Body:
Use BigInteger to avoid numeric limits of primitive int and long:

BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16);                             // Radix 16 indicates hex
System.out.println(x16);

The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.

Demo.


问:
CSS flex box - how to make items center vertically with a full height background
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

```<code><div class="feature-content">
<div class="feature-visual">
    <div class="embed-container">
        <iframe src="https://player.vimeo.com/video/214852366?controls=0&hd=1&autohide=1" title="Factory Pattern & REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
</div>
<div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
</div>
</code>```

CSS:

```<code>article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}
</code>```

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

答:
You can achieve that by changing your css to:

```<code>article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    display: flex;
    align-items: center;
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    width: 80%;
}
</code>```

I added display: flex and align-items: center to .quote in order to center it vertically and removed padding-top from .words to avoid vertical offset.

Note: align-items aligns vertically if flex-direction is row and justify-content aligns horizontally. it does the opposite when flex-direction is column.

Body:
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

Improved our conversion rates to a level that far surpassed expectation.

CSS:

article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

Body:
You can achieve that by changing your css to:

article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    display: flex;
    align-items: center;
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    width: 80%;
}

I added display: flex and align-items: center to .quote in order to center it vertically and removed padding-top from .words to avoid vertical offset.

Note: align-items aligns vertically if flex-direction is row and justify-content aligns horizontally. it does the opposite when flex-direction is column.


问:
Change the color of a div element using only css
I have the following buttons. buttons.

This post helped me out. However, every time I click on anything else, the color change of my button disappears. How can I keep the button colored orange, until I click on a different one?

Here is my css:

```<code>.circle-button{
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-block;
    background: var(--button-background, rgb(110, 109, 105));
    margin-left: 2px;
    margin-right: 2px;
    margin-top: 5px;
    margin-bottom: 5px
}

.circle-button:focus{
    outline: none;
    --button-background: rgb(231, 153, 8);
}
.circle-button:visited{
    --button-background: rgb(153, 13, 130);
</code>```

}

here is my html:

```<code><div class="circle-button" *ngFor="let record of imageRecords; let i = index" tabindex="{{i}}" ></div>
</code>```

答:
Since you're using angular, use class for active div:

CSS:

```<code>.circle-button{
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-block;
    background: var(--button-background, rgb(110, 109, 105));
    margin-left: 2px;
    margin-right: 2px;
    margin-top: 5px;
    margin-bottom: 5px
}

.circle-button.active {
    outline: none;
    --button-background: rgb(231, 153, 8);
}
</code>```

HTML:

```<code><div class="circle-button" *ngFor="let record of imageRecords; let i = index" tabindex="{{i}}" [class.active]="currentTab == i" (click)="currentTab = i"></div>
</code>```

Body:
I have the following buttons. buttons.

This post helped me out. However, every time I click on anything else, the color change of my button disappears. How can I keep the button colored orange, until I click on a different one?

Here is my css:

.circle-button{
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-block;
    background: var(--button-background, rgb(110, 109, 105));
    margin-left: 2px;
    margin-right: 2px;
    margin-top: 5px;
    margin-bottom: 5px
}

.circle-button:focus{
    outline: none;
    --button-background: rgb(231, 153, 8);
}
.circle-button:visited{
    --button-background: rgb(153, 13, 130);

}

here is my html:

Body:
Since you're using angular, use class for active div:

CSS:

.circle-button{
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-block;
    background: var(--button-background, rgb(110, 109, 105));
    margin-left: 2px;
    margin-right: 2px;
    margin-top: 5px;
    margin-bottom: 5px
}

.circle-button.active {
    outline: none;
    --button-background: rgb(231, 153, 8);
}

HTML:

<div class="circle-button" *ngFor="let record of imageRecords; let i = index" tabindex="{{i}}" [class.active]="currentTab == i" (click)="currentTab = i"></div>


问:
Does using non-array placement new for neighboring elements create an array?
I'd like to can create a template function, which can initialize (with placement new) an array, where for each element, a lambda is called to initialize it.

```<code>template <typename OBJECT, typename LAMBDA>
void initialize(void *storage, int size, LAMBDA lambda) {
    for (int i=0; i<size; i++) {
        lambda(static_cast<char*>(storage)+i*sizeof(OBJECT), i);
    }
}
</code>```

Where an actual lambda could be this (for example, an integer array, where each element get initialized to its index):

```<code>[](void *storage, int index){ new(storage) int(index); }
</code>```

And this works. However, as I see, it doesn't create an actual array, because I didn't used a placement-new-array, but separate placement-new calls for each element, even though the memory layout should be the same. Am I right? Can I refer to this memory as an array? If not, can this functionality be achieved somehow?

(Basically, this functionality is the same, if std::vector had a array-generator push_array_back function, which has a size and lambda parameters. And it would push_back an elements of size, initialized to the value lambda gives)

答:
Am I right? Can I refer to this memory as an array? If not, can this functionality be achieved somehow?

This is basically the same underlying problem that std::vector has with data() and pointed out in CWG 2182. It's undefined behavior to refer to this memory as an array, but practically speaking it needs to work because so much code relies on it working. There's no way to achieve it.

Side-node, don't call your callables lambda. They don't have to be lambdas. And also let the language help you with pointer offsetting:

```<code>auto p = static_cast<Object*>(storage);
for (int i = 0; i < size; ++i) {
    construct(static_cast<void*>(p + i), i);
}
</code>```

Body:
I'd like to can create a template function, which can initialize (with placement new) an array, where for each element, a lambda is called to initialize it.

template <typename OBJECT, typename LAMBDA>
void initialize(void *storage, int size, LAMBDA lambda) {
    for (int i=0; i<size; i++) {
        lambda(static_cast<char*>(storage)+i*sizeof(OBJECT), i);
    }
}

Where an actual lambda could be this (for example, an integer array, where each element get initialized to its index):

[](void *storage, int index){ new(storage) int(index); }

And this works. However, as I see, it doesn't create an actual array, because I didn't used a placement-new-array, but separate placement-new calls for each element, even though the memory layout should be the same. Am I right? Can I refer to this memory as an array? If not, can this functionality be achieved somehow?

(Basically, this functionality is the same, if std::vector had a array-generator push_array_back function, which has a size and lambda parameters. And it would push_back an elements of size, initialized to the value lambda gives)

Body:
Am I right? Can I refer to this memory as an array? If not, can this functionality be achieved somehow?

This is basically the same underlying problem that std::vector has with data() and pointed out in CWG 2182. It's undefined behavior to refer to this memory as an array, but practically speaking it needs to work because so much code relies on it working. There's no way to achieve it.

Side-node, don't call your callables lambda. They don't have to be lambdas. And also let the language help you with pointer offsetting:

auto p = static_cast<Object*>(storage);
for (int i = 0; i < size; ++i) {
    construct(static_cast<void*>(p + i), i);
}


问:
Pandas merge two datasets with same number of rows
I have two tables with same number of rows (second table is computed from first one by processing of text inside T1). I have both of them stored as pandas dataframe. T2 is no common column with T1. This is example because my tables are huge:

```<code>T1:
| name  | street  | city   |
|-------|---------|--------|
| David | street1 | Prague |
| John  | street2 | Berlin |
| Joe   | street3 | London |

T2:
| computed1 | computed2 |
|-----------|-----------|
| 0.5       | 0.3       |
| 0.2       | 0.8       |
| 0.1       | 0.6       |

Merged:
| name  | street  | city   | computed1 | computed2 |
|-------|---------|--------|-----------|-----------|
| David | street1 | Prague | 0.5       | 0.3       |
| John  | street2 | Berlin | 0.2       | 0.8       |
| Joe   | street3 | London | 0.1       | 0.6       |
</code>```

I tried these commands:

```<code>pd.concat([T1,T2])
pd.merge([T1,T2])
result=T1.join(T1)
</code>```

With concat and merge I will get only first thousand combined and rest is filled with nan (I double checked that both are same size), and with .join it not combine them because there is nothing in common.

Is there any way how to combine these two tables in pandas?

Thanks

答:
You need reset_index() before concat for default indices:

```<code>df = pd.concat([T1.reset_index(drop=True),T2.reset_index(drop=True)], axis=1)
</code>```

Body:
I have two tables with same number of rows (second table is computed from first one by processing of text inside T1). I have both of them stored as pandas dataframe. T2 is no common column with T1. This is example because my tables are huge:

T1:
| name  | street  | city   |
|-------|---------|--------|
| David | street1 | Prague |
| John  | street2 | Berlin |
| Joe   | street3 | London |

T2:
| computed1 | computed2 |
|-----------|-----------|
| 0.5       | 0.3       |
| 0.2       | 0.8       |
| 0.1       | 0.6       |

Merged:
| name  | street  | city   | computed1 | computed2 |
|-------|---------|--------|-----------|-----------|
| David | street1 | Prague | 0.5       | 0.3       |
| John  | street2 | Berlin | 0.2       | 0.8       |
| Joe   | street3 | London | 0.1       | 0.6       |

I tried these commands:

pd.concat([T1,T2])
pd.merge([T1,T2])
result=T1.join(T1)

With concat and merge I will get only first thousand combined and rest is filled with nan (I double checked that both are same size), and with .join it not combine them because there is nothing in common.

Is there any way how to combine these two tables in pandas?

Thanks

Body:
You need reset_index() before concat for default indices:

df = pd.concat([T1.reset_index(drop=True),T2.reset_index(drop=True)], axis=1)


问:
What are strategies to write large and manageable proofs in Coq?
I have gone through the Software Foundations series and have good understanding of Coq basics. But, proofs of anything non-trivial become too long and tedious.

What are strategies to write manageable large Coq proofs for someone familiar with basics?

答: Certified Programming with Dependent Types (CPDT for short) is a good introduction often recommended along with or in place of Software Foundations.  It places a strong focus on short and automated proofs, and is a good introduction to learning tactic automation.


问:
Detect if a Flash video is playing or not
I have a NetConnection attached to a NetStream, which is in turn attached to a Video. As you can guess, this is a video player. I've looked through the public properties of all three classes and could not find an "isPlaying" property - a boolean that would tell me video is currently running (and not paused, stopped, nor corrupted). Does such a property exist? I've tried the following but they don't work:

return this.video.currentFPS > 0. The FPS is around 25 even when the
video is paused.

Listen on
NetStatusEvent change and update my own private isPlaying property accordingly. The
NetStatus does not change when you pause the video.

答: use a Timer to check your stream.time and compare it to the previous value. writing a custom togglePause() function and storing the state in some private variable'd also be useful


问:
How to get auto response for any envelop completed document sign?
I am using DocuSign api for my client website portal as customer documents digital process. Everything works great except one feature needed.

I am creating dynamic document (with php) and sending to customer via DocuSign api to sign (using DocuSign digital signature setup).

And i have added 'check status' button in my website to check that specific document/envelope (by forwarding envelope unique id to DocuSign api get envelope status) and updating in my database and also downloading that signed document from docUsign.

Now i need the above process to be done automatically which means when the customer signs, a callback should trigger to my website url (like some webhook i need setup) and then i will check that envelop status and update my database.

Can any one give some suggestions or code snippet where i can keep that webhook url option to get auto response from DocuSign (just like paypal IPN)

Thanks in Advance

答:
You can use DocuSign Connect to do exactly what you've described. Using DocuSign Connect, you can configure DocuSign to automatically push Envelope status and documents to an endpoint you specify when the Envelope event(s) you specify occur (for example, Recipient completes/submits an Envelope, or Envelope reaches status = completed, etc.).

DocuSign has published several code samples that show how to use DocuSign Connect. For example:

PHP and Python webhook sample

C# webhook sample

Node webhook sample

Java webhook sample

These samples (and others) can be found in the DocuSign GitHub org.


问:
Use props inside event handler
I'm trying to use props inside an event handler. This is a part of my code

```<code>class Dashboard extends Component {
  componentDidMount() {
    var grid = new Muuri('.grid', {
      //options...
    });
    grid.on('move', (data) => {
      console.log('ok')
      //can't use this.props here
    );
  }
  render() {...}
  constructor() {...}
}
</code>```

The problem is I am not able to access this.props inside the 'move' handler.

答:
You can store the reference for this.props and refer it inside the event handler.

Or
Access the required individual properties using destructors and then access those properties inside event handler.

```<code>class Dashboard extends Component {
    componentDidMount() {

        const {prop1name, prop2Name} = this.props;

        //OR

        const thisProps = this.props;

        var grid = new Muuri('.grid', {
            //options...
        });
        grid.on('move', (data) => {
            console.log('ok')
            //access `this.props` using `thisProps` or access individual properties.
            )}
        render() {}
        constructor() {}
    }
</code>```

Title: Use props inside event handler

Body:
I'm trying to use props inside an event handler. This is a part of my code

class Dashboard extends Component {
  componentDidMount() {
    var grid = new Muuri('.grid', {
      //options...
    });
    grid.on('move', (data) => {
      console.log('ok')
      //can't use this.props here
    );
  }
  render() {...}
  constructor() {...}
}

The problem is I am not able to access this.props inside the 'move' handler.

Body:
You can store the reference for this.props and refer it inside the event handler.

Or
Access the required individual properties using destructors and then access those properties inside event handler.

class Dashboard extends Component {
    componentDidMount() {

        const {prop1name, prop2Name} = this.props;

        //OR

        const thisProps = this.props;

        var grid = new Muuri('.grid', {
            //options...
        });
        grid.on('move', (data) => {
            console.log('ok')
            //access `this.props` using `thisProps` or access individual properties.
            )}
        render() {}
        constructor() {}
    }


问:
Selenium Python - Webscraping Xpath Error
I am trying to Web-scrape the country names from the following page - http://hdr.undp.org/en/composite/trends

I am trying to get the Xpath of the particular element.

So for the first country, it appears like this -

```<code>Country = driver.find_element_by_xpath("//[@id='styleSheet.css']/div/div/div/div/table/tbody/tr[2]/td[2]").text
</code>```

So basically for all the countries, I am using the For loop and range function in python.

```<code>for i in range(2,193):
    try:
        print(i)
        Country = driver.find_element_by_xpath("//[@id='styleSheet.css']/div/div/div/div/table/tbody/tr["+int(i)+"]/td[11]").text
        print(Country)
    except Exception:
        print("none")
</code>```

But the problem is the X-path doesn't work for me. Kindly help me in locating the right element.

I resolved the first problem by changing the int to str as that was the error throwing up.After that it says cannot locate the current element.

答:
You don't have to use XPaths for every single selenium element location problem. There are better ways to locate the countries in this case. What if you would go through every tr element inside the tbody of the table and get the second td element containing a country name:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://hdr.undp.org/en/composite/trends")

table = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".pane-content table")))
for row in table.find_elements_by_css_selector("tbody > tr")[1:]:  # skipping the first header row
    country = row.find_element_by_css_selector("td:nth-child(2)")

    print(country.text)

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

Prints:

```<code>Norway
Australia
Switzerland
...
San Marino
Somalia
Tuvalu
</code>```

Body:
I am trying to Web-scrape the country names from the following page - http://hdr.undp.org/en/composite/trends

I am trying to get the Xpath of the particular element.

So for the first country, it appears like this -

Country = driver.find_element_by_xpath("//[@id='styleSheet.css']/div/div/div/div/table/tbody/tr[2]/td[2]").text

So basically for all the countries, I am using the For loop and range function in python.

for i in range(2,193):
    try:
        print(i)
        Country = driver.find_element_by_xpath("//[@id='styleSheet.css']/div/div/div/div/table/tbody/tr["+int(i)+"]/td[11]").text
        print(Country)
    except Exception:
        print("none")

But the problem is the X-path doesn't work for me. Kindly help me in locating the right element.

I resolved the first problem by changing the int to str as that was the error throwing up.After that it says cannot locate the current element.

Body:
You don't have to use XPaths for every single selenium element location problem. There are better ways to locate the countries in this case. What if you would go through every tr element inside the tbody of the table and get the second td element containing a country name:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://hdr.undp.org/en/composite/trends")

table = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".pane-content table")))
for row in table.find_elements_by_css_selector("tbody > tr")[1:]:  # skipping the first header row
    country = row.find_element_by_css_selector("td:nth-child(2)")

    print(country.text)

driver.close()

Prints:

Norway
Australia
Switzerland
...
San Marino
Somalia
Tuvalu


问:
How can I create a map from object properties?
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

```<code>wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}
</code>```

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?

答:
You could do something like this:</p>

```<code>class Widget {
    int width
    int height

    static void main(args) {
        def obj = new Widget(width: 7, height: 9)

        List<MetaProperty> metaProperties = obj.metaClass.properties

        def props = [:]
        for(MetaProperty mp : metaProperties) {
            props[mp.name] = mp.getProperty(obj)
        }

        // props will look like [width:7, class:class demo.Widget, height:9]
    }
}
</code>```

Body:
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?

Body:
You could do something like this:

class Widget {
    int width
    int height

    static void main(args) {
        def obj = new Widget(width: 7, height: 9)

        List<MetaProperty> metaProperties = obj.metaClass.properties

        def props = [:]
        for(MetaProperty mp : metaProperties) {
            props[mp.name] = mp.getProperty(obj)
        }

        // props will look like [width:7, class:class demo.Widget, height:9]
    }
}


问:
How to specify which version of perl to use on CentOS
I am running CentOS 5.4 which only has version 5.8 of perl available by default, and I have a program which requires perl 5.10, so I compiled perl 5.10 on CentOS.  How do I specify which perl I want to run the program with because the perl command uses 5.8 by default.</p>

答:
I add my voice to recommending against messing with the system perl at all.

No one mentioned App::perlbrew yet. It allows you to have several versions of Perl and switch between them easily. This can be done manually of course but it's much easier to have this tool to do it for you; from the Pod–

```<code># Install some Perls
perlbrew install perl-5.12.2
perlbrew install perl-5.8.1
perlbrew install perl-5.13.6

# See what were installed
perlbrew list

# Switch perl in the $PATH
perlbrew switch perl-5.12.2
perl -v

# Switch to another version
perlbrew switch perl-5.8.1
perl -v

# Switch to a certain perl executable not managed by perlbrew.
perlbrew switch /usr/bin/perl

# Or turn it off completely. Useful when you messed up too deep.
perlbrew off

# Use 'switch' command to turn it back on.
perlbrew switch perl-5.12.2
</code>```

Body:
I add my voice to recommending against messing with the system perl at all.

No one mentioned App::perlbrew yet. It allows you to have several versions of Perl and switch between them easily. This can be done manually of course but it's much easier to have this tool to do it for you; from the Pod–

# Install some Perls
perlbrew install perl-5.12.2
perlbrew install perl-5.8.1
perlbrew install perl-5.13.6

# See what were installed
perlbrew list

# Switch perl in the $PATH
perlbrew switch perl-5.12.2
perl -v

# Switch to another version
perlbrew switch perl-5.8.1
perl -v

# Switch to a certain perl executable not managed by perlbrew.
perlbrew switch /usr/bin/perl

# Or turn it off completely. Useful when you messed up too deep.
perlbrew off

# Use 'switch' command to turn it back on.
perlbrew switch perl-5.12.2


问:
How to do some custom bash scripting command?
I'd like to use some commands on my Orange pi zero within reach, for example: I want to execute one command on ubuntu, and I want to have every commands on 1 file.

my_file (without ending in .sh)

```<code>#!/bin/bash
alias myip='curl ipinfo.io/ip'
alias tururu='echo it works'
</code>```

Have this file, and chmod -x was executed on this file, but when I do on terminal "sh my_file myip", doesn't do anything, but didn't give me an error, so what I'm doing wrong?

Thank you very much

答:
sh myfile myip is one command; it doesn't run sh myfile, then myip. Your script should just look like

```<code>#!/bin/sh
curl ipinfo.io/ip
echo it works
</code>```

then run as sh myfile (or myfile, assuming it is executable and located in a directory on your path).

If, instead, you want to execute myfile so that you can subsequently use myip and tururu as commands, you need to source the file:

```<code>$ source myfile
$ myip
192.0.2.24
$ tururu
it works
</code>```

Body:
I'd like to use some commands on my Orange pi zero within reach, for example: I want to execute one command on ubuntu, and I want to have every commands on 1 file.

my_file (without ending in .sh)

#!/bin/bash
alias myip='curl ipinfo.io/ip'
alias tururu='echo it works'

Have this file, and chmod -x was executed on this file, but when I do on terminal "sh my_file myip", doesn't do anything, but didn't give me an error, so what I'm doing wrong?

Thank you very much

Body:
sh myfile myip is one command; it doesn't run sh myfile, then myip. Your script should just look like

#!/bin/sh
curl ipinfo.io/ip
echo it works

then run as sh myfile (or myfile, assuming it is executable and located in a directory on your path).

If, instead, you want to execute myfile so that you can subsequently use myip and tururu as commands, you need to source the file:

$ source myfile
$ myip
192.0.2.24
$ tururu
it works


问:
ggplot2: Parallel plot with varying yaxis depending on values of X
I have some data with continuous and categorical variables. This data consists of two groups, i.e. treatment and control group. I want to draw a parallel plot via ggplot2, in which categorical variables are represented as proportions of each category.

Furthermore, the range of the yaxis should vary, depending on the range of values of the reflected variables. In case of continuous variables, the yaxis should range from min(x) to max(x). In case of categorical variables, the yaxis should range from 0 to 1.

In the end, the plot should look similar to the following picture, taken from Iacus et al. (2011):

Here is what I got so far:

```<code>library("caret")
library("ggplot2")
library("reshape2")

# Example data
set.seed(123)

N_1 <- 250
N_2 <- 750

x1 <- round(c(rnorm(N_1), rnorm(N_2, 5)), 2)
x2 <- as.factor(c(rbinom(N_1, 1, 0.3), rbinom(N_2, 1, 0.4)))
x3 <- as.factor(c(round(runif(N_1, 0, 2)), round(runif(N_2, 0, 2))))

# Create dummies for categorical variables
df <- data.frame(x1, x2, x3)
dv <- dummyVars(x1 ~., df)
df <- data.frame(x1, predict(dv, newdata = df))

# Replace dummies with proportions
df$x2.0 <- c(rep(mean(df$x2.0[1:N_1]), N_1), rep(mean(df$x2.0[(N_1 + 1):N_2]), N_2))
df$x2.1 <- c(rep(mean(df$x2.1[1:N_1]), N_1), rep(mean(df$x2.1[(N_1 + 1):N_2]), N_2))

df$x3.0 <- c(rep(mean(df$x3.0[1:N_1]), N_1), rep(mean(df$x3.0[(N_1 + 1):N_2]), N_2))
df$x3.1 <- c(rep(mean(df$x3.1[1:N_1]), N_1), rep(mean(df$x3.1[(N_1 + 1):N_2]), N_2))
df$x3.2 <- c(rep(mean(df$x3.2[1:N_1]), N_1), rep(mean(df$x3.2[(N_1 + 1):N_2]), N_2))

# Reorder data for ggplot2
df <- melt(data.frame(id = 1:length(x1), df),
           id.vars = c(rep(0, N_1), rep(1, N_2)))

# Draw plot
ggplot(df, aes(x = variable, y = value, group = id)) +
  geom_path(aes(color = id), alpha = 0.5, lineend = 'round', linejoin = 'round')
</code>```

As you can see, I managed to create a graph with continuous and dummy variables (represented by proportions). However, it feels like my way is kind of inefficient and I did not manage to create varying yaxis for the different variables.

How could I create a plot with varying yaxis in an efficient way with ggplot2?

答:
You can use the dplyr package for the data manipulation. I also normalized the values, so it follows the same 0 to 1 y-axis.

```<code>require(dplyr)

# manipulate the data
pdf <- df %>%
  mutate(id = row_number()) %>%
  gather(key, value, -id) %>%
  group_by(key) %>%
  mutate(min = min(value),
         max = max(value),
         mean = if_else(key != 'x1', mean(value), value),
         norm = (mean-min)/(max-min))

# Draw plot
ggplot(pdf, aes(x = key, y = norm, group = id)) +
  geom_path(aes(color = id), alpha = 0.5, lineend = 'round', linejoin = 'round')
</code>```

Body:
I have some data with continuous and categorical variables. This data consists of two groups, i.e. treatment and control group. I want to draw a parallel plot via ggplot2, in which categorical variables are represented as proportions of each category.

Furthermore, the range of the yaxis should vary, depending on the range of values of the reflected variables. In case of continuous variables, the yaxis should range from min(x) to max(x). In case of categorical variables, the yaxis should range from 0 to 1.

In the end, the plot should look similar to the following picture, taken from Iacus et al. (2011):

Here is what I got so far:

library("caret")
library("ggplot2")
library("reshape2")

# Example data
set.seed(123)

N_1 <- 250
N_2 <- 750

x1 <- round(c(rnorm(N_1), rnorm(N_2, 5)), 2)
x2 <- as.factor(c(rbinom(N_1, 1, 0.3), rbinom(N_2, 1, 0.4)))
x3 <- as.factor(c(round(runif(N_1, 0, 2)), round(runif(N_2, 0, 2))))

# Create dummies for categorical variables
df <- data.frame(x1, x2, x3)
dv <- dummyVars(x1 ~., df)
df <- data.frame(x1, predict(dv, newdata = df))

# Replace dummies with proportions
df$x2.0 <- c(rep(mean(df$x2.0[1:N_1]), N_1), rep(mean(df$x2.0[(N_1 + 1):N_2]), N_2))
df$x2.1 <- c(rep(mean(df$x2.1[1:N_1]), N_1), rep(mean(df$x2.1[(N_1 + 1):N_2]), N_2))

df$x3.0 <- c(rep(mean(df$x3.0[1:N_1]), N_1), rep(mean(df$x3.0[(N_1 + 1):N_2]), N_2))
df$x3.1 <- c(rep(mean(df$x3.1[1:N_1]), N_1), rep(mean(df$x3.1[(N_1 + 1):N_2]), N_2))
df$x3.2 <- c(rep(mean(df$x3.2[1:N_1]), N_1), rep(mean(df$x3.2[(N_1 + 1):N_2]), N_2))

# Reorder data for ggplot2
df <- melt(data.frame(id = 1:length(x1), df),
           id.vars = c(rep(0, N_1), rep(1, N_2)))

# Draw plot
ggplot(df, aes(x = variable, y = value, group = id)) +
  geom_path(aes(color = id), alpha = 0.5, lineend = 'round', linejoin = 'round')

As you can see, I managed to create a graph with continuous and dummy variables (represented by proportions). However, it feels like my way is kind of inefficient and I did not manage to create varying yaxis for the different variables.

How could I create a plot with varying yaxis in an efficient way with ggplot2?

Body:
You can use the dplyr package for the data manipulation. I also normalized the values, so it follows the same 0 to 1 y-axis.

require(dplyr)

# manipulate the data
pdf <- df %>%
  mutate(id = row_number()) %>%
  gather(key, value, -id) %>%
  group_by(key) %>%
  mutate(min = min(value),
         max = max(value),
         mean = if_else(key != 'x1', mean(value), value),
         norm = (mean-min)/(max-min))

# Draw plot
ggplot(pdf, aes(x = key, y = norm, group = id)) +
  geom_path(aes(color = id), alpha = 0.5, lineend = 'round', linejoin = 'round')


问:
Linq: check if one of the property in a list is null for all the objects
```<code>public class P
{
 public string Name {get; set;}
 public string Value {get; set;}
 public Student Student {get; set;}
}

List<P> p = new List<P>();
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "2", Value = null, Student = new Student{Name = "2"}})
p.Add(new P{Name = "1", Value = "xxx", Student = new Student{Name = "2"}})
</code>```

I want to group by P.Name and get only the elements which have all the missing value for P.Value.

In this example I would like to get "1"

And if I need to group for P.Student.Name?

答:
You can use a GroupBy together with an All fro each group:

```<code>var r = p.GroupBy(x => x.Name)
    .Where(g => g.All(x => x.Value == null))
    .Select(g=> g.Key);
</code>```

Edit:
If you need to group by Student.Name you just specify that property in the GroupBy. You can specify any expression based on the item to be used for grouping.

```<code>var r = p.GroupBy(x => x.Student.Name)
    .Where(g => g.All(x => x.Value == null))
    .Select(g=> g.Key);
</code>```

Body:
public class P
{
 public string Name {get; set;}
 public string Value {get; set;}
 public Student Student {get; set;}
}

List
 p = new List
();
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "1", Value = null, Student = new Student{Name = "1"}})
p.Add(new P{Name = "2", Value = null, Student = new Student{Name = "2"}})
p.Add(new P{Name = "1", Value = "xxx", Student = new Student{Name = "2"}})

I want to group by P.Name and get only the elements which have all the missing value for P.Value.

In this example I would like to get "1"

And if I need to group for P.Student.Name?

Body:
You can use a GroupBy together with an All fro each group:

var r = p.GroupBy(x => x.Name)
    .Where(g => g.All(x => x.Value == null))
    .Select(g=> g.Key);

Edit:
If you need to group by Student.Name you just specify that property in the GroupBy. You can specify any expression based on the item to be used for grouping.

var r = p.GroupBy(x => x.Student.Name)
    .Where(g => g.All(x => x.Value == null))
    .Select(g=> g.Key);


问:
C string functions error
I'm working on an assignment, but I'm having trouble with my code :

```<code>int is_ascii_match(const char c1[], const char c2[], char res[MAX_STRING_SIZE]) {
....

    if (val_c1 == val_c2) {
        strcpy(res, strcat(strcat(c1, '&'),c2));
    }
    else
        return 0;
</code>```

I'm getting an error :

Access violation reading location

Do I pass the parameters wrong or..?

答:
'&' is a character literal, which is a small integer. The second argument of strcat is a const char*, which is a pointer to a character (more precisely, a pointer to the first character in a contiguous NUL-terminated array of chars).
You presumably intended "&", which is a two-byte array.

Attempting to interpret a small integer as a pointer leads to precisely the problem indicated by the error.

If it were not for the problem reading the second argument, you might be presented with an error when strcat attempts to modify the string pointed to by its first argument, which is const and thus conceivably in read-only memory. (Modifying the first argument seems semantically incorrect, as well.)

If you compile with warnings enabled, you should see a warning about the types of the argument.

For this particular problem, consider the use of snprintf(res, MAX_STRING_SIZE, "%s&%s", c1, c2), which avoids modifying c1 and protects against buffer overflow. (You should compare the return value with MAX_STRING_SIZE if you care about truncation.)

Title: C string functions error

Body:
I'm working on an assignment, but I'm having trouble with my code :

int is_ascii_match(const char c1[], const char c2[], char res[MAX_STRING_SIZE]) {
....

    if (val_c1 == val_c2) {
        strcpy(res, strcat(strcat(c1, '&'),c2));
    }
    else
        return 0;

I'm getting an error :

Access violation reading location

Do I pass the parameters wrong or..?


问:
Embed Google Earth Engine application into web page
Is there a simpler way to embed a Google Earth Engine (javascript) application into a web page without following the tortured route presented by the Google EE demo apps?

The Earth Engine Code environment makes it quick and fast to develop the core GEE app.  However, it's going to take me 10x the time to embed the GEE app into a web page than it took to do the GEE app.

All the demo apps seem to require (a) using Google App Engine, (b) recoding the GEE app in Python, (c) using jinja2 templating engine to link the python code to the web page, and (d) still some lingering javascript.

For example, in the Trendy Lights demo, the server-side scripter server.py App Engine kicks things off and it gets complicated quickly.  (Even the simpler demos go this route.)

When the user first loads the application in their browser, their
  request is routed to the get() function in the MainHandler class by
  the framework we're using, webapp2.

The get() function sends back the main web page (from index.html)
  along with information the browser needs to render an Earth Engine map
  and the IDs of the polygons to show on the map. This information is
  injected into the index.html template through a templating engine
  called Jinja2, which puts information from the Python context into the
  HTML for the user's browser to receive.

答: The reason it's complicated is due to authorization.  The Earth Engine calls have to be authorized against someone's Earth Engine account. That has to be either the end user (See: https://github.com/google/earthengine-api/tree/master/demos/client-auth, but that only works if the end user has an Earth Engine account), or the application's credentials.  If the application's credentials were just stuck in the javascript, then anyone can steal those credentials and use them to do anything they wanted.  So we recommend using the appengine server-auth route (https://github.com/google/earthengine-api/tree/master/demos/server-auth) to keep your credentials safe.</p>


问:
How to Programatically Start IIS 6.0 SMTP Virtual Server?
I would like to know how to programatically restart IIS 6.0 SMTP server.

The SMTP server I have setup crashes every now and then.  I don't notice it for a couple days, but that is by far way too late to do anything about it.

I want to set up a scheduled task every 30 minutes or so to test if the SMTP server is running, and if its not, the Scheduled task with automatically start it back up.

I have found a way to check if the SMTP server is up and running, but I have not figured out how to restart the process if it crashes.

That way is posted here: Testing SMTP server is running via C#

Any help would be brilliant!

Thank you.

Im developing the Console application in C# to check if its running or not, so any code examples would be great too.

答:
in c# you can write:</p>

```<code>            enum StatusVirtualServerSMTP
            {
                 Started = 2,
                 Stopped = 4
            }

            DirectoryEntry dir = new DirectoryEntry("IIS://localhost/SMTPSVC/1");

            if (Convert.ToInt32(dir.Properties["SERVERSTATE"].Value) == (int)StatusVirtualServerSMTP.Stopped)
            {
                dir.Properties["SERVERSTATE"].Value = (int)StatusVirtualServerSMTP.Started;
                dir.CommitChanges();
            }
</code>```

Body:
in c# you can write:

            enum StatusVirtualServerSMTP
            {
                 Started = 2,
                 Stopped = 4
            }

            DirectoryEntry dir = new DirectoryEntry("IIS://localhost/SMTPSVC/1");

            if (Convert.ToInt32(dir.Properties["SERVERSTATE"].Value) == (int)StatusVirtualServerSMTP.Stopped)
            {
                dir.Properties["SERVERSTATE"].Value = (int)StatusVirtualServerSMTP.Started;
                dir.CommitChanges();
            }


问:
CSS flex box - how to make items center vertically with a full height background
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

```<code><div class="feature-content">
<div class="feature-visual">
    <div class="embed-container">
        <iframe src="https://player.vimeo.com/video/214852366?controls=0&hd=1&autohide=1" title="Factory Pattern & REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
</div>
<div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
</div>
</code>```

CSS:

```<code>article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}
</code>```

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

答:
You could use flexbox, or you could use a simple transform:</p>

```<code>article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;

    // Add these 3 props:
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
</code>```

Body:
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

Improved our conversion rates to a level that far surpassed expectation.

CSS:

article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

Body:
You could use flexbox, or you could use a simple transform:

article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;

    // Add these 3 props:
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}


问:
CSS Print - Strange artifacts only appear in Chrome
I am currently developing a JS/HTML application and there is a HTML page that I require to print. The layout of the page looks like

```<code>    <div class="customerOffer">
        <div class="buttonHeader"><span class="backButton">Back</span><span class="printButton">Print</span></div>
        <div class="panel">
            <div class="panelTitle"><span class="text">Title</span></div>
            <div class="panelBox">
                <div class="column">
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                </div>
                <div class="column right">
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                    <div class="row"><span class="label b">Text</span><span class="inputValueF">£0.00</span></div>
                </div>
            </div>
        </div>
        <div class="panel">
            <div class="panelTitle"><span class="text">Title</span></div>
            <div class="panelBox">
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="separator"></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row important"><span class="label b">Text</span><span class="inputValueF b">£0.00</span></div>
            </div>
        </div>
        <div class="panel">
            <div class="panelTitle"><span class="text">Title</span></div>
            <div class="panelBox">
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="separator"></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row coloured"><span class="label">Text</span><span class="inputValueF">£0.00</span></div>
                <div class="row important"><span class="label b">Text</span><span class="inputValueF b">£0.00</span></div>
            </div>
        </div>
    </div>
</code>```

As you can see the page is made up of a number of "Panels" which have a title bar and some information inside of them. To keep the page from 'breaking' inside one of these panels when printing I added page-break-inside: avoid; to these panels in the @media print tag for this page. Here is the LESS for this HTML page

```<code>@import url(https://fonts.googleapis.com/css?family=Roboto);

@accent: #5280B8;
@secondary: #1e518d;
@background-blue: #4e96e7;
@panel: #FFFFFF;
//@rowOdd: #EFF2F6;
@rowOdd: lighten(@accent, 38%);
@rowEven: #FFFFFF;
@input-background: #e4e4e4;
@button-grey: #c6c7c8;

.button-template{
    height: 30px;
    border: 2px solid #fff;
    border-radius: 5px;
    font-family: Roboto;
    padding: 1px 8px;
    cursor: pointer;
    background-color: @accent;
    color: #fff;
    line-height: 25px;

    &:hover{
        background-color: darken(@accent, 10%);
    }
    &:active{
        background-color: darken(@accent, 20%);
    }
    &:focus{
        outline: none;
    }
}

* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

body {
    font-family: 'Roboto', sans-serif;
    font-weight: 400;
    margin: 0;
    overflow: hidden;
    width: 100%;
    height: 100%;
}

.wrapper{
    position: absolute;
    left: 50%;
    width: 1024px;
    height: 768px;
    transform: translate(-50%, 0);
    overflow: hidden;
    background-image: url(http://media.ca-a.com/MEDIA/OEM/NISSAN/GB/BG/NissanBG.png);

    &:before{
        width: 100%;
        height: 100%;
        content: ' ';
        position: absolute;
        background-color: @background-blue;
        top: 0;
        left: 0;
        z-index: -1;
        opacity: 0.66;
    }

    .customerOffer{
        width: 100%;
        background-color: gray;
        position: absolute;
        left: 200%;
        top: 0px;
        z-index: 1;

        &:before{
            width: 100%;
            height: 100%;
            content: ' ';
            position: absolute;
            background-color: @background-blue;
            top: 0;
            left: 0;
            z-index: -1;
            opacity: 0.66;
        }

        .buttonHeader{
            margin-top: 10px;
            margin-bottom: 10px;
            position: relative;

            .backButton{
                .button-template;
                left: 20px;
                position: relative;
            }
            .printButton{
                .button-template;
                margin-right: 10px;
                left: calc(~"89% - 20px");
                position: relative;
            }
        }

        .panel{
            width: calc(~"100% - 40px");
            overflow: hidden;
            border-radius: 10px;
            position: relative;
            margin-left: 20px;
            margin-right: 20px;
            margin-bottom: 20px;

            .panelTitle{
                width: 100%;
                height: 38px;
                background-color: @accent;

                .text{
                    line-height: 38px;
                    font-size: 18px;
                    font-weight: 500;
                    color: #fff;
                    position: relative;
                    left: 30px;
                }
            }

            .panelBox{
                height: auto;
                width: 100%;
                text-align: justify;
                background-color: @panel;
                border-radius: 0px 0px 10px 10px;

                .column{
                    padding-right: 0px;
                    height: 100%;
                    padding-left: 0px;
                    width: 50%;
                    vertical-align: top;
                    display: inline-block;
                    margin-top: 5px;

                    &.right{
                        float: right;
                    }
                }

                .row{
                    margin-bottom: 8px;

                    &:last-child{
                        border-radius: 0px 0px 8px 8px;
                    }

                    &.coloured{
                        margin-bottom: 0px;
                        padding: 4px 0px 4px 0px;

                        &:nth-child(odd){
                            background-color: @rowOdd;
                        }
                        &:nth-child(even){
                            background-color: @rowEven;
                        }

                        .label{
                            width: auto;
                        }

                        .inputValueF{
                            float: right;
                            margin-right: 10px;

                            &.b{
                                font-weight: bold;
                            }
                        }
                    }

                    &.important{
                        margin-bottom: 0px;
                        padding: 4px 0px 4px 0px;
                        background-color: @secondary;

                        .label{
                            color: @panel;
                            width: auto;
                        }

                        .inputValueF{
                            color: @panel;
                            float: right;
                            margin-right: 10px;

                            &.b{
                                font-weight: bold;
                            }
                        }
                    }

                    .label{
                        vertical-align: top;
                        display: inline-block;
                        width: 100px;
                        margin-left: 20px;

                        &.b{
                            font-weight: bold;
                        }
                    }

                    .inputValueF{
                        display: inline-block;
                    }
                }

                .separator{
                    height: 2px;
                    background-color: #212121;
                    width: 98%;
                    margin-left: 1%;
                }
            }
        }
    }
}

@media print{

    div{
        page-break-inside: avoid;
    }

    .wrapper{
        overflow: visible;
        width: 210mm;
        height: 100%;
        background-color: transparent;
        background-image: none;
        //-webkit-print-color-adjust: exact;

        &:before{
            display: none;
        }

        .customerOffer{
            background-color: transparent;
            background-image: none;
            position: initial;
            overflow: visible;

            &:before{
                display: none;
            }

            .buttonHeader{
                display: none;
            }

            .panelTitle{
                //box-shadow: inset 0 0 0 1000px @accent;
                border: 2px solid @accent
            }

            .panelBox{
                border: 2px solid @accent;

                .row{
                    &.coloured{

                        &:nth-child(odd){
                            box-shadow: inset 0 0 0 1000px @rowOdd;
                        }
                        &:nth-child(even){
                            box-shadow: inset 0 0 0 1000px @rowEven;
                        }
                    }

                    &.important{
                        box-shadow: inset 0 0 0 1000px @secondary;

                        .label{
                            color: @panel;
                        }

                        .inputValueF{
                            color: @panel;
                        }
                    }

                }
            }
        }
    }
}
</code>```

When I print this page in Firefox I get the output I expected.

But when I print it in Chrome, you can see a phantom panelTitle element at the very bottom of the first page. I can only reproduce this with the page-break-inside: avoid; CSS, as otherwise the print will break inside one of the Panels.

Does anyone have any ideas how to remove this phantom element?

答:
Turns out that the issue appears when using the margin property with an @page directive.

At the bottom of my CSS I had

```<code>@page{
    size: auto;   /* auto is the initial value */

    /* this affects the margin in the printer settings */
    margin: 5mm 0mm 5mm 0mm;
}
</code>```

If I reduced the margin to 5mm 0mm 0mm 0mm then the issue will disappear but this obviously produces other issues. Luckily it seems that the printers I have tested this with will not print (by default atleast) 5mm from the edge of the page so it does not appear when physically printing the document.

Body:
I am currently developing a JS/HTML application and there is a HTML page that I require to print. The layout of the page looks like

BackPrint

Title

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Title

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Title

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

Text£0.00

As you can see the page is made up of a number of "Panels" which have a title bar and some information inside of them. To keep the page from 'breaking' inside one of these panels when printing I added page-break-inside: avoid; to these panels in the @media print tag for this page. Here is the LESS for this HTML page

@import url(https://fonts.googleapis.com/css?family=Roboto);

@accent: #5280B8;
@secondary: #1e518d;
@background-blue: #4e96e7;
@panel: #FFFFFF;
//@rowOdd: #EFF2F6;
@rowOdd: lighten(@accent, 38%);
@rowEven: #FFFFFF;
@input-background: #e4e4e4;
@button-grey: #c6c7c8;

.button-template{
    height: 30px;
    border: 2px solid #fff;
    border-radius: 5px;
    font-family: Roboto;
    padding: 1px 8px;
    cursor: pointer;
    background-color: @accent;
    color: #fff;
    line-height: 25px;

    &:hover{
        background-color: darken(@accent, 10%);
    }
    &:active{
        background-color: darken(@accent, 20%);
    }
    &:focus{
        outline: none;
    }
}

* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

body {
    font-family: 'Roboto', sans-serif;
    font-weight: 400;
    margin: 0;
    overflow: hidden;
    width: 100%;
    height: 100%;
}

.wrapper{
    position: absolute;
    left: 50%;
    width: 1024px;
    height: 768px;
    transform: translate(-50%, 0);
    overflow: hidden;
    background-image: url(http://media.ca-a.com/MEDIA/OEM/NISSAN/GB/BG/NissanBG.png);

    &:before{
        width: 100%;
        height: 100%;
        content: ' ';
        position: absolute;
        background-color: @background-blue;
        top: 0;
        left: 0;
        z-index: -1;
        opacity: 0.66;
    }

    .customerOffer{
        width: 100%;
        background-color: gray;
        position: absolute;
        left: 200%;
        top: 0px;
        z-index: 1;

        &:before{
            width: 100%;
            height: 100%;
            content: ' ';
            position: absolute;
            background-color: @background-blue;
            top: 0;
            left: 0;
            z-index: -1;
            opacity: 0.66;
        }

        .buttonHeader{
            margin-top: 10px;
            margin-bottom: 10px;
            position: relative;

            .backButton{
                .button-template;
                left: 20px;
                position: relative;
            }
            .printButton{
                .button-template;
                margin-right: 10px;
                left: calc(~"89% - 20px");
                position: relative;
            }
        }

        .panel{
            width: calc(~"100% - 40px");
            overflow: hidden;
            border-radius: 10px;
            position: relative;
            margin-left: 20px;
            margin-right: 20px;
            margin-bottom: 20px;

            .panelTitle{
                width: 100%;
                height: 38px;
                background-color: @accent;

                .text{
                    line-height: 38px;
                    font-size: 18px;
                    font-weight: 500;
                    color: #fff;
                    position: relative;
                    left: 30px;
                }
            }

            .panelBox{
                height: auto;
                width: 100%;
                text-align: justify;
                background-color: @panel;
                border-radius: 0px 0px 10px 10px;

                .column{
                    padding-right: 0px;
                    height: 100%;
                    padding-left: 0px;
                    width: 50%;
                    vertical-align: top;
                    display: inline-block;
                    margin-top: 5px;

                    &.right{
                        float: right;
                    }
                }

                .row{
                    margin-bottom: 8px;

                    &:last-child{
                        border-radius: 0px 0px 8px 8px;
                    }

                    &.coloured{
                        margin-bottom: 0px;
                        padding: 4px 0px 4px 0px;

                        &:nth-child(odd){
                            background-color: @rowOdd;
                        }
                        &:nth-child(even){
                            background-color: @rowEven;
                        }

                        .label{
                            width: auto;
                        }

                        .inputValueF{
                            float: right;
                            margin-right: 10px;

                            &.b{
                                font-weight: bold;
                            }
                        }
                    }

                    &.important{
                        margin-bottom: 0px;
                        padding: 4px 0px 4px 0px;
                        background-color: @secondary;

                        .label{
                            color: @panel;
                            width: auto;
                        }

                        .inputValueF{
                            color: @panel;
                            float: right;
                            margin-right: 10px;

                            &.b{
                                font-weight: bold;
                            }
                        }
                    }

                    .label{
                        vertical-align: top;
                        display: inline-block;
                        width: 100px;
                        margin-left: 20px;

                        &.b{
                            font-weight: bold;
                        }
                    }

                    .inputValueF{
                        display: inline-block;
                    }
                }

                .separator{
                    height: 2px;
                    background-color: #212121;
                    width: 98%;
                    margin-left: 1%;
                }
            }
        }
    }
}

@media print{

    div{
        page-break-inside: avoid;
    }

    .wrapper{
        overflow: visible;
        width: 210mm;
        height: 100%;
        background-color: transparent;
        background-image: none;
        //-webkit-print-color-adjust: exact;

        &:before{
            display: none;
        }

        .customerOffer{
            background-color: transparent;
            background-image: none;
            position: initial;
            overflow: visible;

            &:before{
                display: none;
            }

            .buttonHeader{
                display: none;
            }

            .panelTitle{
                //box-shadow: inset 0 0 0 1000px @accent;
                border: 2px solid @accent
            }

            .panelBox{
                border: 2px solid @accent;

                .row{
                    &.coloured{

                        &:nth-child(odd){
                            box-shadow: inset 0 0 0 1000px @rowOdd;
                        }
                        &:nth-child(even){
                            box-shadow: inset 0 0 0 1000px @rowEven;
                        }
                    }

                    &.important{
                        box-shadow: inset 0 0 0 1000px @secondary;

                        .label{
                            color: @panel;
                        }

                        .inputValueF{
                            color: @panel;
                        }
                    }

                }
            }
        }
    }
}

When I print this page in Firefox I get the output I expected.

But when I print it in Chrome, you can see a phantom panelTitle element at the very bottom of the first page. I can only reproduce this with the page-break-inside: avoid; CSS, as otherwise the print will break inside one of the Panels.

Does anyone have any ideas how to remove this phantom element?

Body:
Turns out that the issue appears when using the margin property with an @page directive.

At the bottom of my CSS I had

@page{
    size: auto;   /* auto is the initial value */

    /* this affects the margin in the printer settings */
    margin: 5mm 0mm 5mm 0mm;
}

If I reduced the margin to 5mm 0mm 0mm 0mm then the issue will disappear but this obviously produces other issues. Luckily it seems that the printers I have tested this with will not print (by default atleast) 5mm from the edge of the page so it does not appear when physically printing the document.


问:
Django / Python dict values return each letter as item
I've got a problem which I just can't figure out. I've got a dictionary which I get from choices of a django form:

forms.py

```<code> class testForm(forms.Form):
     TEST_CHOICES = (
         ("1", "One"),
         ("2", "Two"),
         ("3", "Three"),
     )

     test_choice_field = forms.MultipleChoiceField(choices=TEST_CHOICES, widget=forms.CheckboxSelectMultiple)
</code>```

In my views.py I iterate through that dict of choices and try to return those choices in a string like this: "One / Two / Three"

```<code> def test_func(request):
     if request.method == 'POST':
         form = testForm(request.POST)
         if form.is_valid():
             test_choice_field = form.cleaned_data["test_choice_field"]
             empty_string = ""
             for numbers in test_choice_field:
                 empty_string += dict(form.fields['test_choice_field'].choices)[numbers]
             subject = "[{}] is the Number you are looking for.".format(empty_string)
</code>```

What I wish for is that my "subject" holds the string "One / Two is the Number you are looking for", depending on which checkbox the user has checked. So if he/she picks all three checkboxes he get: "One / Two / Three is the Number you are looking for" and if it's only one "Two is the Number you are looking for" etc

Now I simply just wanted to do a " / ".join(empty_string), but ended up getting this "O/n/e/T/w/o is the...."

What am I doing wrong? And please don't remove the " / ".join(), I know I could do something with format(), but I'm especially looking for a solution using .join() :)

Thanks for any help!

答:
Try making the following changes

```<code>l = []
for numbers in test_choice_field:
    l.append(dict(form.fields['test_choice_field'].choices)[numbers])
subject = "[{}] is the Number you are looking for.".format('/'.join(l))
</code>```

Problem with your solution was that you were trying to call join on a string.
join takes an iterable of strings and joins it using the connector character. If you pass a string to it, i considers it as an iterable and joins each character in the string with the connector character.

In your case, it need to be a list of strings.

Body:
I've got a problem which I just can't figure out. I've got a dictionary which I get from choices of a django form:

forms.py

 class testForm(forms.Form):
     TEST_CHOICES = (
         ("1", "One"),
         ("2", "Two"),
         ("3", "Three"),
     )

     test_choice_field = forms.MultipleChoiceField(choices=TEST_CHOICES, widget=forms.CheckboxSelectMultiple)

In my views.py I iterate through that dict of choices and try to return those choices in a string like this: "One / Two / Three"

 def test_func(request):
     if request.method == 'POST':
         form = testForm(request.POST)
         if form.is_valid():
             test_choice_field = form.cleaned_data["test_choice_field"]
             empty_string = ""
             for numbers in test_choice_field:
                 empty_string += dict(form.fields['test_choice_field'].choices)[numbers]
             subject = "[{}] is the Number you are looking for.".format(empty_string)

What I wish for is that my "subject" holds the string "One / Two is the Number you are looking for", depending on which checkbox the user has checked. So if he/she picks all three checkboxes he get: "One / Two / Three is the Number you are looking for" and if it's only one "Two is the Number you are looking for" etc

Now I simply just wanted to do a " / ".join(empty_string), but ended up getting this "O/n/e/T/w/o is the...."

What am I doing wrong? And please don't remove the " / ".join(), I know I could do something with format(), but I'm especially looking for a solution using .join() :)

Thanks for any help!

Body:
Try making the following changes

l = []
for numbers in test_choice_field:
    l.append(dict(form.fields['test_choice_field'].choices)[numbers])
subject = "[{}] is the Number you are looking for.".format('/'.join(l))

Problem with your solution was that you were trying to call join on a string.
join takes an iterable of strings and joins it using the connector character. If you pass a string to it, i considers it as an iterable and joins each character in the string with the connector character.

In your case, it need to be a list of strings.


问:
Where can I find the primefaces tag library documentation?
Where can I find primefaces tag library documentation such as this: http://primefaces.prime.com.tr/docs/tag/index.html ?

I already have the jar, the sources of the primefaces. The apidoc supplied is "primefaces 2.2.RC2 API", not the "Tag Library Documentation Generator - Generated Documentation"

Maybe I should try generating it from the source, or maybe from the JAR (although I think the javadocs are not in the bytecodes) ?

答:
Here is the statement to the same question from another user:

optimus.prime:

Javadocs are bundled with zip packages, but for latest 2.2.M1 it is not available. You can use 2.1's bundle to get javadocs though.

With upcoming 2.2.RC1, java and tag docs will be available via bundles distributions.

Look at http://forum.primefaces.org/viewtopic.php?f=3&t=4575


问:
Given a list of tuples representing ranges ,condense the ranges (Write a function)
I am learning Python 2.x and would like to address following issue.
Need a function to condense the ranges

Problem :Given a list of tuples representing ranges ,condense the ranges

```<code>Input : [(2,3),(4,5),(7,8),(8,10),(12,15)]
Output :[(2,5),(7,10),(12,15)]
</code>```

Any pointer or help would be great help

答:
You could proceed for example as in the example below. The idea is to process individual intervals (lb, ub) and for each lower bound lb, mark an increase by 1, while for each upper bound ub, mark a decrease by -1.
Assuming integer input, the code effectively considers intervals (lb-0.5,ub+0.5) so that for example (2, 3) and (4, 5) are merged. In order to avoid using floating point numbers as dictionary keys, the dictionary stat stores double the number...

When you then process these individual "break" points, the total accumulated value (cnt) tells you how many intervals cover current point. As long as this number is greater than zero, we are inside a merged segment. If it drops to zero, we can take the next breakpoint and repeat the procedure...

```<code>spec = {}
L = [(2,3),(4,12),(7,8),(8,10),(12,15)]
for lb, ub in L:
    lb, ub = min(lb, ub), max(lb, ub)
    for v in [2*lb - 1, 2*ub + 1]:
        if not v in spec: spec[v] = 0
    spec[2*lb - 1] += 1
    spec[2*ub + 1] -= 1

break_points = sorted(spec.keys())
N = len(break_points)

idx = -1
while idx < N-1:
    idx += 1

    lb, ub = break_points[idx], None
    cnt = spec[lb]

    while cnt > 0:
        idx += 1
        ub = break_points[idx]
        cnt += spec[ub]

    print((lb+1)/2, (ub-1)/2)
    #prints (2, 15)
</code>```

Body:
I am learning Python 2.x and would like to address following issue.
Need a function to condense the ranges

Problem :Given a list of tuples representing ranges ,condense the ranges

Input : [(2,3),(4,5),(7,8),(8,10),(12,15)]
Output :[(2,5),(7,10),(12,15)]

Any pointer or help would be great help

Body:
You could proceed for example as in the example below. The idea is to process individual intervals (lb, ub) and for each lower bound lb, mark an increase by 1, while for each upper bound ub, mark a decrease by -1.
Assuming integer input, the code effectively considers intervals (lb-0.5,ub+0.5) so that for example (2, 3) and (4, 5) are merged. In order to avoid using floating point numbers as dictionary keys, the dictionary stat stores double the number...

When you then process these individual "break" points, the total accumulated value (cnt) tells you how many intervals cover current point. As long as this number is greater than zero, we are inside a merged segment. If it drops to zero, we can take the next breakpoint and repeat the procedure...

spec = {}
L = [(2,3),(4,12),(7,8),(8,10),(12,15)]
for lb, ub in L:
    lb, ub = min(lb, ub), max(lb, ub)
    for v in [2*lb - 1, 2*ub + 1]:
        if not v in spec: spec[v] = 0
    spec[2*lb - 1] += 1
    spec[2*ub + 1] -= 1

break_points = sorted(spec.keys())
N = len(break_points)

idx = -1
while idx < N-1:
    idx += 1

    lb, ub = break_points[idx], None
    cnt = spec[lb]

    while cnt > 0:
        idx += 1
        ub = break_points[idx]
        cnt += spec[ub]

    print((lb+1)/2, (ub-1)/2)
    #prints (2, 15)