问:
(iOS) crash when view controller property is set
I've problems passing data to a new view controller.

I've two VC. In the "FirstVC" there is a table view with dynamic prototypes cells. The generic cell contains a label and a button and it's assigned to its own class "GenericCell". I want to pass to the SecondVC the text of the cell label when I press the button, but the app crashes with errors:

Unknown class _TtC13testTableView37SecondVC in Interface Builder file.

UIViewController setMyString:]: unrecognized selector sent to instance 0x7fa05e418110

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setMyString:]: unrecognized selector sent to instance 0x7fc8add05710

I tried:

To use the segue (with prepareForSegue method) outside the getText method

1a. Pushing the VC from the outside of the getText method

Implementing and calling set/get method of myString

Adding attributes to myString property

but the app crashes the same.

GenericCell.h

```<code>#import <UIKit/UIKit.h>
@protocol MyCellDelegate
-(void)getText:(NSString *)text;
@end

@interface GenericCell: UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel * label;
@property (assign, nonatomic) id <MyCellDelegate> delegate;
@end
</code>```

GenericCell.m

```<code>#import "GenericCell.h"
@interface GenericCell()
@end

@implementation GenericCell

- (IBAction)buttonPressed {
    if (self.delegate) {
        [self.delegate getText:self.label.text];
    }
}
@end
</code>```

FirstVC.m

```<code>#import "FirstVC.h"
#import "GenericCell.h"
#import "SecondVC.h"

@interface FirstVC() <UITableViewDataSource,UITableViewDelegate, MyCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSString * idToPass;
@end

@implementation FirstVC

NSMutableArray<NSString *> *array;

- (void)viewDidLoad {

    array = [[NSMutableArray alloc]initWithObjects:@"0x22", @"0x11", @"0x24", nil];

    [super viewDidLoad];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=100;
}

-(void)getText:(NSString *)text {
   self.idToPass = text;

   SecondVC * secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
   secondVC.myString = self.idToPass;
   [[self navigationController] pushViewController:secondVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return array.count;
}

- (GenericCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    GenericCell * cell = [[self tableView]dequeueReusableCellWithIdentifier:@"GenericCell" forIndexPath:indexPath];

    cell.delegate = self;
    cell.label.text = [array objectAtIndex:indexPath.row];
    return cell;
}
@end
</code>```

SecondVC.h

```<code>#import <UIKit/UIKit.h>
@interface SecondVC : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;
@property NSString * myString;
@end
</code>```

SecondVC.m

```<code>#import "SecondVC.h"

@interface SecondVC ()
@end

@implementation SecondVC

- (void)viewDidLoad {
    self.label.text = self.myString;
    [super viewDidLoad];
}

@end
</code>```

The "idToPass" is set correctly with delegation.

答:
In getText method you assign text to myProperty instead myString...

It should be:

```<code>secondVC.myString = self.idToPass;
</code>```

Body:
I've problems passing data to a new view controller.

I've two VC. In the "FirstVC" there is a table view with dynamic prototypes cells. The generic cell contains a label and a button and it's assigned to its own class "GenericCell". I want to pass to the SecondVC the text of the cell label when I press the button, but the app crashes with errors:

Unknown class _TtC13testTableView37SecondVC in Interface Builder file.

UIViewController setMyString:]: unrecognized selector sent to instance 0x7fa05e418110

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setMyString:]: unrecognized selector sent to instance 0x7fc8add05710

I tried:

To use the segue (with prepareForSegue method) outside the getText method

1a. Pushing the VC from the outside of the getText method

Implementing and calling set/get method of myString

Adding attributes to myString property

but the app crashes the same.

GenericCell.h

#import <UIKit/UIKit.h>
@protocol MyCellDelegate
-(void)getText:(NSString *)text;
@end

@interface GenericCell: UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel * label;
@property (assign, nonatomic) id <MyCellDelegate> delegate;
@end

GenericCell.m

#import "GenericCell.h"
@interface GenericCell()
@end

@implementation GenericCell

- (IBAction)buttonPressed {
    if (self.delegate) {
        [self.delegate getText:self.label.text];
    }
}
@end

FirstVC.m

#import "FirstVC.h"
#import "GenericCell.h"
#import "SecondVC.h"

@interface FirstVC() <UITableViewDataSource,UITableViewDelegate, MyCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSString * idToPass;
@end

@implementation FirstVC

NSMutableArray<NSString *> *array;

- (void)viewDidLoad {

    array = [[NSMutableArray alloc]initWithObjects:@"0x22", @"0x11", @"0x24", nil];

    [super viewDidLoad];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=100;
}

