问:
HTT response code and Status code in mail by python
We have out own portal which is designed in .ASP. And in that portal there are multiple tabs.
To monitor each page and their loading time (to monitor slowness of each page) I have below code.

I have copied all the .asp pages in one notepad and this script fetches each one to monitor.
(Hoping httpauth works)
When I tried to send email if status code is other than 200 and time taken more than 0.5 sec it will shoot mail
But for each URL it sends different mail, also it only gives URL in subject line.
How do I make like to send only one mail including all errors with respective urls.

```<code>i.e.
https://example.org/node.asp - status 404
https://example.org/frame.asp - response time is 2 sec.
https://example.org/ticketgen.asp - response time is 5 sec.
https://example.org/alert.asp - status 500
</code>```

Below is my code

```<code>#!/usr/bin/env python

import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
from requests.auth import HTTPBasicAuth
import requests

def get_response_time(url):
    return requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd')).elapsed.total_seconds()

def email_alert(message, status):
    fromaddr = 'abc@mysite.com'
    toaddrs = 'xyz@mysite.com'

    server = SMTP('smtp.office365.com')
    server.starttls()
    server.login(fromaddr, 'mypasswd')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

def get_site_status(url):
    response = get_response(url)
   try:
        if response == 200:
            return 'up'
   except AttributeError:
        pass
    return 'down'

def get_response(url):
    '''Return response object from URL'''
    try:
        conn = requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd'))
        #conn.request('HEAD', '/')
        return conn.status_code
    except socket.error:
        return None
    except Exception as e:
        print(e)
        logging.error('Bad URL:{}'.format( url))
        exit(1)

def get_headers(url):
    '''Gets all headers from URL request and returns'''
    response = get_response(url)
    try:
        return getattr(response, 'getheaders')()
    except AttributeError:
        return 'Headers unavailable'

if __name__ == '__main__':
    content = []
    with open("/home/support/url_list.txt") as f:
        content = f.readlines()
    for url in content:
        url = url.strip()
        r_time = get_response_time(url)
        print(r_time)
        if r_time > 0.5 :
        #print("Please send email", url, "as Response Time is", r_time)
         email_alert(str(r_time), url)

    status = get_site_status(url)
    if status == "down":
        #print("Send email", url, "is", status, "and Response is", get_response(url))
        email_alert(str(get_site_status(url)), url)
</code>```

答:
Instead of executing email_alert(str(r_time), url) for each url, what you can do is to cache each url with response time in responses dict. And create email message after  for url in content loop. i.e

```<code>res_times = {}
for url in content:
    url = url.strip()
    r_time = get_response_time(url)
    print(r_time)
    if r_time > 0.5 :
       res_times[url] = r_time

message = ''
#res_times not empty means you have to send error email
for x in res_times.items():
     message += "Url: %s, response time: %s\n" % x
if message:
    email_alert(message, 'error')
</code>```

Body:
We have out own portal which is designed in .ASP. And in that portal there are multiple tabs.
To monitor each page and their loading time (to monitor slowness of each page) I have below code.

I have copied all the .asp pages in one notepad and this script fetches each one to monitor.
(Hoping httpauth works)
When I tried to send email if status code is other than 200 and time taken more than 0.5 sec it will shoot mail
But for each URL it sends different mail, also it only gives URL in subject line.
How do I make like to send only one mail including all errors with respective urls.

i.e.
https://example.org/node.asp - status 404
https://example.org/frame.asp - response time is 2 sec.
https://example.org/ticketgen.asp - response time is 5 sec.
https://example.org/alert.asp - status 500

Below is my code

#!/usr/bin/env python

import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
from requests.auth import HTTPBasicAuth
import requests

def get_response_time(url):
    return requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd')).elapsed.total_seconds()

def email_alert(message, status):
    fromaddr = 'abc@mysite.com'
    toaddrs = 'xyz@mysite.com'

    server = SMTP('smtp.office365.com')
    server.starttls()
    server.login(fromaddr, 'mypasswd')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

def get_site_status(url):
    response = get_response(url)
   try:
        if response == 200:
            return 'up'
   except AttributeError:
        pass
    return 'down'

def get_response(url):
    '''Return response object from URL'''
    try:
        conn = requests.get(url, auth=HTTPBasicAuth('admin', 'secpasswd'))
        #conn.request('HEAD', '/')
        return conn.status_code
    except socket.error:
        return None
    except Exception as e:
        print(e)
        logging.error('Bad URL:{}'.format( url))
        exit(1)

def get_headers(url):
    '''Gets all headers from URL request and returns'''
    response = get_response(url)
    try:
        return getattr(response, 'getheaders')()
    except AttributeError:
        return 'Headers unavailable'

if __name__ == '__main__':
    content = []
    with open("/home/support/url_list.txt") as f:
        content = f.readlines()
    for url in content:
        url = url.strip()
        r_time = get_response_time(url)
        print(r_time)
        if r_time > 0.5 :
        #print("Please send email", url, "as Response Time is", r_time)
         email_alert(str(r_time), url)

    status = get_site_status(url)
    if status == "down":
        #print("Send email", url, "is", status, "and Response is", get_response(url))
        email_alert(str(get_site_status(url)), url)

Body:
Instead of executing email_alert(str(r_time), url) for each url, what you can do is to cache each url with response time in responses dict. And create email message after  for url in content loop. i.e

res_times = {}
for url in content:
    url = url.strip()
    r_time = get_response_time(url)
    print(r_time)
    if r_time > 0.5 :
       res_times[url] = r_time

message = ''
#res_times not empty means you have to send error email
for x in res_times.items():
     message += "Url: %s, response time: %s\n" % x
if message:
    email_alert(message, 'error')


来源: stackexchange

问:
Route planning option for a website
I need to have a route planning option in my website. It must be given route alternatives when the user enter origin and destination.
Look for this example https://www.transitbangkok.com/
 Can someone help Please</p>

答: Transitbangkok does not provide an API. So you can not embed it easily into your site or use their API to perform some search queries.</p>

ContentLicense: CC BY-SA 3.0

Title: Route planning option for a website


问:
Is there a native interface that matches "string" and "Object that implements __toString()"?
We have objects that implement __toString():

```<code>class Foo {
    public function __toString()
    {
        return 'bar';
    }
}
</code>```

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

```<code>function getString():string {
    return 'Works!';
}
</code>```

Returning object of type Foo does not work, because it's not a string:

```<code>function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}
</code>```

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).

答:
The simple answer is "no" - there is no built-in "stringable" hint, although it has occasionally been suggested in the past.

As of PHP 8.0, there will be support for "union types", so string|Stringable would represent "either a string or an instanceof Stringable". However, there's no such interface as Stringable, so this can't be used to detect implementations of __toString.

