问:
How to replace a column value which is missing?
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

```<code>                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN
</code>```

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

```<code>df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)
</code>```

Then I tried:

```<code>df_74034.at[0, 'data/hora'] = 0
</code>```

And I got:

```<code>A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value
</code>```

Thanks for any help!

Body:
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)

Then I tried:

df_74034.at[0, 'data/hora'] = 0

And I got:

A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value

Thanks for any help!

Body:
Your issue is those 2 cells containing whitespaces (blank, tabs or emtpy string). To handle them in general, just use str.strip before compare to ''. You may assign directly using loc and boolean mask on equal of ''

df_74034.loc[df_74034['data/hora'].str.strip().eq(''), 'data/hora'] = t.HumTechRoom

Out[1891]:
                    data/hora  HumExamRoom                 HumTechRoom  \
0  2017-08-18\t09:22:33\t65.9          NaN  2017-08-18\t09:22:33\t65.9
1  2017-10-03\t11:08:26\t60.5          NaN  2017-10-03\t11:08:26\t60.5
2        2018-02-17\t01:45:24          NaN                        69.7
3        2018-02-17\t01:45:55          NaN                        67.5
4        2018-02-17\t01:46:29          NaN                        65.4
5        2018-02-17\t01:47:20          NaN                        63.3
6        2018-02-17\t01:48:35          NaN                        61.3
7        2018-02-17\t01:49:08          NaN                        63.4
8        2018-02-17\t01:49:31          NaN                        65.5

   Machine  TempExamRoom  TempTechRoom
0    74034           NaN           NaN
1    74034           NaN           NaN
2    74034           NaN           NaN
3    74034           NaN           NaN
4    74034           NaN           NaN
5    74034           NaN           NaN
6    74034           NaN           NaN
7    74034           NaN           NaN
8    74034           NaN           NaN


来源: stackexchange

问:
How do I type m≤n in Emacs's Agda mode without it turning into m≰?
What is the best way to type something like m≤n in Emacs's Agda mode?

If I type m \ < = n I get  m≰, which is annoying.

My current workaround is to type m \ < = Space Backspace n but it is not very ergonomic.

Is there something I can do that doesn't require me to type an useless key and then immediately delete it with backspace?

答:
Another option is to use Ctrl+g to exit the "character composition" mode.

So to inputm≤n you can type m \ < = (Ctrl+g) n

ContentLicense: CC BY-SA 4.0


问:
Error when trying to open a file inside a docker with Elixir
I'm inside a docker, running a test and trying to open a file using File.open.

This is my test code:

```<code>upload = %Plug.Upload{
        filename: "funcionarios.csv",
        path: Path.expand("/home/company/code/project/apps/project_web/test/project_2/resolver/funcionarios.csv", __DIR__)
      }
</code>```

This is the error I get:

** (File.Error) could not open "/home/company/code/project/apps/project_web/test/project_2/resolver/funcionarios.csv": no such file or directory

What am I doing wrong?

答:
The problem is that I run my code inside a container and I was passing the local path not the container path.

Using the Path.expand it converts the path to an absolute one.

The correct code is:

```<code>upload = %Plug.Upload{
        filename: "funcionarios.csv",
        path: Path.expand("funcionarios.csv", __DIR__)
      }
</code>```

Body:
I'm inside a docker, running a test and trying to open a file using File.open.

This is my test code:

upload = %Plug.Upload{
        filename: "funcionarios.csv",
        path: Path.expand("/home/company/code/project/apps/project_web/test/project_2/resolver/funcionarios.csv", __DIR__)
      }

This is the error I get:

** (File.Error) could not open "/home/company/code/project/apps/project_web/test/project_2/resolver/funcionarios.csv": no such file or directory

What am I doing wrong?

Body:
The problem is that I run my code inside a container and I was passing the local path not the container path.

Using the Path.expand it converts the path to an absolute one.

The correct code is:

upload = %Plug.Upload{
        filename: "funcionarios.csv",
        path: Path.expand("funcionarios.csv", __DIR__)
      }


问:
Is there a way to connect my YOLO v3 model to my webcam?
I'm following this GitHub repo on yolo_v3 using TensorFlow. The code runs smoothly on single images (images I'm loading from my computer), but I'm trying to connect the model to my webcam.

I tried to look into OpenCV tutorial on capturing a video from camera, but I can't figure out how to combine that with the statement that starts a TensorFlow session to run my model:

```<code>batch_size = len(img_names)
batch = load_images(img_names, model_size=_MODEL_SIZE)

class_names = load_class_names('files/coco.names')
n_classes = len(class_names)
max_output_size = 10
iou_threshold = 0.5
confidence_threshold = 0.5

tf.reset_default_graph()

model = Yolo_v3(n_classes=n_classes, model_size=_MODEL_SIZE,
            max_output_size=max_output_size,
            iou_threshold=iou_threshold,
            confidence_threshold=confidence_threshold)

inputs = tf.placeholder(tf.float32, [batch_size, 416, 416, 3]) #I think
that the batch size will be 1 since we're dealing with 1 frame at a time

detections = model(inputs, training=False)
model_vars = tf.global_variables(scope='yolo_v3_model')
assign_ops = load_weights(model_vars, 'files/yolov3.weights')

with tf.Session() as sess:
    sess.run(assign_ops)
    detection_result = sess.run(detections, feed_dict={inputs: batch})

draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)
</code>```

EDIT:

I have tried to run:

```<code>def generator():
    cap = cv2.VideoCapture(0)
    cap.set(3,416)
    cap.set(4,416)

    time.sleep(10)

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)
</code>```

But I'm either getting an error that says that the image was not loaded properly (empty frame), or this:

```<code>ValueError: Cannot feed value of shape (1, 240, 320, 3) for Tensor 'Placeholder:0', which has shape '(1, 416, 416, 3)'
</code>```

EDIT 2

I feel like it's almost working. I ran

```<code>def generator():
    cap = cv2.VideoCapture(0)
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        frame = cv2.resize(frame, (416, 416))
        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(frame, detection_result, class_names, _MODEL_SIZE)
</code>```

But I'm getting this error:

```<code>AttributeError: 'numpy.ndarray' object has no attribute 'read'
</code>```

I tried to run the code without the last part:

```<code>draw_boxes(frame, detection_result, class_names, _MODEL_SIZE)
</code>```

and my camera does in fact turn on, though without any object detection (the YOLO model)

This is the draw_boxes function by the way:

```<code>def draw_boxes(img_names, boxes_dicts, class_names, model_size):
    """Draws detected boxes.

    Args:
        img_names: A list of input images names.
        boxes_dict: A class-to-boxes dictionary.
        class_names: A class names list.
        model_size: The input size of the model.

    Returns:
        None.
    """
    for num, img_name, boxes_dict in zip(range(len(img_names)), img_names,
                                         boxes_dicts):
        img = Image.open(img_name)
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype(font='files/futur.ttf',
                                  size=(img.size[0] + img.size[1]) // 100)
        resize_factor = \
            (img.size[0] / model_size[0], img.size[1] / model_size[1])
        for cls in range(len(class_names)):
            boxes = boxes_dict[cls]
            if np.size(boxes) != 0:
                color = np.random.permutation([np.random.randint(256), 255, 0])
                for box in boxes:
                    xy, confidence = box[:4], box[4] #xy – Top left corner of the text.
                    xy = [xy[i] * resize_factor[i % 2] for i in range(4)]
                    x0, y0 = xy[0], xy[1]
                    thickness = (img.size[0] + img.size[1]) // 200
                    for t in np.linspace(0, 1, thickness):
                        xy[0], xy[1] = xy[0] + t, xy[1] + t
                        xy[2], xy[3] = xy[2] - t, xy[3] - t
                        draw.rectangle(xy, outline=tuple(color))
                    if class_names[cls] =='car':
                        text = '{} {:.1f}% about {:.1f} cm away'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100,
                                                  Distance_To_Obect(4.3,121,780,xy[3]-xy[1],3.5).distance())
                    elif class_names[cls] =='person':
                        width, height = img.size
                        print(width, height)
                        text = '{} {:.1f}% about {:.1f} cm away'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100,
                                                  Distance_To_Obect(4.3,170,height,xy[3]-xy[1],3.5).distance())

                    else:
                        text = '{} {:.1f}%'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100)
                    text_size = draw.textsize(text, font=font)

                    print ('[x0, y0, x1, y1]', xy[0], xy[1] ,xy[2], xy[3])

                    draw.rectangle(
                        [x0, y0 - text_size[1], x0 + text_size[0], y0],
                        fill=tuple(color)) #fill – Color to use for the text
                    draw.text((x0, y0 - text_size[1]), text, fill='black',
                              font=font)

        display(img)
</code>```

I tried to replace the

```<code>img = Image.open(img_name)
</code>```

with

```<code>Image.fromarray(img_name)
</code>```

But I got an error (after running the file again):

```<code>TypeError: function takes exactly 1 argument (3 given)
</code>```

Also, I have ran

```<code>def generator():
    cap = cv2.VideoCapture(0)
    cap.set(3,416)
    cap.set(4,416)

    time.sleep(10)

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)
</code>```0

And it does contain points

EDIT 3

I tried changing the draw_boxes method to the one in this link

But I got this error:

```<code>def generator():
    cap = cv2.VideoCapture(0)
    cap.set(3,416)
    cap.set(4,416)

    time.sleep(10)

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)
</code>```1

EDIT 4

This is the result_box by the way:

```<code>def generator():
    cap = cv2.VideoCapture(0)
    cap.set(3,416)
    cap.set(4,416)

    time.sleep(10)

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)
</code>```2

答:
in the link you provided the frame is the image you need to feed to yolo. You could place the whole while true from the link into the session and just process frame by frame by running:

```<code>detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
</code>```

or write a generator that provides the frames, kind of cleaner.

```<code>def generator()
    cap = cv2.VideoCapture(0)
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        frame = cv2.resize(frame, (416, 416))
        yield frame
</code>```

and then in your could do:

```<code>with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
</code>```

