问:
How can I swap two nodes inside linked list in C?
I have this linked list

```<code>struct Link
{
    frame_t *frame;
    struct Link *next;
};
</code>```

Now I want to replace two of it's nodes with the function swap() so for example swap(list, 4, 7) will give me

```<code>[1, 2, 3, **7**, 5, 6, **4**, 8, 9, 10]
</code>```

for the list with the list with contents of

```<code>[1, 2, 3, **4**, 5, 6, **7**, 8, 9, 10]
</code>```

What I tried doing was to use the nodes before the ones I actually need to replace but I got infinite loops and nodes that have been cut.

```<code>link_t* tmp = currPrev->next;
link_t* tmpTwo = linkToChangePrev->next;
tmpTwo->next = tmp->next;
currPrev->next = tmpTwo;
tmp->next = tmpTwo;
linkToChangePrev->next = tmpTwo;
</code>```

What is the most effective way to change two nodes in linked list?

答:
Your question is a bit under-specified; what happens if the elements to be swapped occur more than once?

Assuming it's ok to just swap the first instances, I would definitely write code to do it in two steps:

Find the elements holding the data to swap.

Swap them.

Perhaps something like this:

```<code>const struct Node * find_node(const struct Node *list, frame_t *value)
{
  while(list != NULL)
  {
    if(list->frame == value)
      return list;
  }
  return NULL;
}

void swap(struct Node *list, frame_t *value1, frame_t *value2)
{
  struct Node *el1 = (struct Node *) find_node(list, value1);
  struct Node *el2 = (struct Node *) find_node(list, value2);
  if(el1 != NULL && el2 != NULL)
  {
    const frame_t * const f1 = el1->frame;
    el1->frame = el2->frame;
    el2->frame = f1;
  }
}
</code>```

This will simply swap the two first found instances, if there are duplicates.

Body:
I have this linked list

struct Link
{
    frame_t *frame;
    struct Link *next;
};

Now I want to replace two of it's nodes with the function swap() so for example swap(list, 4, 7) will give me

[1, 2, 3, **7**, 5, 6, **4**, 8, 9, 10]

for the list with the list with contents of

[1, 2, 3, **4**, 5, 6, **7**, 8, 9, 10]

What I tried doing was to use the nodes before the ones I actually need to replace but I got infinite loops and nodes that have been cut.

link_t* tmp = currPrev->next;
link_t* tmpTwo = linkToChangePrev->next;
tmpTwo->next = tmp->next;
currPrev->next = tmpTwo;
tmp->next = tmpTwo;
linkToChangePrev->next = tmpTwo;

What is the most effective way to change two nodes in linked list?

Body:
Your question is a bit under-specified; what happens if the elements to be swapped occur more than once?

Assuming it's ok to just swap the first instances, I would definitely write code to do it in two steps:

Find the elements holding the data to swap.

Swap them.

Perhaps something like this:

const struct Node * find_node(const struct Node *list, frame_t *value)
{
  while(list != NULL)
  {
    if(list->frame == value)
      return list;
  }
  return NULL;
}

void swap(struct Node *list, frame_t *value1, frame_t *value2)
{
  struct Node *el1 = (struct Node *) find_node(list, value1);
  struct Node *el2 = (struct Node *) find_node(list, value2);
  if(el1 != NULL && el2 != NULL)
  {
    const frame_t * const f1 = el1->frame;
    el1->frame = el2->frame;
    el2->frame = f1;
  }
}

This will simply swap the two first found instances, if there are duplicates.


来源: stackexchange

问:
How to deploy Node app to server
I have an Angular app that I have on a server and loads the html page when the page loads. I have since made it a fullstack app by using node which entry point is server.js which holds the routes.

Locally, I run node server.js in a powershell cmd but I dont know how to do that on the remote server

How do I tell the server that this is now a node app and that it needs to initally run server.js instead of the angular's html page?

答:
Get yourself a Bitnami MEAN instance on the AWS if you are a starter. It has got complete stack with an Apache server to handle requests. Install nodemon and forever to keep the node process running.

MEAN Stack Deployment Bitnami

Then follow this to deploy your custom application. Here

In this setup Apache will face the external requests and proxy it to your node js application.

ContentLicense: CC BY-SA 3.0

Title: How to deploy Node app to server


问:
Query to fetch superset if subset combination returns null result?
```<code>TABLE : **PROFILE**
RUN_ID| Type | code | gender | vacId

1     | A    | biz  | M      | 110
2     | A    | pro  | M      | 113
3     | A    | tot  | F      | 114
</code>```

Required to return the vacId, based on the input if I input, if code+type combination is not present then return only vacId which equals to given type

TYPE=A AND CODE=BIZ AND GENDER=M , then it should return 110

TYPE=A AND CODE=SYS then should return 110 & 113 , 114 there is no A+SYS combination so returned superset A's data

How can I write a query for this which should work in pgsql and oracle for now.

Is there a way that I can achieve this using COALESCE

答:
You can use conditional where clause, e.g. ($ used for parameters):

```<code>select p.*
from profile p
where case
    when exists (
        select 1
        from profile
        where type = $type and code = $code and gender = $gender
        )
    then type = $type and code = $code and gender = $gender
    else type = $type
    end;
</code>```

Update.

An alternative solution could be to get results in a single json object, what will enable you to use coalesce():

```<code>select coalesce(
    (select jsonb_agg(to_jsonb(p))
    from profile p
    where type = $type and code = $code and gender = $gender),
    (select jsonb_agg(to_jsonb(p))
    from profile p
    where type = $type)
);
</code>```

Body:
TABLE : **PROFILE**
RUN_ID| Type | code | gender | vacId

1     | A    | biz  | M      | 110
2     | A    | pro  | M      | 113
3     | A    | tot  | F      | 114

Required to return the vacId, based on the input if I input, if code+type combination is not present then return only vacId which equals to given type

TYPE=A AND CODE=BIZ AND GENDER=M , then it should return 110

TYPE=A AND CODE=SYS then should return 110 & 113 , 114 there is no A+SYS combination so returned superset A's data

How can I write a query for this which should work in pgsql and oracle for now.

Is there a way that I can achieve this using COALESCE

Body:
You can use conditional where clause, e.g. ($ used for parameters):

select p.*
from profile p
where case
    when exists (
        select 1
        from profile
        where type = $type and code = $code and gender = $gender
        )
    then type = $type and code = $code and gender = $gender
    else type = $type
    end;

Update.

An alternative solution could be to get results in a single json object, what will enable you to use coalesce():

select coalesce(
    (select jsonb_agg(to_jsonb(p))
    from profile p
    where type = $type and code = $code and gender = $gender),
    (select jsonb_agg(to_jsonb(p))
    from profile p
    where type = $type)
);


问:
Cannot find name require Angular2
am trying to learn angular doing a schedulerApp.
here is my code :

app.component.ts

```<code>import {Component} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
import {AboutComponent} from './about/about.component';
import {ExperimentsComponent} from './experiments/experiments.component';
import {HomeComponent} from './home/home.component';
import {calendrierComponent} from './calendrier/calendrier.component';
import {StateService} from './common/state.service';
import {ExperimentsService} from './common/experiments.service';

@Component({
  selector: 'app',
  template: require('./app.component.html'),
  styles: [ require('./app.component.css')],
  directives: [ ROUTER_DIRECTIVES ],
  providers: [StateService, ExperimentsService],
})
@Routes([
  {path: '/',            component: HomeComponent },
  {path: '/home',        component: HomeComponent },
  {path: '/about',       component: AboutComponent },
  {path: '/experiments', component: ExperimentsComponent },
  {path: '/calendrier',  component: calendrierComponent },
  {path: '/*',           component: HomeComponent }
])
export class AppComponent {}
</code>```

when i add these lines :

```<code>import {calendrierComponent} from './calendrier/calendrier.component';

@Routes([
  {path: '/calendrier',  component: calendrierComponent },
])
</code>```

i have these errors :

```<code>Error   Typescript  Cannot find name 'require'. 12:13
Error   Typescript  Cannot find name 'require'. 13:13
</code>```

i tried to add "   "types": [ "node" ] " on my ts.config.json but it didn't do anything... Did you have some idea to unstuck me ? thanks you very much

答:
You do not have to use require. You can pass the file paths directly using the templateUrl and styleUrls options. Angular will automatically resolve the styles and templates based on the paths:

```<code>@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [StateService, ExperimentsService],
})
</code>```

Title: Cannot find name require Angular2

Body:
am trying to learn angular doing a schedulerApp.
here is my code :

app.component.ts