Part of the reason for this, and the design question you need to ask, is what contract are you actually representing here? From the point of view of the calling code, there is no guarantee that the return value can actually be used as a string directly - there are many operations which will behave differently for a string and an object, or which will accept a string but not cast an object automatically. So the only thing that's actually guaranteed by such a hint is that (string)$foo will give a string.

So you have a few options:

As Stefan says, always return an object, implementing some interface Stringable. If the function wants to return a string, it would first wrap it in a simple object.

Instead of a generic Stringable, come up with a more meaningful interface to return; maybe what you actually return is something Loggable, for instance. This way, wrapping the string can give you more concrete benefits: you can add other methods to the interface, and the calling code doesn't need to do an "object or string" check before calling those methods.

If the calling code is only ever going to use the return value as a string, don't return the object at all. Mark the function as returning string, and cast any objects to string before returning them.

If the calling code is expected to inspect the return value and do different things with different kinds of objects, don't limit the return type at all. In PHP 8, you might want to add a union type, but only if there's a short list of possibilities; a return type that's too broad is barely useful as a contract anyway.

ContentLicense: CC BY-SA 4.0

Body:
We have objects that implement __toString():

class Foo {
    public function __toString()
    {
        return 'bar';
    }
}

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

function getString():string {
    return 'Works!';
}

Returning object of type Foo does not work, because it's not a string:

function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).


问:
how to detect clouds in image using opencv python
i am working on a project using opencv in python in which i want to detect the clouds in an image. i have tried a lot of things but i am stuck.i couldn't find the exact range of cloud color values for hsv color space. this is the code i have tried. the following code detect some of the clouds but not all.this is the code.i have also attached an image which i am getting from this code.

```<code>import cv2
import numpy as np

img = cv2.imread('E:/sky.jpg', 1)
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

white = np.array([255, 255, 255])
lowerBound = np.array([30,30,30])

mask = cv2.inRange(hsv, lowerBound, white)

res = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite("E:/clouds.jpg",res)

cv2.imshow("mywindow",res)

cv2.waitKey(0)
</code>```

答:
Try not changing the image to HSV color space.
Remove line

```<code>hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
</code>```

The rest of the code clearly shows you are working with a RGB color based scheme and you have no idea what HSV is. Frankly speaking, i don't see the need for you to work with HSV color space in the first place. It can be done even with grayscale image representation.

Body:
i am working on a project using opencv in python in which i want to detect the clouds in an image. i have tried a lot of things but i am stuck.i couldn't find the exact range of cloud color values for hsv color space. this is the code i have tried. the following code detect some of the clouds but not all.this is the code.i have also attached an image which i am getting from this code.

import cv2
import numpy as np

img = cv2.imread('E:/sky.jpg', 1)
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

white = np.array([255, 255, 255])
lowerBound = np.array([30,30,30])

mask = cv2.inRange(hsv, lowerBound, white)

res = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite("E:/clouds.jpg",res)

cv2.imshow("mywindow",res)

cv2.waitKey(0)

Body:
Try not changing the image to HSV color space.
Remove line

hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

The rest of the code clearly shows you are working with a RGB color based scheme and you have no idea what HSV is. Frankly speaking, i don't see the need for you to work with HSV color space in the first place. It can be done even with grayscale image representation.


问:
Wpf DataGrid hide complete row through DataBinding
Is there a possiblity to hide DataGrid-rows through DataBinding:

If I have items of a BO or a ViewModel that have a visibilty-property, is there a possibility to declare a binding so that the row will be hidden if the property is set to invisible and vice versa?

答:
It should be possible to do it via RowStyle. Something like this:

```<code><DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding Visibility}" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It should be possible to do it via RowStyle. Something like this:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding Visibility}" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>


问:
GATT support on android phone(4.0 and above)
Dose GATT profile works on every android phone(4.0 and above) with BLE hardware? </p>

答:
The Gatt central role is available on devices running at least Android 4.3. See Bluetooth Low Energy

The Gatt peripheral role was added with Android 5.0 to the Android SDK.


问:
Execution 'iwy2vpzo52pmp555ftfn4455' cannot be found (rsExecutionNotFound)
Some users get the following error when running reports.

•   Execution 'iwy2vpzo52pmp555ftfn4455' cannot be found (rsExecutionNotFound)

They run fine in the morning.
Any suggestions?

Thank you

答:
I am using SSRS 2017 and was running into this issue when trying to load a report into my MVC project using URL Access.  The issue for me had to do with session.

To check this for yourself, you can try deleting the RSExecutionSession cookie and reload your report.  Unfortunately, this is only a temporarily fix.

If this does work, try adding rs:ClearSession=true to your query string.

You can read about this setting here.


问:
Strategy flushing file outputs at termination
I have an application that monitors a high-speed communication link and writes logs to a file (via standard C file IO). The response time to messages that arrive on the link is important, so I knowingly don't fflush the file at each message, because this slows down my response time.

However, in some circumstances my application is terminated "violently" (e.g. by killing the process), and in these cases the last few log messages are not written (even if the communication link has been quiet for some time).

What techniques/strategies can I use to make sure most of my data is flushed, but without giving up speed of response?

Edit: The application runs on Windows

答:
I would suggest an asynchronous write-though. That way you don't need to wait for the write IOP to happen, nor will the OS will delay the IOP. See CreateFile() flags FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED.

You don't need FILE_FLAG_NO_BUFFERING. That's only to skip the OS cache. You would only need it if you are worried about the entire OS dying violently.

OwnerDisplayName: eliben

LastEditorDisplayName: eliben

OwnerDisplayName: MSalters


问:
How to change the default grey icon colors for tabBarItems in iOS 7?
I've searched and tried all the possible solutions to no avail. All I want is to change the unselected default grey color to something darker. I'm using Xcode 5 and iOS 7. Would someone help? </p>

<p>(I tried all of these and more: How can I change the text and icon colors for tabBarItems in iOS 7?)</p>

答: you can use story board to change that so easy you just need to select TabBar in the tabBarController in the story board and and in the show identity inspector in the user Defined Runtime Attributes add "unselectedItemTintColor" and change the type to the color and then you can choose the color that you want just like a photo

Body:
I've searched and tried all the possible solutions to no avail. All I want is to change the unselected default grey color to something darker. I'm using Xcode 5 and iOS 7. Would someone help?

(I tried all of these and more: How can I change the text and icon colors for tabBarItems in iOS 7?)


问:
Flutter - Widget animation status remains even after it has been removed
I'm updating a List<Widget> tiles, but even updating, in which I remove one of the elements of tiles, the state of the animation of the element that came out is still active.

In other words, I redo tiles with this.tiles = buildTile(list); the animation state does not change.

In the example below is removed the Widget that has in its text the string foo3, but its animation continues, and the Widget that has in its text the string foo4 receives this animation.

Is there any way to solve this or is this a bug?

```<code>import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> tiles;
  List foos = [];

  @override
  void initState() {
    this.foos = ['foo1', 'foo2', 'foo3', 'foo4'];
    this.tiles = buildTile(this.foos);
    super.initState();
  }

  //function
  List<Widget> buildTile(List list) {
    var x = [];
    for(var i = 0; i < list.length; i++) {
      x.add(
        new ItemCategory(
          key: new Key(list[i]), //new
          category: list[i],
          onPressed: () {
            setState(() {
              list.removeAt(i);
              this.tiles = buildTile(list);
            });
          },
        )
      );
    }
    return x;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Categories'),
      ),
      body: new ListView(
        padding: new EdgeInsets.only(top: 8.0, right: 0.0, left: 0.0),
        children: this.tiles
      )
    );
  }
}

