问:
CustomCell Crash
I am using CustomCell tableview, download data and binding it.When i tap multiple time am getting this error.

```<code>[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170
Sat Jan 22 12:03:26 unknown Fridge[535] <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170'
 *** Call stack at first throw:
 (
  0   CoreFoundation                      0x314d0987 __exceptionPreprocess + 114
  1   libobjc.A.dylib                     0x319a149d objc_exception_throw + 24
  2   CoreFoundation                      0x314d2133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
  3   CoreFoundation                      0x31479aa9 ___forwarding___ + 508
  4   CoreFoundation                      0x31479860 _CF_forwarding_prep_0 + 48
  5   UIKit                               0x339023fb -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] + 66
  6   UIKit                               0x3390235b -[UITableViewRowData invalidateAllSections] + 50
  7   UIKit                               0x33902111 -[UITableView(_UITableViewPrivate) _updateRowData] + 64
  8   UIKit                               0x33902069 -[UITableView noteNumberOfRowsChanged] + 64
  9   UIKit                               0x33901bff -[UITableView reloadData] + 582
  10  UIKit                               0x33904a0b -[UITableView _reloadDataIfNeeded] + 50
  11  UIKit                               0x33904e63 -[UITableView layoutSubviews] + 18
  12  UIKit                               0x338b10cf -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 26
  13  CoreFoundation                      0x3146ebbf -[NSObject(NSObject) performSelector:withObject:] + 22
  14  QuartzCore                          0x30a6c685 -[CALayer layoutSublayers] + 120
  15  QuartzCore                          0x30a6c43d CALayerLayoutIfNeeded + 184
  16  QuartzCore                          0x30a6656d _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 212
  17  QuartzCore                          0x30a66383 _ZN2CA11Transaction6commitEv + 190
  18  QuartzCore                          0x30a89f9d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 52
  19  CoreFoundation                      0x31460c59 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
  20  CoreFoundation                      0x31460acd __CFRunLoopDoObservers + 412
  21  CoreFoundation                      0x314580cb __CFRunLoopRun + 854
  22  CoreFoundation                      0x31457c87 CFRunLoopRunSpecific + 230
  23  CoreFoundation                      0x31457b8f CFRunLoopRunInMode + 58
  24  GraphicsServices                    0x35d664ab GSEventRunModal + 114
  25  GraphicsServices                    0x35d66557 GSEventRun + 62
  26  UIKit                               0x338d5329 -[UIApplication _run] + 412
  27  UIKit                               0x338d2e93 UIApplicationMain + 670
  28  Fridge                              0x00002a7f main + 70
  29  Fridge                              0x00002a34 start + 40
 )
Sat Jan 22 12:03:26 unknown UIKitApplication:com.sdi.Fridge[0xa6da][535] <Notice>: terminate called after throwing an instance of 'NSException'

**Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x184250'**
</code>```

Thanks

答:
Thanks for the detail view of your problem but the only important part is this

```<code>-[NSCFString numberOfSectionsInTableView:]: unrecognized selector
</code>```

It tells that you are calling the method numberOfSectionsInTableView: on a NSCFString

which is seem to be wrong

so check where is that method called in your code

And also the rest is not require in your case.

Edit:

did you release your custom cell in the delegate method tableview. if yes than use autorelease instead.

Title: CustomCell Crash

Body:
I am using CustomCell tableview, download data and binding it.When i tap multiple time am getting this error.

[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170
Sat Jan 22 12:03:26 unknown Fridge[535] <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170'
 *** Call stack at first throw:
 (
  0   CoreFoundation                      0x314d0987 __exceptionPreprocess + 114
  1   libobjc.A.dylib                     0x319a149d objc_exception_throw + 24
  2   CoreFoundation                      0x314d2133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
  3   CoreFoundation                      0x31479aa9 ___forwarding___ + 508
  4   CoreFoundation                      0x31479860 _CF_forwarding_prep_0 + 48
  5   UIKit                               0x339023fb -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] + 66
  6   UIKit                               0x3390235b -[UITableViewRowData invalidateAllSections] + 50
  7   UIKit                               0x33902111 -[UITableView(_UITableViewPrivate) _updateRowData] + 64
  8   UIKit                               0x33902069 -[UITableView noteNumberOfRowsChanged] + 64
  9   UIKit                               0x33901bff -[UITableView reloadData] + 582
  10  UIKit                               0x33904a0b -[UITableView _reloadDataIfNeeded] + 50
  11  UIKit                               0x33904e63 -[UITableView layoutSubviews] + 18
  12  UIKit                               0x338b10cf -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 26
  13  CoreFoundation                      0x3146ebbf -[NSObject(NSObject) performSelector:withObject:] + 22
  14  QuartzCore                          0x30a6c685 -[CALayer layoutSublayers] + 120
  15  QuartzCore                          0x30a6c43d CALayerLayoutIfNeeded + 184
  16  QuartzCore                          0x30a6656d _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 212
  17  QuartzCore                          0x30a66383 _ZN2CA11Transaction6commitEv + 190
  18  QuartzCore                          0x30a89f9d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 52
  19  CoreFoundation                      0x31460c59 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
  20  CoreFoundation                      0x31460acd __CFRunLoopDoObservers + 412
  21  CoreFoundation                      0x314580cb __CFRunLoopRun + 854
  22  CoreFoundation                      0x31457c87 CFRunLoopRunSpecific + 230
  23  CoreFoundation                      0x31457b8f CFRunLoopRunInMode + 58
  24  GraphicsServices                    0x35d664ab GSEventRunModal + 114
  25  GraphicsServices                    0x35d66557 GSEventRun + 62
  26  UIKit                               0x338d5329 -[UIApplication _run] + 412
  27  UIKit                               0x338d2e93 UIApplicationMain + 670
  28  Fridge                              0x00002a7f main + 70
  29  Fridge                              0x00002a34 start + 40
 )
Sat Jan 22 12:03:26 unknown UIKitApplication:com.sdi.Fridge[0xa6da][535] <Notice>: terminate called after throwing an instance of 'NSException'

**Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x184250'**

Thanks

Body:
Thanks for the detail view of your problem but the only important part is this

-[NSCFString numberOfSectionsInTableView:]: unrecognized selector

It tells that you are calling the method numberOfSectionsInTableView: on a NSCFString

which is seem to be wrong

so check where is that method called in your code

And also the rest is not require in your case.

Edit:

did you release your custom cell in the delegate method tableview. if yes than use autorelease instead.


来源: stackexchange

问:
How to Dynamically Label my Buttons Based on Database Query using Tkinter
I am trying to label my button dynamically based on the database results. So in this case the button would be labeled '23'

Database

| id |  number |

| 1 |  23

```<code>from tkinter import *
import pymysql as mdb

from tkinter import ttk

#functions
def functionHolder():
    print("do nothing function holder")

root = Tk()
dbi = mdb.connect("localhost",port=3306, user="access", passwd="***", db="index_db" )
cursor = dbi.cursor()

cursor.execute("""SELECT number FROM caution_elements WHERE id = 1 """)
dbi.commit()
data = cursor.fetchone()[0]
dbi.close()

result =str("%s " % data)

 varButt = Button(root,textvariable=data, command=functionHolder)
 varButt.pack()

 root.mainloop()
</code>```

Button should be labeled [23] I currently get a blank button and no errors

答:
A textvariable option of tkinter widgets require special variable classes such as StringVar, BooleanVar or IntVar. Their values can be accessed using get method and their values can be changed using set as in:

```<code>import tkinter as tk

root = tk.Tk()

data = tk.StringVar()
data.set("This")

def change():
    if data.get() == "This":
        data.set("That")
    else:
        data.set("This")

tk.Label(root, textvariable=data).pack()
tk.Button(root, text="Change", command=change).pack()

root.mainloop()
</code>```

If you are not sure about using class variables another example without them would be:

```<code>import tkinter as tk

root = tk.Tk()

data = "This"

def change():
    global data
    if data == "This":
        data = "That"
        a_label['text'] = data
    else:
        data = "This"
        a_label.config(text=data)

a_label = tk.Label(root, text=data)
a_label.pack()
tk.Button(root, text="Change", command=change).pack()

root.mainloop()
</code>```

Both of the code pieces do the same thing except that when you change data's value, in the first example you're also changing text displayed by the label, and in the second example you need to explicitly update a_label's text option.

Also note that you can use a_widget.config(option=value), a_widget.configure(option=value), a_widget['option'] = value interchangeably given that you're modifying only one option.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to label my button dynamically based on the database results. So in this case the button would be labeled '23'

Database

| id |  number |

| 1 |  23

from tkinter import *
import pymysql as mdb

from tkinter import ttk

#functions
def functionHolder():
    print("do nothing function holder")

root = Tk()
dbi = mdb.connect("localhost",port=3306, user="access", passwd="***", db="index_db" )
cursor = dbi.cursor()

cursor.execute("""SELECT number FROM caution_elements WHERE id = 1 """)
dbi.commit()
data = cursor.fetchone()[0]
dbi.close()

result =str("%s " % data)

 varButt = Button(root,textvariable=data, command=functionHolder)
 varButt.pack()

 root.mainloop()

Button should be labeled [23] I currently get a blank button and no errors

Body:
A textvariable option of tkinter widgets require special variable classes such as StringVar, BooleanVar or IntVar. Their values can be accessed using get method and their values can be changed using set as in:

import tkinter as tk

root = tk.Tk()

data = tk.StringVar()
data.set("This")

def change():
    if data.get() == "This":
        data.set("That")
    else:
        data.set("This")

tk.Label(root, textvariable=data).pack()
tk.Button(root, text="Change", command=change).pack()

root.mainloop()

If you are not sure about using class variables another example without them would be:

import tkinter as tk

root = tk.Tk()

data = "This"

def change():
    global data
    if data == "This":
        data = "That"
        a_label['text'] = data
    else:
        data = "This"
        a_label.config(text=data)

a_label = tk.Label(root, text=data)
a_label.pack()
tk.Button(root, text="Change", command=change).pack()

root.mainloop()

Both of the code pieces do the same thing except that when you change data's value, in the first example you're also changing text displayed by the label, and in the second example you need to explicitly update a_label's text option.