import {Component} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
import {AboutComponent} from './about/about.component';
import {ExperimentsComponent} from './experiments/experiments.component';
import {HomeComponent} from './home/home.component';
import {calendrierComponent} from './calendrier/calendrier.component';
import {StateService} from './common/state.service';
import {ExperimentsService} from './common/experiments.service';

@Component({
  selector: 'app',
  template: require('./app.component.html'),
  styles: [ require('./app.component.css')],
  directives: [ ROUTER_DIRECTIVES ],
  providers: [StateService, ExperimentsService],
})
@Routes([
  {path: '/',            component: HomeComponent },
  {path: '/home',        component: HomeComponent },
  {path: '/about',       component: AboutComponent },
  {path: '/experiments', component: ExperimentsComponent },
  {path: '/calendrier',  component: calendrierComponent },
  {path: '/*',           component: HomeComponent }
])
export class AppComponent {}

when i add these lines :

import {calendrierComponent} from './calendrier/calendrier.component';

@Routes([
  {path: '/calendrier',  component: calendrierComponent },
])

i have these errors :

Error   Typescript  Cannot find name 'require'. 12:13
Error   Typescript  Cannot find name 'require'. 13:13

i tried to add "   "types": [ "node" ] " on my ts.config.json but it didn't do anything... Did you have some idea to unstuck me ? thanks you very much

Body:
You do not have to use require. You can pass the file paths directly using the templateUrl and styleUrls options. Angular will automatically resolve the styles and templates based on the paths:

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [StateService, ExperimentsService],
})


问:
React-google-maps warnings
I've started recently to learn React and I want to build a React App with Google Maps API so I downloaded React-google-maps package but its documentation is outdated. I have this sample code. Console logs error:

process.env.ENV is not defined, assuming 'prod' env

Accessing PropTypes via the main React package is deprecated

Accessing createClass via the main React package is deprecated.

TL:DR How to fix this code

import React from "react";
import ReactDOM from "react-dom";
import {
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow,
} from "react-google-maps";

const MapInit = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapLoad}
    defaultZoom={1}
    defaultCenter={{ lat: -25.363882, lng: 131.044922 }}
  >
  </GoogleMap>
));
class MapContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      markers: [
        {}
      ],
    };
    this.handleMapLoad = this.handleMapLoad.bind(this);
  }
  handleMapLoad(map) {
    this._mapComponent = map;
  }
  render() {
    return (
      <div style={{height: `100%`}}>
        <MapInit
          containerElement={
            <div style={{ height: `100%` }} />
          }
          mapElement={
            <div style={{ height: `100%` }} />
          }
          onMapLoad={this.handleMapLoad}
        />

    );
  }
}

export default MapContainer;```

答:
Those are generated by the library which is probably not updated to use class instead of createClass and is importing PropTypes from React.

You can verify this by browsing to your node_modules and checking the source code. It's a little annoying but there's nothing you can do, apart from sending a pull request to fix it yourself. :)

Title: React-google-maps warnings


问:
Create a mixin for class Meta in ModelForm
Django==1.11.3

The code below seems to violate DRY principle.
But I fail to create a mixin to generalize the three strings with:

exclude;

from_date

through_date.

Could you give me a kick here?

```<code>class BatchDateInputForm(forms.ModelForm):

    class Meta:
        model = BatchDateInput
        exclude = []

        widgets = {
            'user': forms.HiddenInput(),
            'from_date': forms.SelectDateWidget(years=get_years()),
            'through_date': forms.SelectDateWidget(years=get_years()),
        }

class FrameDateForm(ModelForm):

    class Meta:
            model = FrameDate
            exclude = []

            widgets = {
                'frame': forms.HiddenInput(),
                'from_date': forms.SelectDateWidget(years=get_years()),
                'through_date': forms.SelectDateWidget(years=get_years())
            }
</code>```

答:
It really depends on type of attributes you are trying to overload. Here is a way to achive this without using metaclasses, it is not as pretty, but will do the job

```<code>class BaseMeta:
    exclude = []

    widgets = {
        'from_date': forms.SelectDateWidget(years=get_years()),
        'through_date': forms.SelectDateWidget(years=get_years())
    }

class BatchDateInputForm(forms.ModelForm):

    class Meta(BaseMeta):
        model = BatchDateInput

        widgets = BaseMeta.widgets.copy()
        widgets.update({
            'user': forms.HiddenInput(),
        })

class FrameDateForm(ModelForm):

    class Meta(BaseMeta):
        model = FrameDate

        widgets = BaseMeta.widgets.copy()
        widgets.update({
            'frame': forms.HiddenInput(),
        })
</code>```

Note you will have to always rember to copy other dict attributes for BaseMeta otherwise it will update dict attribute on all subclasses

Body:
Django==1.11.3

The code below seems to violate DRY principle.
But I fail to create a mixin to generalize the three strings with:

exclude;

from_date

through_date.

Could you give me a kick here?

class BatchDateInputForm(forms.ModelForm):

    class Meta:
        model = BatchDateInput
        exclude = []

        widgets = {
            'user': forms.HiddenInput(),
            'from_date': forms.SelectDateWidget(years=get_years()),
            'through_date': forms.SelectDateWidget(years=get_years()),
        }

class FrameDateForm(ModelForm):

    class Meta:
            model = FrameDate
            exclude = []

            widgets = {
                'frame': forms.HiddenInput(),
                'from_date': forms.SelectDateWidget(years=get_years()),
                'through_date': forms.SelectDateWidget(years=get_years())
            }

Body:
It really depends on type of attributes you are trying to overload. Here is a way to achive this without using metaclasses, it is not as pretty, but will do the job

class BaseMeta:
    exclude = []

    widgets = {
        'from_date': forms.SelectDateWidget(years=get_years()),
        'through_date': forms.SelectDateWidget(years=get_years())
    }

class BatchDateInputForm(forms.ModelForm):

    class Meta(BaseMeta):
        model = BatchDateInput

        widgets = BaseMeta.widgets.copy()
        widgets.update({
            'user': forms.HiddenInput(),
        })

class FrameDateForm(ModelForm):

    class Meta(BaseMeta):
        model = FrameDate

        widgets = BaseMeta.widgets.copy()
        widgets.update({
            'frame': forms.HiddenInput(),
        })

Note you will have to always rember to copy other dict attributes for BaseMeta otherwise it will update dict attribute on all subclasses


问:
Full size background image for col-*-* in Bootstrap
i already found some questions regarding this topic but none of them could really help me solving my problem.

I like to build a simple Bootstrap grid looking like this:

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-sm-8"> Some Text </div>
    <div class="col-sm-4">
      <img src="..." alt="Full Size Background Image" />
    </div>
  </div>
  <div class="row">
    <div class="col-sm-4">
      <img src="..." alt="Full Size Background Image" />
    </div>
    <div class="col-sm-8"> Some Text </div>
  </div>
</div>
</code>```

The col-sm-4-DIVs should contain a full size background image with the same height as the text and no padding.

Here's a photo of what I mean. I want the background image to cover the red area:

See Example

Any ideas how to do that?

Thank you very much for your help!!!

答:
use css to set the background image on the column</p>

```<code> <div class="row">
    <div class="col-sm-4" style="background-image:url('.....')">
      content......
     </div>
</code>```

Body:
i already found some questions regarding this topic but none of them could really help me solving my problem.

I like to build a simple Bootstrap grid looking like this:

 Some Text

 Some Text

The col-sm-4-DIVs should contain a full size background image with the same height as the text and no padding.

Here's a photo of what I mean. I want the background image to cover the red area:

See Example

Any ideas how to do that?

Thank you very much for your help!!!

Body:
use css to set the background image on the column

 <div class="row">
    <div class="col-sm-4" style="background-image:url('.....')">
      content......
     </div>


问:
Swift - Whitespace count in a string
How do you get the count of the empty space within text?

It would be more helpful to me if explained with an example.

答:
Easiest way is to do something like this:

```<code>let emptySpacesCount = yourString.characters.filter { $0 == " " }.count
</code>```

What this does is it takes characters from your string, filter out everything that is not space and then counts number of remaining elements.

ContentLicense: CC BY-SA 4.0

Title: Swift - Whitespace count in a string

Body:
Easiest way is to do something like this:

let emptySpacesCount = yourString.characters.filter { $0 == " " }.count

What this does is it takes characters from your string, filter out everything that is not space and then counts number of remaining elements.


问:
UWP Light dismiss ContentDialog
Is there a way to make the ContentDialog light dismiss?, so when the user clicks on any thing outside the ContentDialog it should be closed.

Thanks.

答:
By default, ContentDialog is placed in PopupRoot. Behind it, there is a Rectangle which dim and prevent interaction with other elements in the app. You can find it with help of VisualTreeHelper and register a Tapped event to it, so when it's tapped you can hide ContentDialog.