class ItemCategory extends StatefulWidget {
  ItemCategory({ Key key, this.category, this.onPressed}) : super(key: key);

  final String category;
  final VoidCallback onPressed;

  @override
  ItemCategoryState createState() => new ItemCategoryState();
}

class ItemCategoryState extends State<ItemCategory> with TickerProviderStateMixin {
  ItemCategoryState();

  AnimationController _controller;
  Animation<double> _animation;
  double flingOpening;
  bool startFling = true;

  void initState() {
    super.initState();
    _controller = new AnimationController(duration:
      const Duration(milliseconds: 246), vsync: this);

    _animation = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 1.0, curve: Curves.linear),
    );
  }

  void _move(DragUpdateDetails details) {
    final double delta = details.primaryDelta / 304;
    _controller.value -= delta;
  }

  void _settle(DragEndDetails details) {
    if(this.startFling) {
      _controller.fling(velocity: 1.0);
      this.startFling = false;
    } else if(!this.startFling){
      _controller.fling(velocity: -1.0);
      this.startFling = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _width = logicalSize.width;
    this.flingOpening = -(48.0/_width);

    return new GestureDetector(
      onHorizontalDragUpdate: _move,
      onHorizontalDragEnd: _settle,
      child: new Stack(
        children: <Widget>[
          new Positioned.fill(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFFE57373),
                  ),
                  child: new IconButton(
                    icon: new Icon(Icons.delete),
                    color: new Color(0xFFFFFFFF),
                    onPressed: widget.onPressed
                  )
                ),
              ],
            ),
          ),
          new SlideTransition(
            position: new Tween<Offset>(
              begin:  Offset.zero,
              end: new Offset(this.flingOpening, 0.0),
            ).animate(_animation),
            child: new Container(
              decoration: new BoxDecoration(
                border: new Border(
                  top: new BorderSide(style: BorderStyle.solid, color: Colors.black26),
                ),
                color: new Color(0xFFFFFFFF),
              ),
              margin: new EdgeInsets.only(top: 0.0, bottom: 0.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Expanded(
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        new Container(
                          margin: new EdgeInsets.only(left: 16.0),
                          padding: new EdgeInsets.only(right: 40.0, top: 4.5, bottom: 4.5),
                          child: new Row(
                            children: <Widget>[
                              new Container(
                                margin: new EdgeInsets.only(right: 16.0),
                                child: new Icon(
                                  Icons.brightness_1,
                                  color: Colors.black,
                                  size: 35.0,
                                ),
                              ),
                              new Text(widget.category),
                            ],
                          )
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ),
        ],
      )
    );
  }
}
</code>```

答:
You need to pass a key to your children. Or else the renderer won't be able to know which SlideTransition got removed, and use the index.

But in your case there's a much easier solution. Use Dismissible

This is exactly what you're trying to do. But already implemented.

Body:
I'm updating a List<Widget> tiles, but even updating, in which I remove one of the elements of tiles, the state of the animation of the element that came out is still active.

In other words, I redo tiles with this.tiles = buildTile(list); the animation state does not change.

In the example below is removed the Widget that has in its text the string foo3, but its animation continues, and the Widget that has in its text the string foo4 receives this animation.

Is there any way to solve this or is this a bug?

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> tiles;
  List foos = [];

  @override
  void initState() {
    this.foos = ['foo1', 'foo2', 'foo3', 'foo4'];
    this.tiles = buildTile(this.foos);
    super.initState();
  }

  //function
  List<Widget> buildTile(List list) {
    var x = [];
    for(var i = 0; i < list.length; i++) {
      x.add(
        new ItemCategory(
          key: new Key(list[i]), //new
          category: list[i],
          onPressed: () {
            setState(() {
              list.removeAt(i);
              this.tiles = buildTile(list);
            });
          },
        )
      );
    }
    return x;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Categories'),
      ),
      body: new ListView(
        padding: new EdgeInsets.only(top: 8.0, right: 0.0, left: 0.0),
        children: this.tiles
      )
    );
  }
}

class ItemCategory extends StatefulWidget {
  ItemCategory({ Key key, this.category, this.onPressed}) : super(key: key);

  final String category;
  final VoidCallback onPressed;

  @override
  ItemCategoryState createState() => new ItemCategoryState();
}

class ItemCategoryState extends State<ItemCategory> with TickerProviderStateMixin {
  ItemCategoryState();

  AnimationController _controller;
  Animation<double> _animation;
  double flingOpening;
  bool startFling = true;

  void initState() {
    super.initState();
    _controller = new AnimationController(duration:
      const Duration(milliseconds: 246), vsync: this);

    _animation = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 1.0, curve: Curves.linear),
    );
  }

  void _move(DragUpdateDetails details) {
    final double delta = details.primaryDelta / 304;
    _controller.value -= delta;
  }

  void _settle(DragEndDetails details) {
    if(this.startFling) {
      _controller.fling(velocity: 1.0);
      this.startFling = false;
    } else if(!this.startFling){
      _controller.fling(velocity: -1.0);
      this.startFling = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    final ui.Size logicalSize = MediaQuery.of(context).size;
    final double _width = logicalSize.width;
    this.flingOpening = -(48.0/_width);

    return new GestureDetector(
      onHorizontalDragUpdate: _move,
      onHorizontalDragEnd: _settle,
      child: new Stack(
        children: <Widget>[
          new Positioned.fill(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFFE57373),
                  ),
                  child: new IconButton(
                    icon: new Icon(Icons.delete),
                    color: new Color(0xFFFFFFFF),
                    onPressed: widget.onPressed
                  )
                ),
              ],
            ),
          ),
          new SlideTransition(
            position: new Tween<Offset>(
              begin:  Offset.zero,
              end: new Offset(this.flingOpening, 0.0),
            ).animate(_animation),
            child: new Container(
              decoration: new BoxDecoration(
                border: new Border(
                  top: new BorderSide(style: BorderStyle.solid, color: Colors.black26),
                ),
                color: new Color(0xFFFFFFFF),
              ),
              margin: new EdgeInsets.only(top: 0.0, bottom: 0.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Expanded(
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        new Container(
                          margin: new EdgeInsets.only(left: 16.0),
                          padding: new EdgeInsets.only(right: 40.0, top: 4.5, bottom: 4.5),
                          child: new Row(
                            children: <Widget>[
                              new Container(
                                margin: new EdgeInsets.only(right: 16.0),
                                child: new Icon(
                                  Icons.brightness_1,
                                  color: Colors.black,
                                  size: 35.0,
                                ),
                              ),
                              new Text(widget.category),
                            ],
                          )
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ),
        ],
      )
    );
  }
}


问:
How to write a List of string arrays to txt file
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

```<code> static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "<div class=&row rowFullWidth form-inline pb10& hidden>",
                                "<div class=&col-sm-4&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "<span class=&pr5 pl5&>/</span><asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "<span class=&pr5 pl5&>-</span><asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<div class=&pt5&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "</div>",
                                "</div>",
                                "</div>",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }
</code>```

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

答:
Change this line:

```<code>List<string[]> listaStringova = new List<string[]>();
</code>```

To:

```<code>List<string> listaStringova = new List<string>();
</code>```

That's how you declare a list of strings. Then change this:

```<code>listaStringova.Add(htmlLinije);
</code>```

To:

```<code>listaStringova.AddRange(htmlLinije);
</code>```

That's how you add all items of your array to your list.

Body:
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

 static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "/<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "-<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "
",
                                "
",
                                "
",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

Body:
Change this line:

List<string[]> listaStringova = new List<string[]>();

To:

List<string> listaStringova = new List<string>();

That's how you declare a list of strings. Then change this:

listaStringova.Add(htmlLinije);

To:

listaStringova.AddRange(htmlLinije);

That's how you add all items of your array to your list.


问:
CORs error when accessing Square V2 API
I'm making a client-side request out to V2 of the Square API using Vue and Axios. My Vue component is as follows:

```<code>import axios from 'axios';
export default {
    mounted() {
        var instance = axios.create({
            baseURL: 'https://connect.squareup.com/v2/',
            timeout: 1000,
            headers: {
                'Authorization': 'Bearer xxxxxxxxxxxxxxxxx',
                'Accepts': 'application/json',
                'Content-Type': 'application/json'
            }
        });
        instance.get('catalog/list')
        .then(function (response) {
            console.log(response);
        }) ;
    }
}
</code>```

However, when I make that call, I receive the following error:

```<code>Failed to load https://connect.squareup.com/v2/catalog/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://local-env.dev' is therefore not allowed access. The response had HTTP status code 403.
</code>```

That error suggests that there is some configuration that has to happen on the Square side, but I saw no opportunity to whitelist domains, etc.

Has anyone come across this error before, regardless of service, and if so, how did you resolve?

答:
I don't think the Square API supports being called from a browser.  I used Postman to do an OPTIONS request on https://connect.squareup.com/v2/catalog/list and the response was a NOT_FOUND.  The OPTIONS request is needed for proper CORS support.

Plus, if you did this, I would think your auth token would need to be sent to the client -- thus exposing it to everyone.  It looks like the Square API is only designed to be called from a server.  But that is just based on me skimming the docs a bit.  I have no experience using their API.

Title: CORs error when accessing Square V2 API

Body:
I'm making a client-side request out to V2 of the Square API using Vue and Axios. My Vue component is as follows:

import axios from 'axios';
export default {
    mounted() {
        var instance = axios.create({
            baseURL: 'https://connect.squareup.com/v2/',
            timeout: 1000,
            headers: {
                'Authorization': 'Bearer xxxxxxxxxxxxxxxxx',
                'Accepts': 'application/json',
                'Content-Type': 'application/json'
            }
        });
        instance.get('catalog/list')
        .then(function (response) {
            console.log(response);
        }) ;
    }
}

However, when I make that call, I receive the following error:

Failed to load https://connect.squareup.com/v2/catalog/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://local-env.dev' is therefore not allowed access. The response had HTTP status code 403.

That error suggests that there is some configuration that has to happen on the Square side, but I saw no opportunity to whitelist domains, etc.

Has anyone come across this error before, regardless of service, and if so, how did you resolve?


问:
Resizing QListWidget's dimensions to fit its contents
I have a subclass of QListWidget, the widget holds text items in a single column and multiple rows (the usual kind). I want the widget to resize itself to the minimum size where the text items will still be visible. I've tried using the resize() method with the contentsSize() argument, this will resize the widget's height to fit the text contents, however the width stays the same.

Here's a snippet of an overriden method that I'm testing this with:

```<code>override void mousePressEvent(QMouseEvent event)
{
    this.resize(this.contentsSize());
}
</code>```

Note: This is in the D language, and I'm using the QtD wrapper library. Unless I'm doing something wrong it might even be a QtD bug (but I doubt it).

答: If you're content to switch to a QTableView or QTreeView, you can call resizeColumnsToContents(), and resize your widget based on the resulting width. Otherwise you'll have to iterate over your QListWidget contents and get the maximum of the widths of the items.</p>

Body:
I have a subclass of QListWidget, the widget holds text items in a single column and multiple rows (the usual kind). I want the widget to resize itself to the minimum size where the text items will still be visible. I've tried using the resize() method with the contentsSize() argument, this will resize the widget's height to fit the text contents, however the width stays the same.

Here's a snippet of an overriden method that I'm testing this with:

override void mousePressEvent(QMouseEvent event)
{
    this.resize(this.contentsSize());
}

Note: This is in the D language, and I'm using the QtD wrapper library. Unless I'm doing something wrong it might even be a QtD bug (but I doubt it).


问:
PHP Variables - opposite strings
I have a single variable $width that can be a string with any one of these values:

shortest, short, half, long, longest

In my template, I want to create 2 elements - one that has the original value of $width and one that has an opposite width:

short is opposite of long and vice-versa

shortest is opposite of longest and vice-versa

half is opposite of half

This is my code which is working exactly as I want it, but it feels a little repetitive and dirty to me, so I was wondering if a cleaner/smarter PHP syntax exists to store the opposite string pairs and refactor/shorten the code or is that as lean as it can get?

```<code><?
// Possible values - shortest, short, half, long, longest
$width = '';