The expand dims is to create a batch of 1, so eg: makes 399x399x3 into 1x399x399x3.

Something like that, hope it helps a bit

EDIT

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

def convert_bbox_to_absolute(bbox_list, w_img, h_img):
    """
    method to convert the relative points (< 1) to absolute points (< 416)
    :param bbox_list: (list) list of boundary boxes (x, y, w, h, probability)
    :param w_img: (int) width of the image
    :param h_img: (int) height of the image
    :return: bbox_list: (list) list of boundary boxes but this time scaled up
    """
    x, y, w, h, c = zip(*bbox_list)
    y = list(map(lambda y: int(y * w_img), y))
    w = list(map(lambda w: int(w * h_img), w))

    x = list(map(lambda x: int(x * h_img), x))
    h = list(map(lambda h: int(h * w_img), h))
    bbox_list = zip(x, y, w, h, c)
    return list(bbox_list)

def draw_boxes(image, bbox_list):
    """
    Will draw the rectangles on th image and place the probability on them
    :param image:  (np.ndarray) a RGB-color image
    :param bbox_list: (list) list of boundary boxes (x, y, w, h, probability)
    """
    assert type(image) == np.ndarray
    assert type(bbox_list) == list

    assert len(image.shape) == 3
    assert len(bbox_list[0]) == 5

    # get the width and height of the image
    w_img, h_img, _ = image.shape

    # convert the box coordinates to absolute values
    bbox_list = convert_bbox_to_absolute(bbox_list, w_img, h_img)
    for bbox in bbox_list:
        x, y, w, h, c = bbox
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 3)
        cv2.putText(image, str(c), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
    cv2.imshow("", image)
    cv2.waitKey(0)

# creating a black test RGB-image
test_image = np.zeros((512, 416, 3))

# faking some boundary boxes, x, y, w, h, confidence
b_boxes = [[0.5, 0.1, 0.5, 0.9, 0.8], [0.4, 0.1, 0.1, 0.1, 0.4]]

draw_boxes(test_image, b_boxes)
</code>```

This is a very simple example of how you can draw boundary boxes, I assumed that the provided boxes by yolo are normalised because of this link. If you know how I can determine which label belongs to which box, then I'll add that to the code as well.

EDIT 2:

```<code>import numpy as np
import cv2
from random import choices
from string import ascii_lowercase

def draw_boxes(image, bbox_list, label_list):
    """
    Will draw the rectangles on th image and place the probability on them
    :param image:  (np.ndarray) a RGB-color image
    :param bbox_list: (list[dict()]) list dict of boundary boxes  label:(x, y, w, h, probability)
    :param label_list: (list) a list of label names matching the order of the dict keys
    """
    bbox_dict = bbox_list[0]
    assert type(image) == np.ndarray
    assert type(bbox_dict) == dict
    assert type(label_list) == list

    assert len(image.shape) == 3
    assert len(bbox_dict.keys()) == 80
    assert len(label_list) == 80

    for label, bbox in bbox_dict.items():
        if bbox.size == 0:
            continue
        x1, y1, x2, y2, c = np.squeeze(bbox)
        x1, y1, x2, y2 = list(map(lambda val: int(val), [x1, y1, x2, y2]))
        label = label_list[label] + ": {}".format(c)

        cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 3)
        cv2.putText(image, label, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
    cv2.imshow("", image)
    cv2.waitKey(0)

# creating a black test RGB-image
test_image = np.zeros((512, 416, 3))

# faking some boundary boxes, x, y, w, h, confidence and auto generating empty arrays with keys, to match your data
b_boxes = [{
    0: np.array([[131.96371, 131.70601, 341.41946, 358.6781, 0.68467134]]),
    1: np.array([])
}]
for i in range(2, 80):
    b_boxes[0][i] = np.array([])

# get 80 random 10 letter strings to mock labels
labels = ["".join(choices(ascii_lowercase, k=10)) for _ in range(80)]

draw_boxes(test_image, b_boxes, labels)
</code>```

Given your data, I made some changes, hope this helps

Body:
I'm following this GitHub repo on yolo_v3 using TensorFlow. The code runs smoothly on single images (images I'm loading from my computer), but I'm trying to connect the model to my webcam.

I tried to look into OpenCV tutorial on capturing a video from camera, but I can't figure out how to combine that with the statement that starts a TensorFlow session to run my model:

batch_size = len(img_names)
batch = load_images(img_names, model_size=_MODEL_SIZE)

class_names = load_class_names('files/coco.names')
n_classes = len(class_names)
max_output_size = 10
iou_threshold = 0.5
confidence_threshold = 0.5

tf.reset_default_graph()

model = Yolo_v3(n_classes=n_classes, model_size=_MODEL_SIZE,
            max_output_size=max_output_size,
            iou_threshold=iou_threshold,
            confidence_threshold=confidence_threshold)

inputs = tf.placeholder(tf.float32, [batch_size, 416, 416, 3]) #I think
that the batch size will be 1 since we're dealing with 1 frame at a time

detections = model(inputs, training=False)
model_vars = tf.global_variables(scope='yolo_v3_model')
assign_ops = load_weights(model_vars, 'files/yolov3.weights')

with tf.Session() as sess:
    sess.run(assign_ops)
    detection_result = sess.run(detections, feed_dict={inputs: batch})

draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)

EDIT:

I have tried to run:

def generator():
    cap = cv2.VideoCapture(0)
    cap.set(3,416)
    cap.set(4,416)

    time.sleep(10)

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(img_names, detection_result, class_names, _MODEL_SIZE)

But I'm either getting an error that says that the image was not loaded properly (empty frame), or this:

ValueError: Cannot feed value of shape (1, 240, 320, 3) for Tensor 'Placeholder:0', which has shape '(1, 416, 416, 3)'

EDIT 2

I feel like it's almost working. I ran

def generator():
    cap = cv2.VideoCapture(0)
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        frame = cv2.resize(frame, (416, 416))
        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        yield frame
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
        draw_boxes(frame, detection_result, class_names, _MODEL_SIZE)

But I'm getting this error:

AttributeError: 'numpy.ndarray' object has no attribute 'read'

I tried to run the code without the last part:

draw_boxes(frame, detection_result, class_names, _MODEL_SIZE)

and my camera does in fact turn on, though without any object detection (the YOLO model)

This is the draw_boxes function by the way:

def draw_boxes(img_names, boxes_dicts, class_names, model_size):
    """Draws detected boxes.

    Args:
        img_names: A list of input images names.
        boxes_dict: A class-to-boxes dictionary.
        class_names: A class names list.
        model_size: The input size of the model.

    Returns:
        None.
    """
    for num, img_name, boxes_dict in zip(range(len(img_names)), img_names,
                                         boxes_dicts):
        img = Image.open(img_name)
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype(font='files/futur.ttf',
                                  size=(img.size[0] + img.size[1]) // 100)
        resize_factor = \
            (img.size[0] / model_size[0], img.size[1] / model_size[1])
        for cls in range(len(class_names)):
            boxes = boxes_dict[cls]
            if np.size(boxes) != 0:
                color = np.random.permutation([np.random.randint(256), 255, 0])
                for box in boxes:
                    xy, confidence = box[:4], box[4] #xy – Top left corner of the text.
                    xy = [xy[i] * resize_factor[i % 2] for i in range(4)]
                    x0, y0 = xy[0], xy[1]
                    thickness = (img.size[0] + img.size[1]) // 200
                    for t in np.linspace(0, 1, thickness):
                        xy[0], xy[1] = xy[0] + t, xy[1] + t
                        xy[2], xy[3] = xy[2] - t, xy[3] - t
                        draw.rectangle(xy, outline=tuple(color))
                    if class_names[cls] =='car':
                        text = '{} {:.1f}% about {:.1f} cm away'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100,
                                                  Distance_To_Obect(4.3,121,780,xy[3]-xy[1],3.5).distance())
                    elif class_names[cls] =='person':
                        width, height = img.size
                        print(width, height)
                        text = '{} {:.1f}% about {:.1f} cm away'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100,
                                                  Distance_To_Obect(4.3,170,height,xy[3]-xy[1],3.5).distance())

                    else:
                        text = '{} {:.1f}%'.format(class_names[cls], #text – Text to be drawn.
                                                   confidence * 100)
                    text_size = draw.textsize(text, font=font)

                    print ('[x0, y0, x1, y1]', xy[0], xy[1] ,xy[2], xy[3])

                    draw.rectangle(
                        [x0, y0 - text_size[1], x0 + text_size[0], y0],
                        fill=tuple(color)) #fill – Color to use for the text
                    draw.text((x0, y0 - text_size[1]), text, fill='black',
                              font=font)

        display(img)

I tried to replace the

img = Image.open(img_name)

with

Image.fromarray(img_name)

But I got an error (after running the file again):

TypeError: function takes exactly 1 argument (3 given)

Also, I have ran

print (detection_result)

And it does contain points

EDIT 3

I tried changing the draw_boxes method to the one in this link

But I got this error:

OSError                                   Traceback (most recent call last)
<ipython-input-5-fa46870a1059> in <module>
    105         detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})
    106         print(detection_result)
--> 107         draw_boxes(frame, detection_result, class_names, _MODEL_SIZE)

<ipython-input-5-fa46870a1059> in draw_boxes(image, boxes, box_classes, class_names, scores)
     36     font = ImageFont.truetype(
     37         font='font/FiraMono-Medium.otf',
---> 38         size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
     39     thickness = (image.size[0] + image.size[1]) // 300
     40

~\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFont.py in truetype(font, size, index, encoding, layout_engine)
    278
    279     try:
--> 280         return FreeTypeFont(font, size, index, encoding, layout_engine)
    281     except IOError:
    282         ttf_filename = os.path.basename(font)

~\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFont.py in __init__(self, font, size, index, encoding, layout_engine)
    143         if isPath(font):
    144             self.font = core.getfont(font, size, index, encoding,
--> 145                                      layout_engine=layout_engine)
    146         else:
    147             self.font_bytes = font.read()

OSError: cannot open resource

EDIT 4

This is the result_box by the way:

[{0: array([[131.96371   , 131.70601   , 341.41946   , 358.6781    ,
          0.68467134]], dtype=float32), 1: array([], shape=(0, 5), dtype=float32), 2: array([], shape=(0, 5), dtype=float32), 3: array([], shape=(0, 5), dtype=float32), 4: array([], shape=(0, 5), dtype=float32), 5: array([], shape=(0, 5), dtype=float32), 6: array([], shape=(0, 5), dtype=float32), 7: array([], shape=(0, 5), dtype=float32), 8: array([], shape=(0, 5), dtype=float32), 9: array([], shape=(0, 5), dtype=float32), 10: array([], shape=(0, 5), dtype=float32), 11: array([], shape=(0, 5), dtype=float32), 12: array([], shape=(0, 5), dtype=float32), 13: array([], shape=(0, 5), dtype=float32), 14: array([], shape=(0, 5), dtype=float32), 15: array([], shape=(0, 5), dtype=float32), 16: array([], shape=(0, 5), dtype=float32), 17: array([], shape=(0, 5), dtype=float32), 18: array([], shape=(0, 5), dtype=float32), 19: array([], shape=(0, 5), dtype=float32), 20: array([], shape=(0, 5), dtype=float32), 21: array([], shape=(0, 5), dtype=float32), 22: array([], shape=(0, 5), dtype=float32), 23: array([], shape=(0, 5), dtype=float32), 24: array([], shape=(0, 5), dtype=float32), 25: array([], shape=(0, 5), dtype=float32), 26: array([], shape=(0, 5), dtype=float32), 27: array([], shape=(0, 5), dtype=float32), 28: array([], shape=(0, 5), dtype=float32), 29: array([], shape=(0, 5), dtype=float32), 30: array([], shape=(0, 5), dtype=float32), 31: array([], shape=(0, 5), dtype=float32), 32: array([], shape=(0, 5), dtype=float32), 33: array([], shape=(0, 5), dtype=float32), 34: array([], shape=(0, 5), dtype=float32), 35: array([], shape=(0, 5), dtype=float32), 36: array([], shape=(0, 5), dtype=float32), 37: array([], shape=(0, 5), dtype=float32), 38: array([], shape=(0, 5), dtype=float32), 39: array([], shape=(0, 5), dtype=float32), 40: array([], shape=(0, 5), dtype=float32), 41: array([], shape=(0, 5), dtype=float32), 42: array([], shape=(0, 5), dtype=float32), 43: array([], shape=(0, 5), dtype=float32), 44: array([], shape=(0, 5), dtype=float32), 45: array([], shape=(0, 5), dtype=float32), 46: array([], shape=(0, 5), dtype=float32), 47: array([], shape=(0, 5), dtype=float32), 48: array([], shape=(0, 5), dtype=float32), 49: array([], shape=(0, 5), dtype=float32), 50: array([], shape=(0, 5), dtype=float32), 51: array([], shape=(0, 5), dtype=float32), 52: array([], shape=(0, 5), dtype=float32), 53: array([], shape=(0, 5), dtype=float32), 54: array([], shape=(0, 5), dtype=float32), 55: array([], shape=(0, 5), dtype=float32), 56: array([], shape=(0, 5), dtype=float32), 57: array([], shape=(0, 5), dtype=float32), 58: array([], shape=(0, 5), dtype=float32), 59: array([], shape=(0, 5), dtype=float32), 60: array([], shape=(0, 5), dtype=float32), 61: array([], shape=(0, 5), dtype=float32), 62: array([], shape=(0, 5), dtype=float32), 63: array([], shape=(0, 5), dtype=float32), 64: array([], shape=(0, 5), dtype=float32), 65: array([], shape=(0, 5), dtype=float32), 66: array([], shape=(0, 5), dtype=float32), 67: array([], shape=(0, 5), dtype=float32), 68: array([], shape=(0, 5), dtype=float32), 69: array([], shape=(0, 5), dtype=float32), 70: array([], shape=(0, 5), dtype=float32), 71: array([], shape=(0, 5), dtype=float32), 72: array([], shape=(0, 5), dtype=float32), 73: array([], shape=(0, 5), dtype=float32), 74: array([], shape=(0, 5), dtype=float32), 75: array([], shape=(0, 5), dtype=float32), 76: array([], shape=(0, 5), dtype=float32), 77: array([], shape=(0, 5), dtype=float32), 78: array([], shape=(0, 5), dtype=float32), 79: array([], shape=(0, 5), dtype=float32)}]

Body:
in the link you provided the frame is the image you need to feed to yolo. You could place the whole while true from the link into the session and just process frame by frame by running:

detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})

or write a generator that provides the frames, kind of cleaner.

def generator()
    cap = cv2.VideoCapture(0)
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        frame = cv2.resize(frame, (416, 416))
        yield frame

and then in your could do:

with tf.Session() as sess:
    sess.run(assign_ops)
    for frame in generator():
        detection_result = sess.run(detections, feed_dict={inputs: np.expand_dims(frame, 0)})

The expand dims is to create a batch of 1, so eg: makes 399x399x3 into 1x399x399x3.

Something like that, hope it helps a bit

EDIT

import numpy as np
import cv2

def convert_bbox_to_absolute(bbox_list, w_img, h_img):
    """
    method to convert the relative points (< 1) to absolute points (< 416)
    :param bbox_list: (list) list of boundary boxes (x, y, w, h, probability)
    :param w_img: (int) width of the image
    :param h_img: (int) height of the image
    :return: bbox_list: (list) list of boundary boxes but this time scaled up
    """
    x, y, w, h, c = zip(*bbox_list)
    y = list(map(lambda y: int(y * w_img), y))
    w = list(map(lambda w: int(w * h_img), w))

    x = list(map(lambda x: int(x * h_img), x))
    h = list(map(lambda h: int(h * w_img), h))
    bbox_list = zip(x, y, w, h, c)
    return list(bbox_list)

def draw_boxes(image, bbox_list):
    """
    Will draw the rectangles on th image and place the probability on them
    :param image:  (np.ndarray) a RGB-color image
    :param bbox_list: (list) list of boundary boxes (x, y, w, h, probability)
    """
    assert type(image) == np.ndarray
    assert type(bbox_list) == list

    assert len(image.shape) == 3
    assert len(bbox_list[0]) == 5

    # get the width and height of the image
    w_img, h_img, _ = image.shape

    # convert the box coordinates to absolute values
    bbox_list = convert_bbox_to_absolute(bbox_list, w_img, h_img)
    for bbox in bbox_list:
        x, y, w, h, c = bbox
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 3)
        cv2.putText(image, str(c), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
    cv2.imshow("", image)
    cv2.waitKey(0)

# creating a black test RGB-image
test_image = np.zeros((512, 416, 3))

# faking some boundary boxes, x, y, w, h, confidence
b_boxes = [[0.5, 0.1, 0.5, 0.9, 0.8], [0.4, 0.1, 0.1, 0.1, 0.4]]

draw_boxes(test_image, b_boxes)

This is a very simple example of how you can draw boundary boxes, I assumed that the provided boxes by yolo are normalised because of this link. If you know how I can determine which label belongs to which box, then I'll add that to the code as well.

EDIT 2:

import numpy as np
import cv2
from random import choices
from string import ascii_lowercase

def draw_boxes(image, bbox_list, label_list):
    """
    Will draw the rectangles on th image and place the probability on them
    :param image:  (np.ndarray) a RGB-color image
    :param bbox_list: (list[dict()]) list dict of boundary boxes  label:(x, y, w, h, probability)
    :param label_list: (list) a list of label names matching the order of the dict keys
    """
    bbox_dict = bbox_list[0]
    assert type(image) == np.ndarray
    assert type(bbox_dict) == dict
    assert type(label_list) == list

    assert len(image.shape) == 3
    assert len(bbox_dict.keys()) == 80
    assert len(label_list) == 80

    for label, bbox in bbox_dict.items():
        if bbox.size == 0:
            continue
        x1, y1, x2, y2, c = np.squeeze(bbox)
        x1, y1, x2, y2 = list(map(lambda val: int(val), [x1, y1, x2, y2]))
        label = label_list[label] + ": {}".format(c)

        cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 3)
        cv2.putText(image, label, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
    cv2.imshow("", image)
    cv2.waitKey(0)

# creating a black test RGB-image
test_image = np.zeros((512, 416, 3))

# faking some boundary boxes, x, y, w, h, confidence and auto generating empty arrays with keys, to match your data
b_boxes = [{
    0: np.array([[131.96371, 131.70601, 341.41946, 358.6781, 0.68467134]]),
    1: np.array([])
}]
for i in range(2, 80):
    b_boxes[0][i] = np.array([])

# get 80 random 10 letter strings to mock labels
labels = ["".join(choices(ascii_lowercase, k=10)) for _ in range(80)]

draw_boxes(test_image, b_boxes, labels)

Given your data, I made some changes, hope this helps


问:
How write to csv file this data correctly = "type" not """ type """
I've tried to write this data to csv file but it writes not correctly. I want receive "type" not """type"""

python3, pycharm

```<code> import pandas as pd
 import csv

 def main():
    req = pd.read_csv('/Users/user/web/python/Book copy.csv')
    account = 'test'
    transferType = 'Loan'
    comment = "test"

    with open('data2.csv', 'w') as csv_file:
        writer = csv.writer(csv_file, delimiter=';')
        writer.writerow(['"type"','"currency"','"amount"','"comment"'])

        for i in range(len(req)):
            currency = req['Currency'].values[i]
            reqAmount = req['Request'].values[i]
            r = round(reqAmount, -1)
            data = [transferType, account, currency, r, comment]
            writer.writerow(data)

    print("DONE")

if __name__ == '__main__':
    main()
</code>```

"""type"""

答:
Not sure why your header row needs to be quoted but the issue is that " is the default quote character and is being escaped, you need to change it to something else if you really want quoted headers

```<code>writer = csv.writer(csv_file, delimiter=';', quotechar='$')
</code>```

Body:
I've tried to write this data to csv file but it writes not correctly. I want receive "type" not """type"""

python3, pycharm

 import pandas as pd
 import csv

 def main():
    req = pd.read_csv('/Users/user/web/python/Book copy.csv')
    account = 'test'
    transferType = 'Loan'
    comment = "test"

    with open('data2.csv', 'w') as csv_file:
        writer = csv.writer(csv_file, delimiter=';')
        writer.writerow(['"type"','"currency"','"amount"','"comment"'])

        for i in range(len(req)):
            currency = req['Currency'].values[i]
            reqAmount = req['Request'].values[i]
            r = round(reqAmount, -1)
            data = [transferType, account, currency, r, comment]
            writer.writerow(data)

    print("DONE")

if __name__ == '__main__':
    main()

"""type"""

Body:
Not sure why your header row needs to be quoted but the issue is that " is the default quote character and is being escaped, you need to change it to something else if you really want quoted headers

writer = csv.writer(csv_file, delimiter=';', quotechar='$')


问:
Setting attributes to null using a config file set by the user
I am working on a project where I was asked to make it so that the user can enter attributes that they want obscured from a .yml config file. The attribute already has a value in it and it will be set to null based on whether the user wants that attribute obscured.

For example if the variable String country = "Canada"; exists and the user specifies "country" in the config file, country will be set to null.

The class has get and set methods. But I don't really understand how I can set the attributes to null.

For example, I'd have to set the value to null like Object.setCountry=null; but I won't know what set method to use Object.xxxx=null;

答: I used reflection to solve this issue.</p>

Body: I used reflection to solve this issue.


问:
Python Requests SSLError with internal CA
My company operates its own internal CA for internal services, and I need to access hook up Ansible AWX [python] to talk to one of our internal services which uses a cert signed by this CA. Basically:

AWX spins up a container awx_task with /etc/pki/ca-trust/source/anchors mounted in, which contains the root CA cert. [double-checked]

update-ca-trust is run, bundling the CA cert into various things, including /etc/pki/tls/certs/ca-bundle.crt. [double-checked]

requests should use this bundle. There are no CA-related environment variables that I can find inside the container or on the host that would override this.

However when I trigger a test run of an Ansible play which runs inside of awx_task I get the error:

requests.exceptions.SSLError: HTTPSConnectionPool(host='vault.example.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:618)'),))

On the host machine I can run

```<code>import requests
requests.get("https://vault.example.com")
</code>```

and get a 200 response, and if I strace the process I can see it reading /etc/pki/tls/certs/ca-bundle.crt. But from inside awx_task I get the same requests.exceptions.SSLError as above. Unfortunately Docker won't let me run strace inside the container so I can't see what it's trying to read.

But if I modify the code to:

```<code>import requests
requests.get("https://vault.example.com", verify="/etc/pki/tls/certs/ca-bundle.crt")
</code>```

I get a 200 response from inside the container.

What am I missing here?

答:
The problem is what @Will noted, the current version of Requests uses the Certifi bundle which is entirely separate from OpenSSL. The bundle PEM actually lives somewhere in you Python site-packages dir.

Without modifying your code you can override this with the environment variable:

```<code>REQUESTS_CA_BUNDLE=/etc/pki/tls/certs/ca-bundle.crt
</code>```

Editorial: This is an absolutely ridiculous way to enforce CA trust. If you want to pare down your system trust, pare it down at the system level. I'm getting real sick of chasing down random PEM bundles scattered through source trees [which probably never get updated] just because some #devoops nutbag thinks he knows how to run systems better than actual ops and forking their bad ideas off to unsuspecting systems.

(ノಠ益ಠ)ノ彡┻━┻

Body:
My company operates its own internal CA for internal services, and I need to access hook up Ansible AWX [python] to talk to one of our internal services which uses a cert signed by this CA. Basically:

AWX spins up a container awx_task with /etc/pki/ca-trust/source/anchors mounted in, which contains the root CA cert. [double-checked]

update-ca-trust is run, bundling the CA cert into various things, including /etc/pki/tls/certs/ca-bundle.crt. [double-checked]

requests should use this bundle. There are no CA-related environment variables that I can find inside the container or on the host that would override this.

However when I trigger a test run of an Ansible play which runs inside of awx_task I get the error:

requests.exceptions.SSLError: HTTPSConnectionPool(host='vault.example.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:618)'),))

On the host machine I can run

import requests
requests.get("https://vault.example.com")

and get a 200 response, and if I strace the process I can see it reading /etc/pki/tls/certs/ca-bundle.crt. But from inside awx_task I get the same requests.exceptions.SSLError as above. Unfortunately Docker won't let me run strace inside the container so I can't see what it's trying to read.

But if I modify the code to:

import requests
requests.get("https://vault.example.com", verify="/etc/pki/tls/certs/ca-bundle.crt")

I get a 200 response from inside the container.

What am I missing here?

Body:
The problem is what @Will noted, the current version of Requests uses the Certifi bundle which is entirely separate from OpenSSL. The bundle PEM actually lives somewhere in you Python site-packages dir.

Without modifying your code you can override this with the environment variable:

REQUESTS_CA_BUNDLE=/etc/pki/tls/certs/ca-bundle.crt

Editorial: This is an absolutely ridiculous way to enforce CA trust. If you want to pare down your system trust, pare it down at the system level. I'm getting real sick of chasing down random PEM bundles scattered through source trees [which probably never get updated] just because some #devoops nutbag thinks he knows how to run systems better than actual ops and forking their bad ideas off to unsuspecting systems.

(ノಠ益ಠ)ノ彡┻━┻


问:
Get data from Twitter using Tweepy and store in csv file
I'm new to Python, Twitter, and Tweepy. I managed to pull data from Twitter, but I now want to store it into a CSV file.

My code is:

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

import tweepy

auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX'
auth.set_access_token('XXX-XXX', 'XXX'

api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
                           q="google",
                           since="2014-02-14",
                           until="2014-02-15",
                           lang="en").items():
    print tweet.created_at, tweet.text
</code>```

This prints data out on CLI, but I want it to output to a CSV file. I tried a few different options, but it only outputted the first tweet and not all tweets.

答:
You can actually run the program and print the output on another file.
Goto CMD and type

python file.py > newFile.py

The output from file.py will be read to newFile.py

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Python, Twitter, and Tweepy. I managed to pull data from Twitter, but I now want to store it into a CSV file.

My code is:

#!/usr/bin/python

import tweepy

auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX'
auth.set_access_token('XXX-XXX', 'XXX'

api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
                           q="google",
                           since="2014-02-14",
                           until="2014-02-15",
                           lang="en").items():
    print tweet.created_at, tweet.text

This prints data out on CLI, but I want it to output to a CSV file. I tried a few different options, but it only outputted the first tweet and not all tweets.


问:
How to manage the ownership of a file held within a struct in Rust?
Is there a good way to handle the ownership of a file held within a struct using Rust?  As a stripped down example, consider:

```<code>// Buffered file IO
use std::io::{BufReader,BufRead};
use std::fs::File;

// Structure that contains a file
#[derive(Debug)]
struct Foo {
    file : BufReader <File>,
    data : Vec <f64>,
}

// Reads the file and strips the header
fn init_foo(fname : &str) -> Foo {

    // Open the file
    let mut file = BufReader::new(File::open(fname).unwrap());

    // Dump the header
    let mut header = String::new();
    let _ = file.read_line(&mut header);

    // Return our foo
    Foo { file : file, data : Vec::new() }
}

// Read the remaining foo data and process it
fn read_foo(mut foo : Foo) -> Foo {

    // Strip one more line
    let mut header_alt = String::new();
    let _ = foo.file.read_line(&mut header_alt);

    // Read in the rest of the file line by line
    let mut data = Vec::new();
    for (lineno,line) in foo.file.lines().enumerate() {

        // Strip the error
        let line = line.unwrap();

        // Print some diagnostic information
        println!("Line {}: val {}",lineno,line);

        // Save the element
        data.push(line.parse::<f64>().unwrap());
    }

    // Export foo
    Foo { data : data, ..foo}
}

fn main() {

    // Initialize our foo
    let foo = init_foo("foo.txt");

    // Read in our data
    let foo = read_foo(foo);

    // Print out some debugging info
    println!("{:?}",foo);
}
</code>```

This currently gives the compilation error:

```<code>error[E0382]: use of moved value: `foo.file`
  --> src/main.rs:48:5
   |
35 |     for (lineno,line) in foo.file.lines().enumerate() {
   |                          -------- value moved here
...
48 |     Foo { data : data, ..foo}
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^ value used here after move
   |
   = note: move occurs because `foo.file` has type `std::io::BufReader<std::fs::File>`, which does not implement the `Copy` trait

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: Could not compile `rust_file_struct`.

To learn more, run the command again with --verbose.
</code>```

And, to be sure, this makes sense.  Here, lines() takes ownership of the buffered file, so we can't use the value in the return.  What's confusing me is a better way to handle this situation.  Certainly, after the for loop, the file is consumed, so it really can't be used.  To better denote this, we could represent file as Option <BufReader <File>>.  However, this causes some grief because the second read_line call, inside of read_foo, needs a mutable reference to file and I'm not sure how to obtain one it it's wrapped inside of an Option.  Is there a good way of handling the ownership?

To be clear, this is a stripped down example.  In the actual use case, there are several files as well as other data.  I've things structured in this way because it represents a configuration that comes from the command line options.  Some of the options are files, some are flags.  In either case, I'd like to do some processing, but not all, of the files early in order to throw the appropriate errors.

答:
I think you're on track with using the Option within the Foo struct. Assuming the struct becomes:

```<code>struct Foo {
    file : Option<BufReader <File>>,
    data : Vec <f64>,
}
</code>```

The following code is a possible solution:

```<code>// Reads the file and strips the header
fn init_foo(fname : &str) -> Foo {

    // Open the file
    let mut file = BufReader::new(File::open(fname).unwrap());

    // Dump the header
    let mut header = String::new();
    let _ = file.read_line(&mut header);

    // Return our foo
    Foo { file : Some(file), data : Vec::new() }
}

// Read the remaining foo data and process it
fn read_foo(foo : Foo) -> Option<Foo> {

    let mut file = foo.file?;

    // Strip one more line
    let mut header_alt = String::new();
    let _ = file.read_line(&mut header_alt);

    // Read in the rest of the file line by line
    let mut data = Vec::new();
    for (lineno,line) in file.lines().enumerate() {

        // Strip the error
        let line = line.unwrap();

        // Print some diagnostic information
        println!("Line {}: val {}",lineno,line);

        // Save the element
        data.push(line.parse::<f64>().unwrap());
    }

    // Export foo
    Some(Foo { data : data, file: None})
}
</code>```

Note in this case that read_foo returns an optional Foo due to the fact that the file could be None.

On a side note, IMO, unless you absolutely need the BufReader to be travelling along with the Foo, I would discard it. As you've already found, calling lines causes a move, which makes it difficult to retain within another struct. As a suggestion, you could make the file field simply a String so that you could always derive the BufReader and read the file when needed.

For example, here's a solution where a file name (i.e. a &str) can be turned into a Foo with all the line processing done just before the construction of the struct.

```<code>// Buffered file IO
use std::io::{BufReader,BufRead};
use std::fs::File;

// Structure that contains a file
#[derive(Debug)]
struct Foo {
    file : String,
    data : Vec <f64>,
}

trait IntoFoo {
    fn into_foo(self) -> Foo;
}

impl IntoFoo for &str {
    fn into_foo(self) -> Foo {
        // Open the file
        let mut file = BufReader::new(File::open(self).unwrap());

        // Dump the header
        let mut header = String::new();
        let _ = file.read_line(&mut header);

        // Strip one more line
        let mut header_alt = String::new();
        let _ = file.read_line(&mut header_alt);

        // Read in the rest of the file line by line
        let mut data = Vec::new();
        for (lineno,line) in file.lines().enumerate() {

            // Strip the error
            let line = line.unwrap();

            // Print some diagnostic information
            println!("Line {}: val {}",lineno,line);

            // Save the element
            data.push(line.parse::<f64>().unwrap());
        }

        Foo { file: self.to_string(), data }
    }
}

fn main() {

    // Read in our data from the file
    let foo = "foo.txt".into_foo();

    // Print out some debugging info
    println!("{:?}",foo);
}
</code>```

In this case, there's no need to worry about the ownership of the BufReader because it's created, used, and discarded in the same function. Of course, I don't fully know your use case, so this may not be suitable for your implementation.

Body:
Is there a good way to handle the ownership of a file held within a struct using Rust?  As a stripped down example, consider:

// Buffered file IO
use std::io::{BufReader,BufRead};
use std::fs::File;

// Structure that contains a file
#[derive(Debug)]
struct Foo {
    file : BufReader <File>,
    data : Vec <f64>,
}

// Reads the file and strips the header
fn init_foo(fname : &str) -> Foo {

    // Open the file
    let mut file = BufReader::new(File::open(fname).unwrap());

    // Dump the header
    let mut header = String::new();
    let _ = file.read_line(&mut header);

    // Return our foo
    Foo { file : file, data : Vec::new() }
}

// Read the remaining foo data and process it
fn read_foo(mut foo : Foo) -> Foo {

    // Strip one more line
    let mut header_alt = String::new();
    let _ = foo.file.read_line(&mut header_alt);

    // Read in the rest of the file line by line
    let mut data = Vec::new();
    for (lineno,line) in foo.file.lines().enumerate() {

        // Strip the error
        let line = line.unwrap();

        // Print some diagnostic information
        println!("Line {}: val {}",lineno,line);

        // Save the element
        data.push(line.parse::<f64>().unwrap());
    }

    // Export foo
    Foo { data : data, ..foo}
}

fn main() {

    // Initialize our foo
    let foo = init_foo("foo.txt");

    // Read in our data
    let foo = read_foo(foo);

    // Print out some debugging info
    println!("{:?}",foo);
}

This currently gives the compilation error:

error[E0382]: use of moved value: `foo.file`
  --> src/main.rs:48:5
   |
35 |     for (lineno,line) in foo.file.lines().enumerate() {
   |                          -------- value moved here
...
48 |     Foo { data : data, ..foo}
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^ value used here after move
   |
   = note: move occurs because `foo.file` has type `std::io::BufReader<std::fs::File>`, which does not implement the `Copy` trait

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: Could not compile `rust_file_struct`.

To learn more, run the command again with --verbose.

And, to be sure, this makes sense.  Here, lines() takes ownership of the buffered file, so we can't use the value in the return.  What's confusing me is a better way to handle this situation.  Certainly, after the for loop, the file is consumed, so it really can't be used.  To better denote this, we could represent file as Option <BufReader <File>>.  However, this causes some grief because the second read_line call, inside of read_foo, needs a mutable reference to file and I'm not sure how to obtain one it it's wrapped inside of an Option.  Is there a good way of handling the ownership?

To be clear, this is a stripped down example.  In the actual use case, there are several files as well as other data.  I've things structured in this way because it represents a configuration that comes from the command line options.  Some of the options are files, some are flags.  In either case, I'd like to do some processing, but not all, of the files early in order to throw the appropriate errors.

Body:
I think you're on track with using the Option within the Foo struct. Assuming the struct becomes:

struct Foo {
    file : Option<BufReader <File>>,
    data : Vec <f64>,
}

The following code is a possible solution:

// Reads the file and strips the header
fn init_foo(fname : &str) -> Foo {

    // Open the file
    let mut file = BufReader::new(File::open(fname).unwrap());

    // Dump the header
    let mut header = String::new();
    let _ = file.read_line(&mut header);

    // Return our foo
    Foo { file : Some(file), data : Vec::new() }
}

// Read the remaining foo data and process it
fn read_foo(foo : Foo) -> Option<Foo> {

    let mut file = foo.file?;

    // Strip one more line
    let mut header_alt = String::new();
    let _ = file.read_line(&mut header_alt);

    // Read in the rest of the file line by line
    let mut data = Vec::new();
    for (lineno,line) in file.lines().enumerate() {

        // Strip the error
        let line = line.unwrap();

        // Print some diagnostic information
        println!("Line {}: val {}",lineno,line);

        // Save the element
        data.push(line.parse::<f64>().unwrap());
    }

    // Export foo
    Some(Foo { data : data, file: None})
}

Note in this case that read_foo returns an optional Foo due to the fact that the file could be None.

On a side note, IMO, unless you absolutely need the BufReader to be travelling along with the Foo, I would discard it. As you've already found, calling lines causes a move, which makes it difficult to retain within another struct. As a suggestion, you could make the file field simply a String so that you could always derive the BufReader and read the file when needed.

For example, here's a solution where a file name (i.e. a &str) can be turned into a Foo with all the line processing done just before the construction of the struct.

// Buffered file IO
use std::io::{BufReader,BufRead};
use std::fs::File;

// Structure that contains a file
#[derive(Debug)]
struct Foo {
    file : String,
    data : Vec <f64>,
}

trait IntoFoo {
    fn into_foo(self) -> Foo;
}

impl IntoFoo for &str {
    fn into_foo(self) -> Foo {
        // Open the file
        let mut file = BufReader::new(File::open(self).unwrap());

        // Dump the header
        let mut header = String::new();
        let _ = file.read_line(&mut header);

        // Strip one more line
        let mut header_alt = String::new();
        let _ = file.read_line(&mut header_alt);

        // Read in the rest of the file line by line
        let mut data = Vec::new();
        for (lineno,line) in file.lines().enumerate() {

            // Strip the error
            let line = line.unwrap();

            // Print some diagnostic information
            println!("Line {}: val {}",lineno,line);

            // Save the element
            data.push(line.parse::<f64>().unwrap());
        }

        Foo { file: self.to_string(), data }
    }
}

fn main() {

    // Read in our data from the file
    let foo = "foo.txt".into_foo();

    // Print out some debugging info
    println!("{:?}",foo);
}

In this case, there's no need to worry about the ownership of the BufReader because it's created, used, and discarded in the same function. Of course, I don't fully know your use case, so this may not be suitable for your implementation.


问:
Send generic JSON data to MVC2 Controller
I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers.  The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model.  So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.

My ajax call:

```<code>function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
    // Make a call to the server to process the object
    var jsonifiedObject = JSON.stringify(object);
    $.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: jsonifiedObject
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });
}
</code>```

My MVC Controller:

```<code>public ActionResult SaveForm(string obj)
{
    // Ok, try saving the object
    string rc = PassJSONToSomething(obj.ToString());
    string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
    return new ContentResult { Content = message, ContentType = "application/json" };
}
</code>```

The problem is that obj is always null.  Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server?  I'm using MVC2.  This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.

Thanks very much.

答:
Have you tried something like that?</p>

```<code>$.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: {obj :jsonifiedObject}
            , contentType: 'application/json; charset=utf-8'
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });
</code>```

Body:
I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers.  The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model.  So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.

My ajax call:

function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
    // Make a call to the server to process the object
    var jsonifiedObject = JSON.stringify(object);
    $.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: jsonifiedObject
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });
}