You can do this after calling ShowAsync outside ContentDialog code or you can do it inside ContentDialog code. Personally, I implement a class which derives from ContentElement and I override OnApplyTemplate like this:

```<code>protected override void OnApplyTemplate()
{
    // this is here by default
    base.OnApplyTemplate();

    // get all open popups
    // normally there are 2 popups, one for your ContentDialog and one for Rectangle
    var popups = VisualTreeHelper.GetOpenPopups(Window.Current);
    foreach (var popup in popups)
    {
        if (popup.Child is Rectangle)
        {
            // I store a refrence to Rectangle to be able to unregester event handler later
            _lockRectangle = popup.Child as Rectangle;
            _lockRectangle.Tapped += OnLockRectangleTapped;
        }
    }
}
</code>```

and in OnLockRectangleTapped:

```<code>private void OnLockRectangleTapped(object sender, TappedRoutedEventArgs e)
{
    this.Hide();
    _lockRectangle.Tapped -= OnLockRectangleTapped;
}
</code>```

Title: UWP Light dismiss ContentDialog

Body:
By default, ContentDialog is placed in PopupRoot. Behind it, there is a Rectangle which dim and prevent interaction with other elements in the app. You can find it with help of VisualTreeHelper and register a Tapped event to it, so when it's tapped you can hide ContentDialog.

You can do this after calling ShowAsync outside ContentDialog code or you can do it inside ContentDialog code. Personally, I implement a class which derives from ContentElement and I override OnApplyTemplate like this:

protected override void OnApplyTemplate()
{
    // this is here by default
    base.OnApplyTemplate();

    // get all open popups
    // normally there are 2 popups, one for your ContentDialog and one for Rectangle
    var popups = VisualTreeHelper.GetOpenPopups(Window.Current);
    foreach (var popup in popups)
    {
        if (popup.Child is Rectangle)
        {
            // I store a refrence to Rectangle to be able to unregester event handler later
            _lockRectangle = popup.Child as Rectangle;
            _lockRectangle.Tapped += OnLockRectangleTapped;
        }
    }
}

and in OnLockRectangleTapped:

private void OnLockRectangleTapped(object sender, TappedRoutedEventArgs e)
{
    this.Hide();
    _lockRectangle.Tapped -= OnLockRectangleTapped;
}


问:
Element UI and font-awesome
Can anyone explane if it is possible to use font-awesome or another big icon font with Element UI? I've seen FAQ but cannot make it work for me.
 https://github.com/ElemeFE/element/blob/dev/FAQ.md

Thanks.

答: You can just include those libraries / or NPM them and they work, Element UI has a limited set of icons so I have include vue-awesome (font awesome) but I notice the position of the icons if out a bit so you need some CSS to adjust top margins (I needed -4px) and line them with say button text.</p>

Title: Element UI and font-awesome


问:
WPF C# - pack window into page
I'm trying to pack WPF Window into Page class and show it as a part of my application. I really need build in application. Is it possible?

I created Page class MyPage.xaml with MyPage.xaml.cs.
In contructor of MyPage I have

```<code>public MyPage()
    {
        InitializeComponent();

        _prompt = new MyPrompt();
        _prompt.ReadLine += new ReadLineEventHandler(CommandHandler);
        //_prompt.Show();

        this.Content = _prompt;
    }
</code>```

This of course doesn't work. After uncomment //_promt.Show(); line I have seperated window. Is any possibility to make this a part of page?

答:
Is any possibility to make this a part of page?

No, it isn't. A Window must be the root of the element tree and you cannot add a Window as a child of a Page or any other visual I am afraid.

What you could do is to move the contents of your window into a UserControl and use an instance of this one as the Content of your Page. But you cannot use the window directly.

Title: WPF C# - pack window into page

Body:
I'm trying to pack WPF Window into Page class and show it as a part of my application. I really need build in application. Is it possible?

I created Page class MyPage.xaml with MyPage.xaml.cs.
In contructor of MyPage I have

public MyPage()
    {
        InitializeComponent();

        _prompt = new MyPrompt();
        _prompt.ReadLine += new ReadLineEventHandler(CommandHandler);
        //_prompt.Show();

        this.Content = _prompt;
    }

This of course doesn't work. After uncomment //_promt.Show(); line I have seperated window. Is any possibility to make this a part of page?


问:
Choose folders to be ignored during search in VS Code
Right now when I use ⌘+O to search for files, the fuzzy matching appears to operate over all files in the current project. Unfortunately, this includes a number of files from build and vendor directories. So, for instance, if I want to search for all JavaScript files and do ⌘+O and type .js in, the file and symbol results include around 1500 hits and all of them except the two ones are complete noise.

Is there a way to specify certain directories to be ignored for purpose of search?

答:
If I understand correctly you want to exclude files from the vscode
fuzzy finder. If that is the case, I am guessing the above answers are for older versions of vscode.
What worked for me is adding:

```<code>"files.exclude": {
    "**/directory-you-want-to-exclude": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
}
</code>```

to my settings.json. This file can be opened through File>Preferences>Settings

Body:
If I understand correctly you want to exclude files from the vscode
fuzzy finder. If that is the case, I am guessing the above answers are for older versions of vscode.
What worked for me is adding:

"files.exclude": {
    "**/directory-you-want-to-exclude": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
}

to my settings.json. This file can be opened through File>Preferences>Settings


问:
Can I have instances of both java 7 & 8 running together
I am working on a project which runs on java 8, but I frequently use jasper reports which runs on java 7 for generating PDF reports. Problem is that I have to switch between the 7 & 8 versions for this. Is there any way I can let the system know which version of Java to use for which applications. My tomcat server is wrapped within a Hybris server instance which is run externally, so changing compliance level in Eclipse is of no help.</p>

答:
Maybe my question was misunderstood, but I found a way to acheive what I intended to do.
Set your JAVA_HOME to 1.7 version and open iReports application(it did not open if version is set to 1.8). Then reset JAVA_HOME back to 1.8 and run your application normally. Once iReports has started, there is no further issue while developing your reports.
It is more of a hack than a proper solution, but works well enough for me.</p>


问:
Finding closest match in collection of numbers
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

```<code>1, 3, 8, 10, 13, ...
</code>```

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

答:
Common Lisp using iterate library.

```<code>(defun closest-match (list n)
     (iter (for i in list)
            (finding i minimizing (abs (- i n)))
</code>```

OwnerDisplayName: Slace

ContentLicense: CC BY-SA 2.5

Body:
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

LastEditorDisplayName: Allain Lalonde

Body:
Common Lisp using iterate library.