Also note that you can use a_widget.config(option=value), a_widget.configure(option=value), a_widget['option'] = value interchangeably given that you're modifying only one option.


问:
How to save 4d numpy array to images
I want to create an image date_set which includes 176 small images (128*128*3) from one big image (1408, 2048, 3).
I do the following thing:
step 1.
Load the big image and convert it to numpy array. (1408, 2048, 3) 3d array
step 2.
cut it into 176 pieces: (176, 128, 128, 3) 4d array
step 3.
I don't know how to save 176 images from 4d array in this step. Does anyone could help me to solve this problem?
Thanks very much!

```<code>from astropy.io import fits
from astropy.utils.data import download_file
image_file = download_file('https://data.sdss.org/sas/dr12/boss/photoObj/frames/301/1035/3/frame-irg-001035-3-0011.jpg', cache=True )
image = imread(image_file)

def blockshaped(arr, nrows, ncols, c):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size

If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
h, w = arr.shape[:2]
return (arr.reshape(h//nrows, nrows, -1, ncols, c)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols, c))

a= image[:1408, :]
b= blockshaped(a, 128, 128, 3)
b.shape
</code>```

b.shape = (176, 128, 128, 3)

答:
Here's a possible way to do it.</p>

```<code>import numpy as np
import scipy.misc

images = np.zeros((176,128,128,3))
for i in range(len(images)):
    scipy.misc.imsave('date_set_' + str(i) + '.jpg', images[i,:,:,:])
</code>```

Title: How to save 4d numpy array to images

Body:
I want to create an image date_set which includes 176 small images (128*128*3) from one big image (1408, 2048, 3).
I do the following thing:
step 1.
Load the big image and convert it to numpy array. (1408, 2048, 3) 3d array
step 2.
cut it into 176 pieces: (176, 128, 128, 3) 4d array
step 3.
I don't know how to save 176 images from 4d array in this step. Does anyone could help me to solve this problem?
Thanks very much!

from astropy.io import fits
from astropy.utils.data import download_file
image_file = download_file('https://data.sdss.org/sas/dr12/boss/photoObj/frames/301/1035/3/frame-irg-001035-3-0011.jpg', cache=True )
image = imread(image_file)

def blockshaped(arr, nrows, ncols, c):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size