My MVC Controller:

public ActionResult SaveForm(string obj)
{
    // Ok, try saving the object
    string rc = PassJSONToSomething(obj.ToString());
    string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
    return new ContentResult { Content = message, ContentType = "application/json" };
}

The problem is that obj is always null.  Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server?  I'm using MVC2.  This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.

Thanks very much.

Body:
Have you tried something like that?

$.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: {obj :jsonifiedObject}
            , contentType: 'application/json; charset=utf-8'
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });


问:
How the pass HTML element, from one method to other in prototype
How to pass the result from the method playerElementChoice() to startGame()

```<code>class Game {
    constructor() {
        this.options = document.querySelectorAll('.options');
         this.options.forEach(item => {
            item.addEventListener('click', this.playerElementChoice);
        });

    document.querySelector('button.start').addEventListener('click', this.startGame.bind(this));

}

playerElementChoice() {
    const name = this.firstElementChild.className;
    return name;
}

startGame() {
    console.log(this.playerElementChoice());
}
</code>```

}

When trying to call the method playerElementChoice ()in method startGame() I get error:
Cannot read property 'className' of undefined at Game.playerElementChoice (Game.js:17) at Game.startGame (Game.js:28).

What am I doing wrong ?

答:
if you want to select the single option in a list, and log the selected li className value, you must change your code adding some binding:

class Game {
  constructor() {
    this.options = Array.from(document.getElementById('options').children);
    this.startButton = document.querySelector('button.start');
    this.name = '';
    this.playerElementChoice = this.playerElementChoice.bind(this);
    this.startGame = this.startGame.bind(this)
  }

  init() {
    this.options.forEach(item => {
      item.addEventListener('click', this.playerElementChoice)
    });
   this.startButton.addEventListener('click', this.startGame);
  }

  playerElementChoice(e) {
    e.preventDefault();
    this.name = e.target.className;
}

  startGame() {
    console.log(this.name);
  }
}

let game = new Game()
game.init()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="start">start</button>
<ul id="options">
  <li class="option1" name="one">1</li>
  <li class="option2" name="two">2</li>
  <li class="option3" name="three">3</li>
</ul></code>```

Hope it helps

Body:
How to pass the result from the method playerElementChoice() to startGame()

class Game {
    constructor() {
        this.options = document.querySelectorAll('.options');
         this.options.forEach(item => {
            item.addEventListener('click', this.playerElementChoice);
        });

    document.querySelector('button.start').addEventListener('click', this.startGame.bind(this));

}

playerElementChoice() {
    const name = this.firstElementChild.className;
    return name;
}

startGame() {
    console.log(this.playerElementChoice());
}

}

When trying to call the method playerElementChoice ()in method startGame() I get error:
Cannot read property 'className' of undefined at Game.playerElementChoice (Game.js:17) at Game.startGame (Game.js:28).

What am I doing wrong ?

Body:
if you want to select the single option in a list, and log the selected li className value, you must change your code adding some binding:

class Game {
  constructor() {
    this.options = Array.from(document.getElementById('options').children);
    this.startButton = document.querySelector('button.start');
    this.name = '';
    this.playerElementChoice = this.playerElementChoice.bind(this);
    this.startGame = this.startGame.bind(this)
  }

  init() {
    this.options.forEach(item => {
      item.addEventListener('click', this.playerElementChoice)
    });
   this.startButton.addEventListener('click', this.startGame);
  }

  playerElementChoice(e) {
    e.preventDefault();
    this.name = e.target.className;
}

  startGame() {
    console.log(this.name);
  }
}

let game = new Game()
game.init()

<button class="start">start</button>
<ul id="options">
  <li class="option1" name="one">1</li>
  <li class="option2" name="two">2</li>
  <li class="option3" name="three">3</li>
</ul>

Hope it helps


问:
Do `fgetc`, `fputc`, `fgets` and `fputs` require a file opened in text mode, and `fread` and `fwrite` require a file in binary mode?
When using fgetc, fputc, fgets and fputs for a file, do I need to ensure that I have opened the file in text mode not binary mode?

When using fread and fwrite, do I need to  opened the file in binary mode not text mode?

In Linux, I guess there is no difference. But what if in Windows which I currently have no access to?

答:
No. All stdio input and output functions are defined in terms of repeated calls to fgetc or fputc. Aside from POSIX requirements on top (mainly locking being for the whole larger operation rather than at the individual fgetc/fputc granularity), there is no difference between calling fputc or fgetc in a loop yourself, or doing the equivalent with fwrite or fread.

If the C implementation you use treats text files differently from binary, that treatment applies no matter which functions you use to perform the operations.


问:
Why print_r() still exists?
```<code>print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));
</code>```

Then :

```<code>Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));
</code>```

will display:

```<code>array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }
</code>```

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

答: Can you suggest some reason to break hundreds of thousands of PHP scripts by removing it?</p>

Title: Why print_r() still exists?

Body:
print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));

Then :

Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));

will display:

array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know


问:
Spring Data JPA - Custom Sort in JpaRepository
I am using Spring Data JPA with Spring Data REST and i have created a JpaRepository for my Thing entity.

```<code>@Repository
public interface ThingRepository extends JpaRepository<Thing, Long> {