(defun closest-match (list n)
     (iter (for i in list)
            (finding i minimizing (abs (- i n)))


问:
GUI button issue with bunifu
Im having issues with some GUI in my application (Using bunifu). I made it so that when I click a button, it changes the background color AND the text. I was able to make the background change in the properties but had to make code for the text color, when its activated.

```<code>Private Sub BunifuFlatButton2_Click_1(sender As Object, e As EventArgs) Handles BunifuFlatButton2.Click
    BunifuFlatButton2.Textcolor = Color.FromArgb(30, 33, 36)
    BunifuFlatButton3.Textcolor = Color.FromArgb(231, 234, 234)
    MEMAPI.WriteByte(MEMAPI.GameStart + OFFSET_UI, 1)
End Sub

Private Sub BunifuFlatButton3_Click_1(sender As Object, e As EventArgs) Handles BunifuFlatButton3.Click
    BunifuFlatButton3.Textcolor = Color.FromArgb(30, 33, 36)
    BunifuFlatButton2.Textcolor = Color.FromArgb(231, 234, 234)
    MEMAPI.WriteByte(MEMAPI.GameStart + OFFSET_UI, 0)
End Sub
</code>```

The issue is when I click another button on the same panel, it forgets that I pressed that button (only visually) and it doesn't stay with the colors I made it to, as you can see with the Gyazo.

https://gyazo.com/e8faba5b59be8416aeaa9e730d955f76

答:
Clarifications:
Which version of Bunifu Framework are you using, since there were some issues which were fixed on the concurrent updates

Suggestions :
Change Button Forecolor to [White or the TextColor your set on the designer]
Also check OnHoverTextColor [use designer]
Don't forget to check button mismatch could cause UI issue.

Title: GUI button issue with bunifu

Body:
Im having issues with some GUI in my application (Using bunifu). I made it so that when I click a button, it changes the background color AND the text. I was able to make the background change in the properties but had to make code for the text color, when its activated.

Private Sub BunifuFlatButton2_Click_1(sender As Object, e As EventArgs) Handles BunifuFlatButton2.Click
    BunifuFlatButton2.Textcolor = Color.FromArgb(30, 33, 36)
    BunifuFlatButton3.Textcolor = Color.FromArgb(231, 234, 234)
    MEMAPI.WriteByte(MEMAPI.GameStart + OFFSET_UI, 1)
End Sub

Private Sub BunifuFlatButton3_Click_1(sender As Object, e As EventArgs) Handles BunifuFlatButton3.Click
    BunifuFlatButton3.Textcolor = Color.FromArgb(30, 33, 36)
    BunifuFlatButton2.Textcolor = Color.FromArgb(231, 234, 234)
    MEMAPI.WriteByte(MEMAPI.GameStart + OFFSET_UI, 0)
End Sub

The issue is when I click another button on the same panel, it forgets that I pressed that button (only visually) and it doesn't stay with the colors I made it to, as you can see with the Gyazo.

https://gyazo.com/e8faba5b59be8416aeaa9e730d955f76


问:
What does @internal actually mean and how to use it?
What does the @internal tag mean when used in PHPDocs and how does it work? I have read the documentation for this tag and have gotten this definition.

The @internal tag is used to denote that associated Structural Elements are elements internal to this application or library. It may also be used inside a long description to insert a piece of text that is only applicable for the developers of this software.

I get the gist of it but what I don't understand is how would I actually use it in a project? I've read the example and my understanding is that a function marked as @internal means that it's meant to be used as part of the software and not to be used by something external. For example, in a PHP library, if a function is marked as @internal it's not part of the public API that the library provides.

My questions:

Is my understanding of @internal correct? If not, what's the correct usage?

If my understanding is correct, why does PhpStorm strike out my @internal functions implying they aren't meant to be used? How would I properly use a function marked as @internal?

答:
Might be trivial for some but it's a good thing to note that declaring a function private if possible is probably better than using @internal.

Not saying there are no valid uses for this tag but it's always a good choice to review your design if feel like you need to use it.


问:
How do I capitalize text in breadcrumbs?
Here is the html containing bootstrap's breadcrumb,

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  text-transform: lowercase;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="breadcrumb">
  <li>MEP SERVICES </li>
  <li>Electrical</li>
  <li>Lighting</li>
  <li>HT & LT</li>
</ul></code>```

Now its look and feel is,

I want below look and feel.

I have tried below css , but not working.

.breadcrumb>li {
  display: inline-block;
  text-transform: uppercase;
  font-size: 11px;
}
```

答:
use   text-transform: capitalize; in a

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}

.breadcrumb>li>a {
  text-transform: capitalize;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="breadcrumb">
  <li>mep services</li>
  <li>electrical</li>
  <li>lighting</li>
  <li>HT & LT</li>
</ul></code>```

if you really want to have MEP SERVICES fully capitalized in html then you need a bit more code for that:

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}

.breadcrumb>li>a {
  text-transform: capitalize;
}

.breadcrumb>li:first-of-type>a {
  text-transform: lowercase;
}

.breadcrumb>li:first-of-type>a:first-letter {
  text-transform: capitalize;
}
 /* for ::first-letter work `a` needs to be block level element */
.breadcrumb>li>a {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="breadcrumb">
  <li>MEP SERVICES</li>
  <li>electrical</li>
  <li>lighting</li>
  <li>HT & LT</li>
</ul></code>```

Body:
Here is the html containing bootstrap's breadcrumb,

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  text-transform: lowercase;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}

MEP SERVICES

Electrical

Lighting

HT & LT

Now its look and feel is,

I want below look and feel.

I have tried below css , but not working.

.breadcrumb>li {
  display: inline-block;
  text-transform: uppercase;
  font-size: 11px;
}

Body:
use   text-transform: capitalize; in a

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}

.breadcrumb>li>a {
  text-transform: capitalize;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="breadcrumb">
  <li><a href="#">mep services</a></li>
  <li><a href="#">electrical</a></li>
  <li><a href="#">lighting</a></li>
  <li>HT &amp; LT</li>
</ul>

if you really want to have MEP SERVICES fully capitalized in html then you need a bit more code for that:

.breadcrumb {
  margin-top: 0;
  margin-bottom: 0;
  padding: 8px 15px 0 35px;
}

.breadcrumb>li {
  display: inline-block;
  font-size: 11px;
}

.breadcrumb>li+li:before {
  content: "\3E";
  color: #b1afaf;
  font-weight: bold;
}

.breadcrumb>li>a {
  text-transform: capitalize;
}

.breadcrumb>li:first-of-type>a {
  text-transform: lowercase;
}

.breadcrumb>li:first-of-type>a:first-letter {
  text-transform: capitalize;
}
 /* for ::first-letter work `a` needs to be block level element */
.breadcrumb>li>a {
  display: inline-block;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<ul class="breadcrumb">
  <li><a href="#">MEP SERVICES</a></li>
  <li><a href="#">electrical</a></li>
  <li><a href="#">lighting</a></li>
  <li>HT &amp; LT</li>
</ul>


答:
You can use array_column to select only days from the multi dimensional array and then use array_merge to merge the array.

Just like this

```<code>$merger=array_merge(array_column($arr2,'days'),array_column($arr1,'days'));
$merger=implode(',',$merger);
</code>```

It will produce your desired out put.

Title: How to assemble two different array in one array of php

Body:
$arr1 = Array ( [0] => 5 [days] => 5 )
        Array ( [0] => 6 [days] => 6 )
        Array ( [0] => 7 [days] => 7 )
        Array ( [0] => 8 [days] => 8 )
        Array ( [0] => 9 [days] => 9 )
        Array ( [0] => 10 [days] => 10 )
        Array ( [0] => 11 [days] => 11 )
        Array ( [0] => 12 [days] => 12 )
        Array ( [0] => 13 [days] => 13 )
        Array ( [0] => 14 [days] => 14 )
        Array ( [0] => 15 [days] => 15 )
        Array ( [0] => 16 [days] => 16 )
        Array ( [0] => 17 [days] => 17 )
        Array ( [0] => 18 [days] => 18 )
        Array ( [0] => 19 [days] => 19 )
        Array ( [0] => 20 [days] => 20 )
        Array ( [0] => 21 [days] => 21 )
        Array ( [0] => 22 [days] => 22 )
        Array ( [0] => 23 [days] => 23 )
        Array ( [0] => 24 [days] => 24 )
        Array ( [0] => 25 [days] => 25 )
        Array ( [0] => 26 [days] => 26 )
        Array ( [0] => 27 [days] => 27 )
        Array ( [0] => 28 [days] => 28 )
        Array ( [0] => 29 [days] => 29 )
        Array ( [0] => 30 [days] => 30 )
        Array ( [0] => 31 [days] => 31 );

$arr2 = Array ( [0] => 1 [day] => 1
                [1] => 1 [days] => 1 )
        Array ( [0] => 2 [day] => 2 [1] => 2 [days] => 2 ) Array ( [0] => 3 [day] => 3 [1] => 3 [days] => 3 ) Array ( [0] => 4 [day] => 4 [1] => 4 [days] => 4 );

i want to ascending-ly marge $arr1 and $arr2 and the output i expect

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31

help me How can i do like that?

Body:
You can use array_column to select only days from the multi dimensional array and then use array_merge to merge the array.

Just like this

$merger=array_merge(array_column($arr2,'days'),array_column($arr1,'days'));
$merger=implode(',',$merger);

It will produce your desired out put.


问:
why std::move takes forward_reference instead of lvaue reference
Just to confirm what I understood about std::move

std::move - converts T& to T&& so that the T's move constructor would kick in(if it exist otherwise the copy ctor will play its role unless we aren't externally deleted move ctor/assignment).

when I've looked at the possible implementation of std::move it's like

```<code>template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}
</code>```

The reason it uses remove_reference<T> is because of the reference collapsing that applied over the forward_reference T&&

I just wonder why we need forward reference,couldn't we done that by

```<code>template<typename T>
T&& moveInQuestion(T& p){
  return static_cast<T&&>(p);
}

struct someType{};
someType lvalref;
static_assert(is_same<decltype(moveInQuestion(lvalref)),decltype(std::move(lvalref))>::value,"");
</code>```

static_assert hasn't failed.

And I also believe that the value category that meant for std::move is an lvalue with this being the case could moveInQuestion possibly be better than std::move?

答:
The usual example is generic code like

```<code>template<class T>
T frob() {
    std::vector<T> x = /* ... */;
    return std::move(x[0]);
}
</code>```

With your move, this breaks when T is bool, since in that case x[0] is a prvalue proxy reference rather than an lvalue.

Body:
Just to confirm what I understood about std::move

std::move - converts T& to T&& so that the T's move constructor would kick in(if it exist otherwise the copy ctor will play its role unless we aren't externally deleted move ctor/assignment).