if ($width == 'shortest') {
    $opposite_width = 'longest';
}
if ($width == 'short') {
    $opposite_width = 'long';
}
if ($width == 'half') {
    $opposite_width = 'half';
}
if ($width == 'long') {
    $opposite_width = 'short';
}
if ($width == 'longest') {
    $opposite_width = 'shortest';
}

?>

<div class="<?= width ?>"></div>
<div class="<?= opposite_width ?>"></div>
</code>```

Thank you.

答:
Here a small example of how to use an array as a map:

```<code>$widthMap = [
    'shortest' => 'longest',
    'short' => 'long',
    'half' => 'half',
    'long' => 'short',
    'longest' => 'shortest'
];

$width = 'short';
$widthOpposite = $widthMap[$width];
</code>```

Should be pretty easy to use in your code.

This could be optimized further because you have both directions in one map, when you could also use array_flip for the other direction, but in this case it's simpler with just a few values.

Title: PHP Variables - opposite strings

Body:
I have a single variable $width that can be a string with any one of these values:

shortest, short, half, long, longest

In my template, I want to create 2 elements - one that has the original value of $width and one that has an opposite width:

short is opposite of long and vice-versa

shortest is opposite of longest and vice-versa

half is opposite of half

This is my code which is working exactly as I want it, but it feels a little repetitive and dirty to me, so I was wondering if a cleaner/smarter PHP syntax exists to store the opposite string pairs and refactor/shorten the code or is that as lean as it can get?

<?
// Possible values - shortest, short, half, long, longest
$width = '';

if ($width == 'shortest') {
    $opposite_width = 'longest';
}
if ($width == 'short') {
    $opposite_width = 'long';
}
if ($width == 'half') {
    $opposite_width = 'half';
}
if ($width == 'long') {
    $opposite_width = 'short';
}
if ($width == 'longest') {
    $opposite_width = 'shortest';
}

?>

<div class="<?= width ?>">

<div class="<?= opposite_width ?>">

Thank you.

Body:
Here a small example of how to use an array as a map:

$widthMap = [
    'shortest' => 'longest',
    'short' => 'long',
    'half' => 'half',
    'long' => 'short',
    'longest' => 'shortest'
];

$width = 'short';
$widthOpposite = $widthMap[$width];

Should be pretty easy to use in your code.

This could be optimized further because you have both directions in one map, when you could also use array_flip for the other direction, but in this case it's simpler with just a few values.


问:
Is there a way to run MQ on cloud?
I am a PHP developer and have mostly worked in PHP on the web based systems. I know PHP supports AMQP protocols and on a standalone server I can install a broker like Rabbit MQ / Apache MQ etc and use PHP along with it. I have worked earlier with MQ (IBM MQ, Apache MQ, Fusesoft MQ) and I understand that the broker for above have to run on a standalone server (within a LAN/WAN or may be a VPS). I wanted to understand if there is an available module which could be used as a plugin to the apache server to provide the functionality of the brokers.

I have done my research for this and have found no solution so far. All I have come across are few vendors which offer cloud based services for MQ and not any stand alone product which could be installed on the cloud.

I know cloud are not the best options for creating enterprise level infrastructure which clustered servers in LAN/WAN can provide. I am just looking for available options if any.

Thank in advance for your answers.

答: IBM has announced MQ Cloud product to be available in the near future. The MQ cloud offering is intended to be compatible with on-premise MQ offerings. Within the constraints of a cloud environment, users would be able to use the same development tooling for both the cloud and on-premise software.  </p>

Title: Is there a way to run MQ on cloud?


问:
How to handle path with spaces in Inno Setup?
I want to allow paths with spaces (for example program files) when installing my program with Inno Setup. However paths with spaces let my installed service crash.

The Inno Setup file looks like this:

```<code>[Setup]
AppName=Demo
DefaultDirName={pf}\demo

[Files]
Source: "bin\nssm.exe"; DestDir: "{app}"
Source: "bin\jdk1.8.0_152\jre\*"; DestDir: "{app}\jre"; Flags: recursesubdirs
Source: "build\libs\demo.jar"; DestDir: "{app}"

[Run]
Filename: "{app}\nssm.exe"; \
    Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar ""{app}\demo.jar"""
Filename: "{app}\nssm.exe"; Parameters: "start demo"
</code>```

"nssm.exe" is a service wrapper to execute a java application as a windows service.

The critical part is this line:

```<code>Filename: "{app}\nssm.exe"; \
     Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar ""{app}\demo.jar"""