-(void)getText:(NSString *)text {
   self.idToPass = text;

   SecondVC * secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
   secondVC.myString = self.idToPass;
   [[self navigationController] pushViewController:secondVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return array.count;
}

- (GenericCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    GenericCell * cell = [[self tableView]dequeueReusableCellWithIdentifier:@"GenericCell" forIndexPath:indexPath];

    cell.delegate = self;
    cell.label.text = [array objectAtIndex:indexPath.row];
    return cell;
}
@end

SecondVC.h

#import <UIKit/UIKit.h>
@interface SecondVC : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;
@property NSString * myString;
@end

SecondVC.m

#import "SecondVC.h"

@interface SecondVC ()
@end

@implementation SecondVC

- (void)viewDidLoad {
    self.label.text = self.myString;
    [super viewDidLoad];
}

@end

The "idToPass" is set correctly with delegation.

Body:
In getText method you assign text to myProperty instead myString...

It should be:

secondVC.myString = self.idToPass;


来源: stackexchange

问:
How to get the real CaptureElement size?
I'm using CaptureElement to display the output of the camera.

Depending on how the user resizes the window, there can be black borders on either left/right or top/bottom of the camera output.

I'd like to get the size of the camera output WITHOUT including the black borders. I've tried many height/width/size fields that CaptureElement has, including ActualWidth, RenderSize.Width etc. but none of them returns the real width/height of the camera.

If the black border is of width 100px, the actual camera output of width 300px, the width fields will return 2*100px+300px = 500px. They all include the black border.

How do I get only the width and height of the actual camera display?

答:
I've used Sunteen's answer to get the resolution of the camera. Then, I calculated both the camera resolution ratio and the video preview output ratio. Using this information, I could calculate the actual size of the video output.

Here's the solution.

```<code>var props = (VideoEncodingProperties) _mediaCapture.VideoDeviceController
    .GetMediaStreamProperties(MediaStreamType.VideoPreview);

double cameraWidth = props.Width;
double cameraHeight = props.Height;

double previewOutputWidth = CameraPreview.ActualWidth;
double previewOutputHeight =  CameraPreview.ActualHeight;

double cameraRatio = cameraWidth / cameraHeight;
double previewOutputRatio = previewOutputWidth / previewOutputHeight;

double actualWidth = (cameraRatio <= previewOutputRatio) ?
    previewOutputHeight * cameraRatio
    : previewOutputWidth;
double actualHeight = (cameraRatio <= previewOutputRatio) ?
    previewOutputHeight
    : previewOutputWidth / cameraRatio;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've used Sunteen's answer to get the resolution of the camera. Then, I calculated both the camera resolution ratio and the video preview output ratio. Using this information, I could calculate the actual size of the video output.

Here's the solution.

var props = (VideoEncodingProperties) _mediaCapture.VideoDeviceController
    .GetMediaStreamProperties(MediaStreamType.VideoPreview);

double cameraWidth = props.Width;
double cameraHeight = props.Height;

double previewOutputWidth = CameraPreview.ActualWidth;
double previewOutputHeight =  CameraPreview.ActualHeight;

double cameraRatio = cameraWidth / cameraHeight;
double previewOutputRatio = previewOutputWidth / previewOutputHeight;

double actualWidth = (cameraRatio <= previewOutputRatio) ?
    previewOutputHeight * cameraRatio
    : previewOutputWidth;
double actualHeight = (cameraRatio <= previewOutputRatio) ?
    previewOutputHeight
    : previewOutputWidth / cameraRatio;


问:
How to populate dropdown menu from sql table in PHP
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you</p>

```<code> <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
            mysqli_query($db, $sql);

            echo "<select name='unitid'>";
            while ($row = mysql_fetch_array($sql)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
            }
            echo "</select>";
            ?>
</code>```

答:
```<code>        <?php
         $db = mysqli_connect('localhost', 'root', '', 'registration');
          $sql = "Select unitid, unitname from unit where unitname=\"".$unitname."\"";

        $rows = array();
        $return = mysqli_query($db, $sql);
        while($row = mysqli_fetch_array($return, MYSQLI_ASSOC))
            $rows [] = $row;
        echo "<select name='unitid'>";
        for($i=0; $i<count($rows); $i++)
           echo "<option value='".$rows['unitid']."'> ".$rows['unitname']."</option>";

        echo "</select>";
        ?>
</code>```

you didn't fetch the array correctly, so your query basically returned an empty array. You also wrote a wrong query. This solution should work fine

Body:
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you

 <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
            mysqli_query($db, $sql);

            echo "<select name='unitid'>";
            while ($row = mysql_fetch_array($sql)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
            }
            echo "</select>";
            ?>

Body:
        <?php
         $db = mysqli_connect('localhost', 'root', '', 'registration');
          $sql = "Select unitid, unitname from unit where unitname=\"".$unitname."\"";

        $rows = array();
        $return = mysqli_query($db, $sql);
        while($row = mysqli_fetch_array($return, MYSQLI_ASSOC))
            $rows [] = $row;
        echo "<select name='unitid'>";
        for($i=0; $i<count($rows); $i++)
           echo "<option value='".$rows['unitid']."'> ".$rows['unitname']."</option>";

        echo "</select>";
        ?>

you didn't fetch the array correctly, so your query basically returned an empty array. You also wrote a wrong query. This solution should work fine


问:
Repeat scroll function while mouse hovering over element
is there a way how to repeat a function as long as the cursor is hovering over a specific dom element? I want to perform a scroll operation as long as long as the user is hovering over an arrow with an optional timeout. This task should be fullfillled without using jquery!

Here is my current code:

```<code>public overDown() {
    this.tabList.nativeElement.scrollBy(0, 10);
    const element = this.tabList.nativeElement;
    if(element.offsetHeight + element.scrollTop >= element.scrollHeight) {
      console.log('Bottom Limit');
    }
  }

  public overUp() {
    this.tabList.nativeElement.scrollBy(0, -10);
    const element = this.tabList.nativeElement;
    if(element.scrollTop === 0) {
      console.log('Top Limit');
    }
  }
</code>```

And the HTML

```<code><div class="list-arrow-up" (mouseover)="overUp()">▲</div>
  <ul #tabList>
    <li><!--several List items --></span></li>
  </ul>
  <div class="list-arrow-down" (mouseover)="overDown()">▼</div>
</code>```

答:
I would use a different aproach.
I would execute a function when hovering over this specific DOM element, that scrolls down to the bottom, lasting x seconds.
And then I would execute another function that stops this scroll down when cursor goes away from this element.
You can improve performance by checking if you are already at the bottom of the page befor executing scroll down.</p>

Body:
is there a way how to repeat a function as long as the cursor is hovering over a specific dom element? I want to perform a scroll operation as long as long as the user is hovering over an arrow with an optional timeout. This task should be fullfillled without using jquery!

Here is my current code:

public overDown() {
    this.tabList.nativeElement.scrollBy(0, 10);
    const element = this.tabList.nativeElement;
    if(element.offsetHeight + element.scrollTop >= element.scrollHeight) {
      console.log('Bottom Limit');
    }
  }

  public overUp() {
    this.tabList.nativeElement.scrollBy(0, -10);
    const element = this.tabList.nativeElement;
    if(element.scrollTop === 0) {
      console.log('Top Limit');
    }
  }

And the HTML

▲

▼


问:
Scraping a website to download all documents on it with BeautifulSoup throws IOError

Hi, I would like to download all the files that are published on the following website (https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer) via a Python, Julia or whatever language script. It used to be a http website where BeautifulSoup was working fine; it is now a https website on my code is unfortunately not working anymore.

All the files I desire to download are in a 'a' tag and are of class 'download'. Hence the line in the code that is not working is the following:

```<code>fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)
</code>```

which raises the following error:

```<code>raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 403, 'Forbidden', <httplib.HTTPMessage instance at 0x104f79e60>)
</code>```

After some research on the net, I have not been able to find any  information on how I could scrap the document on an https website, would anyone have a suggestion?

Thank you in advance for your answers!

Julien

```<code>import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-
operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):
  document_name = document["title"]
  document_url = mainLocation+document["href"]
  fileDownloader.retrieve(document_url, "files/"+document_name)
</code>```

答:
It's not a https issue, it's just that the page you're trying to scrape has some file access restricted. It's good practice to handle exceptions when you expect them. In this case all of the file links may be broken or not accessible.

Try handling the exception like this:

```<code>import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):

    document_name = document["title"]
    document_url = mainLocation+document["href"]
    try:
        fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)
    except IOError as e:
        print('failed to download: {}'.format(document_url))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi, I would like to download all the files that are published on the following website (https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer) via a Python, Julia or whatever language script. It used to be a http website where BeautifulSoup was working fine; it is now a https website on my code is unfortunately not working anymore.

All the files I desire to download are in a 'a' tag and are of class 'download'. Hence the line in the code that is not working is the following:

fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)

which raises the following error:

raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 403, 'Forbidden', <httplib.HTTPMessage instance at 0x104f79e60>)

After some research on the net, I have not been able to find any  information on how I could scrap the document on an https website, would anyone have a suggestion?

Thank you in advance for your answers!

Julien

import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-
operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):
  document_name = document["title"]
  document_url = mainLocation+document["href"]
  fileDownloader.retrieve(document_url, "files/"+document_name)

Body:
It's not a https issue, it's just that the page you're trying to scrape has some file access restricted. It's good practice to handle exceptions when you expect them. In this case all of the file links may be broken or not accessible.

Try handling the exception like this:

import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):

    document_name = document["title"]
    document_url = mainLocation+document["href"]
    try:
        fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)
    except IOError as e:
        print('failed to download: {}'.format(document_url))


问:
localhost refuses access on port during Docker tutorial
I'm currently getting started with Docker on a Linux VM provided by my university. To get started with docker I'm doing their tutorial (https://docs.docker.com/get-started/part2/#run-the-app). After creating the files the tutorial says to use the command: docker run -p 4000:80 <name of container>

This should host the container on http://localhost:4000 because port 80 is mapped to 4000. But unfortunately when I go to localhost this is shown:

This site is not available.
  Localhost has refused the connection.

Thanks for the help!

答: If you are running docker on a remote VM and want to connect from your machine browser, you need to replace localhost either with the VM hostname or IP. So connect to http://hostname:8080


问:
ggplot2 pie chart bad position of labels

Sample data

```<code>data <- data.frame(Country = c("Mexico","USA","Canada","Chile"), Per = c(15.5,75.3,5.2,4.0))
</code>```

I tried set position of labels.

```<code>ggplot(data =data) +
geom_bar(aes(x = "", y = Per, fill = Country), stat = "identity", width = 1) +
coord_polar("y", start = 0) +
theme_void()+
geom_text(aes(x = 1.2, y = cumsum(Per), label = Per))
</code>```

But pie chart actually look like:

答:
You have to sort the data before calculating the cumulative sum. Then, you can optimize label position, e.g. by subtracting half of Per:

```<code>library(tidyverse)
data %>%
  arrange(-Per) %>%
  mutate(Per_cumsum=cumsum(Per)) %>%
ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(x=1,y = Per_cumsum-Per/2, label=Per)) +
  coord_polar("y", start=0) +
  theme_void()
</code>```

PS:  geom_col uses stat_identity by default: it leaves the data as is.

Or simply use position_stack

```<code>data %>%
  ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(label = Per), position = position_stack(vjust = 0.5))+
  coord_polar(theta = "y") +
  theme_void()
</code>```

From the help:

```<code># To place text in the middle of each bar in a stacked barplot, you
# need to set the vjust parameter of position_stack()
</code>```

Body:
Sample data

data <- data.frame(Country = c("Mexico","USA","Canada","Chile"), Per = c(15.5,75.3,5.2,4.0))

I tried set position of labels.

ggplot(data =data) +
geom_bar(aes(x = "", y = Per, fill = Country), stat = "identity", width = 1) +
coord_polar("y", start = 0) +
theme_void()+
geom_text(aes(x = 1.2, y = cumsum(Per), label = Per))

But pie chart actually look like:

Body:
You have to sort the data before calculating the cumulative sum. Then, you can optimize label position, e.g. by subtracting half of Per:

library(tidyverse)
data %>%
  arrange(-Per) %>%
  mutate(Per_cumsum=cumsum(Per)) %>%
ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(x=1,y = Per_cumsum-Per/2, label=Per)) +
  coord_polar("y", start=0) +
  theme_void()