when I've looked at the possible implementation of std::move it's like

template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}

The reason it uses remove_reference<T> is because of the reference collapsing that applied over the forward_reference T&&

I just wonder why we need forward reference,couldn't we done that by

template<typename T>
T&& moveInQuestion(T& p){
  return static_cast<T&&>(p);
}

struct someType{};
someType lvalref;
static_assert(is_same<decltype(moveInQuestion(lvalref)),decltype(std::move(lvalref))>::value,"");

static_assert hasn't failed.

And I also believe that the value category that meant for std::move is an lvalue with this being the case could moveInQuestion possibly be better than std::move?

Body:
The usual example is generic code like

template<class T>
T frob() {
    std::vector<T> x = /* ... */;
    return std::move(x[0]);
}

With your move, this breaks when T is bool, since in that case x[0] is a prvalue proxy reference rather than an lvalue.


问:
Module that rotates each cell of a 3x3 array around the central cell (not a matrix rotation)
I want to rotate an array but not like a basic matrix rotation. If I have a 3x3 array, I want each of the cells to turn around the central cell.

Here is a 3x3 array:

```<code>import numpy as np

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

[[1 2 3]
 [4 5 6]
 [7 8 9]]
</code>```

I want for instance to rotate it by 45 degrees:

```<code>[[2 3 6]
 [1 5 9]
 [4 7 8]]
</code>```

I can't use scipy.ndimage.interpolation.rotate(tab,45) because it applies a basic matrix rotation and this is not what I want.

```<code>import numpy as np
from scipy import ndimage

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

ndimage.interpolation.rotate(tab,45)

[[0 0 0 0]
 [0 2 6 0]
 [0 4 8 0]
 [0 0 0 0]]
</code>```

Does anybody know how this can be achieved?

答:
You can do this by creating a pair of index arrays (in which a rotation can be seen visually):

```<code>i = np.array([
    [0, 0, 1],
    [0, 1, 2],
    [1, 2, 2]
])
j = np.array([
    [1, 2, 2],
    [0, 1, 2],
    [0, 0, 1]
])
</code>```

Which then works as desired:

```<code>>>> tab = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> tab[i,j]
array([[2, 3, 6],
       [1, 5, 9],
       [4, 7, 8]])
</code>```

This is essentially a vectorized implementation of Balázs Kovacsics' solution, which should be faster than the ndimage solution

To rotate twice, you can use either

```<code>>>> tab[i,j][i,j]
array([[3, 6, 9],
       [2, 5, 8],
       [1, 4, 7]])

>>> i2 = i[i,j]
>>> j2 = j[i,j]
>>> tab[i2,j2]
array([[3, 6, 9],
       [2, 5, 8],
       [1, 4, 7]])
</code>```

Body:
I want to rotate an array but not like a basic matrix rotation. If I have a 3x3 array, I want each of the cells to turn around the central cell.

Here is a 3x3 array:

import numpy as np

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

[[1 2 3]
 [4 5 6]
 [7 8 9]]

I want for instance to rotate it by 45 degrees:

[[2 3 6]
 [1 5 9]
 [4 7 8]]

I can't use scipy.ndimage.interpolation.rotate(tab,45) because it applies a basic matrix rotation and this is not what I want.

import numpy as np
from scipy import ndimage

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

ndimage.interpolation.rotate(tab,45)

[[0 0 0 0]
 [0 2 6 0]
 [0 4 8 0]
 [0 0 0 0]]

Does anybody know how this can be achieved?

Body:
You can do this by creating a pair of index arrays (in which a rotation can be seen visually):

i = np.array([
    [0, 0, 1],
    [0, 1, 2],
    [1, 2, 2]
])
j = np.array([
    [1, 2, 2],
    [0, 1, 2],
    [0, 0, 1]
])

Which then works as desired:

>>> tab = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> tab[i,j]
array([[2, 3, 6],
       [1, 5, 9],
       [4, 7, 8]])

This is essentially a vectorized implementation of Balázs Kovacsics' solution, which should be faster than the ndimage solution

To rotate twice, you can use either

>>> tab[i,j][i,j]
array([[3, 6, 9],
       [2, 5, 8],
       [1, 4, 7]])

>>> i2 = i[i,j]
>>> j2 = j[i,j]
>>> tab[i2,j2]
array([[3, 6, 9],
       [2, 5, 8],
       [1, 4, 7]])


问:
C# Get last Array Element
I has the following collection in my collection:

```<code>{
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [
       {
        "Report_Day": 1,
        "First_Level_Superior" : "WS66"
    },
    {
        "Report_Day": 2,
        "First_Level_Superior" : "CN4"
    }
},
{
    "Target_Year" : 2017,
    "Target_Month" : 7,
    "Performance" : [
       {
        "Report_Day": 10,
        "First_Level_Superior" : "WS66"
    },
    {
        "Report_Day": 11,
        "First_Level_Superior" : "CN4"
    }
}
</code>```

I has the codes to retrieve all Performance.

```<code>var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Include("Performance.$");
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();
</code>```

How can I retrieve the max Report_Day sub document for each document instead of all documents?

答:
You want <code>$slice</code> here to get the "last" which is the "latest" or "max": </p>

```<code>var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Slice("Performance",-1);
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();
</code>```

Title: C# Get last Array Element

Body:
I has the following collection in my collection:

{
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [
       {
        "Report_Day": 1,
        "First_Level_Superior" : "WS66"
    },
    {
        "Report_Day": 2,
        "First_Level_Superior" : "CN4"
    }
},
{
    "Target_Year" : 2017,
    "Target_Month" : 7,
    "Performance" : [
       {
        "Report_Day": 10,
        "First_Level_Superior" : "WS66"
    },
    {
        "Report_Day": 11,
        "First_Level_Superior" : "CN4"
    }
}

I has the codes to retrieve all Performance.

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Include("Performance.$");
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();

How can I retrieve the max Report_Day sub document for each document instead of all documents?

Body:
You want $slice here to get the "last" which is the "latest" or "max":

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017")
var project = Builders<BsonDocument>.Projection.Slice("Performance",-1);
var result = mongoDB.Performance.Find(filterMain).Project(project).ToList();


答:
You can try this example;

    let string = "Whitespace count in a string swift"
    let spaceCount = string.characters.filter{$0 == " "}.count
```

Title: Swift - Whitespace count in a string

Body:
How do you get the count of the empty space within text?

It would be more helpful to me if explained with an example.


问:
No config files after a PostgreSQL installation on Debian Stretch
I had installed postgresql and postgis on new Debian stable (Stretch 9) like I did it on Debian 8.

When I'm connecting as postgresql user, I had an error:

```<code>postgres@servername:~$ psql
</code>```

psql: n'a pas pu se connecter au serveur : Aucun fichier ou dossier de ce type
         Le serveur est-il actif localement et accepte-t-il les connexions sur la
         socket Unix « /var/run/postgresql/.s.PGSQL.5432 » ?

Translation:

psql: cannot connect to server: No file or directory of this kind. Is the server locally activated and does it accept connection on Unix Socket « /var/run/postgresql/.s.PGSQL.5432 » ?

So, I would like to have a look on my config file, but /etc/postgresql directory is empty ! There is no pg_hba.conf and no postgresql.conf !

```<code>root@servername:/etc# locate pg_hba.conf
/usr/share/postgresql/9.6/pg_hba.conf.sample
</code>```

What did I wrong when installing postgresql?

Here is the command that I have launch to install it:

```<code># apt-get install apache2 php phppgadmin postgresql postgresql-client postgis
</code>```

The service seems to be running:

```<code>root@servername:/etc# service postgresql status
● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enable
   Active: active (exited) since Tue 2017-07-04 07:13:05 UTC; 2s ago
  Process: 6982 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 6982 (code=exited, status=0/SUCCESS)

juil. 04 07:13:05 cthedifference systemd[1]: Starting PostgreSQL RDBMS...
juil. 04 07:13:05 cthedifference systemd[1]: Started PostgreSQL RDBMS.
</code>```

But I find no running process:

```<code># ps -edf|grep postgres
root      7077   908  0 07:15 pts/0    00:00:00 grep postgres
</code>```

Log directory /var/log/postgresql/ is empty.

答:
To correctly install and configure postgresql follow the instructions of the official documentation debian:

```<code>apt-get install postgresql postgresql-client
</code>```

The configuration files should be found under /etc/postgresql/9.6/main:

```<code># ls /etc/postgresql/9.6/main
</code>```

Sample output:

```<code>environment  pg_hba.conf    postgresql.conf
pg_ctl.conf  pg_ident.conf  start.conf
</code>```

Body:
I had installed postgresql and postgis on new Debian stable (Stretch 9) like I did it on Debian 8.

When I'm connecting as postgresql user, I had an error:

postgres@servername:~$ psql

psql: n'a pas pu se connecter au serveur : Aucun fichier ou dossier de ce type
         Le serveur est-il actif localement et accepte-t-il les connexions sur la
         socket Unix « /var/run/postgresql/.s.PGSQL.5432 » ?

Translation:

psql: cannot connect to server: No file or directory of this kind. Is the server locally activated and does it accept connection on Unix Socket « /var/run/postgresql/.s.PGSQL.5432 » ?

So, I would like to have a look on my config file, but /etc/postgresql directory is empty ! There is no pg_hba.conf and no postgresql.conf !

root@servername:/etc# locate pg_hba.conf
/usr/share/postgresql/9.6/pg_hba.conf.sample

What did I wrong when installing postgresql?

Here is the command that I have launch to install it:

# apt-get install apache2 php phppgadmin postgresql postgresql-client postgis

The service seems to be running:

root@servername:/etc# service postgresql status
● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enable
   Active: active (exited) since Tue 2017-07-04 07:13:05 UTC; 2s ago
  Process: 6982 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 6982 (code=exited, status=0/SUCCESS)

juil. 04 07:13:05 cthedifference systemd[1]: Starting PostgreSQL RDBMS...
juil. 04 07:13:05 cthedifference systemd[1]: Started PostgreSQL RDBMS.

But I find no running process:

# ps -edf|grep postgres
root      7077   908  0 07:15 pts/0    00:00:00 grep postgres

Log directory /var/log/postgresql/ is empty.

Body:
To correctly install and configure postgresql follow the instructions of the official documentation debian:

apt-get install postgresql postgresql-client

The configuration files should be found under /etc/postgresql/9.6/main:

# ls /etc/postgresql/9.6/main

Sample output:

environment  pg_hba.conf    postgresql.conf
pg_ctl.conf  pg_ident.conf  start.conf


问:
How to post form login using jsoup?
i want to login in here

source code

```<code><HTML><HEAD><TITLE>:: Dhaka Electric Supply Company Limited (DESCO)::</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META http-equiv=Pragma content=no-cache>
<META http-equiv=imagetoolbar content=no>
<META content="Home Page of  Dhaka Electric Supply Company Limited" name=description>
<META content="MSHTML 6.00.2900.2180" name=GENERATOR>
<style type="text/css">
    img{
        border:0px;
    }
</style>
<script type="text/javascript" src="js/ajax-dynamic-content.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/ajax-tooltip.js"></script>
<link rel="stylesheet" href="css/ajax-tooltip.css" media="screen" type="text/css">
<link rel="stylesheet" href="css/ajax-tooltip-demo.css" media="screen" type="text/css">
<LINK media=all href="css/global.css" type=text/css rel=stylesheet>

</HEAD>
<BODY>
<DIV id=over style="DISPLAY: none"></DIV>
<DIV class=baselayout>
<DIV class=pagetopshadow></DIV>
<DIV class=basebg>
<DIV class=pageleft></DIV>
<DIV class=pagecenter>
<DIV id=Header>
</DIV>
<DIV id=Menu>
</DIV>
<DIV id=HomeContent>
<DIV class=right>
<DIV class=homeintro>

<div style="padding-top: 0px;">
<script>
function checkLogin()
 { if( document.login.username.value == '')
  {
  alert( 'Please enter  your account number' );
   return false;
   }return true;
   }
   alert('Payments through VISA and Master Card are stopped by DBBL. only DBBL Nexus card is allowed.');
    </script>

        <form NAME='login' METHOD='POST' ACTION='authentication.php'>

          <table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
          <tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
            <tr>
              <td colspan="2" height="50"></td>
            </tr>
           <tr>
              <td nowrap><span class="textcolor1">Account No. </span></td>
              <td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>

            <tr>
            <td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
            <td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;"  border="0" align="right" title="Login"  onClick="return checkLogin();"/></td>
            </tr>

        </table>

        </form>
<table width="630" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF" bordercolor="#FFFFFF">
  <tr>
    <td width="80"></td>
    <td><img src="images/right_3.gif"/></td>
    <td><span class="textcolor"><strong><a href='https://www.desco.org.bd/index.php?page=internet-bill-payment' target="_blank" class="uiTooltip">Before, use this facility/services please read instructions...</a></strong></span></td>
  </tr>
  </table>
<p align="center" class="textcolor"><strong><a href='https://www.desco.org.bd' class="uiTooltip">Back Home</a></strong></p>
<table align="center" width="135" border="0" cellpadding="2" cellspacing="0" title="Click to Verify - This site chose VeriSign SSL for secure e-commerce and confidential communications.">
<tr>
<td width="135" align="center" valign="top"><script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.desco.org.bd&size=S&use_flash=YES&use_transparent=YES&lang=en"></script><br />
<a href="http://www.verisign.com/ssl-certificate/" target="_blank"  style="color:#000000; text-decoration:none; font:bold 7px verdana,sans-serif; letter-spacing:.5px; text-align:center; margin:0px; padding:0px;">ABOUT SSL CERTIFICATES</a></td>
</tr>
</table>

</div>
<div align="center" style="padding-top:10px;">

<CENTER><B>
    Total Visits:  1</B></CENTER>
</div>
</DIV>
</DIV>
</DIV>
</DIV>
<DIV class=pageright></DIV></DIV>
<DIV class=pagebotshadow>
<DIV  id=Footer>Copyright © 2010 Dhaka Electric Supply Company Ltd. All rights reserved.</DIV>
</DIV>
</DIV>
</BODY>
</HTML>
</code>```

basically below code is the form

```<code><form NAME='login' METHOD='POST' ACTION='authentication.php'>

      <table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
      <tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
        <tr>
          <td colspan="2" height="50"></td>
        </tr>
       <tr>
          <td nowrap><span class="textcolor1">Account No. </span></td>
          <td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>

        <tr>
        <td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
        <td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;"  border="0" align="right" title="Login"  onClick="return checkLogin();"/></td>
        </tr>

    </table>

    </form>
</code>```

i am trying this

```<code>package jsouptest;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JsouptTest {
    public static void main(String[] args) throws Exception {

        Connection.Response loginForm = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
                .method(Connection.Method.GET)
                .execute();

        Document document = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
                .data("cookieexists", "false")
                .data("username", "32007702")
                .data("login", "Login")
                .cookies(loginForm.cookies())
                .post();
        System.out.println(document);

    }

}
</code>```

but im getting below error

```<code>Exception in thread "main" java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:152)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
    at sun.security.ssl.InputRecord.read(InputRecord.java:480)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:439)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
    at jsouptest.JsouptTest.main(JsouptTest.java:12)