</code>```

As suggested in this question/answer, I tried to use double double quotes, but this doesn't help, the service is still crashing. If I change DefaultDirName to a path without spaces everything works as expected.

```<code>DefaultDirName=c:\demo
</code>```

How do I have to handle paths with spaces?

答:
The problem was the combination of Inno Setup and nssm, which both are escaping double quotes with double quotes. That makes multiple double quotes necessary.

Solution:

```<code>Filename: "{app}\nssm.exe"; Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar """"""{app}\demo.jar"""""""
</code>```

See nssm documentation section "Quoting issues".

Body:
I want to allow paths with spaces (for example program files) when installing my program with Inno Setup. However paths with spaces let my installed service crash.

The Inno Setup file looks like this:

[Setup]
AppName=Demo
DefaultDirName={pf}\demo

[Files]
Source: "bin\nssm.exe"; DestDir: "{app}"
Source: "bin\jdk1.8.0_152\jre\*"; DestDir: "{app}\jre"; Flags: recursesubdirs
Source: "build\libs\demo.jar"; DestDir: "{app}"

[Run]
Filename: "{app}\nssm.exe"; \
    Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar ""{app}\demo.jar"""
Filename: "{app}\nssm.exe"; Parameters: "start demo"

"nssm.exe" is a service wrapper to execute a java application as a windows service.

The critical part is this line:

Filename: "{app}\nssm.exe"; \
     Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar ""{app}\demo.jar"""

As suggested in this question/answer, I tried to use double double quotes, but this doesn't help, the service is still crashing. If I change DefaultDirName to a path without spaces everything works as expected.

DefaultDirName=c:\demo

How do I have to handle paths with spaces?

Body:
The problem was the combination of Inno Setup and nssm, which both are escaping double quotes with double quotes. That makes multiple double quotes necessary.

Solution:

Filename: "{app}\nssm.exe"; Parameters: "install demo ""{app}\jre\bin\java.exe"" -jar """"""{app}\demo.jar"""""""

See nssm documentation section "Quoting issues".


问:
UINavigationBar seems to pop 2 items off stack on "back"
I'm manually managing a UINavigationBar for my view.  The Bar itself and the first UINavigationItem are created in Interface Builder.  In my code, based upon various events, I push new navigation items onto the bar and paint the appropriate views as subviews of the main view.  It all seems fine, but when I select the navbar back button, two items are lopped off the items stack, rather than 1 as I would have expected.  To test, I set my controller as the delegate for the bar and trap 2 delegate methods:

```<code>- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
</code>```

and

```<code>- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;
</code>```

I found right before the pop, the items in the nav bar is correct, for example, 3.  In the second method, just after the pop, the items is 1, even though the item popped is the last item - somehow the middle item is missing.  I'm stumped as to how to debug this and would appreciate any ideas.

Note that I'm not using a navigation controller for various reasons.

答:
check if the poppage is user initiated or programmatic like so</p>

```<code>- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    UIViewController *topViewController = self.topViewController;

    ... some logic that justifies implementing shouldPopItem: delegate in the first place -> others have explained the caveats so I won't repeat that ...

    // manual as in opposite of programmatic
    BOOL manualPop = topViewController.navigationItem == item;
    if(manualPop) {
        [self popViewControllerAnimated:YES];
    }
    return YES;
}
</code>```

Body:
I'm manually managing a UINavigationBar for my view.  The Bar itself and the first UINavigationItem are created in Interface Builder.  In my code, based upon various events, I push new navigation items onto the bar and paint the appropriate views as subviews of the main view.  It all seems fine, but when I select the navbar back button, two items are lopped off the items stack, rather than 1 as I would have expected.  To test, I set my controller as the delegate for the bar and trap 2 delegate methods:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;

and

- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;

I found right before the pop, the items in the nav bar is correct, for example, 3.  In the second method, just after the pop, the items is 1, even though the item popped is the last item - somehow the middle item is missing.  I'm stumped as to how to debug this and would appreciate any ideas.

Note that I'm not using a navigation controller for various reasons.

Body:
check if the poppage is user initiated or programmatic like so

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    UIViewController *topViewController = self.topViewController;

    ... some logic that justifies implementing shouldPopItem: delegate in the first place -> others have explained the caveats so I won't repeat that ...

    // manual as in opposite of programmatic
    BOOL manualPop = topViewController.navigationItem == item;
    if(manualPop) {
        [self popViewControllerAnimated:YES];
    }
    return YES;
}


问:
GWT client side unchecked exceptions
I've been working on a project which uses GWT (and SmartGWT), which is (are) new to me.

Whenever runtime exceptions are thrown in the client (no RPCs involved) nothing happens. By that I mean the method does not continue executing, there are no alerts, there is nothing in the Javascript error console or the SmartGWT error console.

I'm assuming this isn't normal practice in GWT applications. Where are these errors (e.g. null pointers) normally logged/handled?

Thanks in advance.

答:
You can do catch them in the next way

```<code>GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
  @Override
  public void onUncaughtException(Throwable e) {
    GWT.log(e.getMessage(), e);
  }
});
</code>```

You can replace the GWT.log by any other logging method.

Title: GWT client side unchecked exceptions

Body:
You can do catch them in the next way

GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
  @Override
  public void onUncaughtException(Throwable e) {
    GWT.log(e.getMessage(), e);
  }
});

You can replace the GWT.log by any other logging method.


问:
3D Line Projection onto a Quad Mesh
I have two 3D points, A and B. These points lie on the surface formed by a quad mesh, M. A and B are not guaranteed to be vertices of the mesh and the line formed between obviously is not guaranteed to lie exactly on the surface.

Lets image one wants to travel from A to B. If we imagine we could project the line onto the surface, I wish to recover the list of faces that projection intersects as we complete the walk from A to B. The line isn't guaranteed to always be inside or outside of the mesh, in fact it could switch from inside to outside or vice versa.

You could think of it as if you were to take a walk along the mesh surface following this line in the "sky" what faces would you visit as you followed the trail from A to B.

I don't need to recover the geodesic distance and I know the line A->B in advance, so it isn't a path finding exercise as such.

How could one go about doing this efficiently?

答:
Hints:

The projection is not really defined as long as you don't have a projection direction. Maybe you want a projection which is as orthogonal as possible to the surface ? Maybe a constant direction can do ? (In the latter case, you just need to intersect the surface with a plane.)

You have to find the facets that are close to the line. If you look in the direction of the segment, the faces will appear as line segments and you have to find the segments close to the projected line (seen as a single point).

If you have arranged the facets in a hierarchy of bounding spheres, you can look in any direction, and efficiently find candidate segments (faces). Using the spheres, you can also reject those that do not intersect the (bounded) line in 3D, past the endoints.

Then you can use the faces close to the endpoints to choose a plane direction, and get the individual intersections of the faces with the plane, and reconstruct a 3D polyline.

Title: 3D Line Projection onto a Quad Mesh


问:
get list of quarters between two dates (SQL)
I would like to receive a list of quarters between given dates (startDate and EndDate parameter).

For example partial quarter dates:

```<code>StartDate : 2017-01-01
EndDate : 2017-06-15
Result : Q1 Q2
</code>```

another sample :

```<code>StartDate : 2017-01-01
EndDate : 2017-06-30
Result : Q2
</code>```

答:
If open to a TVF. I'll often use a Table-Valued Function to return dynamic datetime ranges.

Example - Rows

```<code>Select *
      ,Qtr='Q'+DateName(QUARTER,RetVal)
 from [dbo].[tvf-Range-Date]('2017-01-01','2017-06-15','QQ',1)
</code>```

Returns

```<code>RetSeq  RetVal      Qtr
1       2017-01-01  Q1
2       2017-04-01  Q2
</code>```

Example - Single String

```<code>Select Qtr = Stuff((Select Distinct ' ' + 'Q'+DateName(QUARTER,RetVal)
                     From  [dbo].[tvf-Range-Date]('2017-01-01','2017-06-15','QQ',1)
                     For XML Path ('')),1,1,'')