If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
h, w = arr.shape[:2]
return (arr.reshape(h//nrows, nrows, -1, ncols, c)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols, c))

a= image[:1408, :]
b= blockshaped(a, 128, 128, 3)
b.shape

b.shape = (176, 128, 128, 3)

Body:
Here's a possible way to do it.

import numpy as np
import scipy.misc

images = np.zeros((176,128,128,3))
for i in range(len(images)):
    scipy.misc.imsave('date_set_' + str(i) + '.jpg', images[i,:,:,:])


问:
Can js code on a site prevent other js code from detecting presence of flash?
I'm looking for a workaround to the "AdSense does not let you choose only images but no flash" issue. I'm rather a newbie to JS, but is there any way for one script to prevent other scripts embedded in a site from detecting the presence of the flash plugin? Even if it doesn't work with AdSense, it would be nice to know if there's a hack to do this that might work in other settings.

By the way, I suppose I wouldn't care if it failed to work on IE or obsolete browser versions.

答:
It looks like adsense detects flash by looking at the content of navigator.plugins["Shockwave Flash"]. Unfortunately, you can't just set just that to a different value, as browsers won't let you. Similarly, you can't set navigator.plugins. Some browsers let you delete navigator.plugins, but not all of them.

However, you can set navigator. So the path to do what you want involves creating a fake navigator object.

```<code>var real_navigator = navigator;
navigator = { plugins:[], mimeTypes:[] };
for (var k in real_navigator) {
  var t = typeof real_navigator[k];
  if (t == "string" || t == "function") {
    navigator[k] = real_navigator[k];
  }
}
</code>```

At that point, you can still have scripts that inspect your user-agent and such, but plugins and mimetypes won't show up.

It's not fool-proof, and you'd have to stub ActiveXObject if you want IE to play along, but overall, this should get you closer to your goal.

ContentLicense: CC BY-SA 2.5

Body:
It looks like adsense detects flash by looking at the content of navigator.plugins["Shockwave Flash"]. Unfortunately, you can't just set just that to a different value, as browsers won't let you. Similarly, you can't set navigator.plugins. Some browsers let you delete navigator.plugins, but not all of them.

However, you can set navigator. So the path to do what you want involves creating a fake navigator object.

var real_navigator = navigator;
navigator = { plugins:[], mimeTypes:[] };
for (var k in real_navigator) {
  var t = typeof real_navigator[k];
  if (t == "string" || t == "function") {
    navigator[k] = real_navigator[k];
  }
}

At that point, you can still have scripts that inspect your user-agent and such, but plugins and mimetypes won't show up.

It's not fool-proof, and you'd have to stub ActiveXObject if you want IE to play along, but overall, this should get you closer to your goal.


问:
Pigeonhole proof without decidable equality or excluded middle
In Software Foundations IndProp.v one is asked to prove the pigeonhole principle, and one may use excluded middle, but it is mentioned that it is not strictly necessary.  I've been trying to prove it without EM, but my brain seems to be wired classically.

Q: How would one prove the theorem without using excluded middle?  How should one generally approach proofs for types without decidable equality, where one can't easily reason by cases?

I'd be very happy for a complete proof to look at, but please avoid posting it "in the clear", so as to not spoil the exercise in the Software Foundations course.

The definition uses two inductive predicates, In and  repeats.

```<code>Require Import Lists.List.
Import ListNotations.

Section Pigeon.

  Variable (X:Type).
  Implicit Type (x:X).

  Fixpoint In x l : Prop :=                        (***    In       ***)
    match l with
    | nil => False
    | (x'::l') => x' = x \/ In x l'
    end.

  Hypothesis in_split : forall x l, In x l ->  exists l1 l2, l = l1 ++ x :: l2.
  Hypothesis in_app:    forall x l1 l2, In x (l1++l2) <-> In x l1 \/ In x l2.

  Inductive repeats : list X -> Prop :=            (***    repeats   ***)
    repeats_hd l x : In x l    -> repeats (x::l)
  | repeats_tl l x : repeats l -> repeats (x::l).

  Theorem pigeonhole_principle_NO_EM:              (***   pigeonhole   ***)
    forall l1  l2,
      length l2 < length l1 ->            (* There are more pigeons than nests *)
      (forall x, In x l1 -> In x l2) ->   (* All pigeons are in some nest *)
      repeats l1.                         (* Thus, some pigeons share nest *)
  Proof.

    (* ??? *)
</code>```

答:
I'll describe the thought process that led me to a solution, in case it helps. We may apply induction and it is straightforward to reduce to the case l1 = a::l1', l2 = a::l2'. Now l1' is a subset of a::l2'. My EM-trained intuition is that one of the following holds:

a is in l1'.

a is not in l1'.

In the latter case, each element of l1' is in a::l2' but differs from a, and therefore must be in l2'. Thus l1' is a subset of l2', and we can apply the inductive hypothesis.

Unfortunately if In is not decidable, the above can't be directly formalized. In particular if equality is not decidable for the given type, it's difficult to prove elements are unequal, and therefore difficult to prove a negative statement like ~(In a l1'). However, we wanted to use that negative statement to prove a positive one, namely

```<code>forall x, In x l1' -> In x l2'
</code>```

By analogy, suppose we wanted to prove

```<code>P \/ Q
Q -> R
------
P \/ R
</code>```

The above intuitive argument is like starting from P \/ ~P, and using ~P -> Q -> R in the second case. We can use a direct proof to avoid EM.

Quantifying over the list l1' makes this a bit more complicated, but still we can construct a direct proof using the following lemma, which can be proven by induction.

```<code>Lemma split_or {X} (l : list X) (P Q : X -> Prop) :
  (forall x, In x l -> (P x \/ Q x)) ->
  (exists x, In x l /\ P x) \/ (forall x, In x l -> Q x).
</code>```

Finally note that the intuitive pigeonhole principle could also be formalized as the following way, which cannot be proven when the type has undecidable equality (note that it has a negative statement in the conclusion):

```<code>Definition pigeon2 {X} : Prop := forall (l1 l2 : list X),
  length l2 < length l1 ->
  (exists x, In x l1 /\ ~(In x l2)) \/ repeats l1.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Software Foundations IndProp.v one is asked to prove the pigeonhole principle, and one may use excluded middle, but it is mentioned that it is not strictly necessary.  I've been trying to prove it without EM, but my brain seems to be wired classically.

Q: How would one prove the theorem without using excluded middle?  How should one generally approach proofs for types without decidable equality, where one can't easily reason by cases?

I'd be very happy for a complete proof to look at, but please avoid posting it "in the clear", so as to not spoil the exercise in the Software Foundations course.

The definition uses two inductive predicates, In and  repeats.

Require Import Lists.List.
Import ListNotations.

Section Pigeon.

  Variable (X:Type).
  Implicit Type (x:X).

  Fixpoint In x l : Prop :=                        (***    In       ***)
    match l with
    | nil => False
    | (x'::l') => x' = x \/ In x l'
    end.

  Hypothesis in_split : forall x l, In x l ->  exists l1 l2, l = l1 ++ x :: l2.
  Hypothesis in_app:    forall x l1 l2, In x (l1++l2) <-> In x l1 \/ In x l2.

  Inductive repeats : list X -> Prop :=            (***    repeats   ***)
    repeats_hd l x : In x l    -> repeats (x::l)
  | repeats_tl l x : repeats l -> repeats (x::l).

  Theorem pigeonhole_principle_NO_EM:              (***   pigeonhole   ***)
    forall l1  l2,
      length l2 < length l1 ->            (* There are more pigeons than nests *)
      (forall x, In x l1 -> In x l2) ->   (* All pigeons are in some nest *)
      repeats l1.                         (* Thus, some pigeons share nest *)
  Proof.

    (* ??? *)

Body:
I'll describe the thought process that led me to a solution, in case it helps. We may apply induction and it is straightforward to reduce to the case l1 = a::l1', l2 = a::l2'. Now l1' is a subset of a::l2'. My EM-trained intuition is that one of the following holds:

a is in l1'.

a is not in l1'.

In the latter case, each element of l1' is in a::l2' but differs from a, and therefore must be in l2'. Thus l1' is a subset of l2', and we can apply the inductive hypothesis.

Unfortunately if In is not decidable, the above can't be directly formalized. In particular if equality is not decidable for the given type, it's difficult to prove elements are unequal, and therefore difficult to prove a negative statement like ~(In a l1'). However, we wanted to use that negative statement to prove a positive one, namely

forall x, In x l1' -> In x l2'

By analogy, suppose we wanted to prove

P \/ Q
Q -> R
------
P \/ R

The above intuitive argument is like starting from P \/ ~P, and using ~P -> Q -> R in the second case. We can use a direct proof to avoid EM.

Quantifying over the list l1' makes this a bit more complicated, but still we can construct a direct proof using the following lemma, which can be proven by induction.

Lemma split_or {X} (l : list X) (P Q : X -> Prop) :
  (forall x, In x l -> (P x \/ Q x)) ->
  (exists x, In x l /\ P x) \/ (forall x, In x l -> Q x).

Finally note that the intuitive pigeonhole principle could also be formalized as the following way, which cannot be proven when the type has undecidable equality (note that it has a negative statement in the conclusion):

Definition pigeon2 {X} : Prop := forall (l1 l2 : list X),
  length l2 < length l1 ->
  (exists x, In x l1 /\ ~(In x l2)) \/ repeats l1.


问:
loop through implicit array
I've been stuck on this for awhile now. I'm trying to loop through this array so I can perform some calculations but I cannot figure out how to loop through there values. Any suggestions?

I managed to figure out how to get there collection structures but I want to loop through each structure and grab there values as well and thats what I'm stuck on.

Also, I want to refrain from using cfscript if possible as I'm still in the learning stages of learning coldfusion.

Here is my code:

```<code><cfset houseStuff = {
    Bedroom = [
        'Luxury Duvet Set with Alternative Down Comforter',
        'Accent Coverlet & Shams',
        'Two Sets of Luxurious Liens',
        'Mattress Pad',
        'Blanket',
        'Six Bed Pillows',
        'Clock Radio',
        'Twenty Hangers'
    ],
    Bathroom = [
        'Four Bath Towels',
        'Four Hand Towels',
        'Four Face Towels',
        'Bath Rug',
        'Shower Curtain',
        'Stainless Tooth Brush Holder & Soap Dish',
        'Wastebasket',
        'Artwork',
        'Hair Dryer',
        'Toilet Brush & Plunger'
    ],
    Dining = [
        'Dinnerware',
        'Place Mats',
        'Napkins',
        'Flatware',
        'Glassware & Wine Glasses'
    ],
    Kitchen = [
        'Microwave',
        'Cookware',
        'Mixing Bowls',
        'Baking Dish',
        'Colander',
        'Stainless Utensil Holder',
        'Large Fork',
        'Large Spoon',
        'Spatula',
        'Whisk',
        'Measuring Spoon & Cup',
        'Carving & Paring Knives',
        'Four Steak Knives',
        'Cutting Board',
        'Salt & Pepper Set',
        'Wine Opener',
        'Coffee Maker',
        'Toaster',
        'Electric Can Opener',
        'Flatware Tray',
        'Kitchen Wastebasket',
        'Dish Towels',
        'Pot Holders',
        'Pitcher',
        '10" Non-Stick Frying Pan',
        'Cookie Sheet',
        'Stainless Steel Electric Tea Kettle',
        '3 Piece Non-Metal (Spatula, Spoon, Paste Spoon) Combo'
    ],
    Micellaneous = [
        'Iron & Cutting Board',
        'Cordless Dual Phone with Digital Answering Machine',
        'Broom',
        'Dust Pan',
        'Vacuum',
        'Decor',
        'Laundry Basket'
    ],
    StarterKit = [
        'Bath Tissue',
        'Soap',
        'Shampoo & Conditioner',
        'Paper Towels',
        'Sponge',
        'Laundry Soap',
        'Dishwasher Detergent',
        'Liquid Dish Soap',
        'Extra Light Bulbs',
        'Coffee',
        'Sugar',
        'Creamer',
        'Bottled Water',
        'Oatmeal',
        'Breakfast Bars',
        'Peanuts',
        'Chips',
        'Mints',
        'Welcome Information'
    ],
    MasterBedroom = [
        'Queen bed',
        'Headboard',
        'Two Nightstands',
        'Dresser & Mirrior',
        'Two Lamps',
        'Artwork',
        'LCD Television'
    ],
    LivingRoom = [
        'Sofa',
        'Chair',
        'End Table',
        'Coffee Table',
        'Lamp',
        'LCD TV w/stand',
        'DVD Player',
        'Artwork'
    ],
    DiningRoom = [
        'Dining Table',
        'Dining Chairs',
        'Artwork'
    ],
    OfficePackage = [
        'Desk',
        'Chair',
        'Lamp'
    ],
    AdditionalBedrooms = [
        'Queen or Two Twin Beds',
        'Headboard',
        'Nightstand',
        'Chest of Drawers',
        'Lamp',
        'Artwork'
    ]
} />

<cfloop collection="#houseStuff#" item="key">
    <cfdump var="#key#"> <br>
    <!--- <p style="color:##fff;">#key#:</p> <br /> --->
</cfloop>
</code>```

答:
Nevermind, I finally figured it out. I had to loop through the collection first. Once I do that create another loop inside it to loop over it's structured values.</p>

```<code><cfloop collection="houseStuff" item="key">
   <!---<cfdump var="#houseStuff[key]"> --->
    <cfloop from="1" to="#arrayLen(houseStuff[key])#" index="j">
        #j#
    </cfloop>
</cfloop>
</code>```

Title: loop through implicit array

Body:
I've been stuck on this for awhile now. I'm trying to loop through this array so I can perform some calculations but I cannot figure out how to loop through there values. Any suggestions?

I managed to figure out how to get there collection structures but I want to loop through each structure and grab there values as well and thats what I'm stuck on.

Also, I want to refrain from using cfscript if possible as I'm still in the learning stages of learning coldfusion.

Here is my code:

<cfset houseStuff = {
    Bedroom = [
        'Luxury Duvet Set with Alternative Down Comforter',
        'Accent Coverlet & Shams',
        'Two Sets of Luxurious Liens',
        'Mattress Pad',
        'Blanket',
        'Six Bed Pillows',
        'Clock Radio',
        'Twenty Hangers'
    ],
    Bathroom = [
        'Four Bath Towels',
        'Four Hand Towels',
        'Four Face Towels',
        'Bath Rug',
        'Shower Curtain',
        'Stainless Tooth Brush Holder & Soap Dish',
        'Wastebasket',
        'Artwork',
        'Hair Dryer',
        'Toilet Brush & Plunger'
    ],
    Dining = [
        'Dinnerware',
        'Place Mats',
        'Napkins',
        'Flatware',
        'Glassware & Wine Glasses'
    ],
    Kitchen = [
        'Microwave',
        'Cookware',
        'Mixing Bowls',
        'Baking Dish',
        'Colander',
        'Stainless Utensil Holder',
        'Large Fork',
        'Large Spoon',
        'Spatula',
        'Whisk',
        'Measuring Spoon & Cup',
        'Carving & Paring Knives',
        'Four Steak Knives',
        'Cutting Board',
        'Salt & Pepper Set',
        'Wine Opener',
        'Coffee Maker',
        'Toaster',
        'Electric Can Opener',
        'Flatware Tray',
        'Kitchen Wastebasket',
        'Dish Towels',
        'Pot Holders',
        'Pitcher',
        '10" Non-Stick Frying Pan',
        'Cookie Sheet',
        'Stainless Steel Electric Tea Kettle',
        '3 Piece Non-Metal (Spatula, Spoon, Paste Spoon) Combo'
    ],
    Micellaneous = [
        'Iron & Cutting Board',
        'Cordless Dual Phone with Digital Answering Machine',
        'Broom',
        'Dust Pan',
        'Vacuum',
        'Decor',
        'Laundry Basket'
    ],
    StarterKit = [
        'Bath Tissue',
        'Soap',
        'Shampoo & Conditioner',
        'Paper Towels',
        'Sponge',
        'Laundry Soap',
        'Dishwasher Detergent',
        'Liquid Dish Soap',
        'Extra Light Bulbs',
        'Coffee',
        'Sugar',
        'Creamer',
        'Bottled Water',
        'Oatmeal',
        'Breakfast Bars',
        'Peanuts',
        'Chips',
        'Mints',
        'Welcome Information'
    ],
    MasterBedroom = [
        'Queen bed',
        'Headboard',
        'Two Nightstands',
        'Dresser & Mirrior',
        'Two Lamps',
        'Artwork',
        'LCD Television'
    ],
    LivingRoom = [
        'Sofa',
        'Chair',
        'End Table',
        'Coffee Table',
        'Lamp',
        'LCD TV w/stand',
        'DVD Player',
        'Artwork'
    ],
    DiningRoom = [
        'Dining Table',
        'Dining Chairs',
        'Artwork'
    ],
    OfficePackage = [
        'Desk',
        'Chair',
        'Lamp'
    ],
    AdditionalBedrooms = [
        'Queen or Two Twin Beds',
        'Headboard',
        'Nightstand',
        'Chest of Drawers',
        'Lamp',
        'Artwork'
    ]
} />

<cfloop collection="#houseStuff#" item="key">
    <cfdump var="#key#">

</cfloop>

Body:
Nevermind, I finally figured it out. I had to loop through the collection first. Once I do that create another loop inside it to loop over it's structured values.

<cfloop collection="houseStuff" item="key">
   <!---<cfdump var="#houseStuff[key]"> --->
    <cfloop from="1" to="#arrayLen(houseStuff[key])#" index="j">
        #j#
    </cfloop>
</cfloop>


问:
Angular - upload file as base64
I am trying to upload files from Angular 4 app to a JSON API service that accepts base64 strings as file content.

So what I do is - read the file with FileReader.readAsDataURL, then when user confirms the upload I will create a JSON request to the API and send the base64 string of the file I got earlier.

This is where the problem starts - as soon as I do something with the "content" (log it, send it, w/e) the request will be send, but its insanely slow, e.g. 20 seconds for 2MB file.

I have tried:

using ArrayBuffer and manually converting it to base64

storing the base64 string in HTML and retrieving it later

reading the files after user clicks on upload button

using the old client from @angular/common

using plain XHR request

but everything leads to the same result.

I know where the problem lies. But why does it happen? Is it something browser specific or angular specific? Is there a more preferred approach (keep in mind it has to be base64 string)?

Notes:

changing anything in the API is beyond my control

API is fine, sending any file trough postman will finish immediately

Code:

This method runs when user adds file to the dropzone:

```<code>public onFileChange(files: File[]) : void {
    files.forEach((file: File, index: number) => {
        const reader = new FileReader;

        // UploadedFile is just a simple model that contains filename, size, type and later base64 content
        this.uploadedFiles[index] = new UploadedFile(file);

        //region reader.onprogress
        reader.onprogress = (event: ProgressEvent) => {
            if (event.lengthComputable) {
                this.uploadedFiles[index].updateProgress(
                    Math.round((event.loaded * 100) / event.total)
                );
            }
        };
        //endregion

        //region reader.onloadend
        reader.onloadend = (event: ProgressEvent) => {
            const target: FileReader = <FileReader>event.target;
            const content = target.result.split(',')[1];

            this.uploadedFiles[index].contentLoaded(content);
        };
        //endregion

        reader.readAsDataURL(file);
    });
}
</code>```

This method runs when users clicks save button

```<code>public upload(uploadedFiles: UploadedFile[]) : Observable<null> {
    const body: object = {
        files: uploadedFiles.map((uploadedFile) => {
            return {
                filename: uploadedFile.name,
                // SLOWDOWN HAPPENS HERE
                content: uploadedFile.content
            };
        })
    };

    return this.http.post('file', body)
}
</code>```

答:
For sending big files to server you should use FormData to be able to send it as multi-part instead of a single big file.

Something like:

// import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }
  // Send it.
  return this.http.post(uploadUrl, formData, options);

}```

Also don't forget to set the header 'Content-Type': undefined, I've scratched my head over this for hours.

Title: Angular - upload file as base64

Body:
I am trying to upload files from Angular 4 app to a JSON API service that accepts base64 strings as file content.

So what I do is - read the file with FileReader.readAsDataURL, then when user confirms the upload I will create a JSON request to the API and send the base64 string of the file I got earlier.

This is where the problem starts - as soon as I do something with the "content" (log it, send it, w/e) the request will be send, but its insanely slow, e.g. 20 seconds for 2MB file.

I have tried:

using ArrayBuffer and manually converting it to base64

storing the base64 string in HTML and retrieving it later

reading the files after user clicks on upload button

using the old client from @angular/common

using plain XHR request

but everything leads to the same result.

I know where the problem lies. But why does it happen? Is it something browser specific or angular specific? Is there a more preferred approach (keep in mind it has to be base64 string)?

Notes:

changing anything in the API is beyond my control

API is fine, sending any file trough postman will finish immediately

Code:

This method runs when user adds file to the dropzone:

public onFileChange(files: File[]) : void {
    files.forEach((file: File, index: number) => {
        const reader = new FileReader;

        // UploadedFile is just a simple model that contains filename, size, type and later base64 content
        this.uploadedFiles[index] = new UploadedFile(file);

        //region reader.onprogress
        reader.onprogress = (event: ProgressEvent) => {
            if (event.lengthComputable) {
                this.uploadedFiles[index].updateProgress(
                    Math.round((event.loaded * 100) / event.total)
                );
            }
        };
        //endregion

        //region reader.onloadend
        reader.onloadend = (event: ProgressEvent) => {
            const target: FileReader = <FileReader>event.target;
            const content = target.result.split(',')[1];

            this.uploadedFiles[index].contentLoaded(content);
        };
        //endregion

        reader.readAsDataURL(file);
    });
}

This method runs when users clicks save button

public upload(uploadedFiles: UploadedFile[]) : Observable<null> {
    const body: object = {
        files: uploadedFiles.map((uploadedFile) => {
            return {
                filename: uploadedFile.name,
                // SLOWDOWN HAPPENS HERE
                content: uploadedFile.content
            };
        })
    };

    return this.http.post('file', body)
}

Body:
For sending big files to server you should use FormData to be able to send it as multi-part instead of a single big file.

Something like:

// import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }
  // Send it.
  return this.http.post(uploadUrl, formData, options);

}

Also don't forget to set the header 'Content-Type': undefined, I've scratched my head over this for hours.


问:
Compute median of up to 5 in Scala
So, while answering some other question I stumbled upon the necessity of computing the median of 5. Now, there's a similar question in another language, but I want a Scala algorithm for it, and I'm not sure I'm happy with mine.</p>

答:
Jeez, way to over-think it, guys.</p>

```<code>def med5(a : Int, b: Int, c : Int, d : Int, e : Int) =
   List(a, b, c, d, e).sort(_ > _)(2)
</code>```

Title: Compute median of up to 5 in Scala

Body:
Jeez, way to over-think it, guys.

def med5(a : Int, b: Int, c : Int, d : Int, e : Int) =
   List(a, b, c, d, e).sort(_ > _)(2)


问:
How to replace found regex sub string with spaces with equal length in javascript?
In javascript if I have something like

```<code>string.replace(new RegExp(regex, "ig"), " ")
</code>```

this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?

so if regex was \d+, and the string was

```<code>"123hello4567"
</code>```

it changes to

```<code>"   hello    "
</code>```

Thanks

Body:
In javascript if I have something like

string.replace(new RegExp(regex, "ig"), " ")

this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?

so if regex was \d+, and the string was

"123hello4567"

it changes to

"   hello    "

Thanks

Body:
"123hello4567".replace(new RegExp(/[\d]/, "ig"), " ")
1 => " "
2 => " "
3 => " "

"   hello    "

"123hello4567".replace(new RegExp(/[\d]+/, "ig"), " ")
123 => " "
4567 => " "
" hello "


问:
SQL add IDENTITY base on grouped column value
I have data like this:

```<code>FirstName     LastName
El            Even
Mike          Wheeler
Mike          Byers
Dustin        Henderson
</code>```

And my desired output is to add Identity into each of the unique FirstName

```<code>ID   FirstName     LastName
1    El            Even
2    Mike          Wheeler
2    Mike          Byers
3    Dustin        Henderson
</code>```

The way I do this is:

```<code>/* part 1 */
SELECT IDENTITY(int, 1,1) AS ID, FirstName
INTO TabTemp FROM TabName
GROUP BY FirstName

/* part 2 */
SELECT B.ID, A.FirstName, A.LastName
INTO TabTempFinal FROM TabName A, TabTemp B
WHERE A.FistName = B.FirstName
</code>```

My question is can I achieve the result without using the part 2?

答:
Not really.  You can't add an identity column to a table where the identity is not supposed to be unique.  That is not how identity columns work.

But, you can use dense_rank() instead:

```<code>SELECT DENSE_RANK() OVER (ORDER BY FirstName) AS ID,
       FirstName, LastName
INTO TabTempFinal
FROM TabName ;
</code>```

This generates the unique indicator for each FirstName.  The only difference is that the column is not an identity column.

Body:
I have data like this:

FirstName     LastName
El            Even
Mike          Wheeler
Mike          Byers
Dustin        Henderson

And my desired output is to add Identity into each of the unique FirstName

ID   FirstName     LastName
1    El            Even
2    Mike          Wheeler
2    Mike          Byers
3    Dustin        Henderson

The way I do this is:

/* part 1 */
SELECT IDENTITY(int, 1,1) AS ID, FirstName
INTO TabTemp FROM TabName
GROUP BY FirstName

/* part 2 */
SELECT B.ID, A.FirstName, A.LastName
INTO TabTempFinal FROM TabName A, TabTemp B
WHERE A.FistName = B.FirstName

My question is can I achieve the result without using the part 2?

Body:
Not really.  You can't add an identity column to a table where the identity is not supposed to be unique.  That is not how identity columns work.

But, you can use dense_rank() instead:

SELECT DENSE_RANK() OVER (ORDER BY FirstName) AS ID,
       FirstName, LastName
INTO TabTempFinal
FROM TabName ;

This generates the unique indicator for each FirstName.  The only difference is that the column is not an identity column.


答:
If you just want to replace every digit with a space, keep it simple:

```<code>var str = "123hello4567";
var res = str.replace(/\d/g,' ');

"   hello    "
</code>```

This answers your example, but not exactly your question.  What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once?  You could do something like this:

```<code>var str = "123hello456789goodbye12and456hello12345678again123";
var regex = /(\d+)/;
var match = regex.exec(str);
while (match != null) {
    // Create string of spaces of same length
    var replaceSpaces = match[0].replace(/./g,' ');
    str = str.replace(regex, replaceSpaces);
    match = regex.exec(str);
}

"   hello      goodbye  and   hello        again   "
</code>```

Which will loop through executing the regex (instead of using /g for global).

Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0].  This would remove the regex replace within the loop.  If performance isn't a high priority, this should work fine.

Title: How to replace found regex sub string with spaces with equal length in javascript?

Body:
If you just want to replace every digit with a space, keep it simple:

var str = "123hello4567";
var res = str.replace(/\d/g,' ');

"   hello    "

This answers your example, but not exactly your question.  What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once?  You could do something like this:

var str = "123hello456789goodbye12and456hello12345678again123";
var regex = /(\d+)/;
var match = regex.exec(str);
while (match != null) {
    // Create string of spaces of same length
    var replaceSpaces = match[0].replace(/./g,' ');
    str = str.replace(regex, replaceSpaces);
    match = regex.exec(str);
}

"   hello      goodbye  and   hello        again   "

Which will loop through executing the regex (instead of using /g for global).

Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0].  This would remove the regex replace within the loop.  If performance isn't a high priority, this should work fine.