</code>```

am is missing something? how to fix it?

答:
In my case, it consists in three steps:

Get cookies from login form page;

Post credentials to login form action= URL, renew cookies;

The user will be redirected to index page. Don't parse here, just send Response to the final target URL.

Parse when you reach the final page.

The cookies should be renewed in every step, sometimes add entries, and sometimes you must clear it and reset. Be sure to check the network transmission with Internet Explorer/Chrome/Firefox Dev tool (F12), in the Network panel, cookies part.

Title: How to post form login using jsoup?

Body:
i want to login in here

source code

<TITLE>:: Dhaka Electric Supply Company Limited (DESCO)::</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META http-equiv=Pragma content=no-cache>
<META http-equiv=imagetoolbar content=no>
<META content="Home Page of  Dhaka Electric Supply Company Limited" name=description>
<META content="MSHTML 6.00.2900.2180" name=GENERATOR>

<link rel="stylesheet" href="css/ajax-tooltip.css" media="screen" type="text/css">
<link rel="stylesheet" href="css/ajax-tooltip-demo.css" media="screen" type="text/css">
<LINK media=all href="css/global.css" type=text/css rel=stylesheet>

        <form NAME='login' METHOD='POST' ACTION='authentication.php'>

              Account No.
              <input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''>

             Help
            <input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;"  border="0" align="right" title="Login"  onClick="return checkLogin();"/>

        </form>

    Before, use this facility/services please read instructions...

Back Home

ABOUT SSL CERTIFICATES

    Total Visits:  1

Copyright © 2010 Dhaka Electric Supply Company Ltd. All rights reserved.

basically below code is the form

<form NAME='login' METHOD='POST' ACTION='authentication.php'>

          Account No.
          <input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''>

         Help
        <input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;"  border="0" align="right" title="Login"  onClick="return checkLogin();"/>

    </form>

i am trying this

package jsouptest;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JsouptTest {
    public static void main(String[] args) throws Exception {

        Connection.Response loginForm = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
                .method(Connection.Method.GET)
                .execute();

        Document document = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
                .data("cookieexists", "false")
                .data("username", "32007702")
                .data("login", "Login")
                .cookies(loginForm.cookies())
                .post();
        System.out.println(document);

    }

}

but im getting below error

Exception in thread "main" java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:152)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
    at sun.security.ssl.InputRecord.read(InputRecord.java:480)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:439)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
    at jsouptest.JsouptTest.main(JsouptTest.java:12)

am is missing something? how to fix it?


问:
INSTALL_FAILED_CPU_ABI_INCOMPATIBLE on device using intellij
I've seen some questions about this, but none with real answers nor details. Here is my case:

I have an application that uses Google Maps API v2 which works just fine. Recently I found out that I cannot get it installed on this not ARM-based device.

In order to nail down the problem I'm working with Google Maps samples provided with the SDK (\sdk\extras\google\google_play_services\samples)

which gives me the same error message at install time:

Failure [INSTALL_FAILED_CPU_ABI_INCOMPATIBLE]

I get this message only on a real device using Intellij (12.1.1)

It works fine using both Eclipse on real device and using Intellij on the Emulator configured with CPU: Intel Atom (x86)

Any help would be highly appreciated!

UPDATE

As expected, same thing happens with Android Studio

答:
In android studio, Fix this issue:

1 Download Genymotion-ARM-Translation_v1.1.zip

download url:

https://forum.xda-developers.com/attachment.php?s=9f1870536cb530a1346794b6ef629e90&attachmentid=2680937&d=1397258016

2  Drag the zip file into your running virtual device and click ok

3  restart Genymotion virtual device


问:
User defined Exception doubt
I have this exception class

```<code>class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')
</code>```

and the exception comes as

```<code>Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'
</code>```

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

答:
my problem now is that say I want to display 4 and a string hello along with the error how to do so......

You should put your code inside a try/except code to handle an Exception. Here is an example:
```
try:
    if something:
       raise Value('4')
    # do something else here
except Value as valueException:
    print "Hello, it raises an Value exception '%s'" % valueException.message
```

Title: User defined Exception doubt

Body:
I have this exception class

class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')

and the exception comes as

Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

Body:
my problem now is that say I want to display 4 and a string hello along with the error how to do so......

You should put your code inside a try/except code to handle an Exception. Here is an example:

try:
    if something:
       raise Value('4')
    # do something else here
except Value as valueException:
    print "Hello, it raises an Value exception '%s'" % valueException.message


问:
Geometry.center() not applied
I got a BufferGeometry that I change vertices/colors on from time to time. I do this by creating a new buffergeometry if I need to allocate more space for vertices. If not, I will reuse the one I already have but changing drawRange of it.

My problem is that when I just update a BufferGeometry with new vertices as in the first "if(this.mesh != undefined && this.prev..." part of the code below, my geometry doesn't get center() anymore. Even though I explicitly apply it. If the geometry just need an update later it get's centered again. How can I solve this? (using the code below makes the object flickering between center() and non-center geometry position). Note that mesh.position has nothing to do with this, it's the same all the time.

```<code>if(this.mesh != undefined && this.prev_len > vertices.length) {
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry.setDrawRange(0, vertices.length);
        this.geometry.attributes.position.needsUpdate = true;
        this.geometry.attributes.color.needsUpdate = true;
        this.geometry.computeVertexNormals();

        // Here seems to be the problem. center() is not actually applied?
        // I've debuged three.js and it seems to perform the translate() in center() function. But it seems to be changed afterwards?
        this.mesh.geometry.center();

    } else {
        this.v = new THREE.BufferAttribute(new Float32Array(vertices.length * 3), 3);
        this.c = new THREE.BufferAttribute(new Float32Array(colors.length * 3), 3);
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry = new THREE.BufferGeometry();
        this.geometry.dynamic = true;
        this.geometry.addAttribute('position', this.v);
        this.geometry.addAttribute('color', this.c);
        this.geometry.attributes.position.dynamic = true;
        this.geometry.attributes.color.dynamic = true;
        this.geometry.computeVertexNormals();
        this.prev_len = vertices.length;

        if(this.mesh == undefined) {
            this.mesh = new THREE.Mesh(this.geometry, this.material);
            this.mesh.position.set(
                                   this.from_x,
                                   this.from_y,
                                   this.from_z
            );
            scene.add(this.mesh);
            this.geometry.center();

        } else {
            // This works fine, the geometry becomes centered.
            this.mesh.geometry = this.geometry;
            this.geometry.center();
        }

    }