</code>```

Returns

```<code>Qtr
Q1 Q2
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[tvf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D
     From  cte3,cte0
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[tvf-Range-Date]('2016-10-01','2020-10-01','YY',1)
Select * from [dbo].[tvf-Range-Date]('2016-01-01','2017-01-01','MM',1)
Select * from [dbo].[tvf-Range-Date]('2017-01-01','2017-01-02','MI',15)
*/
</code>```

Body:
I would like to receive a list of quarters between given dates (startDate and EndDate parameter).

For example partial quarter dates:

StartDate : 2017-01-01
EndDate : 2017-06-15
Result : Q1 Q2

another sample :

StartDate : 2017-01-01
EndDate : 2017-06-30
Result : Q2

Body:
If open to a TVF. I'll often use a Table-Valued Function to return dynamic datetime ranges.

Example - Rows

Select *
      ,Qtr='Q'+DateName(QUARTER,RetVal)
 from [dbo].[tvf-Range-Date]('2017-01-01','2017-06-15','QQ',1)

Returns

RetSeq  RetVal      Qtr
1       2017-01-01  Q1
2       2017-04-01  Q2

Example - Single String

Select Qtr = Stuff((Select Distinct ' ' + 'Q'+DateName(QUARTER,RetVal)
                     From  [dbo].[tvf-Range-Date]('2017-01-01','2017-06-15','QQ',1)
                     For XML Path ('')),1,1,'')

Returns

Qtr
Q1 Q2

The UDF if Interested

CREATE FUNCTION [dbo].[tvf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D
     From  cte3,cte0
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[tvf-Range-Date]('2016-10-01','2020-10-01','YY',1)
Select * from [dbo].[tvf-Range-Date]('2016-01-01','2017-01-01','MM',1)
Select * from [dbo].[tvf-Range-Date]('2017-01-01','2017-01-02','MI',15)
*/


问:
How to resize an image on preview (no database)
I have script to preview input type=file (image), and generate it into pdf.

There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.

So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.

Please help how to resize it on my script.

Script:

```<code>  function previewFile(){
   var preview = document.querySelector('img'); //selects the query named img
   var file    = document.querySelector('input[type=file]').files[0]; //sames as here
   var reader  = new FileReader();

   reader.onloadend = function () {
     console.log(reader.result);
       //preview.src = reader.result;
       $('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
   }

   if (file) {
       reader.readAsDataURL(file); //reads the data as a URL
   } else {
       preview.src = "";
   }
}
</code>```

HTML:

```<code><!doctype html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/magang/front.css">
</head>
<body>
    <div class="corpname" contenteditable>RUMAH SAKIT HARUM</div>
    <div class="logosisma"><img src="https://sismadigroup.com/idcard/images/background/logo-id-card.png" width="219" height="70" /></div>
    <div class="logo">
        <!--<img src="resize/resize.php?src=https://sismadigroup.com/idcard/templates/images/avatar/3.jpg&scale=10&q=100">-->
        <img src="https://sismadigroup.com/idcard/templates/images/avatar/3.jpg" width="200" height="240" />
    </div>
    <div class="name highlight" contenteditable>Maesyaroh</div>
    <div class="position" contenteditable>Siswa Magang</div>
    <div class="nik" contenteditable>SM-0035</div>
    <div class="BBP">BENAR   BAIK   PANTAS</div>
    <div class="BBPPoint" style="left:135px;"> . </div>
    <div class="BBPPoint" style="left:203px;"> . </div>
</body>
</html>
</code>```

Edit: PHP for PDF generation:

```<code>$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');
</code>```

答:
I solved the same problem on front-end, before uploading file. You can visit a link!</p>

```<code>import imageSqResizer from './image-square-resizer.js'

let resizer = new imageSqResizer(
    'image-input',
    300,
    (dataUrl) =>
        document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);

//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;
</code>```

Body:
I have script to preview input type=file (image), and generate it into pdf.

There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.

So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.

Please help how to resize it on my script.

Script:

  function previewFile(){
   var preview = document.querySelector('img'); //selects the query named img
   var file    = document.querySelector('input[type=file]').files[0]; //sames as here
   var reader  = new FileReader();

   reader.onloadend = function () {
     console.log(reader.result);
       //preview.src = reader.result;
       $('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
   }

   if (file) {
       reader.readAsDataURL(file); //reads the data as a URL
   } else {
       preview.src = "";
   }
}

HTML:

<!doctype html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/magang/front.css">

RUMAH SAKIT HARUM

Maesyaroh

Siswa Magang

SM-0035

BENAR   BAIK   PANTAS

 .

 .

Edit: PHP for PDF generation:

$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');

Body:
I solved the same problem on front-end, before uploading file. You can visit a link!

import imageSqResizer from './image-square-resizer.js'

let resizer = new imageSqResizer(
    'image-input',
    300,
    (dataUrl) =>
        document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);

//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;


问:
Populate select options from database to dynamic select option using jQuery
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

```<code><?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>
<script>
   var members = "<?php echo $members; ?>";

   $(document).ready(function() {
          var fixHelperModified = function(e, div) {
                var $originals = div.children();
                var $helper = div.clone();
                $helper.children().each(function(index) {
                   $(this).width($originals.eq(index).width())
                });
                return $helper;
             },
             updateIndex = function() {
                $('div.index').each(function(i) {
                   $(this).html(i + 1);
                });
             };
          $("#add").sortable({
             helper: fixHelperModified,
             stop: updateIndex
          }).disableSelection();
          $("#addNew").click(function() {
             $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option>"+members+"</select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
             updateIndex();
          });
          $("body").on('click', '#add .delete', function() {
             $(this).closest(".rem").remove();
             updateIndex();
          });
       });
</script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>
</code>```

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form></code>```

答: Each option have double quotation marks and u put string inside same marks, if i correct understood it will break your code, try wrap inside single quotation or use var myvar = <?php echo json_encode($myVarValue); ?>;

Body:
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

<?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>


问:
Vaadin - multiple error handlers
The project I'm working on already has a "custom" error handler but I have a task to make another one which handles only one exception. My question is can the two handlers co-exist and if yes - where do I set mine to be used by the project?</p>

答:
According to Documentation page about handling errors:

You can customize the default error handling by implementing a custom ErrorHandler and enabling it with setErrorHandler() in any of the components in the component hierarchy, including the UI, or in the VaadinSession object.

That means that what you need to do is most likely doable, and exception will be handled by first error handler it arrives at - unless you want to have two error handlers on the same component (i.e. UI) which is impossible.

Title: Vaadin - multiple error handlers


问:
Custom control Lib with multiple controls and generic.xaml
if i define two default styles for two different controls in one custom control lib i get errors...

is it possible to have two or more controls with a default generic.xaml in one lib?

Thanks

答:
Yes.

Not only is it possible, it is the default behavior.

This is, of course, assuming that the two controls are in the same namespace.

You don't specify the error(s) that you are getting, so I can't offer much more detail.


问:
imessage extension not showing icon xcode ios
I have assigned all the icon size according to apple's guidance about the iMessage extension icon. but the imessage extension won't show the app icon

答: It's just a temporary thing. After some reinstalls or simulator-restarts, it'll show. May be it's some kind of bug in X-Code/Simulator.</p>


问:
make Content_tag to print two elements in same line(Rails)
```<code>content_tag(:p, "link : ") + content_tag(:p, link_to("abc","www.abc.com"))
</code>```

This prints

```<code>link:
abc
</code>```

But I want it to print

```<code>link: abc
</code>```

答:
(Paragraph) is a block element and it's HTML mechanics (so it always takes the whole width of it's container). It doesn't have any relation to ruby/rails code and you can't achieve it making any changes in ruby code. You can achieve with some hacky CSS solutions. But good solution is to go with inline  tags. It will do what you want. And you can use single
 as root element for 2

Body:
content_tag(:p, "link : ") + content_tag(:p, link_to("abc","www.abc.com"))

This prints

link:
abc

But I want it to print

link: abc

Body: <p>(Paragraph) is a block element and it's HTML mechanics (so it always takes the whole width of it's container). It doesn't have any relation to ruby/rails code and you can't achieve it making any changes in ruby code. You can achieve with some hacky CSS solutions. But good solution is to go with inline <span> tags. It will do what you want. And you can use single <p> as root element for 2 <span>