问:
Django Comments: Want to remove user URL, not expand the model. How to?
I'm totally understanding the documentation on expanding the Comments app in Django, and really would like to stick with the automatic functionality but...

In the current app, I have absolutely no use for an "URL" to be submitted along with a comment.

Being minimally invasive of the default setup, how can I prevent this field from showing up with the comment form?

Using Django 1, or Trunk, and as many generic/built-ins as possible (generic views, default comments set up, etc. I have only a single generic view wrapper so far).

答:
I can't comment onto SmileyChris' post for some reason, so I am going to post it here. But, I ran into errors using just SmileyChris' response. You also have to overwrite the get_comment_create_data function because CommentForm is going to look for those Post keys that you removed. So here's my code after I removed three fields.

```<code>class SlimCommentForm(CommentForm):
"""
A comment form which matches the default djanago.contrib.comments one, but with 3 removed fields
"""
def get_comment_create_data(self):
    # Use the data of the superclass, and remove extra fields
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )

SlimCommentForm.base_fields.pop('url')
SlimCommentForm.base_fields.pop('email')
SlimCommentForm.base_fields.pop('name')
</code>```

This is the function that you are overwriting

```<code>def get_comment_create_data(self):
    """
    Returns the dict of data to be used to create a comment. Subclasses in
    custom comment apps that override get_comment_model can override this
    method to add extra fields onto a custom comment model.
    """
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        user_name    = self.cleaned_data["name"],
        user_email   = self.cleaned_data["email"],
        user_url     = self.cleaned_data["url"],
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )
</code>```