    @RestResource(path = "findByName", rel = "findByName")
    Page findByName(@Param("name") String name, Pageable page);

}
</code>```

I want to apply sorting. I want to sort the Thing List based on a custom rating  algorithm.

```<code>List<Thing> sortByRating(List<Thing> things){

    // custom logic

    return things;
};
</code>```

I would like if possible to use a custom function in order to sort the results. What is the best approach to this kind of thing in Spring JPA? How can i make my Repository use my function to sort the result set?

答:
You can customize your object page(Pageable). If you get data of request:

public PageRequest customSort(Args...) {
    String[] newParams = {"newParam"};
    Sort sort = page.getSort();
    Sort.Order dataSort =
        sort.iterator().next();
    Sort newSort = Sort.by(dataSort.getDirection(), newParams);
    return PageRequest.of(page.getPageNumber(), this.getPageSize(), newSort);
}
```

<p>SQL Before:</p>

<pre class="lang-sql prettyprint-override"><code>order by oldParam ASC/DESC;
</code>```

SQL After:

order by newParam ASC/DESC;
```

Body:
I am using Spring Data JPA with Spring Data REST and i have created a JpaRepository for my Thing entity.

@Repository
public interface ThingRepository extends JpaRepository<Thing, Long> {

    @RestResource(path = "findByName", rel = "findByName")
    Page findByName(@Param("name") String name, Pageable page);

}