PS:  geom_col uses stat_identity by default: it leaves the data as is.

Or simply use position_stack

data %>%
  ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(label = Per), position = position_stack(vjust = 0.5))+
  coord_polar(theta = "y") +
  theme_void()

From the help:

# To place text in the middle of each bar in a stacked barplot, you
# need to set the vjust parameter of position_stack()


问:
Access request headers in doPost()
To verify a webhook i need to get a parameter from the request headers. So far i couldn't find any information if it is actually possible to access these headers within Apps Scripts. Only thing that works so far is accessing the body of the post request.</p>

```<code>function doPost(e) {
    // something like this
    var headerParam = e.headers['Content-Type'];
    // ...
}
</code>```

答:
Unfortunately this is not currently possible with doPost() triggers. However there is a pending feature request for this issue on Google's issue tracker. If you'd like to see this feature supported please leave a comment (on the issue thread linked below) and be sure to STAR the issue at the following link:

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

The workaround I currently use is to leverage Google Cloud Functions. I wrote a related article about it here.

Title: Access request headers in doPost()

Body:
To verify a webhook i need to get a parameter from the request headers. So far i couldn't find any information if it is actually possible to access these headers within Apps Scripts. Only thing that works so far is accessing the body of the post request.

function doPost(e) {
    // something like this
    var headerParam = e.headers['Content-Type'];
    // ...
}


问:
C - int not-equal to printf?
What this C statement does?

```<code>i=!({ printf("%d\n",r); });
</code>```

i and r are integers.

I'm trying to parse it using pycparser which doesn't recognize it and raises an error:

pycparser.plyparser.ParseError: :7:6: before: {

Thanks

答:
This is not standard C, but a GCC statement expression extension, which allows putting blocks in expressions and returns the value of the last statement in the block.

Because the block here has only one statement which is itself an expression, this is equivalent to:

```<code>i = !printf("%d\n",r);
</code>```

This sets i to 1 if printf returned 0 (i.e. it succeeded but didn't print any characters), or 0 otherwise. Since this printf will always print at least two characters when it succeeds, i will always be 0.

Title: C - int not-equal to printf?

Body:
What this C statement does?

i=!({ printf("%d\n",r); });

i and r are integers.

I'm trying to parse it using pycparser which doesn't recognize it and raises an error:

pycparser.plyparser.ParseError: :7:6: before: {

Thanks

Body:
This is not standard C, but a GCC statement expression extension, which allows putting blocks in expressions and returns the value of the last statement in the block.

Because the block here has only one statement which is itself an expression, this is equivalent to:

i = !printf("%d\n",r);

This sets i to 1 if printf returned 0 (i.e. it succeeded but didn't print any characters), or 0 otherwise. Since this printf will always print at least two characters when it succeeds, i will always be 0.


问:
How to keep imports neat in Django?
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

```<code>from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse
</code>```

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?

答:
You can also check how they do it at Google:

http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Imports

ContentLicense: CC BY-SA 2.5

Title: How to keep imports neat in Django?

Body:
This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.

I'm looking for  a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?

Update

On request, here is an example from one of my views.py files.

from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from django.core.urlresolvers import reverse

from models import Listing, LocationData

from django.template import RequestContext

import sys
import urllib
if sys.version_info <= (2, 5):
    import simplejson as json
else:
    import json

import forms
import sanitize

from models import RentListing, VacationListing, SaleListing

from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory

from django.core.urlresolvers import reverse

which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Keeping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.

Is it worth breaking the style guideline of not using the * import for the sake of shorter, more maintainable import sections in the actual file?


问:
Typescript and filter Boolean
Consider following code with strictNullChecks turned on:

```<code>var a: (number | null)[] = [0, 1, 2, 3, null, 4, 5, 6];
var b: { value: number; }[] = a.map(x => x != null && { value: x }).filter(Boolean);
</code>```

It fails to compile due to:

```<code>Type '(false | { value: number; })[]' is not assignable to type '{ value: number; }[]'.
  Type 'false | { value: number; }' is not assignable to type '{ value: number; }'.
    Type 'false' is not assignable to type '{ value: number; }'.
</code>```

But it is absolutely clear, that false will be filtered away by .filter(Boolean).

Same problem with null.

Is there a way (except writing as number[]) to mark that value doesn't contain false or null?

答:
If you really don't want to change the generated JavaScript, and instead prefer to force the TypeScript compiler to recognize that Boolean is serving as a guard against false values, you can do this:

```<code>type ExcludesFalse = <T>(x: T | false) => x is T;
var b: { value: number; }[] = a
  .map(x => x != null && { value: x })
  .filter(Boolean as any as ExcludesFalse);
</code>```

This works because you are asserting that Boolean is a type guard, and because Array.filter() is overloaded to return a narrowed array if the callback is a type guard.

The above (Boolean as any as ExcludesFalse) is the cleanest code I could come up with that both works and doesn't change the generated JavaScript.  The constant Boolean is declared to be an instance of the global BooleanConstructor interface, and you can merge an ExcludesFalse-like type guard signature into BooleanConstructor, but not in a way that allows you to just say .filter(Boolean) and have it work.  You can get fancier with the type guard and try to represent guarding against all falsy values (except NaN) but you don't need that for your example.

Anyway, hope that helps; good luck!

Title: Typescript and filter Boolean

Body:
Consider following code with strictNullChecks turned on:

var a: (number | null)[] = [0, 1, 2, 3, null, 4, 5, 6];
var b: { value: number; }[] = a.map(x => x != null && { value: x }).filter(Boolean);

It fails to compile due to:

Type '(false | { value: number; })[]' is not assignable to type '{ value: number; }[]'.
  Type 'false | { value: number; }' is not assignable to type '{ value: number; }'.
    Type 'false' is not assignable to type '{ value: number; }'.

But it is absolutely clear, that false will be filtered away by .filter(Boolean).

Same problem with null.

Is there a way (except writing as number[]) to mark that value doesn't contain false or null?

Body:
If you really don't want to change the generated JavaScript, and instead prefer to force the TypeScript compiler to recognize that Boolean is serving as a guard against false values, you can do this:

type ExcludesFalse = <T>(x: T | false) => x is T;
var b: { value: number; }[] = a
  .map(x => x != null && { value: x })
  .filter(Boolean as any as ExcludesFalse);

This works because you are asserting that Boolean is a type guard, and because Array.filter() is overloaded to return a narrowed array if the callback is a type guard.

The above (Boolean as any as ExcludesFalse) is the cleanest code I could come up with that both works and doesn't change the generated JavaScript.  The constant Boolean is declared to be an instance of the global BooleanConstructor interface, and you can merge an ExcludesFalse-like type guard signature into BooleanConstructor, but not in a way that allows you to just say .filter(Boolean) and have it work.  You can get fancier with the type guard and try to represent guarding against all falsy values (except NaN) but you don't need that for your example.

Anyway, hope that helps; good luck!


问:
How to perform stable sort over multiple columns?
Imagine i have a data set that contains:

```<code>Date            Id
--------------  ----
11/1/2017       null
11/4/2017       3
11/5/2017       null
11/12/2017      10
null            1
null            2
null            7
null            8
null            9
</code>```

I want the rows ordered so that both columns are increasing.

Using a naïve ORDER BY Date, ID does not do it:

There is an ordering

There is an ordering that satisfies the results of my desired sort order:

the date column is always increasing

the id column value is always increasing

Or course, that's not a unique ordering:

```<code>Date            Id
--------------  ---------------
null            1
11/1/2017       null
null            2
11/4/2017       3
null            7
null            8
null            9
11/5/2017       null
11/12/2017      10
</code>```

A programming language could do it

I know i can accomplish this on the client side. In a functional functional programming language: use a stable sorting algorithm:

A stable sort is one which preserves the original order of the input
  set, where the comparison algorithm does not distinguish between two
  or more items.

Consider a sorting algorithm that sorts cards by rank, but not by
  suit.  The stable sort will guarantee that the original order of cards
  having the same rank is preserved; the unstable sort will not.

Unfortunately i have

9.1 million rows

1.8 GB

of monotonically increasing rows to put in best possible chronological sort order. Obviously i'd prefer to do this on the server - which is well suited to handling large amounts of data.

How can i perform a stable-sort in SQL Server?

Example Data

Example SQL Fiddle

```<code>CREATE TABLE #SortDemo (Date datetime NULL, Id int NULL)

INSERT INTO #SortDemo (Date, Id)
VALUES
    ('20171101', null),
    ('20171104',    3),
    ('20171105', null),
    ('20171112',   10),
    (null,          1),
    (null,          2),
    (null,          7),
    (null,          8),
    (null,          9)

SELECT * FROM #SortDemo
ORDER BY Date, Id
</code>```

答:
It is a solvable problem. You don't have to throw your hands up and say computers cannot be used to solve problems.

Start with the data, and add a new surrogate "Rank" column.

```<code>Date            Id    Rank
--------------  ----  ----
null            7     null
null            1     null
null            9     null
null            2     null
null            8     null
11/1/2017       null  null
11/4/2017       3     null
11/5/2017       null  null
11/12/2017      10    null
11/13/2017      null  null
</code>```

Then seed Rank to the Id:

```<code>UPDATE SortDemo SET Rank = Id
WHERE Id IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  null
11/4/2017       3     3
11/5/2017       null  null
11/12/2017      10    10
11/13/2017      null  null
</code>```

Then for the remaining items items with a Date, we need to assign it to the "next" rank:

```<code>Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  null  <-- 3
11/4/2017       3     3
11/5/2017       null  null  <-- 10
11/12/2017      10    10
11/13/2017      null  null  <-- ?
</code>```

with

```<code>UPDATE SortDemo SET Rank = (
      SELECT MIN(Rank) FROM SortDemo s2
      WHERE s2.Date >= SortDemo.Date)
WHERE SortDemo.Date IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  3    <--
11/4/2017       3     3
11/5/2017       null  10   <--
11/12/2017      10    10
11/13/2017      null  null <-- ?
</code>```

There's also the edge case where there are no items "after" us; which we can fix by going backwards to one the highest previous rank:

```<code>UPDATE SortDemo SET Rank = (
      SELECT MAX(Rank) FROM SortDemo s2
      WHERE s2.Date <= SortDemo.Date)
WHERE SortDemo.Date IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  3
11/4/2017       3     3
11/5/2017       null  10
11/12/2017      10    10
11/13/2017      null  10 <--10
</code>```

And we're done

We can now sort by surrogate Rank, and break ties by sorting by Date:

```<code>SELECT * FROM SortDemo
ORDER BY Rank, Date

Date            Id    Rank
--------------  ----  ----
null            1     1
null            2     2
11/1/2017       null  3
11/4/2017       3     3
null            7     7
null            8     8
null            9     9
11/5/2017       null  10
11/12/2017      10    10
11/13/2017      null  10
</code>```

Solution complete. Sql Fiddle

The answer is in escrow until Monday, so i can give people the opportunity to earn reputation for solving a unique problem.

Body:
Imagine i have a data set that contains:

Date            Id
--------------  ----
11/1/2017       null
11/4/2017       3
11/5/2017       null
11/12/2017      10
null            1
null            2
null            7
null            8
null            9

I want the rows ordered so that both columns are increasing.

Using a naïve ORDER BY Date, ID does not do it:

There is an ordering

There is an ordering that satisfies the results of my desired sort order:

the date column is always increasing

the id column value is always increasing

Or course, that's not a unique ordering:

Date            Id
--------------  ---------------
null            1
11/1/2017       null
null            2
11/4/2017       3
null            7
null            8
null            9
11/5/2017       null
11/12/2017      10

A programming language could do it

I know i can accomplish this on the client side. In a functional functional programming language: use a stable sorting algorithm:

A stable sort is one which preserves the original order of the input
  set, where the comparison algorithm does not distinguish between two
  or more items.

Consider a sorting algorithm that sorts cards by rank, but not by
  suit.  The stable sort will guarantee that the original order of cards
  having the same rank is preserved; the unstable sort will not.

Unfortunately i have

9.1 million rows

1.8 GB

of monotonically increasing rows to put in best possible chronological sort order. Obviously i'd prefer to do this on the server - which is well suited to handling large amounts of data.

How can i perform a stable-sort in SQL Server?

Example Data

Example SQL Fiddle

CREATE TABLE #SortDemo (Date datetime NULL, Id int NULL)

INSERT INTO #SortDemo (Date, Id)
VALUES
    ('20171101', null),
    ('20171104',    3),
    ('20171105', null),
    ('20171112',   10),
    (null,          1),
    (null,          2),
    (null,          7),
    (null,          8),
    (null,          9)

SELECT * FROM #SortDemo
ORDER BY Date, Id

Body:
It is a solvable problem. You don't have to throw your hands up and say computers cannot be used to solve problems.

Start with the data, and add a new surrogate "Rank" column.

Date            Id    Rank
--------------  ----  ----
null            7     null
null            1     null
null            9     null
null            2     null
null            8     null
11/1/2017       null  null
11/4/2017       3     null
11/5/2017       null  null
11/12/2017      10    null
11/13/2017      null  null

Then seed Rank to the Id:

UPDATE SortDemo SET Rank = Id
WHERE Id IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  null
11/4/2017       3     3
11/5/2017       null  null
11/12/2017      10    10
11/13/2017      null  null

Then for the remaining items items with a Date, we need to assign it to the "next" rank:

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  null  <-- 3
11/4/2017       3     3
11/5/2017       null  null  <-- 10
11/12/2017      10    10
11/13/2017      null  null  <-- ?

with

UPDATE SortDemo SET Rank = (
      SELECT MIN(Rank) FROM SortDemo s2
      WHERE s2.Date >= SortDemo.Date)
WHERE SortDemo.Date IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  3    <--
11/4/2017       3     3
11/5/2017       null  10   <--
11/12/2017      10    10
11/13/2017      null  null <-- ?

There's also the edge case where there are no items "after" us; which we can fix by going backwards to one the highest previous rank:

UPDATE SortDemo SET Rank = (
      SELECT MAX(Rank) FROM SortDemo s2
      WHERE s2.Date <= SortDemo.Date)
WHERE SortDemo.Date IS NOT NULL

Date            Id    Rank
--------------  ----  ----
null            7     7
null            1     1
null            9     9
null            2     2
null            8     8
11/1/2017       null  3
11/4/2017       3     3
11/5/2017       null  10
11/12/2017      10    10
11/13/2017      null  10 <--10

And we're done

We can now sort by surrogate Rank, and break ties by sorting by Date:

SELECT * FROM SortDemo
ORDER BY Rank, Date

Date            Id    Rank
--------------  ----  ----
null            1     1
null            2     2
11/1/2017       null  3
11/4/2017       3     3
null            7     7
null            8     8
null            9     9
11/5/2017       null  10
11/12/2017      10    10
11/13/2017      null  10

Solution complete. Sql Fiddle

The answer is in escrow until Monday, so i can give people the opportunity to earn reputation for solving a unique problem.


问:
Custom output of user input in java using scanner
is there any way to get custom output, of user input using scanner?

For Example:

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

public class test {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Choose one of the fruits:\n"+
            "1)Mango\n"+
            "2)Apple\n"+
            "3)Melon\n"+
            "4)Papaya\n");
        String fruit = input.next();
        if (fruit.equals("1") || fruit.equals("Mango")) {

        }
    }
}
</code>```

So when i execute it, this is output

```<code>Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1
</code>```

and it exits...

what i want is

```<code>Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1)Mango Selected
</code>```

On pressing 1 it should print Mango Selected... Well i could have added println for that but i also want to not show 1 or Mango (whatever user entered) instead i want to show my custom message..

How to do it?

答:
I'd store your fruits in an array, and print the option based on the user's input from said array.

```<code>String[] list = new String[]{"Mango", "Apple", "Melon", "Papaya"};
</code>```

Print them first to the console:

```<code>System.out.println(Arrays.toString(list));
</code>```

Then get and simply print the user's option:

```<code>System.out.println("Choose a fruit:");
int fruit = input.nextInt();
System.out.println(list[fruit - 1] + " selected.");
</code>```

Try it online!

Body:
is there any way to get custom output, of user input using scanner?

For Example:

import java.util.Scanner;

public class test {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Choose one of the fruits:\n"+
            "1)Mango\n"+
            "2)Apple\n"+
            "3)Melon\n"+
            "4)Papaya\n");
        String fruit = input.next();
        if (fruit.equals("1") || fruit.equals("Mango")) {

        }
    }
}

So when i execute it, this is output

Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1

and it exits...

what i want is

Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1)Mango Selected

On pressing 1 it should print Mango Selected... Well i could have added println for that but i also want to not show 1 or Mango (whatever user entered) instead i want to show my custom message..

How to do it?

Body:
I'd store your fruits in an array, and print the option based on the user's input from said array.

String[] list = new String[]{"Mango", "Apple", "Melon", "Papaya"};

Print them first to the console:

System.out.println(Arrays.toString(list));

Then get and simply print the user's option:

System.out.println("Choose a fruit:");
int fruit = input.nextInt();
System.out.println(list[fruit - 1] + " selected.");

Try it online!


问:
Why doesn't this code work? Javascript if statement, else if statement
This is a javascript code, and I wanted to make it like:
if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question."
But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question."
help!</p>

```<code>var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}
</code>```

答:
Ok, so the problem is in line

```<code>if(id || "yes" || "no")
</code>```

You check whteher the id variable exist or string "yes" exist or string "no" exist. So it is allways true.

If you want to check if string contains some value you can do it either by regular expression (more) or simply by indexOf eg:

var id;

id = prompt("Are you happy?");

if (id == "yes") {

  alert("That's cool.");

} else if(id == "no") {

  alert("I'll make you happy.");

} else if(id.indexOf('yes') >= 0 || id.indexOf('no') >= 0) {

  alert("Type only yes or no, without any extra texts.");

} else {

  alert("you didn't even answer the question.");

}```