Body:
I can't comment onto SmileyChris' post for some reason, so I am going to post it here. But, I ran into errors using just SmileyChris' response. You also have to overwrite the get_comment_create_data function because CommentForm is going to look for those Post keys that you removed. So here's my code after I removed three fields.

class SlimCommentForm(CommentForm):
"""
A comment form which matches the default djanago.contrib.comments one, but with 3 removed fields
"""
def get_comment_create_data(self):
    # Use the data of the superclass, and remove extra fields
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )

SlimCommentForm.base_fields.pop('url')
SlimCommentForm.base_fields.pop('email')
SlimCommentForm.base_fields.pop('name')

This is the function that you are overwriting

def get_comment_create_data(self):
    """
    Returns the dict of data to be used to create a comment. Subclasses in
    custom comment apps that override get_comment_model can override this
    method to add extra fields onto a custom comment model.
    """
    return dict(
        content_type = ContentType.objects.get_for_model(self.target_object),
        object_pk    = force_unicode(self.target_object._get_pk_val()),
        user_name    = self.cleaned_data["name"],
        user_email   = self.cleaned_data["email"],
        user_url     = self.cleaned_data["url"],
        comment      = self.cleaned_data["comment"],
        submit_date  = datetime.datetime.now(),
        site_id      = settings.SITE_ID,
        is_public    = True,
        is_removed   = False,
    )


答:
You could just use the dense_rank window function:

```<code>SELECT DENSE_RANK() OVER (ORDER BY first_name) AS id,
       first_name,
       last_name
FROM   tabname
</code>```

Title: SQL add IDENTITY base on grouped column value

Body:
You could just use the dense_rank window function:

SELECT DENSE_RANK() OVER (ORDER BY first_name) AS id,
       first_name,
       last_name
FROM   tabname


问:
showing gridlines with QTreeView
I am using a QTreeView with a custom delegate and i subclassed QAbstractItemModel.
I would like to see gridlines for items without children.

At first display, everything’s looks fine but whenever the mouse hovers over an item, the bottom or top line dissappears and reappears when hovering back to the item.

since this is my first post, it seems that i cannot post some images to show the unwanted effect.

But i guess something's wrong with my custom delegate or my stylesheet for the QTreeView :

```<code>void ProjetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() > 0 && !index.model()->hasChildren(index))
    {
        QPen pen;
        pen.setColor(QColor(Qt::lightGray));
        pen.setWidth(1);
        painter->setPen(pen);
        painter->drawRect(option.rect);
        QStyledItemDelegate::paint(painter,option,index);
    }
    else QStyledItemDelegate::paint(painter,option,index);
}
</code>```

The stylesheet used is :

```<code>QString treeViewStyle =
    "QTreeView { show-decoration-selected: 1; }"
    "QTreeView::item:hover { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 white); }"
    "QTreeView::item:selected:active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black; }"
    "QTreeView::item:selected:!active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black;}" ;
</code>```

Has anyone an idea of how to get rid of this dynamic behavior and keep the initial correct view at first display ?

Thanks.

答:
Using an item delegate might be good, but it might result in low performances when displaying lots of items, since every item has to cycle through its paint method.
Also, if using different delegates for every column (with some having their own paint method), this might be a problem.

Another approach could be to implement QTreeView.drawRow(), which has the advantage of not drawing actual rectangles that might result in inconsistent drawing with non-black (or with alpha component) colors.
I am using PyQt, but this should to be still readable for other languages.

```<code>def drawRow(self, painter, option, index):
    QtGui.QTreeView.drawRow(self, painter, option, index)
    painter.setPen(QtCore.Qt.lightGray)
    y = option.rect.y()
    #saving is mandatory to keep alignment through out the row painting
    painter.save()
    painter.translate(self.visualRect(self.model().index(0, 0)).x() - self.indentation() - .5, -.5)
    for sectionId in range(self.header().count() - 1):
        painter.translate(self.header().sectionSize(sectionId), 0)
        painter.drawLine(0, y, 0, y + option.rect.height())
    painter.restore()
    #don't draw the line before the root index
    if index == self.model().index(0, 0):
        return
    painter.drawLine(0, y, option.rect.width(), y)
</code>```

The code above draws an horizontal line before every row and a vertical one before every column, keeping track of the header section size and tree indentation; keep in mind that I've not checked how it behaves with the rootIsDecorated property.

Title: showing gridlines with QTreeView

Body:
I am using a QTreeView with a custom delegate and i subclassed QAbstractItemModel.
I would like to see gridlines for items without children.

At first display, everything’s looks fine but whenever the mouse hovers over an item, the bottom or top line dissappears and reappears when hovering back to the item.

since this is my first post, it seems that i cannot post some images to show the unwanted effect.

But i guess something's wrong with my custom delegate or my stylesheet for the QTreeView :

void ProjetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() > 0 && !index.model()->hasChildren(index))
    {
        QPen pen;
        pen.setColor(QColor(Qt::lightGray));
        pen.setWidth(1);
        painter->setPen(pen);
        painter->drawRect(option.rect);
        QStyledItemDelegate::paint(painter,option,index);
    }
    else QStyledItemDelegate::paint(painter,option,index);
}

The stylesheet used is :

QString treeViewStyle =
    "QTreeView { show-decoration-selected: 1; }"
    "QTreeView::item:hover { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 white); }"
    "QTreeView::item:selected:active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black; }"
    "QTreeView::item:selected:!active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black;}" ;

Has anyone an idea of how to get rid of this dynamic behavior and keep the initial correct view at first display ?

Thanks.

Body:
Using an item delegate might be good, but it might result in low performances when displaying lots of items, since every item has to cycle through its paint method.
Also, if using different delegates for every column (with some having their own paint method), this might be a problem.

Another approach could be to implement QTreeView.drawRow(), which has the advantage of not drawing actual rectangles that might result in inconsistent drawing with non-black (or with alpha component) colors.
I am using PyQt, but this should to be still readable for other languages.

def drawRow(self, painter, option, index):
    QtGui.QTreeView.drawRow(self, painter, option, index)
    painter.setPen(QtCore.Qt.lightGray)
    y = option.rect.y()
    #saving is mandatory to keep alignment through out the row painting
    painter.save()
    painter.translate(self.visualRect(self.model().index(0, 0)).x() - self.indentation() - .5, -.5)
    for sectionId in range(self.header().count() - 1):
        painter.translate(self.header().sectionSize(sectionId), 0)
        painter.drawLine(0, y, 0, y + option.rect.height())
    painter.restore()
    #don't draw the line before the root index
    if index == self.model().index(0, 0):
        return
    painter.drawLine(0, y, option.rect.width(), y)

The code above draws an horizontal line before every row and a vertical one before every column, keeping track of the header section size and tree indentation; keep in mind that I've not checked how it behaves with the rootIsDecorated property.


问:
Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :

```<code>var myArray = [['Apples',22],['Orange',55],['Berry',23]];
</code>```

Another array with the order it should be in :

```<code>var myOrder = [0,2,1];
</code>```

My resulting array would look like this :

```<code>var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
</code>```

My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!

答:
The optimal way appears to me to be:

Initialize empty finalArray

Loop over your myOrder array

2.1. Push myArray[index] to finalArray

Like so:

```<code>let finalArray = [];
for(let index of myOrder) {
    finalArray.push(myArray[index]);
}
</code>```

Review the for...of syntax if you're not familiar with it.

Body:
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :

var myArray = [['Apples',22],['Orange',55],['Berry',23]];

Another array with the order it should be in :

var myOrder = [0,2,1];

My resulting array would look like this :

var finalArray = [['Apples',22],['Berry',23],['Orange',55]]

My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!

Body:
The optimal way appears to me to be:

Initialize empty finalArray

Loop over your myOrder array

2.1. Push myArray[index] to finalArray

Like so:

let finalArray = [];
for(let index of myOrder) {
    finalArray.push(myArray[index]);
}

Review the for...of syntax if you're not familiar with it.


问:
Design a REST api which will fetch results from multiple apis using Nodejs

Am trying to design a REST api which will throw an aggregated response from multiple apis.

Following is the NodeJS code am trying to execute -

```<code>Pseudo Code start
//endpoint to be called from a browser / REST client

router.get('/api/v1/getItems', (req, response, next) => {

var result = {} // hold the aggregated response from multiple apis
    //internally fire another endpoint & add the response over to the var result
 http.get(endpoint 1, function(resp){
 add response to result})
 http.get(endpoint 2, function(resp){
 add response to result
})
return response.json(result);
}

Pseudo Code end

// endpoint to be called from the browser or REST Client.
router.get('/api/v1/getItems', (req, response, next) => {
  var results = {};

// Nested Endpoint 1
  var optionsgetmsg = {
    host : 'host.domain.com', // tthe domain name
    port : 9043,
    path : '/services/itemdata', // the rest of the url
    method : 'GET' // do GET
};

//child endpoint
  var reqGet = http.request(optionsgetmsg, function(res) {

    res.on('data', function(d) {

        console.log("d "+ d); // child response
        results.itemdata = d;
        return response.send(results);
        //process.stdout.write(d);

    });

    res.on('end', function(d){

    })

  });
  reqGet.end();
  reqGet.on('error', function(e) {
      console.error(e);
  });
});
</code>```