问:
Add an X to the end of a div with pure CSS?
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span></code>```

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

答:
I thought I'd add my way, just in case. I never think it's worth over complicating things but in this instance, I think it's worth using a hex code to get a better character than an 'X' (I've used the multiplication symbol).

Also vertically aligning your text to the centre will make the everything pleasing to the eye, or at least it does for me.

These are the 4 lines of CSS needed.

```<code>.categoryTag::after {
  content: ' \D7';
  vertical-align: middle;
}
</code>```

EXAMPLE:

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  padding: 6px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after {
  content: ' \D7';
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">Category 1</span>
<span class="categoryTag">Category 2</span>
<span class="categoryTag">Category 3</span></code>```

I hope you find this helpful.

Body:
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

category 1
category 2
category 3

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

Body:
I thought I'd add my way, just in case. I never think it's worth over complicating things but in this instance, I think it's worth using a hex code to get a better character than an 'X' (I've used the multiplication symbol).

Also vertically aligning your text to the centre will make the everything pleasing to the eye, or at least it does for me.

These are the 4 lines of CSS needed.

.categoryTag::after {
  content: ' \D7';
  vertical-align: middle;
}

EXAMPLE:

.categoryTag {
  display: inline-block;
  background-color: #eaeaea;
  border-radius: 4px;
  padding: 6px;
  font-size: 12px;
  cursor: pointer;
  margin: 4px;
}

.categoryTag::after {
  content: ' \D7';
  vertical-align: middle;
}

<span class="categoryTag">Category 1</span>
<span class="categoryTag">Category 2</span>
<span class="categoryTag">Category 3</span>

I hope you find this helpful.


答:
You can make array with opposite values, kind of map like normal -> opposite. Simple implementation:

```<code>function getOpposite($word) {
    $map = [
       'shortest' => 'longest',
       'short' => 'long',
       'half' => 'half'
    ];

    if(isset($map[$word])) {
        return $map[$word];
    }

    //reverse finding
    $flippedMap = array_flip($map);

    if(isset($flippedMap[$word])) {
        return $flippedMap[$word];
    }

    return null;
}
</code>```

Now you can use function in your view:

```<code><div class="<?= $width ?>"></div>
<div class="<?= getOpposite($width) ?>"></div>
</code>```

Title: PHP Variables - opposite strings

Body:
You can make array with opposite values, kind of map like normal -> opposite. Simple implementation:

function getOpposite($word) {
    $map = [
       'shortest' => 'longest',
       'short' => 'long',
       'half' => 'half'
    ];

    if(isset($map[$word])) {
        return $map[$word];
    }

    //reverse finding
    $flippedMap = array_flip($map);

    if(isset($flippedMap[$word])) {
        return $flippedMap[$word];
    }

    return null;
}

Now you can use function in your view:

<div class="<?= $width ?>"></div>
<div class="<?= getOpposite($width) ?>"></div>


问:
SPI kernel module, how to istantiate the driver?

I've been tasked to import the spi driver into an existing platform running Openwrt.

After  "successfully" build the full Openwrt: packages and the kernel matching the one running into the platform, including the spidev kernel module I run into some trouble in make this module work.

**insmod** of the driver terminates without error, and I see that in the **/sys/class** the creation of the directory **spidev**, but it is empty.

Looking at the code of the spidev kernel module, the function **probe** has caught my eye. My feel is that this function is what actually allocates the minor device number an make the device available to be used. But it's not clear to me who, or what should call it.

Another doubt I have is about the architecture. The spi depends on the underlaying architecture, which in my case is the MT7620 soc which is a mipsel architecture have a specific spi code. In my understanding this SOC specific code is wrapped by the spidev kernel module and the link between these two entities should be
```<code>status = spi_register_driver(&spidev_spi_driver);
</code>```

in the

```<code>static int __init spidev_init(void)
</code>```

function.

Again, I'm far to be sure of what I'm writing and I'm here asking for directions.

答:
First, you may want to read the Linux Device Driver - Chapter 14.

Generally speaking, in the Linux kernel you have devices and drivers on a bus (subsystem). You have to register them using the functions register_device() and register_driver() (the exact name depends on the subsystem). When a device or a driver get registered the subsystem will try to match devices with drivers. If they match, the subsystem calls the driver's function probe(). So, the execution of the probe() function can be triggered by the driver registration or the device registration. This also means that the device exists before the execution of probe()

Back to your specific case: SPI. To register a device instance you need to use spi_alloc_device and spi_add_device, or spi_new_device. Where to put this code? This depends on your need. Typically, the SPI devices are declared in some architecture file or device-tree description. Probably you can also do it in a module (not sure).

The spidev is a Linux device driver that exports the SPI raw interface to the user-space. This means that once you register an SPI device instance the driver spidev take control of it. Actually, the spidev does nothing: it waits for an user-space program to read/write data on the SPI bus. So, you will end up writing the driver for your device in userspace.

Body:
I've been tasked to import the spi driver into an existing platform running Openwrt.

After  "successfully" build the full Openwrt: packages and the kernel matching the one running into the platform, including the spidev kernel module I run into some trouble in make this module work.

**insmod** of the driver terminates without error, and I see that in the **/sys/class** the creation of the directory **spidev**, but it is empty.

Looking at the code of the spidev kernel module, the function **probe** has caught my eye. My feel is that this function is what actually allocates the minor device number an make the device available to be used. But it's not clear to me who, or what should call it.

Another doubt I have is about the architecture. The spi depends on the underlaying architecture, which in my case is the MT7620 soc which is a mipsel architecture have a specific spi code. In my understanding this SOC specific code is wrapped by the spidev kernel module and the link between these two entities should be

status = spi_register_driver(&spidev_spi_driver);

in the

static int __init spidev_init(void)

function.

Again, I'm far to be sure of what I'm writing and I'm here asking for directions.