I want to apply sorting. I want to sort the Thing List based on a custom rating  algorithm.

List<Thing> sortByRating(List<Thing> things){

    // custom logic

    return things;
};

I would like if possible to use a custom function in order to sort the results. What is the best approach to this kind of thing in Spring JPA? How can i make my Repository use my function to sort the result set?

Body:
You can customize your object page(Pageable). If you get data of request:

public PageRequest customSort(Args...) {
    String[] newParams = {"newParam"};
    Sort sort = page.getSort();
    Sort.Order dataSort =
        sort.iterator().next();
    Sort newSort = Sort.by(dataSort.getDirection(), newParams);
    return PageRequest.of(page.getPageNumber(), this.getPageSize(), newSort);
}

SQL Before:

order by oldParam ASC/DESC;

SQL After:

order by newParam ASC/DESC;


问:
Button click handlers with arguments
What is the recommended approach for passing an argument to a svelte button click handler?

The use case is a repeating button inside an each list. From what I can tell the documentation only shows examples of how to deal with a single button where you can use a global variable to pass data. This is not as practical if you are stamping out a list of buttons in a grid.

Example:

```<code>{#each comments as c}
    <div class="comment-block">

    <div class="comment"> {c.text} </div>
    <!-- How can I pass c.id to the  approveComment handler? -->
    <button on:click="{approveComment}">Approve</button>
    </div>
{/each}

<script>
function approveComment() {
  // how can I pass an id to this method
}
</script>
</code>```

One solution is to move the content of the each block into another component, and pass in the comment object as a prop, but I am curious if you can bind an input value to the button handler per iteration through the loop.

答:
The function approveComment has the event as an argument.  Change your function declaration to:

```<code>function approveComment(event) {
  // now you can access event.target where you can store
  // the id from your button, e.g.:
  const id = event.target.value;
  console.log(id);
}
</code>```

You also need to declare the c.id in the value property of your button:

```<code><button on:click={approveComment} value={c.id}>Approve</button>
</code>```

Title: Button click handlers with arguments

Body:
What is the recommended approach for passing an argument to a svelte button click handler?

The use case is a repeating button inside an each list. From what I can tell the documentation only shows examples of how to deal with a single button where you can use a global variable to pass data. This is not as practical if you are stamping out a list of buttons in a grid.

Example:

{#each comments as c}

 {c.text}

    <button on:click="{approveComment}">Approve</button>

{/each}

One solution is to move the content of the each block into another component, and pass in the comment object as a prop, but I am curious if you can bind an input value to the button handler per iteration through the loop.

Body:
The function approveComment has the event as an argument.  Change your function declaration to:

function approveComment(event) {
  // now you can access event.target where you can store
  // the id from your button, e.g.:
  const id = event.target.value;
  console.log(id);
}

You also need to declare the c.id in the value property of your button:

<button on:click={approveComment} value={c.id}>Approve</button>


问:
init let properties with reference to self in subclass in swift
I'm learning swift and coming across the following problem very often. I will have a class with a property that feels as if it should be a let property as it will only be set once. I'd also like this child object to maintain a reference to its owner, which should also be a let property, as the parent relationship will not change. The problem arises when the parent class subclasses another class and all let properties need to be set before super.init () is run but requires a reference to self to init.

Here's a quick example

```<code>class NodeView: UIView {
    let _nodePlugView: NodePlugView

    init (node: Node) {
        _nodePlugView = NodePlugView (parentView: self)
        super.init ()
    }
}
</code>```

Of course, I could just use var for these _nodePlugView but it doesn't feel quite right. Is there another pattern that people would recommend?

答:
This is a good use case for an implicitly unwrapped optional.

The Apple documentation states:

“Implicitly unwrapped optionals are useful when an optional’s value is
  confirmed to exist immediately after the optional is first defined and
  can definitely be assumed to exist at every point thereafter. The
  primary use of implicitly unwrapped optionals in Swift is during class
  initialization.”

This means that you can use an implicitly unwrapped optional when a property depends on some aspect of self (but not the superclass) when it is initialised.

The property will be nil until it is set in the init() method and then must never be nil again.

```<code>class NodeView: UIView {

    var _nodePlugView: NodePlugView!

    init (node: Node) {
        super.init()
        _nodePlugView = NodePlugView (parentView: self)
    }
}
</code>```

Body:
I'm learning swift and coming across the following problem very often. I will have a class with a property that feels as if it should be a let property as it will only be set once. I'd also like this child object to maintain a reference to its owner, which should also be a let property, as the parent relationship will not change. The problem arises when the parent class subclasses another class and all let properties need to be set before super.init () is run but requires a reference to self to init.

Here's a quick example

class NodeView: UIView {
    let _nodePlugView: NodePlugView

    init (node: Node) {
        _nodePlugView = NodePlugView (parentView: self)
        super.init ()
    }
}

Of course, I could just use var for these _nodePlugView but it doesn't feel quite right. Is there another pattern that people would recommend?

Body:
This is a good use case for an implicitly unwrapped optional.

The Apple documentation states:

“Implicitly unwrapped optionals are useful when an optional’s value is
  confirmed to exist immediately after the optional is first defined and
  can definitely be assumed to exist at every point thereafter. The
  primary use of implicitly unwrapped optionals in Swift is during class
  initialization.”

This means that you can use an implicitly unwrapped optional when a property depends on some aspect of self (but not the superclass) when it is initialised.

The property will be nil until it is set in the init() method and then must never be nil again.

class NodeView: UIView {

    var _nodePlugView: NodePlugView!

    init (node: Node) {
        super.init()
        _nodePlugView = NodePlugView (parentView: self)
    }
}


问:
How to merge formatted and unformatted cells while keeping the formatting of the formatted cell to apply to the merged cell in Google Sheets?
How to horizontally merge formatted and unformatted cells from 2 columns while keeping the formatting of whichever formatted cell to apply to the merged cell?

So far, I've done it manually in 4 steps:

Step 1:

Step 2:

Step 3:

Step 4:

Result:

How to automate the process with a formula?

答:
there isn't really a formula for that (best you could have would be to merge it but without formatting). Maybe you should try keyboard shortcuts especially this combo:

select range

press LEFT ALT + O

press M

press H

press ENTER

then you could use AHK for example and map this key combo to some key and invoke it with a single press


问:
Pure css Chessboard with div & no classes or ids, is it possible?
I have the following layout

```

Is it possible to make a chess board using only css and without changing the above html? That means no classes or ids.
I've been searching for ideas an such for 2 days now. I tried with nth-child() and some variations but no success.

I am awfully curious if this can be done. It was given as an assignment to someone.

So please, any ideas?

答:
const HelloWorld = {
  template: '#tmpl',
  name: "HelloWorld",
  methods: {
    board (s) {
      return Array.from({length:s**2}).map((_,i)=>(parseInt(i/s,10)+1)%2===i%s%2)
    },
  },
};

new Vue({
  el: '#app',
  components: { HelloWorld },
  template: '<HelloWorld />'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hello {
  display: grid;
  grid-template-columns: repeat(8, 20px);
}
.square {
  width: 20px;
  height: 20px;
}</code>```

```

Not pure CSS but less of code solution

Body:
I have the following layout

Is it possible to make a chess board using only css and without changing the above html? That means no classes or ids.
I've been searching for ideas an such for 2 days now. I tried with nth-child() and some variations but no success.

I am awfully curious if this can be done. It was given as an assignment to someone.

So please, any ideas?

Body:
const HelloWorld = {
  template: '#tmpl',
  name: "HelloWorld",
  methods: {
    board (s) {
      return Array.from({length:s**2}).map((_,i)=>(parseInt(i/s,10)+1)%2===i%s%2)
    },
  },
};

new Vue({
  el: '#app',
  components: { HelloWorld },
  template: '<HelloWorld />'
})

.hello {
  display: grid;
  grid-template-columns: repeat(8, 20px);
}
.square {
  width: 20px;
  height: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="tmpl">
  <div class="hello">
    <div
      class="square"
      v-for="(square, idx) in board(8)"
      :key="idx"
      :style="{ background: square ? '#FFF' : '#000' }"
    ></div>
  </div>
</script>

<div id="app"></div>

Not pure CSS but less of code solution


问:
Change style of table data in hidden table row on reveal of table row
It's difficult to describe what I'm trying to do in the title, but basically I have a table with 9 cols, but one is display='none'.

Onclick of the row above, the hidden row becomes style='table-row'.

I have set the style of the 2nd TD to have a white background, 15px padding and and "red borders", successfully, but can't get the borders to 5px...

Here is (the important part of) my code:

CSS:

```<code>.formbg{
    padding: 15px;
    border: 5px;   /* This line is not rendering on the output.*/
    border-color: #c22034;
    background-color: white;
    display: table-data;
}
</code>```

HTML

```<code><tr class='toolboxrow'><td onclick='getForms()' ><img onclick='getForms()' src='image.jpg' /></td>
<td><span class='tbtext' onclick='getForms()' >Order Forms</span></td></tr>

<tr id='PersonalForms' style='display:none'><td></td>
<td class='formbg'>
<h3>Personalized Forms</h3>
<form action='DrsPortal.php' method='post'>
<input class='onlineform' name='title' placeholder='Title'  />
<input class='onlineform' name='given' placeholder='Given Name' />
<input class='onlineform' name='surname' placeholder='Surname' /><br>
<input class='onlineformsubmit' type='submit' value='Submit'>
</form>
</td>
</tr>
</code>```

Javascript

```<code>function getForms(){
    document.getElementById('PersonalForms').style.display='table-row'
}
</code>```

答: Due to the initial value "none" of the css property "border-style", border-width has no effect. Just use border-style: solid (or the shorthand property border: 5px solid #c22034) to render the border.

Body:
It's difficult to describe what I'm trying to do in the title, but basically I have a table with 9 cols, but one is display='none'.

Onclick of the row above, the hidden row becomes style='table-row'.

I have set the style of the 2nd TD to have a white background, 15px padding and and "red borders", successfully, but can't get the borders to 5px...

Here is (the important part of) my code:

CSS:

.formbg{
    padding: 15px;
    border: 5px;   /* This line is not rendering on the output.*/
    border-color: #c22034;
    background-color: white;
    display: table-data;
}

HTML

Order Forms

Personalized Forms

<form action='DrsPortal.php' method='post'>
<input class='onlineform' name='title' placeholder='Title'  />
<input class='onlineform' name='given' placeholder='Given Name' />
<input class='onlineform' name='surname' placeholder='Surname' />

<input class='onlineformsubmit' type='submit' value='Submit'>
</form>

Javascript

function getForms(){
    document.getElementById('PersonalForms').style.display='table-row'
}


问:
ASP.net WebPart title icons
I'm creating a web part page in ASP.net i want to display icons for minimise, restore, close etc instead of the drop down menu which is currently showing.  This code adds an icon next to the minimise icon in the menu but i want to remove the menu completly and render 3 icons in the top right of each web part. Does anyone have an example how to achieve that?</p>

```<code><asp:WebPartManager ID="WebPartManager1" runat="server"  Personalization-Enabled="true" >
</asp:WebPartManager>

<asp:WebPartZone ID="WebPartZone1" runat="server" HeaderText="zone 1">            <MinimizeVerb ImageUrl="img/os_minimise.gif"  />
  <ZoneTemplate>
    <asp:Label ID="lblZone1Header" runat="server"><h1>Zone 1</h1></asp:Label>
    <uc1:TestControl ID="TestControl1" runat="server"  />
  </ZoneTemplate>
</asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone2" runat="server" HeaderTexxt="zone 2">
</asp:WebPartZone>

<asp:EditorZone ID="EditorZone1" runat="server">
  <ZoneTemplate>
    <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
  </ZoneTemplate>
</asp:EditorZone>
</code>```

答: Web Part Zone has a property WebPartVerbRenderMode set it to menu and then Set Icons for Minimize,Restore,Close verbs etc.</p>

ContentLicense: CC BY-SA 2.5

Title: ASP.net WebPart title icons

Body:
I'm creating a web part page in ASP.net i want to display icons for minimise, restore, close etc instead of the drop down menu which is currently showing.  This code adds an icon next to the minimise icon in the menu but i want to remove the menu completly and render 3 icons in the top right of each web part. Does anyone have an example how to achieve that?

<asp:WebPartManager ID="WebPartManager1" runat="server"  Personalization-Enabled="true" >
</asp:WebPartManager>

<asp:WebPartZone ID="WebPartZone1" runat="server" HeaderText="zone 1">            <MinimizeVerb ImageUrl="img/os_minimise.gif"  />
  <ZoneTemplate>
    <asp:Label ID="lblZone1Header" runat="server">
Zone 1
</asp:Label>
    <uc1:TestControl ID="TestControl1" runat="server"  />
  </ZoneTemplate>
</asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone2" runat="server" HeaderTexxt="zone 2">
</asp:WebPartZone>

<asp:EditorZone ID="EditorZone1" runat="server">
  <ZoneTemplate>
    <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
  </ZoneTemplate>
</asp:EditorZone>


问:
Extracting the dimensions of a rectangle
So I'm working on an image processing project with sonar images. To be more specific, I am trying to extract the dimensions of an image of a pool taken by a sonar scanner. I was able to extract the rectangular region of the pool but I can not figure out how to get the dimensions of each edge in terms of pixels. I am working with OpenCV in Python.

I would appreciate if anyone would give me any suggestion on how this could be done.

I already tried finding the line intersections of hough lines but that did not have promising results.

Code so far.

import cv2
import numpy as np
from scipy import ndimage as ndi
from scipy.ndimage.measurements import label

def largest_component(indices):
    #this function takes a list of indices denoting
    #the white regions of the image and returns the largest
    #white object of connected indices

    return_arr = np.zeros((512,512), dtype=np.uint8)
    for index in indeces:
        return_arr[index[0]][index[1]] = 255

    return return_arr

image = cv2.imread('sonar_dataset/useful/sonarXY_5.bmp', 0)
image_gaussian = ndi.gaussian_filter(image, 4)
image_gaussian_inv = cv2.bitwise_not(image_gaussian)
kernel = np.ones((3,3),np.uint8)

# double thresholding extracting the sides of the rectangle
ret1, img1 = cv2.threshold(image_gaussian_inv, 120, 255, cv2.THRESH_BINARY)
ret2, img2 = cv2.threshold(image_gaussian_inv, 150, 255, cv2.THRESH_BINARY)

double_threshold = img1 - img2
closing = cv2.morphologyEx(double_threshold, cv2.MORPH_CLOSE, kernel1)

labeled, ncomponents = label(closing, kernel)
indices = np.indices(closing.shape).T[:,:,[1, 0]]
twos = indices[labeled == 2]
area =[np.sum(labeled==val) for val in range(ncomponents+1)]

rectangle = largest_component(twos)

cv2.imshow('rectangle', rectangle)
cv2.waitKey(0)
```

The original image and extracted object are below.

答:
It's not perfect, but this simple approach should be a good starting point for you:

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

img = cv2.imread(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img1.png')
print(img.shape)
img_moments=cv2.moments(img[:,:,0]) #use only one channel here (cv2.moments operates only on single channels images)
print(img_moments)
# print(dir(img_moments))

# calculate centroid (center of mass of image)
x = img_moments['m10'] / img_moments['m00']
y = img_moments['m01'] / img_moments['m00']

# calculate orientation of image intensity (it corresponds to the image intensity axis)
u00 = img_moments['m00']
u20 = img_moments['m20'] - x*img_moments['m10']
u02 = img_moments['m02'] - y*img_moments['m01']
u11 = img_moments['m11'] - x*img_moments['m01']

u20_prim = u20/u00
u02_prim = u02/u00
u11_prim = u11/u00

angle = 0.5 * math.atan(2*u11_prim / (u20_prim - u02_prim))
print('The image should be rotated by: ', math.degrees(angle) / 2.0, ' degrees')

cols,rows = img.shape[:2]
# rotate the image by half of this angle
rotation_matrix = cv2.getRotationMatrix2D((cols/2,rows/2), math.degrees(angle / 2.0), 1)
img_rotated = cv2.warpAffine(img, rotation_matrix ,(cols,rows))
# print(img_rotated.shape, img_rotated.dtype)

cv2.imwrite(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img1_rotated.png', img_rotated)

img_rotated_clone = np.copy(img_rotated)
img_rotated_clone2 = np.copy(img_rotated)

# first method - just calculate bounding rect
bounding_rect = cv2.boundingRect(img_rotated[:, :, 0])
cv2.rectangle(img_rotated_clone, (bounding_rect[0], bounding_rect[1]),
    (bounding_rect[0] + bounding_rect[2], bounding_rect[1] + bounding_rect[3]), (255,0,0), 2)

# second method - find columns and rows with biggest sums
def nlargest_cols(a, n):
    col_sums = [(np.sum(col), idx) for idx, col in enumerate(a.T)]
    return sorted(col_sums, key=lambda a: a[0])[-n:]

def nlargest_rows(a, n):
    col_sums = [(np.sum(col), idx) for idx, col in enumerate(a[:,])]
    return sorted(col_sums, key=lambda a: a[0])[-n:]

top15_cols_indices = nlargest_cols(img_rotated[:,:,0], 15)
top15_rows_indices = nlargest_rows(img_rotated[:,:,0], 15)

for a in top15_cols_indices:
    cv2.line(img_rotated_clone, (a[1], 0), (a[1], rows), (0, 255, 0), 1)

for a in top15_rows_indices:
    cv2.line(img_rotated_clone, (0, a[1]), (cols, a[1]), (0, 0, 255), 1)

cv2.imwrite(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img2.png', img_rotated_clone)
</code>```

Of course you need to adjust paths. img1.png is the second image from your question, img1_rotated is the result of rotating the image:

and img2 is the final output:

The blue rectangle is method1 (just a bounding rect) and green and red lines (15 red and 15 green - all 1 pixel wide) is the second method.

The algorithm is quite simple:

Calculate image moments to determine the main axis of image intensity (I don't know how to describe it well - check the wiki page https://en.wikipedia.org/wiki/Image_moment#Examples_2 ). Basically this is the angle by which you have to rotate the image to make white pixels distributed horizontally or vertically.

Once you know the angle - rotate the image (and save the result).

Method 1 - calculate and draw rotated rect of all pixels.

Method 2 - find 15 rows and 15 cols with biggest sums (== biggest count of white pixels) and draw horizontal/vertical lines in those rows/columns. Note that the number 15 was selected by trial and error, but it should be easy to select 2 columns (and rows) with big sum which are not close to each other. Those columns/rows are good candidates to be rectangle boundaries.

Hope it is what you were looking for, let me know of you will have any questions.

Body:
So I'm working on an image processing project with sonar images. To be more specific, I am trying to extract the dimensions of an image of a pool taken by a sonar scanner. I was able to extract the rectangular region of the pool but I can not figure out how to get the dimensions of each edge in terms of pixels. I am working with OpenCV in Python.

I would appreciate if anyone would give me any suggestion on how this could be done.

I already tried finding the line intersections of hough lines but that did not have promising results.

Code so far.

import cv2
import numpy as np
from scipy import ndimage as ndi
from scipy.ndimage.measurements import label

def largest_component(indices):
    #this function takes a list of indices denoting
    #the white regions of the image and returns the largest
    #white object of connected indices

    return_arr = np.zeros((512,512), dtype=np.uint8)
    for index in indeces:
        return_arr[index[0]][index[1]] = 255

    return return_arr

image = cv2.imread('sonar_dataset/useful/sonarXY_5.bmp', 0)
image_gaussian = ndi.gaussian_filter(image, 4)
image_gaussian_inv = cv2.bitwise_not(image_gaussian)
kernel = np.ones((3,3),np.uint8)

# double thresholding extracting the sides of the rectangle
ret1, img1 = cv2.threshold(image_gaussian_inv, 120, 255, cv2.THRESH_BINARY)
ret2, img2 = cv2.threshold(image_gaussian_inv, 150, 255, cv2.THRESH_BINARY)

double_threshold = img1 - img2
closing = cv2.morphologyEx(double_threshold, cv2.MORPH_CLOSE, kernel1)

labeled, ncomponents = label(closing, kernel)
indices = np.indices(closing.shape).T[:,:,[1, 0]]
twos = indices[labeled == 2]
area =[np.sum(labeled==val) for val in range(ncomponents+1)]

rectangle = largest_component(twos)

cv2.imshow('rectangle', rectangle)
cv2.waitKey(0)

The original image and extracted object are below.

Body:
It's not perfect, but this simple approach should be a good starting point for you:

import cv2, math
import numpy as np

img = cv2.imread(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img1.png')
print(img.shape)
img_moments=cv2.moments(img[:,:,0]) #use only one channel here (cv2.moments operates only on single channels images)
print(img_moments)
# print(dir(img_moments))

# calculate centroid (center of mass of image)
x = img_moments['m10'] / img_moments['m00']
y = img_moments['m01'] / img_moments['m00']

# calculate orientation of image intensity (it corresponds to the image intensity axis)
u00 = img_moments['m00']
u20 = img_moments['m20'] - x*img_moments['m10']
u02 = img_moments['m02'] - y*img_moments['m01']
u11 = img_moments['m11'] - x*img_moments['m01']

u20_prim = u20/u00
u02_prim = u02/u00
u11_prim = u11/u00

angle = 0.5 * math.atan(2*u11_prim / (u20_prim - u02_prim))
print('The image should be rotated by: ', math.degrees(angle) / 2.0, ' degrees')

cols,rows = img.shape[:2]
# rotate the image by half of this angle
rotation_matrix = cv2.getRotationMatrix2D((cols/2,rows/2), math.degrees(angle / 2.0), 1)
img_rotated = cv2.warpAffine(img, rotation_matrix ,(cols,rows))
# print(img_rotated.shape, img_rotated.dtype)

cv2.imwrite(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img1_rotated.png', img_rotated)

img_rotated_clone = np.copy(img_rotated)
img_rotated_clone2 = np.copy(img_rotated)

# first method - just calculate bounding rect
bounding_rect = cv2.boundingRect(img_rotated[:, :, 0])
cv2.rectangle(img_rotated_clone, (bounding_rect[0], bounding_rect[1]),
    (bounding_rect[0] + bounding_rect[2], bounding_rect[1] + bounding_rect[3]), (255,0,0), 2)

# second method - find columns and rows with biggest sums
def nlargest_cols(a, n):
    col_sums = [(np.sum(col), idx) for idx, col in enumerate(a.T)]
    return sorted(col_sums, key=lambda a: a[0])[-n:]

def nlargest_rows(a, n):
    col_sums = [(np.sum(col), idx) for idx, col in enumerate(a[:,])]
    return sorted(col_sums, key=lambda a: a[0])[-n:]

top15_cols_indices = nlargest_cols(img_rotated[:,:,0], 15)
top15_rows_indices = nlargest_rows(img_rotated[:,:,0], 15)

for a in top15_cols_indices:
    cv2.line(img_rotated_clone, (a[1], 0), (a[1], rows), (0, 255, 0), 1)

for a in top15_rows_indices:
    cv2.line(img_rotated_clone, (0, a[1]), (cols, a[1]), (0, 0, 255), 1)

cv2.imwrite(R'D:\dev\projects\stackoverflow\dimensions_of_rectangle\img2.png', img_rotated_clone)

Of course you need to adjust paths. img1.png is the second image from your question, img1_rotated is the result of rotating the image:

and img2 is the final output:

The blue rectangle is method1 (just a bounding rect) and green and red lines (15 red and 15 green - all 1 pixel wide) is the second method.

The algorithm is quite simple:

Calculate image moments to determine the main axis of image intensity (I don't know how to describe it well - check the wiki page https://en.wikipedia.org/wiki/Image_moment#Examples_2 ). Basically this is the angle by which you have to rotate the image to make white pixels distributed horizontally or vertically.

Once you know the angle - rotate the image (and save the result).

Method 1 - calculate and draw rotated rect of all pixels.

Method 2 - find 15 rows and 15 cols with biggest sums (== biggest count of white pixels) and draw horizontal/vertical lines in those rows/columns. Note that the number 15 was selected by trial and error, but it should be easy to select 2 columns (and rows) with big sum which are not close to each other. Those columns/rows are good candidates to be rectangle boundaries.

Hope it is what you were looking for, let me know of you will have any questions.