</code>```

答:
It seems that the problem is center() is not applied to an geometry that has been updated with new positions. And calculation of a new center() for an updated BufferGeometry will create a false offset that's reflected by the changes to the position attribute.

My solution, that works, is to save the offset that is returned from geometry.center() and apply it for updated geometries.

```<code>this.offset = this.geometry.center();
</code>```

Then apply it manually when just updating position, like this:

```<code>this.geometry.translate(this.offset.x, this.offset.y, this.offset.z);
</code>```

Not sure if this is a "correct" solution or just a workaround. But works for me.

Title: Geometry.center() not applied

Body:
I got a BufferGeometry that I change vertices/colors on from time to time. I do this by creating a new buffergeometry if I need to allocate more space for vertices. If not, I will reuse the one I already have but changing drawRange of it.

My problem is that when I just update a BufferGeometry with new vertices as in the first "if(this.mesh != undefined && this.prev..." part of the code below, my geometry doesn't get center() anymore. Even though I explicitly apply it. If the geometry just need an update later it get's centered again. How can I solve this? (using the code below makes the object flickering between center() and non-center geometry position). Note that mesh.position has nothing to do with this, it's the same all the time.

if(this.mesh != undefined && this.prev_len > vertices.length) {
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry.setDrawRange(0, vertices.length);
        this.geometry.attributes.position.needsUpdate = true;
        this.geometry.attributes.color.needsUpdate = true;
        this.geometry.computeVertexNormals();

        // Here seems to be the problem. center() is not actually applied?
        // I've debuged three.js and it seems to perform the translate() in center() function. But it seems to be changed afterwards?
        this.mesh.geometry.center();

    } else {
        this.v = new THREE.BufferAttribute(new Float32Array(vertices.length * 3), 3);
        this.c = new THREE.BufferAttribute(new Float32Array(colors.length * 3), 3);
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry = new THREE.BufferGeometry();
        this.geometry.dynamic = true;
        this.geometry.addAttribute('position', this.v);
        this.geometry.addAttribute('color', this.c);
        this.geometry.attributes.position.dynamic = true;
        this.geometry.attributes.color.dynamic = true;
        this.geometry.computeVertexNormals();
        this.prev_len = vertices.length;

        if(this.mesh == undefined) {
            this.mesh = new THREE.Mesh(this.geometry, this.material);
            this.mesh.position.set(
                                   this.from_x,
                                   this.from_y,
                                   this.from_z
            );
            scene.add(this.mesh);
            this.geometry.center();

        } else {
            // This works fine, the geometry becomes centered.
            this.mesh.geometry = this.geometry;
            this.geometry.center();
        }

    }

Body:
It seems that the problem is center() is not applied to an geometry that has been updated with new positions. And calculation of a new center() for an updated BufferGeometry will create a false offset that's reflected by the changes to the position attribute.

My solution, that works, is to save the offset that is returned from geometry.center() and apply it for updated geometries.

this.offset = this.geometry.center();

Then apply it manually when just updating position, like this:

this.geometry.translate(this.offset.x, this.offset.y, this.offset.z);

Not sure if this is a "correct" solution or just a workaround. But works for me.


问:
React CSS Transition Group
Can someone help me with slide up/down transition that I am trying to create for a
fullscreen popup.
I am unable to get the desired ease in slide up effect using CSSTransitionGroup.
The code example can be found here

Any help would be much appreciated.
Thanks

答:
Theres a few issues at play here, all easy to fix:

1) You must use import CSSTransitionGroup from 'react-addons-css-transition-group rather than just the plain old transition group package - that only adds lifecycle hooks, which the CSS version uses to add/remove classes

2) The most important thing to understand is what actually triggers an animation. CSS transition groups works by applying transition classes to child  elements that are entering and exiting its children (kept track of by a key), but in order to do so the CSSTransitionGroup must exist already, it is the children that conditionally exist or not. In your code, by only adding the CSSTransition group itself when the popup state is open, means that it cannot monitor its children so it all just appears and dissappears with no transition. Therefore you must make CSSTransition group always be rendered, but then conditionally add the popup div as a child when the state is open...

```<code>const PopUp = ({ state, close }) => {

  return (
      <CSSTransitionGroup
            transitionName="pop"
            transitionAppear={true}
            transitionAppearTimeout={2000}
            transitionEnterTimeout={2000}
            transitionLeaveTimeout={300}
            component="div"
            >
           {state.open && <div key="popup"
              style={{
                width: window.innerWidth,
                position: 'fixed',
                left: 0,
                top: 0,
                overflowX: 'hidden',
                backgroundColor: 'white',
                zIndex: '999',
              }}
            >
              <span>I am a popup</span>
              <FlatButton label="Close" onClick={close} />
            </div>
           }
      </CSSTransitionGroup>
  );
};
</code>```

3) You can see from the above I have also added the appear in case the animation is to happen on first mount -  in your case its fine as has already rendered in the closed state first but worth noting here for future reference

4) Finally you are animating on the height property in CSS, but you have set the height explicitly to height: window.innerHeight in your style property. This will translate to the style tag in HTML, which always takes precedence over any CSS stylesheet rules, so your animated height always loses out to it. Remove that and your animation works - however the height will not be set after the animation ends. You can fix this by keeping your height: window.innerHeight and forcing the CSS defined heights to override it with the height: 100vh !important; syntax (although this is in fact bad CSS practice as causes its own headaches when you create more complex stylesheets, as it stops you being able to use specificity)

Here is a working version: https://codesandbox.io/s/W7Q8QP56W

For further improvement on this I suggest you either move all your CSS for this component to a stylesheet so they can work overriding each other as normal using specificity and the cascade, or use something like opacity to animate on instead (as the default default is 1 you wont need to set it in your JS style prop) - react will remove the element entirely once the animation is done anyway, so you wont be blocked interacting with the page when its closed so you are free to hard code it to the full page height

Title: React CSS Transition Group

Body:
Theres a few issues at play here, all easy to fix:

1) You must use import CSSTransitionGroup from 'react-addons-css-transition-group rather than just the plain old transition group package - that only adds lifecycle hooks, which the CSS version uses to add/remove classes

2) The most important thing to understand is what actually triggers an animation. CSS transition groups works by applying transition classes to child  elements that are entering and exiting its children (kept track of by a key), but in order to do so the CSSTransitionGroup must exist already, it is the children that conditionally exist or not. In your code, by only adding the CSSTransition group itself when the popup state is open, means that it cannot monitor its children so it all just appears and dissappears with no transition. Therefore you must make CSSTransition group always be rendered, but then conditionally add the popup div as a child when the state is open...

const PopUp = ({ state, close }) => {

  return (
      <CSSTransitionGroup
            transitionName="pop"
            transitionAppear={true}
            transitionAppearTimeout={2000}
            transitionEnterTimeout={2000}
            transitionLeaveTimeout={300}
            component="div"
            >
           {state.open && <div key="popup"
              style={{
                width: window.innerWidth,
                position: 'fixed',
                left: 0,
                top: 0,
                overflowX: 'hidden',
                backgroundColor: 'white',
                zIndex: '999',
              }}
            >
              <span>I am a popup</span>
              <FlatButton label="Close" onClick={close} />
            </div>
           }
      </CSSTransitionGroup>
  );
};

3) You can see from the above I have also added the appear in case the animation is to happen on first mount -  in your case its fine as has already rendered in the closed state first but worth noting here for future reference

4) Finally you are animating on the height property in CSS, but you have set the height explicitly to height: window.innerHeight in your style property. This will translate to the style tag in HTML, which always takes precedence over any CSS stylesheet rules, so your animated height always loses out to it. Remove that and your animation works - however the height will not be set after the animation ends. You can fix this by keeping your height: window.innerHeight and forcing the CSS defined heights to override it with the height: 100vh !important; syntax (although this is in fact bad CSS practice as causes its own headaches when you create more complex stylesheets, as it stops you being able to use specificity)

Here is a working version: https://codesandbox.io/s/W7Q8QP56W

For further improvement on this I suggest you either move all your CSS for this component to a stylesheet so they can work overriding each other as normal using specificity and the cascade, or use something like opacity to animate on instead (as the default default is 1 you wont need to set it in your JS style prop) - react will remove the element entirely once the animation is done anyway, so you wont be blocked interacting with the page when its closed so you are free to hard code it to the full page height


问:
Have narrowing conversion error in C++ arm from Android NDK
I have narrowing conversion error in C++ arm from Android NDK.

Have a following code:

```<code>int16_t ax = li.A.x, ay = li.A.y;
int16_t bx = li.B.x, by = li.B.y;
Rect16 rcA = { ax - 8, ay - 8, ax + 8, ay + 8 };
Rect16 rcB = { bx - 8, by - 8, bx + 8, by + 8 };
</code>```

And get this error, when try to compile:

```<code>error: narrowing conversion of '(((int)ay) + -0x00000000000000008)' from 'int' to 'int16_t' inside { }
</code>```

Rect16 struct:

```<code>typedef struct tagRect16 {
    int16_t left, top, right, bottom;
} Rect16;
</code>```

答: Your problem stems from the fact that in the expression ay - 8 the compiler says you are calling int operator-(int, int).  You need to tell the compiler that 8 is a short, using a method like in this question.

Body:
I have narrowing conversion error in C++ arm from Android NDK.

Have a following code:

int16_t ax = li.A.x, ay = li.A.y;
int16_t bx = li.B.x, by = li.B.y;
Rect16 rcA = { ax - 8, ay - 8, ax + 8, ay + 8 };
Rect16 rcB = { bx - 8, by - 8, bx + 8, by + 8 };

And get this error, when try to compile:

error: narrowing conversion of '(((int)ay) + -0x00000000000000008)' from 'int' to 'int16_t' inside { }

Rect16 struct:

typedef struct tagRect16 {
    int16_t left, top, right, bottom;
} Rect16;


问:
Swift - Whitespace count in a string
How do you get the count of the empty space within text?

It would be more helpful to me if explained with an example.

答:
You can either use componentsSeparatedBy or filter function like

```<code>let array = string.components(separatedBy:" ")
let spaceCount = array.count - 1
</code>```

or

```<code>let spaceCount = string.filter{$0 == " "}.count
</code>```

Title: Swift - Whitespace count in a string

Body:
You can either use componentsSeparatedBy or filter function like

let array = string.components(separatedBy:" ")
let spaceCount = array.count - 1

or

let spaceCount = string.filter{$0 == " "}.count


问:
rescue_from not working in ActiveJob
My class:

```<code>class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def self.call
    um = UserMedia.call('81274092340912873',100)
  end

  def destroy_user
    print "User to be destroyed"
  end

end
</code>```

UserMedia.call('81274092340912873',100) raises UserMediaException::UserNotFound exception.

I'm trying to test rescue_from, but I'm not able to make it work. The message "User to be destroyed" never gets printed.

The custom exception that I'm rescuing (UserMediaException::UserNotFound) inherits from StandardError.

Any idea why this happens?

答:
According to ActiveJobs documentation, all jobs class must have their business logic in a perform instance method.

Your code should be :

```<code>class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def perform
    um = UserMedia.call('81274092340912873',100)
  end

  private

  def destroy_user
    print "User to be destroyed"
  end

end
</code>```

After you can use your jobs with perform_later to enqueue it or perform_now to execute it directly :

```<code>TestUpdateJob.perform_later # Enqueue your job and execute it asynchronously
TestUpdateJob.perform_now # Execute your job now
</code>```

Title: rescue_from not working in ActiveJob

Body:
My class:

class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def self.call
    um = UserMedia.call('81274092340912873',100)
  end

  def destroy_user
    print "User to be destroyed"
  end

end

UserMedia.call('81274092340912873',100) raises UserMediaException::UserNotFound exception.

I'm trying to test rescue_from, but I'm not able to make it work. The message "User to be destroyed" never gets printed.

The custom exception that I'm rescuing (UserMediaException::UserNotFound) inherits from StandardError.

Any idea why this happens?

Body:
According to ActiveJobs documentation, all jobs class must have their business logic in a perform instance method.

Your code should be :

class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def perform
    um = UserMedia.call('81274092340912873',100)
  end

  private

  def destroy_user
    print "User to be destroyed"
  end

end

After you can use your jobs with perform_later to enqueue it or perform_now to execute it directly :

TestUpdateJob.perform_later # Enqueue your job and execute it asynchronously
TestUpdateJob.perform_now # Execute your job now