Regards, KJ

Body:
This is a javascript code, and I wanted to make it like:
if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question."
But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question."
help!

var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}

Body:
Ok, so the problem is in line

if(id || "yes" || "no")

You check whteher the id variable exist or string "yes" exist or string "no" exist. So it is allways true.

If you want to check if string contains some value you can do it either by regular expression (more) or simply by indexOf eg:

var id;

id = prompt("Are you happy?");

if (id == "yes") {

  alert("That's cool.");

} else if(id == "no") {

  alert("I'll make you happy.");

} else if(id.indexOf('yes') >= 0 || id.indexOf('no') >= 0) {

  alert("Type only yes or no, without any extra texts.");

} else {

  alert("you didn't even answer the question.");

}

Regards, KJ


问:
How can I stop the programme when user enters "stop" (c# console)
the question with image

This is my code and I explained everything in the code.

```<code>Console.Write("If you write stop program will stop.");
        string a;
        string b = "stop";

        a=Console.ReadLine(); //I try to get a value for my a string

        for (int i = -3; i <= a.Length; i+=4) // try to read them with 4 length groups
        {
            if (a[i] == b) //and my logic was like this if it see the stop it will stop but I couldn't write it.
            {

            }
        }
</code>```

答:
Within your function (I suppose it's the application entry point):</p>

```<code>while (true)
{
    String line = Console.ReadLine();

    if ((line == null) || (line.ToLowerInvariant() == "stop"))
        break;

    // implement your logic here... for example, if you want to print
    // a word at once even if the user entered multiples:

    String[] split = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    for (Int32 i = 0 ; i < split.Length; ++i)
        Console.WriteLine(split[i]);
}
</code>```

Body:
the question with image

This is my code and I explained everything in the code.

Console.Write("If you write stop program will stop.");
        string a;
        string b = "stop";

        a=Console.ReadLine(); //I try to get a value for my a string

        for (int i = -3; i <= a.Length; i+=4) // try to read them with 4 length groups
        {
            if (a[i] == b) //and my logic was like this if it see the stop it will stop but I couldn't write it.
            {

            }
        }

Body:
Within your function (I suppose it's the application entry point):

while (true)
{
    String line = Console.ReadLine();

    if ((line == null) || (line.ToLowerInvariant() == "stop"))
        break;

    // implement your logic here... for example, if you want to print
    // a word at once even if the user entered multiples:

    String[] split = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    for (Int32 i = 0 ; i < split.Length; ++i)
        Console.WriteLine(split[i]);
}


问:
How to connect Android to Node.js?
I'm trying to connect Android to Node.js, i have a server running in port 3000 to my localhost, when i try past data from POST method using postman, it works perfectly, but when i do the same with Android whit class HttpUrlConnection this is the result.

Result in the server

this is the code from Node.js

```<code>router.post('/', (req, res)=>{
  console.log(req.query);
  res.send({
    mensaje: 'I am from usuario routes'
  });
});
</code>```

and this is from android

```<code>    URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
//con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.connect();

OutputStream out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
wrt.append(data);
wrt.flush();

wrt.close();
out.close();
con.disconnect();
</code>```

答: The request in Android is perfect, but in Node i was not using a middleware to convert the body, i used body-parse module and it works.</p>

Title: How to connect Android to Node.js?

Body:
I'm trying to connect Android to Node.js, i have a server running in port 3000 to my localhost, when i try past data from POST method using postman, it works perfectly, but when i do the same with Android whit class HttpUrlConnection this is the result.

Result in the server

this is the code from Node.js

router.post('/', (req, res)=>{
  console.log(req.query);
  res.send({
    mensaje: 'I am from usuario routes'
  });
});

and this is from android

    URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
//con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.connect();

OutputStream out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
wrt.append(data);
wrt.flush();

wrt.close();
out.close();
con.disconnect();


问:
Spring oauth2 and digest authentication will work together
I have added spring oauth2 into my restful service. Most of the services are consumed by my own portal so getting the token then calling the api is fine. However i have exposed some more web services which has to be called without this token concept. Those consumers have username and password.

The best example is Swagger implementation. Where opening the swagger page should be authenticated via digest instead of oauth token.

The below code changes i made but it is not working.
I believe, i no need to call oauth server from the resource server in this case. So just made the below code within the resource server. But seen the problem like after authentication page accepted my credentials it is again rerouting/redirecting to the same authentication page.

Please help.

```<code>@Configuration
@EnableResourceServer
public class ResourceServerImpl extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable().requestMatchers().antMatchers("/**").and().authorizeRequests()
        .antMatchers(HttpMethod.POST, "/url1/path1/path2").hasAnyAuthority( "FUNCTION_FN1")
        .antMatchers(HttpMethod.GET, "/url2/path1/path2").hasAnyAuthority( "FUNCTION_FN2")
        .antMatchers("/swagger-ui.html").hasRole("USER")
        .anyRequest().authenticated()
        .and().formLogin().and().httpBasic()
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}
</code>```

UPDATE
I dont think this is possible to make some request to be authenticated with DIGEST and some are with OAUTH. So currently i made swagger url also to be authenticated with oauth token, instead of digest support.

答:
Yes, it's definitely possible to configure multiple authorization mechanisms in the same application. Distinct instance of  WebSecurityConfigurerAdapter should be provided for each mechanism.
@EnableResourceServer and @EnableAuthorizationServer provide corresponding oauth adapters. ApiSecurityConfiguration provides adapter for basic auth.

Here is minimal working sample for basic and oauth2:

```<code>@SpringBootApplication
public class TestApp {

    @RestController
    public static class Endpoints {

        // doesn't require any authentication
        @RequestMapping("/test")
        public String test() {
            return "no auth";
        }

        // requires basic authentication
        @RequestMapping("/api/test")
        public String apiTest() {
            return "basic auth";
        }

        // requires oauth authentication
        @RequestMapping("/oauth/test")
        public String oauthTest() {
            return "oauth";
        }
    }

    @Configuration
    @EnableWebSecurity
    public static class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/api/**")
                    .and()
                    .authorizeRequests().antMatchers("/api/**").hasRole("USER")
                    .and()
                    .httpBasic();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("user")
                    .password("password")
                    .roles("USER");
        }
    }

    @Configuration
    @EnableAuthorizationServer
    public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                    .withClient("test")
                    .secret("test")
                    .authorizedGrantTypes("client_credentials")
                    .authorities("USER")
                    .scopes("read", "write", "test")
                    .resourceIds("oauth2-resource")
                    .accessTokenValiditySeconds(120);
        }
    }

    @Configuration
    @EnableResourceServer
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/oauth/**")
                    .and()
                    .authorizeRequests().antMatchers("/oauth/**").authenticated();
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }
}
</code>```

pom.xml

```<code>  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.springframework.security.oauth</groupId>
      <artifactId>spring-security-oauth2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  </dependencies>
</code>```

Body:
I have added spring oauth2 into my restful service. Most of the services are consumed by my own portal so getting the token then calling the api is fine. However i have exposed some more web services which has to be called without this token concept. Those consumers have username and password.

The best example is Swagger implementation. Where opening the swagger page should be authenticated via digest instead of oauth token.

The below code changes i made but it is not working.
I believe, i no need to call oauth server from the resource server in this case. So just made the below code within the resource server. But seen the problem like after authentication page accepted my credentials it is again rerouting/redirecting to the same authentication page.

Please help.

@Configuration
@EnableResourceServer
public class ResourceServerImpl extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable().requestMatchers().antMatchers("/**").and().authorizeRequests()
        .antMatchers(HttpMethod.POST, "/url1/path1/path2").hasAnyAuthority( "FUNCTION_FN1")
        .antMatchers(HttpMethod.GET, "/url2/path1/path2").hasAnyAuthority( "FUNCTION_FN2")
        .antMatchers("/swagger-ui.html").hasRole("USER")
        .anyRequest().authenticated()
        .and().formLogin().and().httpBasic()
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}

UPDATE
I dont think this is possible to make some request to be authenticated with DIGEST and some are with OAUTH. So currently i made swagger url also to be authenticated with oauth token, instead of digest support.

Body:
Yes, it's definitely possible to configure multiple authorization mechanisms in the same application. Distinct instance of  WebSecurityConfigurerAdapter should be provided for each mechanism.
@EnableResourceServer and @EnableAuthorizationServer provide corresponding oauth adapters. ApiSecurityConfiguration provides adapter for basic auth.

Here is minimal working sample for basic and oauth2:

@SpringBootApplication
public class TestApp {

    @RestController
    public static class Endpoints {

        // doesn't require any authentication
        @RequestMapping("/test")
        public String test() {
            return "no auth";
        }

        // requires basic authentication
        @RequestMapping("/api/test")
        public String apiTest() {
            return "basic auth";
        }

        // requires oauth authentication
        @RequestMapping("/oauth/test")
        public String oauthTest() {
            return "oauth";
        }
    }

    @Configuration
    @EnableWebSecurity
    public static class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/api/**")
                    .and()
                    .authorizeRequests().antMatchers("/api/**").hasRole("USER")
                    .and()
                    .httpBasic();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("user")
                    .password("password")
                    .roles("USER");
        }
    }

    @Configuration
    @EnableAuthorizationServer
    public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                    .withClient("test")
                    .secret("test")
                    .authorizedGrantTypes("client_credentials")
                    .authorities("USER")
                    .scopes("read", "write", "test")
                    .resourceIds("oauth2-resource")
                    .accessTokenValiditySeconds(120);
        }
    }

    @Configuration
    @EnableResourceServer
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/oauth/**")
                    .and()
                    .authorizeRequests().antMatchers("/oauth/**").authenticated();
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }
}

pom.xml

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.springframework.security.oauth</groupId>
      <artifactId>spring-security-oauth2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  </dependencies>


问:
How to use safe center with flexbox?
Centred flexbox items can have undesirable behaviour when they overflow their container.

Several non-flex solutions have been provided for this issue, but according to MDN there is a safe value which is described as follows.

If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.

It can be used as follows.

```<code>align-items: safe center;
</code>```

Unfortunately, I haven't been able to find any examples or discussions of this, or determine how much browser support there is for it.

I have attempted to use safe in this CodePen. However, it doesn't work for me. The safe seems to be ignored, or perhaps the container element is improperly styled.

I'd really appreciate it if anyone could shed some light on safe and whether and how it can be used to solve the overflow problem, as demonstrated by the CodePen example.

答:
The newer keyword safe still has bad browser support, so to get the same effect, cross browser, use auto margins for now, which should be set on the flex item.

Updated codepen

Note, to compensate for the modal's 50px top/bottom margin, use padding on modal-container.

```<code>.modal-container
{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;                /*  changed  */
  position: fixed;
  width: 100vw;
  height: 100vh;
  overflow-y: scroll;
  padding: 50px 0;                        /*  added  */
  box-sizing: border-box;                 /*  added  */
}
.modal-container > #modal
{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto 0;                         /*  changed  */
  padding: 12px;
  width: 50%;
  background-color: #333;
  cursor: pointer;
}
</code>```

Title: How to use safe center with flexbox?

Body:
Centred flexbox items can have undesirable behaviour when they overflow their container.

Several non-flex solutions have been provided for this issue, but according to MDN there is a safe value which is described as follows.

If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.

It can be used as follows.

align-items: safe center;

Unfortunately, I haven't been able to find any examples or discussions of this, or determine how much browser support there is for it.

I have attempted to use safe in this CodePen. However, it doesn't work for me. The safe seems to be ignored, or perhaps the container element is improperly styled.

I'd really appreciate it if anyone could shed some light on safe and whether and how it can be used to solve the overflow problem, as demonstrated by the CodePen example.

Body:
The newer keyword safe still has bad browser support, so to get the same effect, cross browser, use auto margins for now, which should be set on the flex item.

Updated codepen

Note, to compensate for the modal's 50px top/bottom margin, use padding on modal-container.

.modal-container
{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;                /*  changed  */
  position: fixed;
  width: 100vw;
  height: 100vh;
  overflow-y: scroll;
  padding: 50px 0;                        /*  added  */
  box-sizing: border-box;                 /*  added  */
}
.modal-container > #modal
{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto 0;                         /*  changed  */
  padding: 12px;
  width: 50%;
  background-color: #333;
  cursor: pointer;
}


问:
Read string and integer from a file using fscanf
I am having a structure like this

```<code>struct tm1
{
    char buf[80];
    int val;
} pl;
</code>```

I want to fill this structure from a file and the file contains current time and one value. Like this

```<code>Mon Dec  4 19:36:23 2017 98
</code>```

Now I want to do fscanf of time and the value i.e 98 from the file and put those values in the structure (time should go to the structure member buf and the value i.e. 98 should go to the structure member val.)

Now the problem is fscanf terminates at first white space, so to resolve this I tried

```<code> fscanf(infile,"%[^\n]",pl.buf);
</code>```

but after doing this value 98 from the file also going to structure member buf..

How can I store time in structure member buf and the value 98 in structure member val ?

答:
It would be best to use fgets() to fetch lines of input. Then sscanf() could be used to parse the input.

You can combine assignment suppression (*) with a scanset directive (%[]) to ignore the first part of the date: %*[^0-9] %*d. Scan the time, then use suppression again to ignore the year. Note that the behavior of a dash in a scanset, e.g. %*[^0-9] is implementation-defined, but this commonly behaves as expected to indicate a range. A completely portable alternative would be to use: %*[^0123456789] instead.

Here is an example program:

```<code>#include <stdio.h>
#include <stdlib.h>

struct tm1
{
    char buf[80];
    int val;
};

int main(void)
{
    struct tm1 p1;

    FILE *fp = fopen("file.dat", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[4096];
    while (fgets(buffer, sizeof buffer, fp)) {
        if (sscanf(buffer, "%*[^0-9] %*d %79s %*d %d", p1.buf, &p1.val) == 2) {
            printf("%s, %d\n", p1.buf, p1.val);
        }
    }

    return 0;
}
</code>```

Program output:

19:36:23, 98
```

<h2>Update</h2>

<p>I appear to have misunderstood OP's question. The above solution does not store the entire date in the <code>buf</code> field of the <code>struct</code>. In order to store the entire date, it would be nice to have some delimiter between the date and the final value to help in parsing input lines. In absence of such a delimiter, the techniques mentioned above may still be useful.</p>

<p>The <code>%n</code> directive stores the number of characters read from the input stream so far when it is encountered. This can be used to identify the location following the date in the example input. Consider:</p>

```sscanf(buffer, "%*[^0123456789] %*d %*s %*d%n", &tail)
```

<p>Here <code>sscanf()</code> ignores each of the date components, and stores the character count in <code>tail</code>, which amounts to the index of the character following the date in <code>buffer[]</code>. <code>sscanf()</code> can be used again to get the final value by scanning:</p>

```sscanf(buffer + tail, "%d", &p1.val)
```

<p>Then a null-terminator can be placed after the date, allowing the date to be copied to the appropriate field of the <code>struct</code>.</p>

<p>Here is another example program. The parsing is not bullet-proof here, but it should handle well-formatted data. Note that when <code>tail</code> is too large, the line is skipped. This indicates that the date string would not fit into <code>p1.buf</code>.</p>

```#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct tm1
{
    char buf[80];
    int val;
};

int main(void)
{
    struct tm1 p1;

    FILE *fp = fopen("file.dat", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[4096];
    while (fgets(buffer, sizeof buffer, fp)) {
        int tail = 0;
        if (sscanf(buffer, "%*[^0123456789] %*d %*s %*d%n", &tail) == 0) {
            if ((unsigned) tail < sizeof p1.buf
                && sscanf(buffer + tail, "%d", &p1.val) == 1) {
                buffer[tail] = '\0';
                strcpy(p1.buf, buffer);
                printf("%s, %d\n", p1.buf, p1.val);
            }
        }
    }

    return 0;
}
```

<p>Here is a sample input file:</p>

<pre class="lang-none prettyprint-override"><code>Mon Dec  4 19:36:23 2017 98
Tues Dec  5 19:36:28 2017 99
Wed Dec  6 19:36:21 2017 95
Thur Dec  7 19:36:23 2017 89
Fri Dec  8 19:36:20 2017 93
Sat Dec  9 19:36:22 2017 oops! 95
Sun Dec  10 19:36:23 2017 98
Sun               Dec                      10                   19:36:23                     2017 98
Mon Dec  11 19:36:25 2017 97
</code>```

And here is the program output:

Mon Dec  4 19:36:23 2017, 98
Tues Dec  5 19:36:28 2017, 99
Wed Dec  6 19:36:21 2017, 95
Thur Dec  7 19:36:23 2017, 89
Fri Dec  8 19:36:20 2017, 93
Sun Dec  10 19:36:23 2017, 98
Mon Dec  11 19:36:25 2017, 97
```

Body:
I am having a structure like this

struct tm1
{
    char buf[80];
    int val;
} pl;

I want to fill this structure from a file and the file contains current time and one value. Like this

Mon Dec  4 19:36:23 2017 98

Now I want to do fscanf of time and the value i.e 98 from the file and put those values in the structure (time should go to the structure member buf and the value i.e. 98 should go to the structure member val.)

Now the problem is fscanf terminates at first white space, so to resolve this I tried

 fscanf(infile,"%[^\n]",pl.buf);

but after doing this value 98 from the file also going to structure member buf..

How can I store time in structure member buf and the value 98 in structure member val ?

Body:
It would be best to use fgets() to fetch lines of input. Then sscanf() could be used to parse the input.

You can combine assignment suppression (*) with a scanset directive (%[]) to ignore the first part of the date: %*[^0-9] %*d. Scan the time, then use suppression again to ignore the year. Note that the behavior of a dash in a scanset, e.g. %*[^0-9] is implementation-defined, but this commonly behaves as expected to indicate a range. A completely portable alternative would be to use: %*[^0123456789] instead.

Here is an example program:

#include <stdio.h>
#include <stdlib.h>

struct tm1
{
    char buf[80];
    int val;
};

int main(void)
{
    struct tm1 p1;

    FILE *fp = fopen("file.dat", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[4096];
    while (fgets(buffer, sizeof buffer, fp)) {
        if (sscanf(buffer, "%*[^0-9] %*d %79s %*d %d", p1.buf, &p1.val) == 2) {
            printf("%s, %d\n", p1.buf, p1.val);
        }
    }

    return 0;
}

Program output:

19:36:23, 98

Update

I appear to have misunderstood OP's question. The above solution does not store the entire date in the buf field of the struct. In order to store the entire date, it would be nice to have some delimiter between the date and the final value to help in parsing input lines. In absence of such a delimiter, the techniques mentioned above may still be useful.

The %n directive stores the number of characters read from the input stream so far when it is encountered. This can be used to identify the location following the date in the example input. Consider:

sscanf(buffer, "%*[^0123456789] %*d %*s %*d%n", &tail)

Here sscanf() ignores each of the date components, and stores the character count in tail, which amounts to the index of the character following the date in buffer[]. sscanf() can be used again to get the final value by scanning:

sscanf(buffer + tail, "%d", &p1.val)

Then a null-terminator can be placed after the date, allowing the date to be copied to the appropriate field of the struct.

Here is another example program. The parsing is not bullet-proof here, but it should handle well-formatted data. Note that when tail is too large, the line is skipped. This indicates that the date string would not fit into p1.buf.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct tm1
{
    char buf[80];
    int val;
};

int main(void)
{
    struct tm1 p1;

    FILE *fp = fopen("file.dat", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[4096];
    while (fgets(buffer, sizeof buffer, fp)) {
        int tail = 0;
        if (sscanf(buffer, "%*[^0123456789] %*d %*s %*d%n", &tail) == 0) {
            if ((unsigned) tail < sizeof p1.buf
                && sscanf(buffer + tail, "%d", &p1.val) == 1) {
                buffer[tail] = '\0';
                strcpy(p1.buf, buffer);
                printf("%s, %d\n", p1.buf, p1.val);
            }
        }
    }

    return 0;
}

Here is a sample input file:

Mon Dec  4 19:36:23 2017 98
Tues Dec  5 19:36:28 2017 99
Wed Dec  6 19:36:21 2017 95
Thur Dec  7 19:36:23 2017 89
Fri Dec  8 19:36:20 2017 93
Sat Dec  9 19:36:22 2017 oops! 95
Sun Dec  10 19:36:23 2017 98
Sun               Dec                      10                   19:36:23                     2017 98
Mon Dec  11 19:36:25 2017 97

And here is the program output:

Mon Dec  4 19:36:23 2017, 98
Tues Dec  5 19:36:28 2017, 99
Wed Dec  6 19:36:21 2017, 95
Thur Dec  7 19:36:23 2017, 89
Fri Dec  8 19:36:20 2017, 93
Sun Dec  10 19:36:23 2017, 98
Mon Dec  11 19:36:25 2017, 97


答:
It looks like it is using a GNU C extension that allows to write a block statement where an expression is expected. The value of the block statement is the value of the last expression of the block.

For example:

```<code>int x = ({ int a = 1; a+2; });
</code>```

will initialize x with 3.

In your particular case the extension does not look very useful, because:

```<code>i=!({ printf("%d\n",r); });
</code>```

is identical to:

```<code>i=!printf("%d\n",r);
</code>```

I'm guessing that your original code is probably generated by some dark magic macro.

BTW, this code does not make much sense. It looks like it wants to check whether printf failed or suceeded in writing the text. But according to the specification, printf will return the number of bytes written if success or a negative value if error. So it will return 0 only if it writes 0 chars, and that will not happen with a \n at the end, and i will always end up being 0, either with or without error.

Title: C - int not-equal to printf?

Body:
What this C statement does?

i=!({ printf("%d\n",r); });

i and r are integers.

I'm trying to parse it using pycparser which doesn't recognize it and raises an error:

pycparser.plyparser.ParseError: :7:6: before: {

Thanks

Body:
It looks like it is using a GNU C extension that allows to write a block statement where an expression is expected. The value of the block statement is the value of the last expression of the block.

For example:

int x = ({ int a = 1; a+2; });

will initialize x with 3.

In your particular case the extension does not look very useful, because:

i=!({ printf("%d\n",r); });

is identical to:

i=!printf("%d\n",r);

I'm guessing that your original code is probably generated by some dark magic macro.

BTW, this code does not make much sense. It looks like it wants to check whether printf failed or suceeded in writing the text. But according to the specification, printf will return the number of bytes written if success or a negative value if error. So it will return 0 only if it writes 0 chars, and that will not happen with a \n at the end, and i will always end up being 0, either with or without error.


问:
WebPack is trying to load all required modules and then breaking
I'm using webpack to build a project where the client and server-side share certain concepts (a shared state). Because of this, I've set up webpack to compile both of them, like so:

```<code>const path = require('path')

module.exports = [
  {
    entry: './lib/client.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'static')
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['babel-preset-env', 'babel-preset-react']
            }
          }
        }
      ]
    }
  },
  {
    entry: './lib/server.js',
    target: 'node',
    output: {
      filename: 'index.js',
      path: path.resolve(__dirname)
    }
  }
]
</code>```

Unfortunately, when this compiles, webpack seems to be loading up every require'd module on the server-side and breaking when it can't find them. It's even trying to load some .node modules, which cause it to output a warning.

It finally breaks at this error, probably a result of my server code having require('pg') in it:

```<code> ERROR in ./node_modules/pg/lib/native/client.js
    Module not found: Error: Can't resolve 'pg-native' in 'C:\...\node_modules\pg\lib\native'
     @ ./node_modules/pg/lib/native/client.js 10:13-33
     @ ./node_modules/pg/lib/native/index.js
     @ ./node_modules/pg/lib/index.js
     @ ./lib/server.js
</code>```

How do I get it to ignore the required modules and just keep them as regular require calls in the output? target: 'node' doesn't seem to help.

Update: For whatever reason, trying to build the exact same project on my Linux system works perfectly, so it seems to be a platform-specific problem.

答:
I think you are using or importing 'pg-native' module in one of the Javascript file.

If you want it to work then install that module npm install pg-native --save
If you don't want to use 'pg-native' then better you refactor your code and remove usage of it

Body:
I'm using webpack to build a project where the client and server-side share certain concepts (a shared state). Because of this, I've set up webpack to compile both of them, like so:

const path = require('path')

module.exports = [
  {
    entry: './lib/client.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'static')
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['babel-preset-env', 'babel-preset-react']
            }
          }
        }
      ]
    }
  },
  {
    entry: './lib/server.js',
    target: 'node',
    output: {
      filename: 'index.js',
      path: path.resolve(__dirname)
    }
  }
]

Unfortunately, when this compiles, webpack seems to be loading up every require'd module on the server-side and breaking when it can't find them. It's even trying to load some .node modules, which cause it to output a warning.

It finally breaks at this error, probably a result of my server code having require('pg') in it:

 ERROR in ./node_modules/pg/lib/native/client.js
    Module not found: Error: Can't resolve 'pg-native' in 'C:\...\node_modules\pg\lib\native'
     @ ./node_modules/pg/lib/native/client.js 10:13-33
     @ ./node_modules/pg/lib/native/index.js
     @ ./node_modules/pg/lib/index.js
     @ ./lib/server.js

How do I get it to ignore the required modules and just keep them as regular require calls in the output? target: 'node' doesn't seem to help.

Update: For whatever reason, trying to build the exact same project on my Linux system works perfectly, so it seems to be a platform-specific problem.


问:
Find a range address
I want to select some range based on cells value, as they might be each time in different column.

So my first thought was something like below, but I'm not sure if that's the right way?

```<code>Sub RangeBetween()

Dim rng1 As Range, rng2 As Range
Dim totalRange As Range
Dim c1, c2 As Integer

c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
someA= c1 - 1

c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
someB= c2 - 1

Set rng1 = Range("???")
Set rng2 = Range("???")

Set totalRange = Range(rng1.Address & ":" & rng2.Address)
    totalRange .Select
    End Sub
</code>```

Thanks

答:
Or you can use Match()</p>

```<code>Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long

c1 = 0
c2 = 0
With Worksheets("Sheet1") 'Change to your worksheet
    On Error Resume Next
        c1 = Application.WorksheetFunction.Match("A", .Rows(1), 0)
        c2 = Application.WorksheetFunction.Match("B", .Rows(1), 0)
    On Error GoTo 0

    If c1 > 0 And c2 > 0 Then
        Set totalRange = .Range(.Cells(1, c1), .Cells(1, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub
</code>```

Title: Find a range address

Body:
I want to select some range based on cells value, as they might be each time in different column.

So my first thought was something like below, but I'm not sure if that's the right way?

Sub RangeBetween()

Dim rng1 As Range, rng2 As Range
Dim totalRange As Range
Dim c1, c2 As Integer

c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
someA= c1 - 1

c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
someB= c2 - 1

Set rng1 = Range("???")
Set rng2 = Range("???")

Set totalRange = Range(rng1.Address & ":" & rng2.Address)
    totalRange .Select
    End Sub

Thanks

Body:
Or you can use Match()

Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long

c1 = 0
c2 = 0
With Worksheets("Sheet1") 'Change to your worksheet
    On Error Resume Next
        c1 = Application.WorksheetFunction.Match("A", .Rows(1), 0)
        c2 = Application.WorksheetFunction.Match("B", .Rows(1), 0)
    On Error GoTo 0

    If c1 > 0 And c2 > 0 Then
        Set totalRange = .Range(.Cells(1, c1), .Cells(1, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub


问:
How can I convert a std::vector<float> to a float array?

Possible Duplicate:

  Getting array from std:vector

I've been reading the answers to this question and found them useful, but how can I do the same with a float type?

答:
The same thing.</p>

```<code>std::vector<float> v(10);
float *p = &v[0];
</code>```

Body:
The same thing.

std::vector<float> v(10);
float *p = &v[0];


问:
Azure Functions: CosmosDBTrigger connection string storage
I asked yesterday where to store the connection string for a CosmosDBTrigger. It worked great until I had to push it up to Azure. Now the function isn't working at all. It works locally just fine though. There is no difference between codebases so the only thing I can think of is the connection string isn't be pulled from local.settings.json when on Azure. I mean, it wouldn't surprise me if that was the case since the file has the word local in it.

I tried putting the contents in the host.json, but that didn't work either.

How do you specify the connection string when your Function is running on Azure?

答:
local.settings.json is not used in Azure. Instead, settings are taken from App Service Settings.

For your yesterday's example, go to Function App's Application settings tab and add a value with key DbConnString there.

If you are using func CLI, you can publish settings from local.settings.json file to Azure Application settings by running

```<code>func azure functionapp public <App> --publish-local-settings
</code>```

Body:
local.settings.json is not used in Azure. Instead, settings are taken from App Service Settings.

For your yesterday's example, go to Function App's Application settings tab and add a value with key DbConnString there.

If you are using func CLI, you can publish settings from local.settings.json file to Azure Application settings by running

func azure functionapp public <App> --publish-local-settings


问:
Connection to specific WiFi if already have connection to another
I've been fighting like a fish for two days already, and I can not find a solution. I tried this code but it through time worked on Android 5(Lollipop) and didn't work at 7.1.1.(Nougat) I have another Scenario where phone loses connection and after this, it needs to return to the old Wifi. </p>

```<code>public void setWifiConnection1(View view){
  WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

  WifiConfiguration wc = new WifiConfiguration();
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

  wc.SSID = "\"NETWORK_NAME\"";
  wc.preSharedKey = "\"PASSWORD\"";
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.priority = 999999;
    wifiManager.setWifiEnabled(true);
    int netId = wifiManager.addNetwork(wc);
    if (netId == -1) {
        netId = getExistingNetworkId(wc.SSID);
    }
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

 private int getExistingNetworkId(String SSID) {

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}
</code>```

答:
wifiManager.setWifiEnabled(true);

You can't execute your code right after this line. You should do a wifiManager.isWifiEnabled() check and subscribe to a broadcast if it's disabled.

Next...

```<code>wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
</code>```

This part is very odd: why do you disconnect ? Be aware that most of WifiManager operations are asynchronous so that's why you observe different results each time - real "disconnect" may occur after you've tried to enable your desired network.

You can always get inspiration from system API: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773

So correct sequence is:

```<code>wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();
</code>```

But if you are allowed to do so, it's more convenient to use system API directly.

Body:
I've been fighting like a fish for two days already, and I can not find a solution. I tried this code but it through time worked on Android 5(Lollipop) and didn't work at 7.1.1.(Nougat) I have another Scenario where phone loses connection and after this, it needs to return to the old Wifi.

public void setWifiConnection1(View view){
  WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

  WifiConfiguration wc = new WifiConfiguration();
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

  wc.SSID = "\"NETWORK_NAME\"";
  wc.preSharedKey = "\"PASSWORD\"";
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.priority = 999999;
    wifiManager.setWifiEnabled(true);
    int netId = wifiManager.addNetwork(wc);
    if (netId == -1) {
        netId = getExistingNetworkId(wc.SSID);
    }
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

 private int getExistingNetworkId(String SSID) {

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}

Body:
wifiManager.setWifiEnabled(true);

You can't execute your code right after this line. You should do a wifiManager.isWifiEnabled() check and subscribe to a broadcast if it's disabled.

Next...

wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

This part is very odd: why do you disconnect ? Be aware that most of WifiManager operations are asynchronous so that's why you observe different results each time - real "disconnect" may occur after you've tried to enable your desired network.

You can always get inspiration from system API: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773

So correct sequence is:

wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();

But if you are allowed to do so, it's more convenient to use system API directly.