The result in the above case should be the output 'd'. The output 'd' is the response from the child endpoint.

Actual result am getting is an empty object. {}

答:
If you are sending JSON, you must set the headers correctly and the response:

```<code> //child endpoint
var reqGet = http.request(optionsgetmsg, function(res) {

res.on('data', function(d) {
    res.setHeader('Content-Type', 'application/json');
    var results = d;
    response.send(JSON.stringify(results));

});
</code>```

It is unclear as to what exactly you are asking for.

Body:
Am trying to design a REST api which will throw an aggregated response from multiple apis.

Following is the NodeJS code am trying to execute -

Pseudo Code start
//endpoint to be called from a browser / REST client

router.get('/api/v1/getItems', (req, response, next) => {

var result = {} // hold the aggregated response from multiple apis
    //internally fire another endpoint & add the response over to the var result
 http.get(endpoint 1, function(resp){
 add response to result})
 http.get(endpoint 2, function(resp){
 add response to result
})
return response.json(result);
}

Pseudo Code end

// endpoint to be called from the browser or REST Client.
router.get('/api/v1/getItems', (req, response, next) => {
  var results = {};

// Nested Endpoint 1
  var optionsgetmsg = {
    host : 'host.domain.com', // tthe domain name
    port : 9043,
    path : '/services/itemdata', // the rest of the url
    method : 'GET' // do GET
};

//child endpoint
  var reqGet = http.request(optionsgetmsg, function(res) {

    res.on('data', function(d) {

        console.log("d "+ d); // child response
        results.itemdata = d;
        return response.send(results);
        //process.stdout.write(d);

    });

    res.on('end', function(d){

    })

  });
  reqGet.end();
  reqGet.on('error', function(e) {
      console.error(e);
  });
});

The result in the above case should be the output 'd'. The output 'd' is the response from the child endpoint.

Actual result am getting is an empty object. {}

Body:
If you are sending JSON, you must set the headers correctly and the response:

 //child endpoint
var reqGet = http.request(optionsgetmsg, function(res) {

res.on('data', function(d) {
    res.setHeader('Content-Type', 'application/json');
    var results = d;
    response.send(JSON.stringify(results));

});

It is unclear as to what exactly you are asking for.


答:
You could do an update with a CTE using DENSE_RANK:

```<code>WITH cte AS (
    SELECT FirstName, LastName, DENSE_RANK() OVER (ORDER BY FirstName) dr
    FROM TabName
)

UPDATE cte
SET ID = dr;
</code>```

This assumes that you already have a column called ID.

Body:
You could do an update with a CTE using DENSE_RANK:

WITH cte AS (
    SELECT FirstName, LastName, DENSE_RANK() OVER (ORDER BY FirstName) dr
    FROM TabName
)

UPDATE cte
SET ID = dr;

This assumes that you already have a column called ID.


答:
You can use splice to insert so long as the same number of elements are present in both the arrays.

You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray

var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];

var finalArray = [];

myOrder.forEach(function(val, index) {
    finalArray.splice(val, 0, myArray[index]);
});

console.log(finalArray);```

Title: Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?


问:
Can you see NHibernate results mid-query during debugging in Visual Studio?
Having been comfortably using Entity Framework for many years, I've just been thrown in the deep end with a project that uses NHibernate and I'm really struggling. The documentation is sparse and unhelpful if you're working with it for the first time, and most tutorial and example sites are out of date - I understand it changed significantly in v3?

Normally, I learn things best when trying to work with them, so I jumped in and tried to see what I could do. But I've hit a bug in this pre-existing function (none of this code is mine):

```<code>public IDictionary<long, string> GetSeriesFilterData(string userId)
{
    Series seriesAlias = null;
    Event eventAlias = null;
    Session sessionAlias = null;
    Dealership dealershipAlias = null;

    var query = _repository.Session.QueryOver(() => seriesAlias)
        .Where(() => !seriesAlias.IsArchived);

    var dealershipIds = QueryOver.Of<ApplicationUserDealership>()
        .Where(x => x.ApplicationUser_Key == userId)
        .SelectList(list => list.SelectGroup(x => x.Dealership_Id));

    dealershipIds.Where(x => x.Dealership_Id == dealershipAlias.Id);
    query
        .JoinAlias(() => sessionAlias.Dealership, () => dealershipAlias, JoinType.LeftOuterJoin)
        .WithSubquery.WhereExists(dealershipIds);

    var results = query.SelectList(x => x
            .SelectGroup(() => seriesAlias.Id)
            .SelectGroup(() => seriesAlias.Name))
        .List<object[]>()
        .ToDictionary(x => (long) x[0], x => (string) x[1]);

    return results;
}
</code>```

The exception, thrown when collecting the result, is:

An exception of type 'NHibernate.QueryException' occurred in NHibernate.dll but was not handled in user code

Additional information: could not resolve property: sessionAlias

My suspicion is that this is because dealershipIds is empty, but I'm struggling to prove that this is the case. Working with Entity Framework, it's possible to see the results of a query during debugging by unpacking its object graph. However, I can't seem to do that in NHibernate.

Is it possible to see the results of a query fragment via debugging, or do I have to pull it out with a Select statement?

答:
The QueryOver you've posted seems to be missing the part where the
sessionAlias alias is assigned to something.

As it's being done for the others (except eventAlias which seems completely unused) the alias needs to be assigned to a property/path on the entity class being queried via JoinAlias/JoinQueryOver or to the entity itself as it's done on the QueryOver creation with seriesAlias.

Then, that alias (variable) can be used in Where, OrderBy, etc.

For example, supposing that Session is an entity referenced from a property of Series (no clue regarding your actual entity model) the following would fix your problem as it will bind sessionAlias to that property:

```<code>// This binds the alias to the property.
query.JoinAlias(s => s.Session, () => sessionAlias);

// This is the same as above, but uses the previously defined alias for the main entity,
// just to show how aliases can be used.
query.JoinAlias(() => seriesAlias.Session, () => sessionAlias);
</code>```

Body:
Having been comfortably using Entity Framework for many years, I've just been thrown in the deep end with a project that uses NHibernate and I'm really struggling. The documentation is sparse and unhelpful if you're working with it for the first time, and most tutorial and example sites are out of date - I understand it changed significantly in v3?

Normally, I learn things best when trying to work with them, so I jumped in and tried to see what I could do. But I've hit a bug in this pre-existing function (none of this code is mine):

public IDictionary<long, string> GetSeriesFilterData(string userId)
{
    Series seriesAlias = null;
    Event eventAlias = null;
    Session sessionAlias = null;
    Dealership dealershipAlias = null;

    var query = _repository.Session.QueryOver(() => seriesAlias)
        .Where(() => !seriesAlias.IsArchived);

    var dealershipIds = QueryOver.Of<ApplicationUserDealership>()
        .Where(x => x.ApplicationUser_Key == userId)
        .SelectList(list => list.SelectGroup(x => x.Dealership_Id));

    dealershipIds.Where(x => x.Dealership_Id == dealershipAlias.Id);
    query
        .JoinAlias(() => sessionAlias.Dealership, () => dealershipAlias, JoinType.LeftOuterJoin)
        .WithSubquery.WhereExists(dealershipIds);

    var results = query.SelectList(x => x
            .SelectGroup(() => seriesAlias.Id)
            .SelectGroup(() => seriesAlias.Name))
        .List<object[]>()
        .ToDictionary(x => (long) x[0], x => (string) x[1]);

    return results;
}

The exception, thrown when collecting the result, is:

An exception of type 'NHibernate.QueryException' occurred in NHibernate.dll but was not handled in user code

Additional information: could not resolve property: sessionAlias

My suspicion is that this is because dealershipIds is empty, but I'm struggling to prove that this is the case. Working with Entity Framework, it's possible to see the results of a query during debugging by unpacking its object graph. However, I can't seem to do that in NHibernate.

Is it possible to see the results of a query fragment via debugging, or do I have to pull it out with a Select statement?

Body:
The QueryOver you've posted seems to be missing the part where the
sessionAlias alias is assigned to something.

As it's being done for the others (except eventAlias which seems completely unused) the alias needs to be assigned to a property/path on the entity class being queried via JoinAlias/JoinQueryOver or to the entity itself as it's done on the QueryOver creation with seriesAlias.

Then, that alias (variable) can be used in Where, OrderBy, etc.

For example, supposing that Session is an entity referenced from a property of Series (no clue regarding your actual entity model) the following would fix your problem as it will bind sessionAlias to that property:

// This binds the alias to the property.
query.JoinAlias(s => s.Session, () => sessionAlias);

// This is the same as above, but uses the previously defined alias for the main entity,
// just to show how aliases can be used.
query.JoinAlias(() => seriesAlias.Session, () => sessionAlias);


答:
Easy enough using .reduce:

var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];

function reorder(array, order) {
    return order.reduce((newArray, orderIndex) => {
        newArray.push(array[orderIndex]);
        return newArray;
    }, []);
}

console.log(reorder(myArray, myOrder))```


问:
Gets last digit of a number
I need to define the last digit of a number assign this to value.
After this, return the last digit.

My snippet of code doesn't work correctly...

Code:

```<code>public int lastDigit(int number) {
    String temp = Integer.toString(number);
    int[] guess = new int[temp.length()];
    int last = guess[temp.length() - 1];

    return last;
}
</code>```

Question:

How to solve this issue?

答:
Another interesting way to do it which would also allow more than just the last number to be taken would be:

```<code>int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;

int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>
</code>```

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454

Title: Gets last digit of a number

Body:
I need to define the last digit of a number assign this to value.
After this, return the last digit.

My snippet of code doesn't work correctly...

Code:

public int lastDigit(int number) {
    String temp = Integer.toString(number);
    int[] guess = new int[temp.length()];
    int last = guess[temp.length() - 1];

    return last;
}

Question:

How to solve this issue?

Body:
Another interesting way to do it which would also allow more than just the last number to be taken would be:

int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;

int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454


问:
how can we get image from local?
I store image in local by this code...

```<code>NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageName = [NSString stringWithFormat:@"image.png"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
</code>```

[imageData writeToFile:fullPathToFile atomically:YES];

I can see this image in my iphone simulator bundle ...but how can i get back this image ?

答:
If you mean recreate the image from a file, you can do that very simply by using UIImage's +imageWithContentsOfFile: method:

```<code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"someImageName"];
UIImage *image = [UIImage imageWithContentsOfFile:fullPathToFile];
</code>```

Title: how can we get image from local?

Body:
I store image in local by this code...

NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageName = [NSString stringWithFormat:@"image.png"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

[imageData writeToFile:fullPathToFile atomically:YES];

I can see this image in my iphone simulator bundle ...but how can i get back this image ?

Body:
If you mean recreate the image from a file, you can do that very simply by using UIImage's +imageWithContentsOfFile: method:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"someImageName"];
UIImage *image = [UIImage imageWithContentsOfFile:fullPathToFile];


问:
AWS signature 4: Java and Crypto-JS does not march
I am using java to do some post with AWS signature header. The signing process is below

```<code>    private String calculateSignature(String stringToSign) {
        try {
                byte[] signatureKey = getSignatureKey(secretAccessKey, currentDate, regionName, serviceName);
                byte[] signature = HmacSHA256(stringToSign, signatureKey);
                String strHexSignature = bytesToHex(signature);
                return strHexSignature;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
    }

    private byte[] HmacSHA256(String data, byte[] key) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF8"));
    }

    private byte[] getSignatureKey(String key, String date, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
        byte[] kDate = HmacSHA256(date, kSecret);
        byte[] kRegion = HmacSHA256(regionName, kDate);
        byte[] kService = HmacSHA256(serviceName, kRegion);
        byte[] kSigning = HmacSHA256(aws4Request, kService);
        return kSigning;
    }

    private String bytesToHex(byte[] bytes) {
        final StringBuilder hexString = new StringBuilder();
        for(byte b : bytes)
            hexString.append(String.format("%02x", b));
        return hexString.toString().toLowerCase().trim();
    }
</code>```

However, when I send use this signature, it does not match the signature calculated by the server. The server is written in PHP, and it us Crypto-JS to calculate the signature. I have compared two strings need to sign and Canonical Request between Java and PHP. They are matching.

I have checked space, command and other characteries. but cannot figure out why. Are Java HmacSHA256 and crypto-js HmacSHA256 different? Or something wrong with bytesToHex method?

The Java output of Canonical Request

```<code>POST
/

content-length:667
content-type:application/json
host:host.name.com
x-amz-date:20171205T012629Z
x-amz-target:_20141201.XXXXXXX

content-length;content-type;host;x-amz-date;x-amz-target
c5b31b699700e6debe4548836a723f89b73ffcef6570e1bed4c534c0f247dc26
</code>```

The PHP returns:

```<code>POST
/

content-length:667
content-type:application/json
host:host.name.com
x-amz-date:20171205T012629Z
x-amz-target:_20141201.XXXXXXX

content-length;content-type;host;x-amz-date;x-amz-target
c5b31b699700e6debe4548836a723f89b73ffcef6570e1bed4c534c0f247dc26
</code>```

Any help or any idea will be appreciated.

答: Found the issue. The reason was the algorithm of the secret key was changed, but i was not aware of that change</p>

Body:
I am using java to do some post with AWS signature header. The signing process is below

    private String calculateSignature(String stringToSign) {
        try {
                byte[] signatureKey = getSignatureKey(secretAccessKey, currentDate, regionName, serviceName);
                byte[] signature = HmacSHA256(stringToSign, signatureKey);
                String strHexSignature = bytesToHex(signature);
                return strHexSignature;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
    }

    private byte[] HmacSHA256(String data, byte[] key) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF8"));
    }

    private byte[] getSignatureKey(String key, String date, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
        byte[] kDate = HmacSHA256(date, kSecret);
        byte[] kRegion = HmacSHA256(regionName, kDate);
        byte[] kService = HmacSHA256(serviceName, kRegion);
        byte[] kSigning = HmacSHA256(aws4Request, kService);
        return kSigning;
    }

    private String bytesToHex(byte[] bytes) {
        final StringBuilder hexString = new StringBuilder();
        for(byte b : bytes)
            hexString.append(String.format("%02x", b));
        return hexString.toString().toLowerCase().trim();
    }

However, when I send use this signature, it does not match the signature calculated by the server. The server is written in PHP, and it us Crypto-JS to calculate the signature. I have compared two strings need to sign and Canonical Request between Java and PHP. They are matching.

I have checked space, command and other characteries. but cannot figure out why. Are Java HmacSHA256 and crypto-js HmacSHA256 different? Or something wrong with bytesToHex method?

The Java output of Canonical Request

POST
/

content-length:667
content-type:application/json
host:host.name.com
x-amz-date:20171205T012629Z
x-amz-target:_20141201.XXXXXXX

content-length;content-type;host;x-amz-date;x-amz-target
c5b31b699700e6debe4548836a723f89b73ffcef6570e1bed4c534c0f247dc26

The PHP returns:

POST
/

content-length:667
content-type:application/json
host:host.name.com
x-amz-date:20171205T012629Z
x-amz-target:_20141201.XXXXXXX

content-length;content-type;host;x-amz-date;x-amz-target
c5b31b699700e6debe4548836a723f89b73ffcef6570e1bed4c534c0f247dc26

Any help or any idea will be appreciated.


问:
Rails Background Jobs running twice
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

```<code>scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end
</code>```

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

答:
You need a distributed lock since ECS instances don't share files, the most common ones being Zookeeper, Consul and Redis.

Below an example with Zookeeper, from the docs:

```<code>class ZookeptScheduler < Rufus::Scheduler

  def initialize(zookeeper, opts={})
    @zk = zookeeper
    super(opts)
  end

  def lock
    @zk_locker = @zk.exclusive_locker('scheduler')
    @zk_locker.lock # returns true if the lock was acquired, false else
  end

  def unlock
    @zk_locker.unlock
  end

  def confirm_lock
    return false if down?
    @zk_locker.assert!
  rescue ZK::Exceptions::LockAssertionFailedError => e
    # we've lost the lock, shutdown (and return false to at least prevent
    # this job from triggering
    shutdown
    false
  end
end
</code>```

You could maybe use EFS to share a lockfile, but this is not the correct way.

Title: Rails Background Jobs running twice

Body:
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

Body:
You need a distributed lock since ECS instances don't share files, the most common ones being Zookeeper, Consul and Redis.

Below an example with Zookeeper, from the docs:

class ZookeptScheduler < Rufus::Scheduler

  def initialize(zookeeper, opts={})
    @zk = zookeeper
    super(opts)
  end

  def lock
    @zk_locker = @zk.exclusive_locker('scheduler')
    @zk_locker.lock # returns true if the lock was acquired, false else
  end

  def unlock
    @zk_locker.unlock
  end

  def confirm_lock
    return false if down?
    @zk_locker.assert!
  rescue ZK::Exceptions::LockAssertionFailedError => e
    # we've lost the lock, shutdown (and return false to at least prevent
    # this job from triggering
    shutdown
    false
  end
end

You could maybe use EFS to share a lockfile, but this is not the correct way.


问:
Makefiles with source / object files in different directories
I have a project with the following directory structure:

```<code>         $tests/              $doc/
          |                     |-makefile
   +------+-------+             |
   |      |       |           tests/
  test1/ test2/  test3/         |
   |      |       |       test1.rst, test2.rst, test3.rst
 test1.e test2.e test3.e
</code>```

A file in the $doc/tests directory e.g test1.rst is created from $tests/test1/test1.e. I'm having problems with the makefile specifying that the source files are in $tests/*/*.e and the destination files are in $doc/tests/*.rst.

I've seen several similar questions but haven't been able to workout the correct makefile syntax.

This makefile works for a single file example

```<code>SOURCES = $(wildcard $(tests)/*/*.e)
OBJECTS = $(addprefix $(doc)/tests/,$(notdir $(SOURCES:.e=.rst)))

# single file trial
SRC = $(tests)/test1/test1.e
OBJ = $(doc)/tests/test1.rst

$(OBJ): $(SRC)

debugvars:
    @echo SOURCES=$(SOURCES)
    @echo OBJECTS=$(OBJECTS)

# define how to create any RST file from a testcase
%.rst:
    $(scripts)/wr_rst.py --infile $<

# define how to create an RST file from a testcase
%.rst: %.e
    $(scripts)/wr_rst.py --infile $<

.e.rst:
    $(scripts)/wr_rst.py --infile $<

.SUFFIXES: .e .rst
</code>```

I'm having trouble when using the full list of objects i.e.

```<code>all: $(OBJECTS)

$(OBJECTS): $(SOURCES)
    $(scripts)/wr_rst.py --infile $<
</code>```

test1.rst is generated 3 times and test2,3.rst are ignored. The $(SOURCES) and $(OBJECTS) are correct. I suspect that $< does not iterate over the (SOURCES)

Here is some of the output from make -d

```<code>     No implicit rule found for `$tests/test3/test3.e'.
 Finished prerequisites of target file `$tests/test3/test3.e'.
No need to remake target `$tests/test3/test3.e'.
Considering target file `tests/test3.rst'.
 File `tests/test3.rst' does not exist.
  Pruning file `$tests/test1/test1.e'.
  Pruning file `$tests/test2/test2.e'.
  Pruning file `$tests/test3/test3.e'.
 Finished prerequisites of target file `tests/test3.rst'.
Must remake target `tests/test3.rst'.
$scripts/wr_rst.py --inile $tests/test1/test1.e
Putting child 0x00ee6420 (tests/test3.rst) PID 11720 on the chain.
Live child 0x00ee6420 (tests/test3.rst) PID 11720
Writing RST file $doc/tests/test1.rst
Reaping winning child 0x00ee6420 PID 11720
Removing child 0x00ee6420 PID 11720 from chain.
Successfully remade target file `tests/test3.rst'.
</code>```

答:
(This question looks very familiar-- I'd almost swear that one essentially the same has been asked and answered.)

Let's take this in stages. We could write the rules one at a time:

```<code>$(doc)/tests/test1.rst: $(tests)/test1/test1.e
    ...
</code>```

but that's tedious. It's the kind of situation that cries out for a wildcard solution, such as a pattern rule, but one of Make's serious shortcomings is its crude handling of wildcards. A pattern rule in which the wildcard is repeated:

```<code>$(doc)/tests/%.rst: $(tests)/%/%.e
    ...
</code>```

is not allowed. But we could write the rules using eval:

```<code>define template
$(doc)/tests/$(1).rst: $(tests)/$(1)/$(1).e
    use some tool to build $$@ from $$<
endef

$(eval $(call template,test1))
$(eval $(call template,test2))
...
</code>```

Then instead of writing all of those eval statements, we can delegate that job to foreach:

```<code>TESTS := test1 test2 ...

$(foreach TEST,$(TESTS),$(eval $(call template,$(TEST)))
</code>```

Then instead of writing that list of tests, we can delegate that to wildcard, and use the same list to construct a list of target files:

```<code>TESTS := $(notdir $(wildcard $(tests)/*))
TARGETS := $(patsubst %,$(doc)/tests/%.rst,$(TESTS))

all: $(TARGETS)
</code>```

Putting all of these together is straightforward, but this answer is getting long.

Body:
I have a project with the following directory structure:

         $tests/              $doc/
          |                     |-makefile
   +------+-------+             |
   |      |       |           tests/
  test1/ test2/  test3/         |
   |      |       |       test1.rst, test2.rst, test3.rst
 test1.e test2.e test3.e

A file in the $doc/tests directory e.g test1.rst is created from $tests/test1/test1.e. I'm having problems with the makefile specifying that the source files are in $tests/*/*.e and the destination files are in $doc/tests/*.rst.

I've seen several similar questions but haven't been able to workout the correct makefile syntax.

This makefile works for a single file example

SOURCES = $(wildcard $(tests)/*/*.e)
OBJECTS = $(addprefix $(doc)/tests/,$(notdir $(SOURCES:.e=.rst)))

# single file trial
SRC = $(tests)/test1/test1.e
OBJ = $(doc)/tests/test1.rst

$(OBJ): $(SRC)

debugvars:
    @echo SOURCES=$(SOURCES)
    @echo OBJECTS=$(OBJECTS)

# define how to create any RST file from a testcase
%.rst:
    $(scripts)/wr_rst.py --infile $<

# define how to create an RST file from a testcase
%.rst: %.e
    $(scripts)/wr_rst.py --infile $<

.e.rst:
    $(scripts)/wr_rst.py --infile $<

.SUFFIXES: .e .rst

I'm having trouble when using the full list of objects i.e.

all: $(OBJECTS)

$(OBJECTS): $(SOURCES)
    $(scripts)/wr_rst.py --infile $<

test1.rst is generated 3 times and test2,3.rst are ignored. The $(SOURCES) and $(OBJECTS) are correct. I suspect that $< does not iterate over the (SOURCES)

Here is some of the output from make -d

     No implicit rule found for `$tests/test3/test3.e'.
 Finished prerequisites of target file `$tests/test3/test3.e'.
No need to remake target `$tests/test3/test3.e'.
Considering target file `tests/test3.rst'.
 File `tests/test3.rst' does not exist.
  Pruning file `$tests/test1/test1.e'.
  Pruning file `$tests/test2/test2.e'.
  Pruning file `$tests/test3/test3.e'.
 Finished prerequisites of target file `tests/test3.rst'.
Must remake target `tests/test3.rst'.
$scripts/wr_rst.py --inile $tests/test1/test1.e
Putting child 0x00ee6420 (tests/test3.rst) PID 11720 on the chain.
Live child 0x00ee6420 (tests/test3.rst) PID 11720
Writing RST file $doc/tests/test1.rst
Reaping winning child 0x00ee6420 PID 11720
Removing child 0x00ee6420 PID 11720 from chain.
Successfully remade target file `tests/test3.rst'.

Body:
(This question looks very familiar-- I'd almost swear that one essentially the same has been asked and answered.)

Let's take this in stages. We could write the rules one at a time:

$(doc)/tests/test1.rst: $(tests)/test1/test1.e
    ...

but that's tedious. It's the kind of situation that cries out for a wildcard solution, such as a pattern rule, but one of Make's serious shortcomings is its crude handling of wildcards. A pattern rule in which the wildcard is repeated:

$(doc)/tests/%.rst: $(tests)/%/%.e
    ...

is not allowed. But we could write the rules using eval:

define template
$(doc)/tests/$(1).rst: $(tests)/$(1)/$(1).e
    use some tool to build $$@ from $$<
endef

$(eval $(call template,test1))
$(eval $(call template,test2))
...

Then instead of writing all of those eval statements, we can delegate that job to foreach:

TESTS := test1 test2 ...

$(foreach TEST,$(TESTS),$(eval $(call template,$(TEST)))

Then instead of writing that list of tests, we can delegate that to wildcard, and use the same list to construct a list of target files:

TESTS := $(notdir $(wildcard $(tests)/*))
TARGETS := $(patsubst %,$(doc)/tests/%.rst,$(TESTS))

all: $(TARGETS)

Putting all of these together is straightforward, but this answer is getting long.


问:
How to store command arguments which contain double quotes in an array?
I have a Bash script which generates, stores and modifies values in an array. These values are later used as arguments for a command.

For a MCVE I thought of an arbitrary command bash -c 'echo 0="$0" ; echo 1="$1"' which explains my problem. I will call my command with two arguments -option1=withoutspace and -option2="with space". So it would look like this

```<code>> bash -c 'echo 0="$0" ; echo 1="$1"' -option1=withoutspace -option2="with space"
</code>```

if the call to the command would be typed directly into the shell. It prints

```<code>0=-option1=withoutspace
1=-option2=with space
</code>```

In my Bash script, the arguments are part of an array. However

```<code>#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2="with space"')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"
</code>```

prints

```<code>0=-option1=withoutspace
1=-option2="with space"
</code>```

which still shows the double quotes (because they are interpreted literally?). What works is

```<code>#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"
</code>```

which prints again

```<code>0=-option1=withoutspace
1=-option2=with space
</code>```

What do I have to change to make ARGUMENTS+=('-option2="with space"') work as well as ARGUMENTS+=('-option2=with space')?

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)

答:
Get rid of the single quotes. Write the options exactly as you would on the command line.

```<code>ARGUMENTS+=(-option1=withoutspace)
ARGUMENTS+=(-option2="with space")
</code>```

Note that this is exactly equivalent to your second option:

```<code>ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')
</code>```

-option2="with space" and '-option2=with space' both evaluate to the same string. They're two ways of writing the same thing.

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)

It's the exact right thing to do. Arrays are perfect for this. Using a flat string would be a mistake.

Body:
I have a Bash script which generates, stores and modifies values in an array. These values are later used as arguments for a command.

For a MCVE I thought of an arbitrary command bash -c 'echo 0="$0" ; echo 1="$1"' which explains my problem. I will call my command with two arguments -option1=withoutspace and -option2="with space". So it would look like this

> bash -c 'echo 0="$0" ; echo 1="$1"' -option1=withoutspace -option2="with space"

if the call to the command would be typed directly into the shell. It prints

0=-option1=withoutspace
1=-option2=with space

In my Bash script, the arguments are part of an array. However

#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2="with space"')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"

prints

0=-option1=withoutspace
1=-option2="with space"

which still shows the double quotes (because they are interpreted literally?). What works is

#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"

which prints again

0=-option1=withoutspace
1=-option2=with space

What do I have to change to make ARGUMENTS+=('-option2="with space"') work as well as ARGUMENTS+=('-option2=with space')?

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)

Body:
Get rid of the single quotes. Write the options exactly as you would on the command line.

ARGUMENTS+=(-option1=withoutspace)
ARGUMENTS+=(-option2="with space")

Note that this is exactly equivalent to your second option:

ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')

-option2="with space" and '-option2=with space' both evaluate to the same string. They're two ways of writing the same thing.

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)

It's the exact right thing to do. Arrays are perfect for this. Using a flat string would be a mistake.


问:
Automatically open latest powerpoint file in folder
I've been looking for a script to automatically open the latest PowerPoint show in a folder. I have a couple computers that are used for presenting information to staff and would like to have it open the latest version of the PowerPoint Show without me having to do it. I've see something like it mentioned before but never could find the script myself.</p>

答:
Assuming your file extensions are "pptx" and they are all contained in the same folder you could use the following batch file to start the file that was most recently modified:</p>

```<code>for /F "delims=" %%i in ('dir /B /O:-D *.txt') do (
    start "dummy" "%%i"
    exit /B 0
)
</code>```

Body:
Assuming your file extensions are "pptx" and they are all contained in the same folder you could use the following batch file to start the file that was most recently modified:

for /F "delims=" %%i in ('dir /B /O:-D *.txt') do (
    start "dummy" "%%i"
    exit /B 0
)


问:
Adding Json Object into url
I want to be able to delete item based on the book_id.

```<code>tbody.insertAdjacentHTML('beforeend', '<tr><td>' + obj.book_id + '</td><td>' + <a href="delete_books?book_id=" + obj.book_id + >Delete</a> + '</td></tr>'
</code>```

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.

答:
```<code>tbody.insertAdjacentHTML('beforeend', '<tr><td>' + obj.book_id + '</td><td>' + '<a href=' + 'delete_books?book_id=' + obj.book_id + '>Delete</a></td></tr>');
</code>```

Title: Adding Json Object into url

Body:
I want to be able to delete item based on the book_id.

tbody.insertAdjacentHTML('beforeend', '
' + obj.book_id + '	' + Delete + '
'

I am not sure how to form the url. The link can't seem to work.
I want to be able to retrieve the id and delete in my  servlet file.